text
stringlengths
2
1.04M
meta
dict
#include "problems/cvrp/operators/intra_cross_exchange.h" namespace vroom { namespace cvrp { IntraCrossExchange::IntraCrossExchange(const Input& input, const utils::SolutionState& sol_state, RawRoute& s_raw_route, Index s_vehicle, Index s_rank, Index t_rank, bool check_s_reverse, bool check_t_reverse) : Operator(OperatorName::IntraCrossExchange, input, sol_state, s_raw_route, s_vehicle, s_rank, s_raw_route, s_vehicle, t_rank), _gain_upper_bound_computed(false), // Required for consistency in compute_gain if check_s_reverse or // check_t_reverse are false. _reversed_s_gain(NO_GAIN), _reversed_t_gain(NO_GAIN), reverse_s_edge(false), reverse_t_edge(false), check_s_reverse(check_s_reverse), check_t_reverse(check_t_reverse), s_normal_t_normal_is_valid(false), s_normal_t_reverse_is_valid(false), s_reverse_t_reverse_is_valid(false), s_reverse_t_normal_is_valid(false), _moved_jobs(t_rank - s_rank + 2), _first_rank(s_rank), _last_rank(t_rank + 2) { // Use s_rank as smallest rank for symmetry reasons. assert(s_rank + 2 < t_rank); // Avoid common edge. assert(s_route.size() >= 5); assert(t_rank < s_route.size() - 1); // Either moving edges of single jobs or whole shipments. assert((_input.jobs[this->s_route[s_rank]].type == JOB_TYPE::SINGLE and _input.jobs[this->s_route[s_rank + 1]].type == JOB_TYPE::SINGLE and check_s_reverse) or (_input.jobs[this->s_route[s_rank]].type == JOB_TYPE::PICKUP and _input.jobs[this->s_route[s_rank + 1]].type == JOB_TYPE::DELIVERY and !check_s_reverse and _sol_state.matching_delivery_rank[s_vehicle][s_rank] == s_rank + 1)); assert((_input.jobs[this->t_route[t_rank]].type == JOB_TYPE::SINGLE and _input.jobs[this->t_route[t_rank + 1]].type == JOB_TYPE::SINGLE and check_t_reverse) or (_input.jobs[this->t_route[t_rank]].type == JOB_TYPE::PICKUP and _input.jobs[this->t_route[t_rank + 1]].type == JOB_TYPE::DELIVERY and !check_t_reverse and _sol_state.matching_delivery_rank[t_vehicle][t_rank] == t_rank + 1)); _moved_jobs[0] = s_route[t_rank]; _moved_jobs[1] = s_route[t_rank + 1]; std::copy(s_route.begin() + s_rank + 2, s_route.begin() + t_rank, _moved_jobs.begin() + 2); _moved_jobs[_moved_jobs.size() - 2] = s_route[s_rank]; _moved_jobs[_moved_jobs.size() - 1] = s_route[s_rank + 1]; } Eval IntraCrossExchange::gain_upper_bound() { const auto& v = _input.vehicles[s_vehicle]; // Consider the cost of replacing edge starting at rank s_rank with // target edge. Part of that cost (for adjacent edges) is stored in // _sol_state.edge_evals_around_edge. reverse_* checks whether we // should change the target edge order. Index s_index = _input.jobs[s_route[s_rank]].index(); Index s_after_index = _input.jobs[s_route[s_rank + 1]].index(); Index t_index = _input.jobs[s_route[t_rank]].index(); Index t_after_index = _input.jobs[s_route[t_rank + 1]].index(); // Determine costs added with target edge. Eval previous_cost; Eval next_cost; Eval reverse_previous_cost; Eval reverse_next_cost; if (s_rank == 0) { if (v.has_start()) { auto p_index = v.start.value().index(); previous_cost = v.eval(p_index, t_index); reverse_previous_cost = v.eval(p_index, t_after_index); } } else { auto p_index = _input.jobs[s_route[s_rank - 1]].index(); previous_cost = v.eval(p_index, t_index); reverse_previous_cost = v.eval(p_index, t_after_index); } auto n_index = _input.jobs[s_route[s_rank + 2]].index(); next_cost = v.eval(t_after_index, n_index); reverse_next_cost = v.eval(t_index, n_index); _normal_s_gain = _sol_state.edge_evals_around_edge[s_vehicle][s_rank] - previous_cost - next_cost; auto s_gain_upper_bound = _normal_s_gain; if (check_t_reverse) { const auto reverse_edge_cost = v.eval(t_index, t_after_index) - v.eval(t_after_index, t_index); _reversed_s_gain = _sol_state.edge_evals_around_edge[s_vehicle][s_rank] + reverse_edge_cost - reverse_previous_cost - reverse_next_cost; s_gain_upper_bound = std::max(_normal_s_gain, _reversed_s_gain); } // Consider the cost of replacing edge starting at rank t_rank with // source edge. Part of that cost (for adjacent edges) is stored in // _sol_state.edge_evals_around_edge. reverse_* checks whether we // should change the source edge order. next_cost = Eval(); reverse_previous_cost = Eval(); reverse_next_cost = Eval(); auto p_index = _input.jobs[s_route[t_rank - 1]].index(); previous_cost = v.eval(p_index, s_index); reverse_previous_cost = v.eval(p_index, s_after_index); if (t_rank == s_route.size() - 2) { if (v.has_end()) { auto n_index = v.end.value().index(); next_cost = v.eval(s_after_index, n_index); reverse_next_cost = v.eval(s_index, n_index); } } else { auto n_index = _input.jobs[s_route[t_rank + 2]].index(); next_cost = v.eval(s_after_index, n_index); reverse_next_cost = v.eval(s_index, n_index); } _normal_t_gain = _sol_state.edge_evals_around_edge[t_vehicle][t_rank] - previous_cost - next_cost; auto t_gain_upper_bound = _normal_t_gain; if (check_s_reverse) { const auto reverse_edge_cost = v.eval(s_index, s_after_index) - v.eval(s_after_index, s_index); _reversed_t_gain = _sol_state.edge_evals_around_edge[t_vehicle][t_rank] + reverse_edge_cost - reverse_previous_cost - reverse_next_cost; t_gain_upper_bound = std::max(_normal_t_gain, _reversed_t_gain); } _gain_upper_bound_computed = true; return s_gain_upper_bound + t_gain_upper_bound; } void IntraCrossExchange::compute_gain() { assert(_gain_upper_bound_computed); assert(s_normal_t_normal_is_valid or s_normal_t_reverse_is_valid or s_reverse_t_reverse_is_valid or s_reverse_t_normal_is_valid); stored_gain = NO_GAIN; if (s_normal_t_normal_is_valid) { const auto current_gain = _normal_s_gain + _normal_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = false; reverse_t_edge = false; } } if (s_normal_t_reverse_is_valid) { const auto current_gain = _reversed_s_gain + _normal_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = false; reverse_t_edge = true; } } if (s_reverse_t_reverse_is_valid) { const auto current_gain = _reversed_s_gain + _reversed_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = true; reverse_t_edge = true; } } if (s_reverse_t_normal_is_valid) { const auto current_gain = _normal_s_gain + _reversed_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = true; reverse_t_edge = false; } } gain_computed = true; } bool IntraCrossExchange::is_valid() { assert(_gain_upper_bound_computed); const auto delivery = source.delivery_in_range(_first_rank, _last_rank); const auto& s_v = _input.vehicles[s_vehicle]; const auto s_travel_time = _sol_state.route_evals[s_vehicle].duration; const auto s_normal_t_normal_duration = _normal_s_gain.duration + _normal_t_gain.duration; s_normal_t_normal_is_valid = s_v.ok_for_travel_time(s_travel_time - s_normal_t_normal_duration) and source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); std::swap(_moved_jobs[0], _moved_jobs[1]); if (check_t_reverse) { const auto s_normal_t_reverse_duration = _reversed_s_gain.duration + _normal_t_gain.duration; s_normal_t_reverse_is_valid = s_v.ok_for_travel_time(s_travel_time - s_normal_t_reverse_duration) && source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } std::swap(_moved_jobs[_moved_jobs.size() - 2], _moved_jobs[_moved_jobs.size() - 1]); if (check_s_reverse and check_t_reverse) { const auto s_reversed_t_reversed_duration = _reversed_s_gain.duration + _reversed_t_gain.duration; s_reverse_t_reverse_is_valid = s_v.ok_for_travel_time(s_travel_time - s_reversed_t_reversed_duration) and source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } std::swap(_moved_jobs[0], _moved_jobs[1]); if (check_s_reverse) { const auto s_reverse_t_normal_duration = _normal_s_gain.duration + _reversed_t_gain.duration; s_reverse_t_normal_is_valid = s_v.ok_for_travel_time(s_travel_time - s_reverse_t_normal_duration) && source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } // Reset to initial situation before potential application and TW // checks. std::swap(_moved_jobs[_moved_jobs.size() - 2], _moved_jobs[_moved_jobs.size() - 1]); return s_normal_t_normal_is_valid or s_normal_t_reverse_is_valid or s_reverse_t_reverse_is_valid or s_reverse_t_normal_is_valid; } void IntraCrossExchange::apply() { assert(!reverse_s_edge or (_input.jobs[s_route[s_rank]].type == JOB_TYPE::SINGLE and _input.jobs[s_route[s_rank + 1]].type == JOB_TYPE::SINGLE)); assert(!reverse_t_edge or (_input.jobs[t_route[t_rank]].type == JOB_TYPE::SINGLE and _input.jobs[t_route[t_rank + 1]].type == JOB_TYPE::SINGLE)); std::swap(s_route[s_rank], s_route[t_rank]); std::swap(s_route[s_rank + 1], s_route[t_rank + 1]); if (reverse_s_edge) { std::swap(s_route[t_rank], s_route[t_rank + 1]); } if (reverse_t_edge) { std::swap(s_route[s_rank], s_route[s_rank + 1]); } source.update_amounts(_input); } std::vector<Index> IntraCrossExchange::addition_candidates() const { return {}; } std::vector<Index> IntraCrossExchange::update_candidates() const { return {s_vehicle}; } } // namespace cvrp } // namespace vroom
{ "content_hash": "024237d08134a4d501418997dbd5f5ed", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 80, "avg_line_length": 37.17088607594937, "alnum_prop": 0.558317725183041, "repo_name": "VROOM-Project/vroom", "id": "0df479029d74cca2bb3b7ea080a83209c64e8f77", "size": "11857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/problems/cvrp/operators/intra_cross_exchange.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "24295" }, { "name": "C++", "bytes": "1326264" }, { "name": "Makefile", "bytes": "2755" }, { "name": "Shell", "bytes": "1124" }, { "name": "TeX", "bytes": "5468" } ], "symlink_target": "" }
<?php /** * Theme related functions. * */ /** * Get title for the webpage by concatenating page specific title with site-wide title. * * @param string $title for this page. * @return string/null wether the favicon is defined or not. */ function get_title($title) { global $hampux; return $title . (isset($hampux['title_append']) ? $hampux['title_append'] : null); } /** * Creates a navigation bar. * * @param string $menu for the navigation bar. * @return string as the html for the menu. */ function generate_navbar($menu) { $html = "<nav>\n<ul class='{$menu['class']}'>\n"; foreach($menu['items'] as $item) { $selected = $menu['callback_selected']($item['url']) ? " class='selected' " : null; $html .= "<li{$selected}><a href='{$item['url']}' title='{$item['title']}'>{$item['text']}</a></li>\n"; } $html .= "</ul>\n</nav>\n"; return $html; }
{ "content_hash": "249d1e3ef419e9306e8b8792106dcbd7", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 107, "avg_line_length": 27.65625, "alnum_prop": 0.607909604519774, "repo_name": "hamdav01/Hampux", "id": "d54b0a49c54d43106738edb4337e60b37babd3ce", "size": "885", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "theme/functions.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "159" }, { "name": "CSS", "bytes": "15962" }, { "name": "JavaScript", "bytes": "2718" }, { "name": "PHP", "bytes": "19085" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "415c38a015fee3a4843441f0f7a4d903", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "17ed1af4de47c1326e5c41cbe976769103ffc35e", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Aspleniaceae/Asplenium/Asplenium adiantum-nigrum/Asplenium adiantum-nigrum corunnense/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using namespace DirectX; using namespace std; extern "C" { LPBYTE g_cameraStructAddress = nullptr; LPBYTE g_cameraMatrixAddress = nullptr; LPBYTE g_hudToggleAddress = nullptr; } namespace IGCS::GameSpecific::CameraManipulator { static float _originalMatrixData[12]; static float _currentCameraCoords[3]; static LPBYTE _timestopAddress = nullptr; // newValue: 1 == time should be frozen, 0 == normal gameplay void setTimeStopValue(uint8_t newValue) { if (nullptr != _timestopAddress) { *(_timestopAddress + TIMESTOP_IN_STRUCT_OFFSET) = newValue; } } void setTimestopAddress(LPBYTE timestopAddress) { DWORD64 addressToUse = ((DWORD64*)timestopAddress)[0]; #ifdef _DEBUG cout << "timestop var absolute address source: " << (hex) << (void*)timestopAddress << endl; cout << "timestop var absolute address: " << (hex) << (void*)addressToUse << endl; #endif // DEBUG _timestopAddress = reinterpret_cast<LPBYTE>(addressToUse); } void toggleHud() { uint8_t currentValue = *(g_hudToggleAddress); toggleHud(currentValue == 0 ? (uint8_t)1 : (uint8_t)0); } void toggleHud(uint8_t newValue) { if (nullptr == g_hudToggleAddress) { return; } // g_hudToggleAddress is a uint8_t array with bit flags (1 per uint8_t). It hides hud parts. We have to set each element individually. g_hudToggleAddress[0] = newValue; g_hudToggleAddress[1] = newValue; g_hudToggleAddress[3] = newValue; g_hudToggleAddress[6] = newValue; g_hudToggleAddress[7] = newValue; g_hudToggleAddress[8] = newValue; g_hudToggleAddress[9] = newValue; g_hudToggleAddress[10] = newValue; g_hudToggleAddress[13] = newValue; g_hudToggleAddress[20] = newValue; g_hudToggleAddress[23] = newValue; } // Resets the FOV to the default void resetFoV() { if (nullptr == g_cameraStructAddress) { return; } float* fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress+ FOV_IN_STRUCT_OFFSET); *fovInMemory = DEFAULT_FOV_DEGREES ; } // changes the FoV with the specified amount void changeFoV(float amount) { if (nullptr == g_cameraStructAddress) { return; } float* fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress + FOV_IN_STRUCT_OFFSET); *fovInMemory += amount; } XMFLOAT3 getCurrentCameraCoords() { return XMFLOAT3(_currentCameraCoords[0], _currentCameraCoords[1], _currentCameraCoords[2]); } // newLookQuaternion: newly calculated quaternion of camera view space. Can be used to construct a 4x4 matrix if the game uses a matrix instead of a quaternion // newCoords are the new coordinates for the camera in worldspace. void writeNewCameraValuesToGameData(XMFLOAT3 newCoords, XMVECTOR newLookQuaternion) { if (nullptr == g_cameraStructAddress) { return; } // game uses a 3x3 matrix for look data. We have to calculate a rotation matrix from our quaternion and store the upper 3x3 matrix (_11-_33) in memory. XMMATRIX rotationMatrixPacked = XMMatrixRotationQuaternion(newLookQuaternion); XMFLOAT4X4 rotationMatrix; XMStoreFloat4x4(&rotationMatrix, rotationMatrixPacked); float* matrixInMemory = reinterpret_cast<float*>(g_cameraMatrixAddress); matrixInMemory[0] = rotationMatrix._11; matrixInMemory[1] = rotationMatrix._21; matrixInMemory[2] = rotationMatrix._31; matrixInMemory[3] = newCoords.x; matrixInMemory[4] = rotationMatrix._12; matrixInMemory[5] = rotationMatrix._22; matrixInMemory[6] = rotationMatrix._32; matrixInMemory[7] = newCoords.y; matrixInMemory[8] = rotationMatrix._13; matrixInMemory[9] = rotationMatrix._23; matrixInMemory[10] = rotationMatrix._33; matrixInMemory[11] = newCoords.z; _currentCameraCoords[0] = newCoords.x; _currentCameraCoords[1] = newCoords.y; _currentCameraCoords[2] = newCoords.z; } // Waits for the interceptor to pick up the camera struct address. Should only return if address is found void waitForCameraStructAddresses(LPBYTE hostImageAddress) { Console::WriteLine("Waiting for camera struct interception..."); while (nullptr == g_cameraStructAddress) { Sleep(100); } Console::WriteLine("Camera found."); // also store the matrix address for checks in the intercepted asm. g_cameraMatrixAddress = g_cameraStructAddress + MATRIX_IN_CAMERA_STRUCT; #ifdef _DEBUG cout << "Camera struct address: " << hex << (void*)g_cameraStructAddress << endl; cout << "Camera matrix address: " << hex << (void*)g_cameraMatrixAddress << endl; #endif } // should restore the camera values in the camera structures to the cached values. This assures the free camera is always enabled at the original camera location. void restoreOriginalCameraValues() { float* matrixInMemory = reinterpret_cast<float*>(g_cameraMatrixAddress); memcpy(matrixInMemory, _originalMatrixData, 12 * sizeof(float)); } void cacheOriginalCameraValues() { float* matrixInMemory = reinterpret_cast<float*>(g_cameraMatrixAddress); memcpy(_originalMatrixData, matrixInMemory, 12 * sizeof(float)); float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + COORDS_IN_CAMERA_STRUCT); memcpy(_currentCameraCoords, coordsInMemory, 3 * sizeof(float)); } }
{ "content_hash": "3d24a553be1a4c6ec2df12648cb23f34", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 163, "avg_line_length": 31.80246913580247, "alnum_prop": 0.7331133540372671, "repo_name": "FransBouma/InjectableGenericCameraSystem", "id": "db3406521e830069599f3beceaada55d1a740f29", "size": "6983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Cameras/Mafia3/InjectableGenericCameraSystem/CameraManipulator.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "446746" }, { "name": "C", "bytes": "2569785" }, { "name": "C#", "bytes": "843174" }, { "name": "C++", "bytes": "16433213" } ], "symlink_target": "" }
<?php namespace ZfcDatagrid\Renderer; use Zend\View\Model\ViewModel; interface RendererInterface { /** * @return array */ public function getSortConditions(); /** * @return array */ public function getFilters(); /** * Return the name of the renderer. * * @return string */ public function getName(); /** * Determine if the renderer is for export. * * @return bool */ public function isExport(); /** * Determin if the renderer is HTML * It can be export + html -> f.x. * printing for HTML. * * @return bool */ public function isHtml(); /** * Execute all... * * @return ViewModel Response\Stream */ public function execute(); }
{ "content_hash": "4022e06b4aaa3ef93181f306f3ca2ee0", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 47, "avg_line_length": 16.5, "alnum_prop": 0.547979797979798, "repo_name": "ThaDafinser/ZfcDatagrid", "id": "046b9e342a91b0e07dfdce857acb789648d53476", "size": "792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ZfcDatagrid/Renderer/RendererInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "33958" }, { "name": "PHP", "bytes": "521404" } ], "symlink_target": "" }
#include "config.h" #include <stdlib.h> #include <assert.h> #include "libgfortran.h" #if defined (HAVE_GFC_INTEGER_8) /* Allocates a block of memory with internal_malloc if the array needs repacking. */ GFC_INTEGER_8 * internal_pack_8 (gfc_array_i8 * source) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type stride[GFC_MAX_DIMENSIONS]; index_type stride0; index_type dim; index_type ssize; const GFC_INTEGER_8 *src; GFC_INTEGER_8 *dest; GFC_INTEGER_8 *destptr; int n; int packed; /* TODO: Investigate how we can figure out if this is a temporary since the stride=0 thing has been removed from the frontend. */ dim = GFC_DESCRIPTOR_RANK (source); ssize = 1; packed = 1; for (n = 0; n < dim; n++) { count[n] = 0; stride[n] = source->dim[n].stride; extent[n] = source->dim[n].ubound + 1 - source->dim[n].lbound; if (extent[n] <= 0) { /* Do nothing. */ packed = 1; break; } if (ssize != stride[n]) packed = 0; ssize *= extent[n]; } if (packed) return source->data; /* Allocate storage for the destination. */ destptr = (GFC_INTEGER_8 *)internal_malloc_size (ssize * sizeof (GFC_INTEGER_8)); dest = destptr; src = source->data; stride0 = stride[0]; while (src) { /* Copy the data. */ *(dest++) = *src; /* Advance to the next element. */ src += stride0; count[0]++; /* Advance to the next source element. */ n = 0; while (count[n] == extent[n]) { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ src -= stride[n] * extent[n]; n++; if (n == dim) { src = NULL; break; } else { count[n]++; src += stride[n]; } } } return destptr; } #endif
{ "content_hash": "e157f218dc14686b635152b70251b37b", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 83, "avg_line_length": 23.021052631578947, "alnum_prop": 0.5331504343850023, "repo_name": "shaotuanchen/sunflower_exp", "id": "f7b27e05ea1e456ba4d624f6abbc15890f429eb8", "size": "3589", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "tools/source/gcc-4.2.4/libgfortran/generated/in_pack_i8.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "459993" }, { "name": "Awk", "bytes": "6562" }, { "name": "Batchfile", "bytes": "9028" }, { "name": "C", "bytes": "50326113" }, { "name": "C++", "bytes": "2040239" }, { "name": "CSS", "bytes": "2355" }, { "name": "Clarion", "bytes": "2484" }, { "name": "Coq", "bytes": "61440" }, { "name": "DIGITAL Command Language", "bytes": "69150" }, { "name": "Emacs Lisp", "bytes": "186910" }, { "name": "Fortran", "bytes": "5364" }, { "name": "HTML", "bytes": "2171356" }, { "name": "JavaScript", "bytes": "27164" }, { "name": "Logos", "bytes": "159114" }, { "name": "M", "bytes": "109006" }, { "name": "M4", "bytes": "100614" }, { "name": "Makefile", "bytes": "5409865" }, { "name": "Mercury", "bytes": "702" }, { "name": "Module Management System", "bytes": "56956" }, { "name": "OCaml", "bytes": "253115" }, { "name": "Objective-C", "bytes": "57800" }, { "name": "Papyrus", "bytes": "3298" }, { "name": "Perl", "bytes": "70992" }, { "name": "Perl 6", "bytes": "693" }, { "name": "PostScript", "bytes": "3440120" }, { "name": "Python", "bytes": "40729" }, { "name": "Redcode", "bytes": "1140" }, { "name": "Roff", "bytes": "3794721" }, { "name": "SAS", "bytes": "56770" }, { "name": "SRecode Template", "bytes": "540157" }, { "name": "Shell", "bytes": "1560436" }, { "name": "Smalltalk", "bytes": "10124" }, { "name": "Standard ML", "bytes": "1212" }, { "name": "TeX", "bytes": "385584" }, { "name": "WebAssembly", "bytes": "52904" }, { "name": "Yacc", "bytes": "510934" } ], "symlink_target": "" }
using System.Linq; using Plainion.Wiki.AST; using Plainion.Wiki.Rendering; namespace Plainion.Wiki.Xaml.Rendering.RenderActions { [XamlRenderAction( typeof( LineBreak ) )] public class LineBreakRenderAction : GenericRenderAction<LineBreak> { protected override void Render( LineBreak lineBreak ) { WriteLine( "<LineBreak/>" ); } } }
{ "content_hash": "ee27bb98597c0035a1f6a381f4545c42", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 71, "avg_line_length": 26.8, "alnum_prop": 0.6517412935323383, "repo_name": "ronin4net/Plainion.Notes", "id": "bbb5841623e8caa7a9420cc3dff9adc0407e0750", "size": "404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Plainion.Wiki.Xaml/Rendering/RenderActions/LineBreakRenderAction.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "660564" }, { "name": "CSS", "bytes": "7721" }, { "name": "F#", "bytes": "681" }, { "name": "HTML", "bytes": "1450" }, { "name": "JavaScript", "bytes": "2509" } ], "symlink_target": "" }
FROM balenalib/beaglebone-green-gateway-debian:bookworm-build ENV NODE_VERSION 12.22.9 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "43b175e6b06c9be3e4c2343de0bc434dae16991a747dae5a4ddc0ebb7644e433 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bookworm \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.22.9, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "880a7bd2998e77324d1f005525b853c5", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 696, "avg_line_length": 67.7560975609756, "alnum_prop": 0.7109431245500359, "repo_name": "resin-io-library/base-images", "id": "f6f4b8ce417765adfe871d2986f0b45efdc10cac", "size": "2799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/beaglebone-green-gateway/debian/bookworm/12.22.9/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
using System; // //Module : AAANGULARSEPARATION.CPP //Purpose: Implementation for the algorithms which obtain various separation distances between celestial objects //Created: PJN / 29-12-2003 //History: None // //Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) // //All rights reserved. // //Copyright / Usage Details: // //You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) //when your product is released in binary form. You are allowed to modify the source code in any way you want //except you cannot modify the copyright details at the top of each module. If you want to distribute source //code with your application, then you are only allowed to distribute versions released by the author. This is //to maintain a single distribution point for the source code. // // //////////////////////////// Includes ///////////////////////////////////////// ////////////////////// Classes //////////////////////////////////////////////// public class ASEP // was CAAAngularSeparation { //Static methods //////////////////////////// Implementation /////////////////////////////////// public static double Separation(double Alpha1, double Delta1, double Alpha2, double Delta2) { Delta1 = CT.D2R(Delta1); Delta2 = CT.D2R(Delta2); Alpha1 = CT.H2R(Alpha1); Alpha2 = CT.H2R(Alpha2); double x = Math.Cos(Delta1) * Math.Sin(Delta2) - Math.Sin(Delta1) * Math.Cos(Delta2) * Math.Cos(Alpha2 - Alpha1); double y = Math.Cos(Delta2) * Math.Sin(Alpha2 - Alpha1); double z = Math.Sin(Delta1) * Math.Sin(Delta2) + Math.Cos(Delta1) * Math.Cos(Delta2) * Math.Cos(Alpha2 - Alpha1); double @value = Math.Atan2(Math.Sqrt(x * x + y * y), z); @value = CT.R2D(@value); if (@value < 0) @value += 180; return @value; } public static double PositionAngle(double alpha1, double delta1, double alpha2, double delta2) { double Alpha1; double Delta1; double Alpha2; double Delta2; Delta1 = CT.D2R(delta1); Delta2 = CT.D2R(delta2); Alpha1 = CT.H2R(alpha1); Alpha2 = CT.H2R(alpha2); double DeltaAlpha = Alpha1 - Alpha2; double demoninator = Math.Cos(Delta2) * Math.Tan(Delta1) - Math.Sin(Delta2) * Math.Cos(DeltaAlpha); double numerator = Math.Sin(DeltaAlpha); double @value = Math.Atan2(numerator, demoninator); @value = CT.R2D(@value); return @value; } public static double DistanceFromGreatArc(double Alpha1, double Delta1, double Alpha2, double Delta2, double Alpha3, double Delta3) { Delta1 = CT.D2R(Delta1); Delta2 = CT.D2R(Delta2); Delta3 = CT.D2R(Delta3); Alpha1 = CT.H2R(Alpha1); Alpha2 = CT.H2R(Alpha2); Alpha3 = CT.H2R(Alpha3); double X1 = Math.Cos(Delta1) * Math.Cos(Alpha1); double X2 = Math.Cos(Delta2) * Math.Cos(Alpha2); double Y1 = Math.Cos(Delta1) * Math.Sin(Alpha1); double Y2 = Math.Cos(Delta2) * Math.Sin(Alpha2); double Z1 = Math.Sin(Delta1); double Z2 = Math.Sin(Delta2); double A = Y1 * Z2 - Z1 * Y2; double B = Z1 * X2 - X1 * Z2; double C = X1 * Y2 - Y1 * X2; double m = Math.Tan(Alpha3); double n = Math.Tan(Delta3) / Math.Cos(Alpha3); double @value = Math.Asin((A + B * m + C * n) / (Math.Sqrt(A * A + B * B + C * C) * Math.Sqrt(1 + m * m + n * n))); @value = CT.R2D(@value); if (@value < 0) @value = Math.Abs(@value); return @value; } //public static double SmallestCircle(double Alpha1, double Delta1, double Alpha2, double Delta2, double Alpha3, double Delta3, ref bool bType1) //{ // double d1 = Separation(Alpha1, Delta1, Alpha2, Delta2); // double d2 = Separation(Alpha1, Delta1, Alpha3, Delta3); // double d3 = Separation(Alpha2, Delta2, Alpha3, Delta3); // double a = d1; // double b = d2; // double c = d3; // if (b > a) // { // a = d2; // b = d1; // c = d3; // } // if (c > a) // { // a = d3; // b = d1; // c = d2; // } // double @value; // if (a > Math.Sqrt(b * b + c * c)) // { // bType1 = true; // @value = a; // } // else // { // bType1 = false; // @value = 2 * a * b * c / (Math.Sqrt((a + b + c) * (a + b - c) * (b + c - a) * (a + c - b))); // } // return @value; //} }
{ "content_hash": "d81977a55fea7fddc250f014e977e765", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 148, "avg_line_length": 32.87412587412587, "alnum_prop": 0.5398851308232291, "repo_name": "juoni/wwt-web-client", "id": "8b8e1742d9a8968f449b4403a4249f594fed58c7", "size": "4701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HTML5SDK/wwtlib/AstroCalc/AAAngularSeparation.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "55893" }, { "name": "Batchfile", "bytes": "39" }, { "name": "C#", "bytes": "1972739" }, { "name": "CSS", "bytes": "257377" }, { "name": "HTML", "bytes": "34634" }, { "name": "JavaScript", "bytes": "13607698" }, { "name": "PowerShell", "bytes": "3208" } ], "symlink_target": "" }
module Physics.Falling.Integrator.Integrable ( Integrable(..) ) where class Integrable rb where integratePosition :: Double -> rb -> rb integrateVelocity :: Double -> rb -> rb
{ "content_hash": "5a7d0f619e54bb650504f1c6bae1df53", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 44, "avg_line_length": 20.333333333333332, "alnum_prop": 0.7158469945355191, "repo_name": "sebcrozet/falling", "id": "5d3ab57a89cae058141d733018343c2818446356", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "Physics/Falling/Integrator/Integrable.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "140297" } ], "symlink_target": "" }
title: Resultados da Seletiva IME 2010 date: '2010-08-22 00:00:00' layout: post permalink: seletiva-2010 categories: - seletiva - contests --- A Seletiva 2010 do IME para a Maratona de Programação teve a participação de 8 times competido por vagas para a Primeira Fase da Maratona de Programação. Outros 147 times participaram presencialmente ou pela internet. ## Placar, estatísticas, problemas, etc. - [Placar](https://www.ime.usp.br/~maratona/assets/seletivas/2010/score/score.html) - [Prova](https://www.ime.usp.br/~maratona/assets/seletivas/2010/caderno.pdf) ([Errata](https://www.ime.usp.br/~maratona/assets/seletivas/2010/errata.pdf)) - [Dados (estatísticas, submissões, etc)](https://www.ime.usp.br/~maratona/assets/seletivas/2010/data.tar.xz) - [Entradas e saídas dos problemas](https://www.ime.usp.br/~maratona/assets/seletivas/2010/io.tar.xz) - [Soluções dos juízes](https://www.ime.usp.br/~maratona/assets/seletivas/2010/io.tar.xz) - [Prova na Codeforces Gym](http://codeforces.com/gym/101055) ## Patrocínio [<img src="https://www.ime.usp.br/~maratona/assets/seletivas/2013/patrocinio/caelum-ensino-inovacao.png" style="width:30%">](http://www.caelum.com.br/)
{ "content_hash": "0b7bbda873d4b69135049fcc0493639e", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 155, "avg_line_length": 48.958333333333336, "alnum_prop": 0.7582978723404256, "repo_name": "victorsenam/blog-maratonime", "id": "af901e1cf2e150e372b3c842b8ff5b9f47e99922", "size": "1193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2010-08-22-resultados-seletiva-2010.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "97377" }, { "name": "HTML", "bytes": "218715" }, { "name": "JavaScript", "bytes": "70072" }, { "name": "Ruby", "bytes": "3600" }, { "name": "Shell", "bytes": "1416" } ], "symlink_target": "" }
namespace Google.Cloud.Security.PrivateCA.V1Beta1.Snippets { // [START privateca_v1beta1_generated_CertificateAuthorityService_ListCertificateAuthorities_async_flattened] using Google.Api.Gax; using Google.Cloud.Security.PrivateCA.V1Beta1; using System; using System.Linq; using System.Threading.Tasks; public sealed partial class GeneratedCertificateAuthorityServiceClientSnippets { /// <summary>Snippet for ListCertificateAuthoritiesAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ListCertificateAuthoritiesAsync() { // Create client CertificateAuthorityServiceClient certificateAuthorityServiceClient = await CertificateAuthorityServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListCertificateAuthoritiesResponse, CertificateAuthority> response = certificateAuthorityServiceClient.ListCertificateAuthoritiesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((CertificateAuthority item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListCertificateAuthoritiesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (CertificateAuthority item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<CertificateAuthority> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (CertificateAuthority item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END privateca_v1beta1_generated_CertificateAuthorityService_ListCertificateAuthorities_async_flattened] }
{ "content_hash": "4d62065c475f0e3faee1ddad6a8d3600", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 176, "avg_line_length": 48.2, "alnum_prop": 0.6466113416320886, "repo_name": "jskeet/google-cloud-dotnet", "id": "65541b6bee04de00d5dbdc8e6ef311717ae897a2", "size": "3514", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "apis/Google.Cloud.Security.PrivateCA.V1Beta1/Google.Cloud.Security.PrivateCA.V1Beta1.GeneratedSnippets/CertificateAuthorityServiceClient.ListCertificateAuthoritiesAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "268415427" }, { "name": "CSS", "bytes": "1346" }, { "name": "Dockerfile", "bytes": "3173" }, { "name": "HTML", "bytes": "3823" }, { "name": "JavaScript", "bytes": "226" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65260" }, { "name": "sed", "bytes": "1030" } ], "symlink_target": "" }
package election import ( "fmt" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/tools" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" "github.com/GoogleCloudPlatform/kubernetes/pkg/watch" "github.com/coreos/go-etcd/etcd" "github.com/golang/glog" ) // Master is used to announce the current elected master. type Master string // IsAnAPIObject is used solely so we can work with the watch package. // TODO: Either fix watch so this isn't necessary, or make this a real API Object. // TODO: when it becomes clear how this package will be used, move these declarations to // to the proper place. func (Master) IsAnAPIObject() {} // NewEtcdMasterElector returns an implementation of election.MasterElector backed by etcd. func NewEtcdMasterElector(h tools.EtcdGetSet) MasterElector { return &etcdMasterElector{etcd: h} } type empty struct{} // internal implementation struct type etcdMasterElector struct { etcd tools.EtcdGetSet done chan empty events chan watch.Event } // Elect implements the election.MasterElector interface. func (e *etcdMasterElector) Elect(path, id string) watch.Interface { e.done = make(chan empty) e.events = make(chan watch.Event) go util.Forever(func() { e.run(path, id) }, time.Second*5) return e } func (e *etcdMasterElector) run(path, id string) { masters := make(chan string) errors := make(chan error) go e.master(path, id, 30, masters, errors, e.done) for { select { case m := <-masters: e.events <- watch.Event{ Type: watch.Modified, Object: Master(m), } case e := <-errors: glog.Errorf("error in election: %v", e) } } } // ResultChan implements the watch.Interface interface. func (e *etcdMasterElector) ResultChan() <-chan watch.Event { return e.events } // extendMaster attempts to extend ownership of a master lock for TTL seconds. // returns "", nil if extension failed // returns id, nil if extension succeeded // returns "", err if an error occurred func (e *etcdMasterElector) extendMaster(path, id string, ttl uint64, res *etcd.Response) (string, error) { // If it matches the passed in id, extend the lease by writing a new entry. // Uses compare and swap, so that if we TTL out in the meantime, the write will fail. // We don't handle the TTL delete w/o a write case here, it's handled in the next loop // iteration. _, err := e.etcd.CompareAndSwap(path, id, ttl, "", res.Node.ModifiedIndex) if err != nil && !tools.IsEtcdTestFailed(err) { return "", err } if err != nil && tools.IsEtcdTestFailed(err) { return "", nil } return id, nil } // becomeMaster attempts to become the master for this lock. // returns "", nil if the attempt failed // returns id, nil if the attempt succeeded // returns "", err if an error occurred func (e *etcdMasterElector) becomeMaster(path, id string, ttl uint64) (string, error) { _, err := e.etcd.Create(path, id, ttl) if err != nil && !tools.IsEtcdNodeExist(err) { // unexpected error return "", err } if err != nil && tools.IsEtcdNodeExist(err) { return "", nil } return id, nil } // handleMaster performs one loop of master locking. // on success it returns <master>, nil // on error it returns "", err // in situations where you should try again due to concurrent state changes (e.g. another actor simultaneously acquiring the lock) // it returns "", nil func (e *etcdMasterElector) handleMaster(path, id string, ttl uint64) (string, error) { res, err := e.etcd.Get(path, false, false) // Unexpected error, bail out if err != nil && !tools.IsEtcdNotFound(err) { return "", err } // There is no master, try to become the master. if err != nil && tools.IsEtcdNotFound(err) { return e.becomeMaster(path, id, ttl) } // This should never happen. if res.Node == nil { return "", fmt.Errorf("unexpected response: %#v", res) } // We're not the master, just return the current value if res.Node.Value != id { return res.Node.Value, nil } // We are the master, try to extend out lease return e.extendMaster(path, id, ttl, res) } // master provices a distributed master election lock, maintains lock until failure, or someone sends something in the done channel. // The basic algorithm is: // while !done // Get the current master // If there is no current master // Try to become the master // Otherwise // If we are the master, extend the lease // If the master is different than the last time through the loop, report the master // Sleep 80% of TTL func (e *etcdMasterElector) master(path, id string, ttl uint64, masters chan<- string, errors chan<- error, done <-chan empty) { lastMaster := "" for { master, err := e.handleMaster(path, id, ttl) if err != nil { errors <- err } else if len(master) == 0 { continue } else if master != lastMaster { lastMaster = master masters <- master } // TODO: Add Watch here, skip the polling for faster reactions // If done is closed, break out. select { case <-done: return case <-time.After(time.Duration((ttl*8)/10) * time.Second): } } } // ResultChan implements the watch.Interface interface func (e *etcdMasterElector) Stop() { close(e.done) }
{ "content_hash": "3e1ff226ad72c61cfec5884c158bac71", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 132, "avg_line_length": 30.140350877192983, "alnum_prop": 0.6998447807528133, "repo_name": "matttproud/kubernetes", "id": "35775f2a03fa1c712f3450f044a27b2fda39e6b4", "size": "5732", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "pkg/election/etcd_master.go", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookFunctionsImTanRequestBuilder. /// </summary> public partial class WorkbookFunctionsImTanRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsImTanRequest>, IWorkbookFunctionsImTanRequestBuilder { /// <summary> /// Constructs a new <see cref="WorkbookFunctionsImTanRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="inumber">A inumber parameter for the OData method call.</param> public WorkbookFunctionsImTanRequestBuilder( string requestUrl, IBaseClient client, Newtonsoft.Json.Linq.JToken inumber) : base(requestUrl, client) { this.SetParameter("inumber", inumber, true); } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IWorkbookFunctionsImTanRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new WorkbookFunctionsImTanRequest(functionUrl, this.Client, options); if (this.HasParameter("inumber")) { request.RequestBody.Inumber = this.GetParameter<Newtonsoft.Json.Linq.JToken>("inumber"); } return request; } } }
{ "content_hash": "e67e8da9dfe62a8aeb4a2a519f67e16d", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 165, "avg_line_length": 40.86666666666667, "alnum_prop": 0.6383904295812942, "repo_name": "ginach/msgraph-sdk-dotnet", "id": "4c3d50dd970cede5af242ab4db05e7ce1634592a", "size": "2316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsImTanRequestBuilder.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "12839763" }, { "name": "Smalltalk", "bytes": "12638" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using Confuser.Core; using Confuser.Renamer; using Ookii.Dialogs.Wpf; namespace ConfuserEx { /// <summary> /// Interaction logic for StackTraceDecoder.xaml /// </summary> public partial class StackTraceDecoder : Window { public StackTraceDecoder() { InitializeComponent(); } readonly Dictionary<string, string> symMap = new Dictionary<string, string>(); void PathBox_TextChanged(object sender, TextChangedEventArgs e) { if (File.Exists(PathBox.Text)) LoadSymMap(PathBox.Text); } void LoadSymMap(string path) { string shortPath = path; if (path.Length > 35) shortPath = "..." + path.Substring(path.Length - 35, 35); try { symMap.Clear(); using (var reader = new StreamReader(File.OpenRead(path))) { var line = reader.ReadLine(); while (line != null) { int tabIndex = line.IndexOf('\t'); if (tabIndex == -1) throw new FileFormatException(); symMap.Add(line.Substring(0, tabIndex), line.Substring(tabIndex + 1)); line = reader.ReadLine(); } } status.Content = "Loaded symbol map from '" + shortPath + "' successfully."; } catch { status.Content = "Failed to load symbol map from '" + shortPath + "'."; } } void ChooseMapPath(object sender, RoutedEventArgs e) { var ofd = new VistaOpenFileDialog(); ofd.Filter = "Symbol maps (*.map)|*.map|All Files (*.*)|*.*"; if (ofd.ShowDialog() ?? false) { PathBox.Text = ofd.FileName; } } readonly Regex mapSymbolMatcher = new Regex("_[a-zA-Z0-9]+"); readonly Regex passSymbolMatcher = new Regex("[a-zA-Z0-9_$]{23,}"); ReversibleRenamer renamer; void Decode_Click(object sender, RoutedEventArgs e) { var trace = stackTrace.Text; if (optSym.IsChecked ?? true) stackTrace.Text = mapSymbolMatcher.Replace(trace, DecodeSymbolMap); else { renamer = new ReversibleRenamer(PassBox.Text); stackTrace.Text = passSymbolMatcher.Replace(trace, DecodeSymbolPass); } } string DecodeSymbolMap(Match match) { var sym = match.Value; return symMap.GetValueOrDefault(sym, sym); } string DecodeSymbolPass(Match match) { var sym = match.Value; try { return renamer.Decrypt(sym); } catch { return sym; } } } }
{ "content_hash": "93fd8986fec60a4635729d0d5d9bc083", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 80, "avg_line_length": 27.272727272727273, "alnum_prop": 0.6670833333333334, "repo_name": "Desolath/ConfuserEx3", "id": "6a7b74cd54a8329ecd928a7c5cabc2a37bec45e9", "size": "2402", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "ConfuserEx/StackTraceDecoder.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "232" }, { "name": "C#", "bytes": "1288975" } ], "symlink_target": "" }
package com.perm.kate.api; import org.json.JSONException; import org.json.JSONObject; public class City { public long cid; public String name; public static City parse(JSONObject o) throws NumberFormatException, JSONException{ City c = new City(); c.cid = o.getLong("id"); c.name = o.optString("title"); return c; } }
{ "content_hash": "1d5c60571b1bb2bb47b769096acaad06", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 87, "avg_line_length": 24.0625, "alnum_prop": 0.6207792207792208, "repo_name": "romanbrandhall/MyApp", "id": "ca86390cfbd7055a9d4a59113ffdc3acd9f320f8", "size": "385", "binary": false, "copies": "2", "ref": "refs/heads/roman", "path": "AndroidVkSdk/src/com/perm/kate/api/City.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "258933" } ], "symlink_target": "" }
#define BENCH_MACH #include <mach/mach_time.h> #include <stdint.h> #elif defined(_WIN32) #define BENCH_QPC #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <malloc.h> #else #define BENCH_GTOD #include <sys/time.h> #endif static void* memalign(size_t count, size_t align) { #ifdef _WIN32 return _aligned_malloc(count,align); #else void *ptr; int e = posix_memalign(&ptr, align, count); // if( e == EINVAL ) printf("EINVAL posix_memalign\n"); // if( e == ENOMEM ) printf("ENOMEM posix_memalign\n"); return ptr; #endif } static void memfree(void* ptr) { #ifdef _WIN32 _aligned_free(ptr); #else free(ptr); #endif } namespace profiler { #ifdef BENCH_GTOD typedef struct timeval time_t; #endif #ifdef BENCH_MACH typedef const uint64_t time_t; #endif #ifdef BENCH_QPC typedef LARGE_INTEGER time_t; #endif void init(); time_t now(); double diffTime(time_t start, time_t end); } std::string formatTime(double d, double relative=-1); void profile(const char* name, void (*func)(), int iterations, int elements); #endif
{ "content_hash": "f8bd46427894f7d58fd5c3bf086ed665", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 77, "avg_line_length": 20.46551724137931, "alnum_prop": 0.615838247683235, "repo_name": "scoopr/vectorial", "id": "ddefcced3bf7b74c2266598cffab95f284a38ab0", "size": "1276", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bench/bench.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "32955" }, { "name": "C++", "bytes": "147104" }, { "name": "M", "bytes": "1705" }, { "name": "Makefile", "bytes": "10964" }, { "name": "Ruby", "bytes": "505" } ], "symlink_target": "" }
namespace Microsoft.Azure.Management.ResourceManager { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The APIs listed in this specification can be used to manage Template /// Spec resources through the Azure Resource Manager. /// </summary> public partial class TemplateSpecsClient : ServiceClient<TemplateSpecsClient>, ITemplateSpecsClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription Id which forms part of the URI for every service call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// The preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// The retry timeout in seconds for Long Running Operations. Default value is /// 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// Whether a unique x-ms-client-request-id should be generated. When set to /// true a unique x-ms-client-request-id value is generated and included in /// each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the ITemplateSpecsOperations. /// </summary> public virtual ITemplateSpecsOperations TemplateSpecs { get; private set; } /// <summary> /// Gets the ITemplateSpecVersionsOperations. /// </summary> public virtual ITemplateSpecVersionsOperations TemplateSpecVersions { get; private set; } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='httpClient'> /// HttpClient to be used /// </param> /// <param name='disposeHttpClient'> /// True: will dispose the provided httpClient on calling TemplateSpecsClient.Dispose(). False: will not dispose provided httpClient</param> protected TemplateSpecsClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient) { Initialize(); } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected TemplateSpecsClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected TemplateSpecsClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected TemplateSpecsClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected TemplateSpecsClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TemplateSpecsClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='httpClient'> /// HttpClient to be used /// </param> /// <param name='disposeHttpClient'> /// True: will dispose the provided httpClient on calling TemplateSpecsClient.Dispose(). False: will not dispose provided httpClient</param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TemplateSpecsClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TemplateSpecsClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TemplateSpecsClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the TemplateSpecsClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TemplateSpecsClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { TemplateSpecs = new TemplateSpecsOperations(this); TemplateSpecVersions = new TemplateSpecVersionsOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2019-06-01-preview"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<TemplateSpecArtifact>("kind")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<TemplateSpecArtifact>("kind")); CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
{ "content_hash": "6e2064528b4d787e6c34a133575492c3", "timestamp": "", "source": "github", "line_count": 359, "max_line_length": 190, "avg_line_length": 40.710306406685234, "alnum_prop": 0.5874101950051317, "repo_name": "stankovski/azure-sdk-for-net", "id": "244a001684574424b4e9ad8e954a5f97d809a21b", "size": "14968", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "sdk/resources/Microsoft.Azure.Management.Resource/src/Generated/TemplateSpecsClient.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "33972632" }, { "name": "Cucumber", "bytes": "89597" }, { "name": "Shell", "bytes": "675" } ], "symlink_target": "" }
#include "db_config.h" #include "db_int.h" #include "dbinc/log.h" #include "dbinc/db_page.h" #include "dbinc/qam.h" #ifndef lint static const char copyright[] = "Copyright (c) 1996,2008 Oracle. All rights reserved.\n"; #endif enum which_open { OPEN_ORIGINAL, OPEN_HOT_BACKUP }; int db_hotbackup_backup_dir_clean __P((DB_ENV *, char *, char *, int *, int, int)); int db_hotbackup_data_copy __P((DB_ENV *, char *, char *, char *, int)); int db_hotbackup_env_init __P((DB_ENV **, char *, char **, char ***, char *, enum which_open)); int db_hotbackup_main __P((int, char *[])); int db_hotbackup_read_data_dir __P((DB_ENV *, char *, char *, char *, int, int)); int db_hotbackup_read_log_dir __P((DB_ENV *, char *, char *, char *, int *, int, int)); int db_hotbackup_usage __P((void)); int db_hotbackup_version_check __P((void)); const char *progname; int db_hotbackup(args) char *args; { int argc; char **argv; __db_util_arg("db_hotbackup", args, &argc, &argv); return (db_hotbackup_main(argc, argv) ? EXIT_FAILURE : EXIT_SUCCESS); } #include <stdio.h> #define ERROR_RETURN ERROR int db_hotbackup_main(argc, argv) int argc; char *argv[]; { extern char *optarg; extern int optind, __db_getopt_reset; time_t now; DB_ENV *dbenv; u_int data_cnt, data_next; int ch, checkpoint, copy_min, db_config, exitval; int remove_max, ret, update, verbose; char *backup_dir, **data_dir, **dir, *home, *log_dir, *passwd; char home_buf[DB_MAXPATHLEN], time_buf[CTIME_BUFLEN]; /* * Make sure all verbose message are output before any error messages * in the case where the output is being logged into a file. This * call has to be done before any operation is performed on the stream. * * Use unbuffered I/O because line-buffered I/O requires a buffer, and * some operating systems have buffer alignment and size constraints we * don't want to care about. There isn't enough output for the calls * to matter. */ setbuf(stdout, NULL); if ((progname = __db_rpath(argv[0])) == NULL) progname = argv[0]; else ++progname; if ((ret = db_hotbackup_version_check()) != 0) return (ret); checkpoint = db_config = data_cnt = data_next = exitval = update = verbose = 0; data_dir = NULL; backup_dir = home = passwd = NULL; log_dir = NULL; copy_min = remove_max = 0; __db_getopt_reset = 1; while ((ch = getopt(argc, argv, "b:cDd:h:l:P:uVv")) != EOF) switch (ch) { case 'b': backup_dir = optarg; break; case 'c': checkpoint = 1; break; case 'D': db_config = 1; break; case 'd': /* * User can specify a list of directories -- keep an * array, leaving room for the trailing NULL. */ if (data_dir == NULL || data_next >= data_cnt - 2) { data_cnt = data_cnt == 0 ? 20 : data_cnt * 2; if ((data_dir = realloc(data_dir, data_cnt * sizeof(*data_dir))) == NULL) { fprintf(stderr, "%s: %s\n", progname, strerror(errno)); return (EXIT_FAILURE); } } data_dir[data_next++] = optarg; break; case 'h': home = optarg; break; case 'l': log_dir = optarg; break; case 'P': passwd = strdup(optarg); memset(optarg, 0, strlen(optarg)); if (passwd == NULL) { fprintf(stderr, "%s: strdup: %s\n", progname, strerror(errno)); return (EXIT_FAILURE); } break; case 'u': update = 1; break; case 'V': printf("%s\n", db_version(NULL, NULL, NULL)); return (EXIT_SUCCESS); case 'v': verbose = 1; break; case '?': default: return (db_hotbackup_usage()); } argc -= optind; argv += optind; if (argc != 0) return (db_hotbackup_usage()); /* NULL-terminate any list of data directories. */ if (data_dir != NULL) { data_dir[data_next] = NULL; /* * -d is relative to the current directory, to run a checkpoint * we must have directories relative to the environment. */ if (checkpoint == 1) { fprintf(stderr, "%s: cannot specify -d and -c\n", progname); return (db_hotbackup_usage()); } } if (db_config && (data_dir != NULL || log_dir != NULL)) { fprintf(stderr, "%s: cannot specify -D and -d or -l\n", progname); return (db_hotbackup_usage()); } /* Handle possible interruptions. */ __db_util_siginit(); /* * The home directory defaults to the environment variable DB_HOME. * The log directory defaults to the home directory. * * We require a source database environment directory and a target * backup directory. */ if (home == NULL) { home = home_buf; if ((ret = __os_getenv( NULL, "DB_HOME", &home, sizeof(home_buf))) != 0) { fprintf(stderr, "%s failed to get environment variable DB_HOME: %s\n", progname, db_strerror(ret)); return (EXIT_FAILURE); } /* * home set to NULL if __os_getenv failed to find DB_HOME. */ } if (home == NULL) { fprintf(stderr, "%s: no source database environment specified\n", progname); return (db_hotbackup_usage()); } if (backup_dir == NULL) { fprintf(stderr, "%s: no target backup directory specified\n", progname); return (db_hotbackup_usage()); } if (verbose) { (void)time(&now); printf("%s: hot backup started at %s", progname, __os_ctime(&now, time_buf)); } /* Open the source environment. */ if (db_hotbackup_env_init(&dbenv, home, (db_config || log_dir != NULL) ? &log_dir : NULL, db_config ? &data_dir : NULL, passwd, OPEN_ORIGINAL) != 0) goto shutdown; if (db_config && __os_abspath(log_dir)) { fprintf(stderr, "%s: DB_CONFIG must not contain an absolute path for the log directory", progname); goto shutdown; } /* * If the -c option is specified, checkpoint the source home * database environment, and remove any unnecessary log files. */ if (checkpoint) { if (verbose) printf("%s: %s: force checkpoint\n", progname, home); if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, DB_FORCE)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->txn_checkpoint"); goto shutdown; } if (!update) { if (verbose) printf("%s: %s: remove unnecessary log files\n", progname, home); if ((ret = dbenv->log_archive(dbenv, NULL, DB_ARCH_REMOVE)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->log_archive"); goto shutdown; } } } /* * If the target directory for the backup does not exist, create it * with mode read-write-execute for the owner. Ignore errors here, * it's simpler and more portable to just always try the create. If * there's a problem, we'll fail with reasonable errors later. */ (void)__os_mkdir(NULL, backup_dir, DB_MODE_700); /* * If -u was specified, remove all log files; if -u was not specified, * remove all files. * * Potentially there are two directories to clean, the log directory * and the target directory. First, clean up the log directory if * it's different from the target directory, then clean up the target * directory. */ if (db_config && log_dir != NULL && db_hotbackup_backup_dir_clean( dbenv, backup_dir, log_dir, &remove_max, update, verbose) != 0) goto shutdown; if (db_hotbackup_backup_dir_clean(dbenv, backup_dir, NULL, &remove_max, update, verbose) != 0) goto shutdown; /* * If the -u option was not specified, copy all database files found in * the database environment home directory, or any directory specified * using the -d option, into the target directory for the backup. */ if (!update) { if (db_hotbackup_read_data_dir(dbenv, home, backup_dir, home, verbose, db_config) != 0) goto shutdown; if (data_dir != NULL) for (dir = data_dir; *dir != NULL; ++dir) { /* * Don't allow absolute path names taken from * the DB_CONFIG file -- running recovery with * them would corrupt the source files. */ if (db_config && __os_abspath(*dir)) { fprintf(stderr, "%s: data directory '%s' is absolute path, not permitted with -D option\n", progname, *dir); goto shutdown; } if (db_hotbackup_read_data_dir(dbenv, home, backup_dir, *dir, verbose, db_config) != 0) goto shutdown; } } /* * Copy all log files found in the directory specified by the -l option * (or in the database environment home directory, if no -l option was * specified), into the target directory for the backup. * * The log directory defaults to the home directory. */ if (db_hotbackup_read_log_dir(dbenv, db_config ? home : NULL, backup_dir, log_dir == NULL ? home : log_dir, &copy_min, update, verbose) != 0) goto shutdown; /* * If we're updating a snapshot, the lowest-numbered log file copied * into the backup directory should be less than, or equal to, the * highest-numbered log file removed from the backup directory during * cleanup. */ if (update && remove_max < copy_min && !(remove_max == 0 && copy_min == 1)) { fprintf(stderr, "%s: the largest log file removed (%d) must be greater\n", progname, remove_max); fprintf(stderr, "%s: than or equal the smallest log file copied (%d)\n", progname, copy_min); goto shutdown; } /* Close the source environment. */ if ((ret = dbenv->close(dbenv, 0)) != 0) { fprintf(stderr, "%s: dbenv->close: %s\n", progname, db_strerror(ret)); dbenv = NULL; goto shutdown; } /* Perform catastrophic recovery on the hot backup. */ if (verbose) printf("%s: %s: run catastrophic recovery\n", progname, backup_dir); if (db_hotbackup_env_init( &dbenv, backup_dir, NULL, NULL, passwd, OPEN_HOT_BACKUP) != 0) goto shutdown; /* * Remove any unnecessary log files from the hot backup. */ if (verbose) printf("%s: %s: remove unnecessary log files\n", progname, backup_dir); if ((ret = dbenv->log_archive(dbenv, NULL, DB_ARCH_REMOVE)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->log_archive"); goto shutdown; } if (0) { shutdown: exitval = 1; } if (dbenv != NULL && (ret = dbenv->close(dbenv, 0)) != 0) { exitval = 1; fprintf(stderr, "%s: dbenv->close: %s\n", progname, db_strerror(ret)); } if (exitval == 0) { if (verbose) { (void)time(&now); printf("%s: hot backup completed at %s", progname, __os_ctime(&now, time_buf)); } } else { fprintf(stderr, "%s: HOT BACKUP FAILED!\n", progname); } /* Resend any caught signal. */ __db_util_sigresend(); return (exitval == 0 ? EXIT_SUCCESS : EXIT_FAILURE); } /* * env_init -- * Open a database environment. */ int db_hotbackup_env_init(dbenvp, home, log_dirp, data_dirp, passwd, which) DB_ENV **dbenvp; char *home, **log_dirp, ***data_dirp, *passwd; enum which_open which; { DB_ENV *dbenv; int ret; *dbenvp = NULL; /* * Create an environment object and initialize it for error reporting. */ if ((ret = db_env_create(&dbenv, 0)) != 0) { fprintf(stderr, "%s: db_env_create: %s\n", progname, db_strerror(ret)); return (1); } dbenv->set_errfile(dbenv, stderr); setbuf(stderr, NULL); dbenv->set_errpfx(dbenv, progname); /* Any created intermediate directories are created private. */ if ((ret = dbenv->set_intermediate_dir_mode(dbenv, "rwx------")) != 0) { dbenv->err(dbenv, ret, "DB_ENV->set_intermediate_dir_mode"); return (1); } /* * If a log directory has been specified, and it's not the same as the * home directory, set it for the environment. */ if (log_dirp != NULL && *log_dirp != NULL && (ret = dbenv->set_lg_dir(dbenv, *log_dirp)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->set_lg_dir: %s", *log_dirp); return (1); } /* Optionally set the password. */ if (passwd != NULL && (ret = dbenv->set_encrypt(dbenv, passwd, DB_ENCRYPT_AES)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->set_encrypt"); return (1); } switch (which) { case OPEN_ORIGINAL: /* * Opening the database environment we're trying to back up. * We try to attach to a pre-existing environment; if that * fails, we create a private environment and try again. */ if ((ret = dbenv->open(dbenv, home, DB_USE_ENVIRON, 0)) != 0 && (ret == DB_VERSION_MISMATCH || (ret = dbenv->open(dbenv, home, DB_CREATE | DB_INIT_LOG | DB_INIT_TXN | DB_PRIVATE | DB_USE_ENVIRON, 0)) != 0)) { dbenv->err(dbenv, ret, "DB_ENV->open: %s", home); return (1); } if (log_dirp != NULL && *log_dirp == NULL) (void)dbenv->get_lg_dir(dbenv, (const char **)log_dirp); if (data_dirp != NULL && *data_dirp == NULL) (void)dbenv->get_data_dirs( dbenv, (const char ***)data_dirp); break; case OPEN_HOT_BACKUP: /* * Opening the backup copy of the database environment. We * better be the only user, we're running recovery. * Ensure that there at least minimal cache for worst * case page size. */ if ((ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024 * 10, 0)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->set_cachesize: %s", home); return (1); } if ((ret = dbenv->open(dbenv, home, DB_CREATE | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_PRIVATE | DB_RECOVER_FATAL | DB_USE_ENVIRON, 0)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->open: %s", home); return (1); } break; } *dbenvp = dbenv; return (0); } /* * backup_dir_clean -- * Clean out the backup directory. */ int db_hotbackup_backup_dir_clean(dbenv, backup_dir, log_dir, remove_maxp, update, verbose) DB_ENV *dbenv; char *backup_dir, *log_dir; int *remove_maxp, update, verbose; { ENV *env; int cnt, fcnt, ret, v; char **names, *dir, buf[DB_MAXPATHLEN], path[DB_MAXPATHLEN]; env = dbenv->env; /* We may be cleaning a log directory separate from the target. */ if (log_dir != NULL) { if ((size_t)snprintf(buf, sizeof(buf), "%s%c%s", backup_dir, PATH_SEPARATOR[0] ,log_dir) >= sizeof(buf)) { dbenv->errx(dbenv, "%s%c%s: path too long", backup_dir, PATH_SEPARATOR[0] ,log_dir); return (1); } dir = buf; } else dir = backup_dir; /* Get a list of file names. */ if ((ret = __os_dirlist(env, dir, 0, &names, &fcnt)) != 0) { if (log_dir != NULL && !update) return (0); dbenv->err(dbenv, ret, "%s: directory read", dir); return (1); } for (cnt = fcnt; --cnt >= 0;) { /* * Skip non-log files (if update was specified). */ if (strncmp(names[cnt], LFPREFIX, sizeof(LFPREFIX) - 1)) { if (update) continue; } else { /* Track the highest-numbered log file removed. */ v = atoi(names[cnt] + sizeof(LFPREFIX) - 1); if (*remove_maxp < v) *remove_maxp = v; } if ((size_t)snprintf(path, sizeof(path), "%s%c%s", dir, PATH_SEPARATOR[0], names[cnt]) >= sizeof(path)) { dbenv->errx(dbenv, "%s%c%s: path too long", dir, PATH_SEPARATOR[0], names[cnt]); return (1); } if (verbose) printf("%s: removing %s\n", progname, path); if (__os_unlink(env, path, 0) != 0) return (1); } __os_dirfree(env, names, fcnt); if (verbose && *remove_maxp != 0) printf("%s: highest numbered log file removed: %d\n", progname, *remove_maxp); return (0); } /* * read_data_dir -- * Read a directory looking for databases to copy. */ int db_hotbackup_read_data_dir(dbenv, home, backup_dir, dir, verbose, db_config) DB_ENV *dbenv; char *home, *backup_dir, *dir; int verbose, db_config; { ENV *env; int cnt, fcnt, ret; char *bd, **names; char buf[DB_MAXPATHLEN], bbuf[DB_MAXPATHLEN]; env = dbenv->env; bd = backup_dir; if (db_config && dir != home) { /* Build a path name to the destination. */ if ((size_t)(cnt = snprintf(bbuf, sizeof(bbuf), "%s%c%s%c", backup_dir, PATH_SEPARATOR[0], dir, PATH_SEPARATOR[0])) >= sizeof(buf)) { dbenv->errx(dbenv, "%s%c%s: path too long", backup_dir, PATH_SEPARATOR[0], dir); return (1); } bd = bbuf; /* Create the path. */ if ((ret = __db_mkpath(env, bd)) != 0) { dbenv->err(dbenv, ret, "%s: cannot create", bd); return (1); } /* step on the trailing '/' */ bd[cnt - 1] = '\0'; /* Build a path name to the source. */ if ((size_t)snprintf(buf, sizeof(buf), "%s%c%s", home, PATH_SEPARATOR[0], dir) >= sizeof(buf)) { dbenv->errx(dbenv, "%s%c%s: path too long", home, PATH_SEPARATOR[0], dir); return (1); } dir = buf; } /* Get a list of file names. */ if ((ret = __os_dirlist(env, dir, 0, &names, &fcnt)) != 0) { dbenv->err(dbenv, ret, "%s: directory read", dir); return (1); } for (cnt = fcnt; --cnt >= 0;) { /* * Skip files in DB's name space (but not Queue * extent files, we need them). */ if (!strncmp(names[cnt], LFPREFIX, sizeof(LFPREFIX) - 1)) continue; if (!strncmp(names[cnt], DB_REGION_PREFIX, sizeof(DB_REGION_PREFIX) - 1) && strncmp(names[cnt], QUEUE_EXTENT_PREFIX, sizeof(QUEUE_EXTENT_PREFIX) - 1)) continue; /* * Skip DB_CONFIG. */ if (!db_config && !strncmp(names[cnt], "DB_CONFIG", sizeof("DB_CONFIG"))) continue; /* Copy the file. */ if (db_hotbackup_data_copy(dbenv, names[cnt], dir, bd, verbose) != 0) return (1); } __os_dirfree(env, names, fcnt); return (0); } /* * read_log_dir -- * * Read a directory looking for log files to copy. If home * is passed then we are possibly using a log dir in the destination, * following DB_CONFIG configuration. */ int db_hotbackup_read_log_dir(dbenv, home, backup_dir, log_dir, copy_minp, update, verbose) DB_ENV *dbenv; char *home, *backup_dir, *log_dir; int *copy_minp, update, verbose; { ENV *env; u_int32_t aflag; int cnt, ret, v; char **begin, **names, *backupd, *logd; char from[DB_MAXPATHLEN], to[DB_MAXPATHLEN]; env = dbenv->env; if (home != NULL && log_dir != NULL) { if ((size_t)snprintf(from, sizeof(from), "%s%c%s", home, PATH_SEPARATOR[0], log_dir) >= sizeof(from)) { dbenv->errx(dbenv, "%s%c%s: path too long", home, PATH_SEPARATOR[0], log_dir); return (1); } logd = strdup(from); if ((size_t)(cnt = snprintf(to, sizeof(to), "%s%c%s%c", backup_dir, PATH_SEPARATOR[0], log_dir, PATH_SEPARATOR[0])) >= sizeof(to)) { dbenv->errx(dbenv, "%s%c%s: path too long", backup_dir, PATH_SEPARATOR[0], log_dir); return (1); } backupd = strdup(to); /* Create the backup log directory. */ if ((ret = __db_mkpath(env, backupd)) != 0) { dbenv->err(dbenv, ret, "%s: cannot create", backupd); return (1); } /* Step on the trailing '/'. */ backupd[cnt - 1] = '\0'; } else { backupd = backup_dir; logd = log_dir; } again: aflag = DB_ARCH_LOG; /* * If this is an update and we are deleting files, first process * those files that can be removed, then repeat with the rest. */ if (update) aflag = 0; /* Get a list of file names to be copied. */ if ((ret = dbenv->log_archive(dbenv, &names, aflag)) != 0) { dbenv->err(dbenv, ret, "DB_ENV->log_archive"); return (1); } if (names == NULL) goto done; begin = names; for (; *names != NULL; names++) { /* Track the lowest-numbered log file copied. */ v = atoi(*names + sizeof(LFPREFIX) - 1); if (*copy_minp == 0 || *copy_minp > v) *copy_minp = v; if ((size_t)snprintf(from, sizeof(from), "%s%c%s", logd, PATH_SEPARATOR[0], *names) >= sizeof(from)) { dbenv->errx(dbenv, "%s%c%s: path too long", logd, PATH_SEPARATOR[0], *names); return (1); } /* * If we're going to remove the file, attempt to rename the * instead of copying and then removing. The likely failure * is EXDEV (source and destination are on different volumes). * Fall back to a copy, regardless of the error. We don't * worry about partial contents, the copy truncates the file * on open. */ if (update) { if ((size_t)snprintf(to, sizeof(to), "%s%c%s", backupd, PATH_SEPARATOR[0], *names) >= sizeof(to)) { dbenv->errx(dbenv, "%s%c%s: path too long", backupd, PATH_SEPARATOR[0], *names); return (1); } if (__os_rename(env, from, to, 1) == 0) { if (verbose) printf("%s: moving %s to %s\n", progname, from, to); continue; } } /* Copy the file. */ if (db_hotbackup_data_copy(dbenv, *names, logd, backupd, verbose) != 0) return (1); if (update) { if (verbose) printf("%s: removing %s\n", progname, from); if ((ret = __os_unlink(env, from, 0)) != 0) { dbenv->err(dbenv, ret, "unlink of %s failed", from); return (1); } } } free(begin); done: if (update) { update = 0; goto again; } if (verbose && *copy_minp != 0) printf("%s: lowest numbered log file copied: %d\n", progname, *copy_minp); if (logd != log_dir) free(logd); if (backupd != backup_dir) free(backupd); return (0); } /* * data_copy -- * Copy a file into the backup directory. */ int db_hotbackup_data_copy(dbenv, file, from_dir, to_dir, verbose) DB_ENV *dbenv; char *file, *from_dir, *to_dir; int verbose; { DB_FH *rfhp, *wfhp; ENV *env; size_t nr, nw; int ret; char *buf; rfhp = wfhp = NULL; env = dbenv->env; ret = 0; if (verbose) printf("%s: copying %s%c%s to %s%c%s\n", progname, from_dir, PATH_SEPARATOR[0], file, to_dir, PATH_SEPARATOR[0], file); /* * We MUST copy multiples of the page size, atomically, to ensure a * database page is not updated by another thread of control during * the copy. * * !!! * The current maximum page size for Berkeley DB is 64KB; we will have * to increase this value if the maximum page size is ever more than a * megabyte */ if ((buf = malloc(MEGABYTE)) == NULL) { dbenv->err(dbenv, errno, "%lu buffer allocation", (u_long)MEGABYTE); return (1); } /* Open the input file. */ if (snprintf(buf, MEGABYTE, "%s%c%s", from_dir, PATH_SEPARATOR[0], file) >= MEGABYTE) { dbenv->errx(dbenv, "%s%c%s: path too long", from_dir, PATH_SEPARATOR[0], file); goto err; } if ((ret = __os_open(env, buf, 0, DB_OSO_RDONLY, 0, &rfhp)) != 0) { dbenv->err(dbenv, ret, "%s", buf); goto err; } /* Open the output file. */ if (snprintf(buf, MEGABYTE, "%s%c%s", to_dir, PATH_SEPARATOR[0], file) >= MEGABYTE) { dbenv->errx(dbenv, "%s%c%s: path too long", to_dir, PATH_SEPARATOR[0], file); goto err; } if ((ret = __os_open(env, buf, 0, DB_OSO_CREATE | DB_OSO_TRUNC, DB_MODE_600, &wfhp)) != 0) { dbenv->err(dbenv, ret, "%s", buf); goto err; } /* Copy the data. */ while ((ret = __os_read(env, rfhp, buf, MEGABYTE, &nr)) == 0 && nr > 0) if ((ret = __os_write(env, wfhp, buf, nr, &nw)) != 0) break; if (0) { err: ret = 1; } if (buf != NULL) free(buf); if (rfhp != NULL && __os_closehandle(env, rfhp) != 0) ret = 1; /* We may be running on a remote filesystem; force the flush. */ if (wfhp != NULL) { if (__os_fsync(env, wfhp) != 0) ret = 1; if (__os_closehandle(env, wfhp) != 0) ret = 1; } return (ret); } int db_hotbackup_usage() { (void)fprintf(stderr, "usage: %s [-cDuVv]\n\t%s\n", progname, "[-d data_dir ...] [-h home] [-l log_dir] [-P password] -b backup_dir"); return (EXIT_FAILURE); } int db_hotbackup_version_check() { int v_major, v_minor, v_patch; /* Make sure we're loaded with the right version of the DB library. */ (void)db_version(&v_major, &v_minor, &v_patch); if (v_major != DB_VERSION_MAJOR || v_minor != DB_VERSION_MINOR) { fprintf(stderr, "%s: version %d.%d doesn't match library version %d.%d\n", progname, DB_VERSION_MAJOR, DB_VERSION_MINOR, v_major, v_minor); return (EXIT_FAILURE); } return (0); }
{ "content_hash": "0cc68a8ba729a6fd3ae3dd06e698cd18", "timestamp": "", "source": "github", "line_count": 873, "max_line_length": 87, "avg_line_length": 26.769759450171822, "alnum_prop": 0.6059477963200685, "repo_name": "nzavagli/UnrealPy", "id": "881eee0770e825b54e3baed3241463fcd9250a67", "size": "23561", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/db-4.7.25.0/build_vxworks/db_hotbackup/db_hotbackup.c", "mode": "33188", "license": "mit", "language": [ { "name": "APL", "bytes": "587" }, { "name": "ASP", "bytes": "2753" }, { "name": "ActionScript", "bytes": "5686" }, { "name": "Ada", "bytes": "94225" }, { "name": "Agda", "bytes": "3154" }, { "name": "Alloy", "bytes": "6579" }, { "name": "ApacheConf", "bytes": "12482" }, { "name": "AppleScript", "bytes": "421" }, { "name": "Assembly", "bytes": "1093261" }, { "name": "AutoHotkey", "bytes": "3733" }, { "name": "AutoIt", "bytes": "667" }, { "name": "Awk", "bytes": "63276" }, { "name": "Batchfile", "bytes": "147828" }, { "name": "BlitzBasic", "bytes": "185102" }, { "name": "BlitzMax", "bytes": "2387" }, { "name": "Boo", "bytes": "1111" }, { "name": "Bro", "bytes": "7337" }, { "name": "C", "bytes": "108397183" }, { "name": "C#", "bytes": "156749" }, { "name": "C++", "bytes": "13535833" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CMake", "bytes": "12441" }, { "name": "COBOL", "bytes": "114812" }, { "name": "CSS", "bytes": "430375" }, { "name": "Ceylon", "bytes": "1387" }, { "name": "Chapel", "bytes": "4366" }, { "name": "Cirru", "bytes": "2574" }, { "name": "Clean", "bytes": "9679" }, { "name": "Clojure", "bytes": "23871" }, { "name": "CoffeeScript", "bytes": "20149" }, { "name": "ColdFusion", "bytes": "9006" }, { "name": "Common Lisp", "bytes": "49017" }, { "name": "Coq", "bytes": "66" }, { "name": "Cucumber", "bytes": "390" }, { "name": "Cuda", "bytes": "776" }, { "name": "D", "bytes": "7556" }, { "name": "DIGITAL Command Language", "bytes": "425938" }, { "name": "DTrace", "bytes": "6706" }, { "name": "Dart", "bytes": "591" }, { "name": "Dylan", "bytes": "6343" }, { "name": "Ecl", "bytes": "2599" }, { "name": "Eiffel", "bytes": "2145" }, { "name": "Elixir", "bytes": "4340" }, { "name": "Emacs Lisp", "bytes": "18303" }, { "name": "Erlang", "bytes": "5746" }, { "name": "F#", "bytes": "19156" }, { "name": "FORTRAN", "bytes": "38458" }, { "name": "Factor", "bytes": "10194" }, { "name": "Fancy", "bytes": "2581" }, { "name": "Fantom", "bytes": "25331" }, { "name": "GAP", "bytes": "29880" }, { "name": "GLSL", "bytes": "450" }, { "name": "Gnuplot", "bytes": "11501" }, { "name": "Go", "bytes": "5444" }, { "name": "Golo", "bytes": "1649" }, { "name": "Gosu", "bytes": "2853" }, { "name": "Groff", "bytes": "3458639" }, { "name": "Groovy", "bytes": "2586" }, { "name": "HTML", "bytes": "92126540" }, { "name": "Haskell", "bytes": "49593" }, { "name": "Haxe", "bytes": "16812" }, { "name": "Hy", "bytes": "7237" }, { "name": "IDL", "bytes": "2098" }, { "name": "Idris", "bytes": "2771" }, { "name": "Inform 7", "bytes": "1944" }, { "name": "Inno Setup", "bytes": "18796" }, { "name": "Ioke", "bytes": "469" }, { "name": "Isabelle", "bytes": "21392" }, { "name": "Jasmin", "bytes": "9428" }, { "name": "Java", "bytes": "4040623" }, { "name": "JavaScript", "bytes": "223927" }, { "name": "Julia", "bytes": "27687" }, { "name": "KiCad", "bytes": "475" }, { "name": "Kotlin", "bytes": "971" }, { "name": "LSL", "bytes": "160" }, { "name": "Lasso", "bytes": "18650" }, { "name": "Lean", "bytes": "6921" }, { "name": "Limbo", "bytes": "9891" }, { "name": "Liquid", "bytes": "862" }, { "name": "LiveScript", "bytes": "972" }, { "name": "Logos", "bytes": "19509" }, { "name": "Logtalk", "bytes": "7260" }, { "name": "Lua", "bytes": "8677" }, { "name": "Makefile", "bytes": "2053844" }, { "name": "Mask", "bytes": "815" }, { "name": "Mathematica", "bytes": "191" }, { "name": "Max", "bytes": "296" }, { "name": "Modelica", "bytes": "6213" }, { "name": "Modula-2", "bytes": "23838" }, { "name": "Module Management System", "bytes": "14798" }, { "name": "Monkey", "bytes": "2587" }, { "name": "Moocode", "bytes": "3343" }, { "name": "MoonScript", "bytes": "14862" }, { "name": "Myghty", "bytes": "3939" }, { "name": "NSIS", "bytes": "7663" }, { "name": "Nemerle", "bytes": "1517" }, { "name": "NewLisp", "bytes": "42726" }, { "name": "Nimrod", "bytes": "37191" }, { "name": "Nit", "bytes": "55581" }, { "name": "Nix", "bytes": "2448" }, { "name": "OCaml", "bytes": "42416" }, { "name": "Objective-C", "bytes": "104883" }, { "name": "Objective-J", "bytes": "15340" }, { "name": "Opa", "bytes": "172" }, { "name": "OpenEdge ABL", "bytes": "49943" }, { "name": "PAWN", "bytes": "6555" }, { "name": "PHP", "bytes": "68611" }, { "name": "PLSQL", "bytes": "45772" }, { "name": "Pan", "bytes": "1241" }, { "name": "Pascal", "bytes": "349743" }, { "name": "Perl", "bytes": "5931502" }, { "name": "Perl6", "bytes": "113623" }, { "name": "PigLatin", "bytes": "6657" }, { "name": "Pike", "bytes": "8479" }, { "name": "PostScript", "bytes": "18216" }, { "name": "PowerShell", "bytes": "14236" }, { "name": "Prolog", "bytes": "43750" }, { "name": "Protocol Buffer", "bytes": "3401" }, { "name": "Puppet", "bytes": "130" }, { "name": "Python", "bytes": "122886156" }, { "name": "QML", "bytes": "3912" }, { "name": "R", "bytes": "49247" }, { "name": "Racket", "bytes": "11341" }, { "name": "Rebol", "bytes": "17708" }, { "name": "Red", "bytes": "10536" }, { "name": "Redcode", "bytes": "830" }, { "name": "Ruby", "bytes": "91403" }, { "name": "Rust", "bytes": "6788" }, { "name": "SAS", "bytes": "15603" }, { "name": "SaltStack", "bytes": "1040" }, { "name": "Scala", "bytes": "730" }, { "name": "Scheme", "bytes": "50346" }, { "name": "Scilab", "bytes": "943" }, { "name": "Shell", "bytes": "2925097" }, { "name": "ShellSession", "bytes": "320" }, { "name": "Smali", "bytes": "832" }, { "name": "Smalltalk", "bytes": "158636" }, { "name": "Smarty", "bytes": "523" }, { "name": "SourcePawn", "bytes": "130" }, { "name": "Standard ML", "bytes": "36869" }, { "name": "Swift", "bytes": "2035" }, { "name": "SystemVerilog", "bytes": "265" }, { "name": "Tcl", "bytes": "6077233" }, { "name": "TeX", "bytes": "487999" }, { "name": "Tea", "bytes": "391" }, { "name": "TypeScript", "bytes": "535" }, { "name": "VHDL", "bytes": "4446" }, { "name": "VimL", "bytes": "32053" }, { "name": "Visual Basic", "bytes": "19441" }, { "name": "XQuery", "bytes": "4289" }, { "name": "XS", "bytes": "178055" }, { "name": "XSLT", "bytes": "1995174" }, { "name": "Xtend", "bytes": "727" }, { "name": "Yacc", "bytes": "25665" }, { "name": "Zephir", "bytes": "485" }, { "name": "eC", "bytes": "31545" }, { "name": "mupad", "bytes": "2442" }, { "name": "nesC", "bytes": "23697" }, { "name": "xBase", "bytes": "3349" } ], "symlink_target": "" }
namespace infrt { namespace host_context { struct KernelRegistry; } // namespace host_context } // namespace infrt namespace infrt { namespace kernel { void RegisterTensorKernels(host_context::KernelRegistry* registry); } // namespace kernel } // namespace infrt
{ "content_hash": "cdfbfe7d223b70f05c2bf37ab87c0f21", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 67, "avg_line_length": 20.76923076923077, "alnum_prop": 0.7555555555555555, "repo_name": "PaddlePaddle/Paddle", "id": "df8e25c32393c903c3e6801e23095aeff6eca9b4", "size": "908", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "paddle/infrt/kernel/tensor_kernels.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "58544" }, { "name": "C", "bytes": "210300" }, { "name": "C++", "bytes": "36848680" }, { "name": "CMake", "bytes": "902619" }, { "name": "Cuda", "bytes": "5227207" }, { "name": "Dockerfile", "bytes": "4361" }, { "name": "Go", "bytes": "49796" }, { "name": "Java", "bytes": "16630" }, { "name": "Jinja", "bytes": "23852" }, { "name": "MLIR", "bytes": "39982" }, { "name": "Python", "bytes": "36203874" }, { "name": "R", "bytes": "1332" }, { "name": "Shell", "bytes": "553177" } ], "symlink_target": "" }
"""docstring"""
{ "content_hash": "30c29c2885c71b49b5a9fe1f407e4ba9", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 15, "avg_line_length": 16, "alnum_prop": 0.5625, "repo_name": "Titulacion-Sistemas/PythonTitulacion-EV", "id": "fb1e2b64861dd3af1f1fa4cad9050569dcc75c11", "size": "16", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "Lib/site-packages/pylint/test/input/func_reqattrs.py", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "2117" }, { "name": "C", "bytes": "469338" }, { "name": "C++", "bytes": "93276" }, { "name": "CSS", "bytes": "173812" }, { "name": "JavaScript", "bytes": "203291" }, { "name": "PowerShell", "bytes": "8104" }, { "name": "Python", "bytes": "17198855" }, { "name": "Shell", "bytes": "2237" }, { "name": "TeX", "bytes": "1527" }, { "name": "Visual Basic", "bytes": "904" }, { "name": "XSLT", "bytes": "154751" } ], "symlink_target": "" }
package com.jayway.jsonpath.internal.path; import static java.util.Arrays.asList; import com.jayway.jsonpath.Option; import com.jayway.jsonpath.PathNotFoundException; import com.jayway.jsonpath.internal.PathRef; /** * */ public class WildcardPathToken extends PathToken { WildcardPathToken() { } @Override public void evaluate(String currentPath, PathRef parent, Object model, EvaluationContextImpl ctx) { if (ctx.jsonProvider().isMap(model)) { for (String property : ctx.jsonProvider().getPropertyKeys(model)) { handleObjectProperty(currentPath, model, ctx, asList(property)); } } else if (ctx.jsonProvider().isArray(model)) { /* * Assert.assertNotNull(ctx.getCurrentProperty()); ctx.configuration().jsonProvider().setProperty(curr, ctx.getCurrentProperty(), arrObj); * ctx.setLineageParent(arrObj); */ for (int idx = 0; idx < ctx.jsonProvider().length(model); idx++) { try { handleArrayIndex(idx, currentPath, model, ctx); } catch (PathNotFoundException p){ if(ctx.options().contains(Option.REQUIRE_PROPERTIES)){ throw p; } } } } } @Override public boolean isTokenDefinite() { return false; } @Override public String getPathFragment() { return "[*]"; } }
{ "content_hash": "19cae352969a1eb9f3caa1ff64c7225c", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 150, "avg_line_length": 29.392156862745097, "alnum_prop": 0.5857238158772515, "repo_name": "lafaspot/JsonPath", "id": "aae9532b5569baa2894b426e94eca54ef1c84502", "size": "2112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "json-path/src/main/java/com/jayway/jsonpath/internal/path/WildcardPathToken.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "6380" }, { "name": "HTML", "bytes": "15940" }, { "name": "Java", "bytes": "791515" }, { "name": "JavaScript", "bytes": "3809" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Messaging.EventHubs.Authorization; using Azure.Messaging.EventHubs.Core; using Azure.Messaging.EventHubs.Producer; using Moq; using NUnit.Framework; namespace Azure.Messaging.EventHubs.Tests { /// <summary> /// The suite of tests for the <see cref="TransportProducerPool" /> class. /// </summary> /// [TestFixture] public class TransportProducerPoolTests { /// <summary> /// The pool periodically removes and closes expired items. /// </summary> /// [Test] public void TransportProducerPoolRemovesExpiredItems() { var transportProducer = new ObservableTransportProducerMock(); var connection = new MockConnection(() => transportProducer); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); DateTimeOffset oneMinuteAgo = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { // An expired item in the pool ["0"] = new TransportProducerPool.PoolItem("0", transportProducer, removeAfter: oneMinuteAgo), ["1"] = new TransportProducerPool.PoolItem("0", transportProducer), ["2"] = new TransportProducerPool.PoolItem("0", transportProducer), }; TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy), startingPool); GetExpirationCallBack(transportProducerPool).Invoke(null); Assert.That(startingPool.TryGetValue("0", out _), Is.False, "PerformExpiration should remove an expired producer from the pool."); Assert.That(transportProducer.CloseCallCount, Is.EqualTo(1), "PerformExpiration should close an expired producer."); Assert.That(startingPool.TryGetValue("1", out _), Is.True, "PerformExpiration should not remove valid producers."); Assert.That(startingPool.TryGetValue("2", out _), Is.True, "PerformExpiration should not remove valid producers."); } /// <summary> /// When a <see cref="TransportProducerPool.PoolItem" /> is requested /// its <see cref="TransportProducerPool.PoolItem.RemoveAfter" /> will be increased. /// </summary> /// [Test] public void TransportProducerPoolRefreshesAccessedItems() { DateTimeOffset oneMinuteAgo = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)); var transportProducer = new ObservableTransportProducerMock(); var connection = new MockConnection(() => transportProducer); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { // An expired item in the pool ["0"] = new TransportProducerPool.PoolItem("0", transportProducer, removeAfter: oneMinuteAgo) }; TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy), startingPool); // This call should refresh the timespan associated to the item _ = transportProducerPool.GetPooledProducer("0"); // The expiration call back should not remove the item GetExpirationCallBack(transportProducerPool).Invoke(null); Assert.That(startingPool.TryGetValue("0", out _), Is.True, "The item in the pool should be refreshed and not have been removed."); } /// <summary> /// When a <see cref="TransportProducerPool.PooledProducer" /> is disposed, the <see cref="TimeSpan"/> /// of the associated <see cref="TransportProducerPool.PoolItem" /> is increased. /// </summary> /// [Test] public async Task PoolItemsAreRefreshedOnDisposal() { var transportProducer = new ObservableTransportProducerMock(); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { ["0"] = new TransportProducerPool.PoolItem("0", transportProducer) }; var connection = new MockConnection(() => transportProducer); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy)); var expectedTime = DateTimeOffset.UtcNow.AddMinutes(10); await using var pooledProducer = transportProducerPool.GetPooledProducer("0"); // This call should refresh the timespan associated to an item in the pool await pooledProducer.DisposeAsync(); Assert.That(startingPool["0"].RemoveAfter, Is.InRange(expectedTime.AddMinutes(-1), expectedTime.AddMinutes(1)), $"The remove after of a pool item should be extended."); } /// <summary> /// When a partition producer is requested its expiration time will be increased. /// </summary> /// [Test] public async Task TransportProducerPoolTracksAProducerUsage() { DateTimeOffset oneMinuteAgo = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)); var transportProducer = new ObservableTransportProducerMock(); var connection = new MockConnection(() => transportProducer); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { // An expired item in the pool ["0"] = new TransportProducerPool.PoolItem("0", transportProducer, removeAfter: oneMinuteAgo) }; TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy), startingPool); var pooledProducer = transportProducerPool.GetPooledProducer("0"); startingPool.TryGetValue("0", out var poolItem); await using (pooledProducer) { Assert.That(poolItem.ActiveInstances.Count, Is.EqualTo(1), "The usage of a transport producer should be tracked."); } Assert.That(poolItem.ActiveInstances.Count, Is.EqualTo(0), "After usage an active instance should be removed from the pool."); } /// <summary> /// It is possible to configure how long a <see cref="TransportProducerPool.PoolItem" /> should sit in memory. /// </summary> /// [Test] public async Task TransportProducerPoolAllowsConfiguringRemoveAfter() { var transportProducer = new ObservableTransportProducerMock(); var connection = new MockConnection(() => transportProducer); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { ["0"] = new TransportProducerPool.PoolItem("0", transportProducer) }; TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy), startingPool); var pooledProducer = transportProducerPool.GetPooledProducer("0", TimeSpan.FromMinutes(-1)); await using (var _ = pooledProducer.ConfigureAwait(false)) { }; GetExpirationCallBack(transportProducerPool).Invoke(null); Assert.That(transportProducer.CloseCallCount, Is.EqualTo(1)); } /// <summary> /// The <see cref="TransportProducerPool"/> returns the <see cref="TransportProducer" /> /// matching the right partition id. /// </summary> /// [Test] [TestCase(null)] [TestCase("0")] public void TransportProducerPoolAllowsTakingTheRightTransportProducer(string partitionId) { var transportProducer = new ObservableTransportProducerMock(); var partitionProducer = new ObservableTransportProducerMock(partitionId); var connection = new MockConnection(() => partitionProducer); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { ["0"] = new TransportProducerPool.PoolItem("0", partitionProducer) }; TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy), eventHubProducer: transportProducer); var returnedProducer = transportProducerPool.GetPooledProducer(partitionId).TransportProducer as ObservableTransportProducerMock; Assert.That(returnedProducer.PartitionId, Is.EqualTo(partitionId)); } /// <summary> /// Verifies functionality of the <see cref="TransportProducerPool.CloseAsync" /> /// method. /// </summary> /// [Test] public void CloseAsyncSurfacesExceptionsForTransportProducer() { var transportProducer = new Mock<TransportProducer>(); var partitionProducer = new Mock<TransportProducer>(); var connection = new MockConnection(() => partitionProducer.Object); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { ["0"] = new TransportProducerPool.PoolItem("0", partitionProducer.Object) }; TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy), eventHubProducer: transportProducer.Object); transportProducer .Setup(producer => producer.CloseAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromException(new InvalidCastException())); var _ = transportProducerPool.GetPooledProducer(null).TransportProducer as ObservableTransportProducerMock; Assert.That(async () => await transportProducerPool.CloseAsync(), Throws.InstanceOf<InvalidCastException>()); } /// <summary> /// Verifies functionality of the <see cref="TransportProducerPool.CloseAsync" /> /// method. /// </summary> /// [Test] public void CloseAsyncSurfacesExceptionsForPartitionTransportProducer() { var transportProducer = new Mock<TransportProducer>(); var partitionProducer = new Mock<TransportProducer>(); var connection = new MockConnection(() => partitionProducer.Object); var retryPolicy = new EventHubProducerClientOptions().RetryOptions.ToRetryPolicy(); var startingPool = new ConcurrentDictionary<string, TransportProducerPool.PoolItem> { ["0"] = new TransportProducerPool.PoolItem("0", partitionProducer.Object) }; TransportProducerPool transportProducerPool = new TransportProducerPool(partition => connection.CreateTransportProducer(partition, TransportProducerFeatures.None, null, retryPolicy), eventHubProducer: transportProducer.Object); partitionProducer .Setup(producer => producer.CloseAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromException(new InvalidCastException())); var _ = transportProducerPool.GetPooledProducer("0"); Assert.That(async () => await transportProducerPool.CloseAsync(), Throws.InstanceOf<InvalidCastException>()); } /// <summary> /// Gets the routine responsible of finding expired producers. /// </summary> /// private static TimerCallback GetExpirationCallBack(TransportProducerPool pool) => (TimerCallback) typeof(TransportProducerPool) .GetMethod("CreateExpirationTimerCallback", BindingFlags.NonPublic | BindingFlags.Instance) .Invoke(pool, null); /// <summary> /// Serves as a non-functional connection for testing producer functionality. /// </summary> /// private class MockConnection : EventHubConnection { public EventHubsRetryPolicy GetPropertiesInvokedWith = null; public EventHubsRetryPolicy GetPartitionIdsInvokedWith = null; public EventHubsRetryPolicy GetPartitionPropertiesInvokedWith = null; public Func<TransportProducer> TransportProducerFactory = () => Mock.Of<TransportProducer>(); public bool WasClosed = false; public MockConnection(string namespaceName = "fakeNamespace", string eventHubName = "fakeEventHub") : base(namespaceName, eventHubName, new Mock<EventHubTokenCredential>(Mock.Of<TokenCredential>()).Object) { } public MockConnection(Func<TransportProducer> transportProducerFactory, string namespaceName, string eventHubName) : this(namespaceName, eventHubName) { TransportProducerFactory = transportProducerFactory; } public MockConnection(Func<TransportProducer> transportProducerFactory) : this(transportProducerFactory, "fakeNamespace", "fakeEventHub") { } internal override Task<EventHubProperties> GetPropertiesAsync(EventHubsRetryPolicy retryPolicy, CancellationToken cancellationToken = default) { GetPropertiesInvokedWith = retryPolicy; return Task.FromResult(new EventHubProperties(EventHubName, DateTimeOffset.Parse("2015-10-27T00:00:00Z"), new string[] { "0", "1" })); } internal async override Task<string[]> GetPartitionIdsAsync(EventHubsRetryPolicy retryPolicy, CancellationToken cancellationToken = default) { GetPartitionIdsInvokedWith = retryPolicy; return await base.GetPartitionIdsAsync(retryPolicy, cancellationToken); } internal override Task<PartitionProperties> GetPartitionPropertiesAsync(string partitionId, EventHubsRetryPolicy retryPolicy, CancellationToken cancellationToken = default) { GetPartitionPropertiesInvokedWith = retryPolicy; return Task.FromResult(default(PartitionProperties)); } internal override TransportProducer CreateTransportProducer(string partitionId, TransportProducerFeatures requestedFeatures, PartitionPublishingOptions partitionOptions, EventHubsRetryPolicy retryPolicy) => TransportProducerFactory(); internal override TransportClient CreateTransportClient(string fullyQualifiedNamespace, string eventHubName, EventHubTokenCredential credential, EventHubConnectionOptions options) { var client = new Mock<TransportClient>(); client .Setup(client => client.ServiceEndpoint) .Returns(new Uri($"amgp://{ fullyQualifiedNamespace }.com/{ eventHubName }")); return client.Object; } } /// <summary> /// Allows for observation of operations performed by the producer for testing purposes. /// </summary> /// private class ObservableTransportProducerMock : TransportProducer { public int CloseCallCount = 0; public bool WasCloseCalled = false; public (IEnumerable<EventData>, SendEventOptions) SendCalledWith; public EventDataBatch SendBatchCalledWith; public CreateBatchOptions CreateBatchCalledWith; public string PartitionId { get; set; } public ObservableTransportProducerMock(string partitionId = default) { PartitionId = partitionId; } public override Task SendAsync(IEnumerable<EventData> events, SendEventOptions sendOptions, CancellationToken cancellationToken) { SendCalledWith = (events, sendOptions); return Task.CompletedTask; } public override Task SendAsync(EventDataBatch batch, CancellationToken cancellationToken) { SendBatchCalledWith = batch; return Task.CompletedTask; } public override ValueTask<TransportEventBatch> CreateBatchAsync(CreateBatchOptions options, CancellationToken cancellationToken) { CreateBatchCalledWith = options; return new ValueTask<TransportEventBatch>(Task.FromResult((TransportEventBatch)new MockTransportBatch())); } public override ValueTask<PartitionPublishingProperties> ReadInitializationPublishingPropertiesAsync(CancellationToken cancellationToken) => throw new NotImplementedException(); public override Task CloseAsync(CancellationToken cancellationToken) { WasCloseCalled = true; ++CloseCallCount; return Task.CompletedTask; } } /// <summary> /// Serves as a non-functional transport event batch for satisfying the /// non-null constraints of the <see cref="EventDataBatch" /> created by /// the producer being tested. /// </summary> /// private class MockTransportBatch : TransportEventBatch { public override long MaximumSizeInBytes { get; } public override long SizeInBytes { get; } public override int Count { get; } public override TransportProducerFeatures ActiveFeatures { get; } public override bool TryAdd(EventData eventData) => throw new NotImplementedException(); public override IEnumerable<T> AsEnumerable<T>() => throw new NotImplementedException(); public override void Dispose() => throw new NotImplementedException(); public override void Clear() { } } } }
{ "content_hash": "98e2da303b8d0ef100161671b0fe76f0", "timestamp": "", "source": "github", "line_count": 395, "max_line_length": 239, "avg_line_length": 51.41012658227848, "alnum_prop": 0.6289949278573891, "repo_name": "ayeletshpigelman/azure-sdk-for-net", "id": "c24b5b6bbcd27f1c82613ea7bac64e386cc0fc74", "size": "20309", "binary": false, "copies": "2", "ref": "refs/heads/ayshpige/InternalBranchForDebuging", "path": "sdk/eventhub/Azure.Messaging.EventHubs/tests/Producer/TransportProducerPoolTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "Batchfile", "bytes": "28895" }, { "name": "C#", "bytes": "45912328" }, { "name": "CSS", "bytes": "685" }, { "name": "HTML", "bytes": "45212" }, { "name": "JavaScript", "bytes": "7875" }, { "name": "PowerShell", "bytes": "24250" }, { "name": "Shell", "bytes": "1470" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
""" This example shows how to use the FedEx RateRequest service. The variables populated below represents the minimum required values. You will need to fill all of these, or risk seeing a SchemaValidationError exception thrown by suds. TIP: Near the bottom of the module, see how to check the if the destination is Out of Delivery Area (ODA). """ import logging from example_config import CONFIG_OBJ from fedex.services.rate_service import FedexRateServiceRequest # Set this to the INFO level to see the response from Fedex printed in stdout. logging.basicConfig(level=logging.INFO) # This is the object that will be handling our tracking request. # We're using the FedexConfig object from example_config.py in this dir. rate_request = FedexRateServiceRequest(CONFIG_OBJ) rate_request.RequestedShipment.ServiceType = 'FEDEX_FREIGHT_ECONOMY' rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP' rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING' rate_request.RequestedShipment.FreightShipmentDetail.TotalHandlingUnits = 1 rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightAccountNumber = CONFIG_OBJ.freight_account_number rate_request.RequestedShipment.Shipper.Address.PostalCode = '72601' rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US' rate_request.RequestedShipment.Shipper.Address.City = 'Harrison' rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'AR' rate_request.RequestedShipment.Shipper.Address.Residential = False rate_request.RequestedShipment.Recipient.Address.PostalCode = '72601' rate_request.RequestedShipment.Recipient.Address.CountryCode = 'US' rate_request.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'AR' rate_request.RequestedShipment.Recipient.Address.City = 'Harrison' #include estimated duties and taxes in rate quote, can be ALL or NONE rate_request.RequestedShipment.EdtRequestType = 'NONE' # note: in order for this to work in test, you may need to use the # specially provided LTL addresses emailed to you when signing up. rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Contact.PersonName = 'Sender Name' rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Contact.CompanyName = 'Some Company' rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Contact.PhoneNumber = '9012638716' rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.StreetLines = ['2000 Freight LTL Testing'] rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.City = 'Harrison' rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.StateOrProvinceCode = 'AR' rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.PostalCode = '72601' rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.CountryCode = 'US' rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.Residential = False spec = rate_request.create_wsdl_object_of_type('ShippingDocumentSpecification') spec.ShippingDocumentTypes = [spec.CertificateOfOrigin] rate_request.RequestedShipment.ShippingDocumentSpecification = spec role = rate_request.create_wsdl_object_of_type('FreightShipmentRoleType') rate_request.RequestedShipment.FreightShipmentDetail.Role = role.SHIPPER # Designates the terms of the "collect" payment for a Freight #Shipment. Can be NON_RECOURSE_SHIPPER_SIGNED or STANDARD rate_request.RequestedShipment.FreightShipmentDetail.CollectTermsType = 'STANDARD' package1_weight = rate_request.create_wsdl_object_of_type('Weight') package1_weight.Value = 500.0 package1_weight.Units = "LB" rate_request.RequestedShipment.FreightShipmentDetail.PalletWeight = package1_weight package1 = rate_request.create_wsdl_object_of_type('FreightShipmentLineItem') package1.Weight = package1_weight package1.Packaging = 'PALLET' package1.Description = 'Products' package1.FreightClass = 'CLASS_500' rate_request.RequestedShipment.FreightShipmentDetail.LineItems = package1 # If you'd like to see some documentation on the ship service WSDL, un-comment # this line. (Spammy). #print rate_request.client # Un-comment this to see your complete, ready-to-send request as it stands # before it is actually sent. This is useful for seeing what values you can # change. #print rate_request.RequestedShipment # Fires off the request, sets the 'response' attribute on the object. rate_request.send_request() # This will show the reply to your rate_request being sent. You can access the # attributes through the response attribute on the request object. This is # good to un-comment to see the variables returned by the FedEx reply. #print rate_request.response # Here is the overall end result of the query. print "HighestSeverity:", rate_request.response.HighestSeverity # RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None for service in rate_request.response.RateReplyDetails: for detail in service.RatedShipmentDetails: for surcharge in detail.ShipmentRateDetail.Surcharges: if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA': print "%s: ODA rate_request charge %s" % (service.ServiceType, surcharge.Amount.Amount) for rate_detail in service.RatedShipmentDetails: print "%s: Net FedEx Charge %s %s" % (service.ServiceType, rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency, rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount)
{ "content_hash": "f65e376a1b63f0ce269bdc5d40d603d8", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 140, "avg_line_length": 50.54867256637168, "alnum_prop": 0.820203081232493, "repo_name": "AxiaCore/python-fedex", "id": "0fe7d9746a64a16e99b8b7065bab5ced87d0fa45", "size": "5734", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "examples/freight_rate_request.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "87999" }, { "name": "Shell", "bytes": "45" } ], "symlink_target": "" }
import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Queen' copyright = u'2013, Kashif Malik' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Queendoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Queen.tex', u'Queen Documentation', u'Kashif Malik', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'queen', u'Queen Documentation', [u'Kashif Malik'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Queen', u'Queen Documentation', u'Kashif Malik', 'Queen', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
{ "content_hash": "2b286b69b28b68356a8dbc9b566c3c36", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 80, "avg_line_length": 31.903930131004365, "alnum_prop": 0.7003832466465918, "repo_name": "kalail/queen", "id": "87d0a4036520b91f101d5ebe31e8c4d2d99069e8", "size": "7722", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/conf.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "27344" }, { "name": "Shell", "bytes": "5094" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "d1aff9b4b31519e748b90bda79e62bd9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "f80707566b8d02e1df4469f6cee7488588c53e59", "size": "185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Araceae/Anthurium/Anthurium incomptum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.example; import android.app.NativeActivity; import android.content.Intent; import android.os.Bundle; import com.google.firebase.messaging.MessageForwardingService; /** * SampleNativeActivity is a NativeActivity that updates its intent when new intents are sent to * it. * * This is a workaround for a known issue that prevents the native C++ library from responding to * data payloads when both a data and notification payload are sent to the app while it is in the * background. */ public class SampleNativeActivity extends NativeActivity { // The key in the intent's extras that maps to the incoming message's message ID. Only sent by // the server, GmsCore sends EXTRA_MESSAGE_ID_KEY below. Server can't send that as it would get // stripped by the client. private static final String EXTRA_MESSAGE_ID_KEY_SERVER = "message_id"; // An alternate key value in the intent's extras that also maps to the incoming message's message // ID. Used by upstream, and set by GmsCore. private static final String EXTRA_MESSAGE_ID_KEY = "google.message_id"; // The key in the intent's extras that maps to the incoming message's sender value. private static final String EXTRA_FROM = "google.message_id"; /** * Workaround for when a message is sent containing both a Data and Notification payload. * * When the app is in the foreground all data payloads are sent to the method * `::firebase::messaging::Listener::OnMessage`. However, when the app is in the background, if a * message with both a data and notification payload is receieved the data payload is stored on * the notification Intent. NativeActivity does not provide native callbacks for onNewIntent, so * it cannot route the data payload that is stored in the Intent to the C++ function OnMessage. As * a workaround, we override onNewIntent so that it forwards the intent to the C++ library's * service which in turn forwards the data to the native C++ messaging library. */ @Override protected void onNewIntent(Intent intent) { // If we do not have a 'from' field this intent was not a message and should not be handled. It // probably means this intent was fired by tapping on the app icon. Bundle extras = intent.getExtras(); String from = extras.getString(EXTRA_FROM); String messageId = extras.getString(EXTRA_MESSAGE_ID_KEY); if (messageId == null) { messageId = extras.getString(EXTRA_MESSAGE_ID_KEY_SERVER); } if (from != null && messageId != null) { Intent message = new Intent(this, MessageForwardingService.class); message.setAction(MessageForwardingService.ACTION_REMOTE_INTENT); message.putExtras(intent); message.setData(intent.getData()); // When running on Android O or later, the work will be dispatched as a job via // JobScheduler.enqueue. When running on older versions of the platform, // it will use Context.startService. MessageForwardingService.enqueueWork(this, message); } setIntent(intent); } }
{ "content_hash": "fa7f64b9cb8dbd5c0a5de3e2eed04fd2", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 100, "avg_line_length": 48.31578947368421, "alnum_prop": 0.7369281045751634, "repo_name": "firebase/firebase-cpp-sdk", "id": "2e17b570efc5cdc920e4a9b49f568621084b17ba", "size": "3672", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "messaging/integration_test/src/android/java/com/google/firebase/example/SampleNativeActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3734" }, { "name": "C", "bytes": "84626" }, { "name": "C++", "bytes": "7496469" }, { "name": "CMake", "bytes": "402069" }, { "name": "Java", "bytes": "403250" }, { "name": "Kotlin", "bytes": "3278" }, { "name": "Objective-C", "bytes": "673832" }, { "name": "Objective-C++", "bytes": "659778" }, { "name": "Python", "bytes": "463609" }, { "name": "Ruby", "bytes": "16155" }, { "name": "Shell", "bytes": "77075" }, { "name": "Swift", "bytes": "16598" } ], "symlink_target": "" }
static const char * MapOutOfBandToText(CMICmnMIOutOfBandRecord::OutOfBand_e veType) { switch (veType) { case CMICmnMIOutOfBandRecord::eOutOfBand_Running: return "running"; case CMICmnMIOutOfBandRecord::eOutOfBand_Stopped: return "stopped"; case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointCreated: return "breakpoint-created"; case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointModified: return "breakpoint-modified"; case CMICmnMIOutOfBandRecord::eOutOfBand_Thread: return ""; // "" Meant to be empty case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupAdded: return "thread-group-added"; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupExited: return "thread-group-exited"; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupRemoved: return "thread-group-removed"; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted: return "thread-group-started"; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadCreated: return "thread-created"; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadExited: return "thread-exited"; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadSelected: return "thread-selected"; case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleLoaded: return "library-loaded"; case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleUnloaded: return "library-unloaded"; case CMICmnMIOutOfBandRecord::eOutOfBand_TargetStreamOutput: return ""; case CMICmnMIOutOfBandRecord::eOutOfBand_ConsoleStreamOutput: return ""; case CMICmnMIOutOfBandRecord::eOutOfBand_LogStreamOutput: return ""; } assert(false && "unknown CMICmnMIOutofBandRecord::OutOfBand_e"); return NULL; } static const char * MapOutOfBandToToken(CMICmnMIOutOfBandRecord::OutOfBand_e veType) { switch (veType) { case CMICmnMIOutOfBandRecord::eOutOfBand_Running: return "*"; case CMICmnMIOutOfBandRecord::eOutOfBand_Stopped: return "*"; case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointCreated: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointModified: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_Thread: return "@"; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupAdded: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupExited: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupRemoved: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadCreated: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadExited: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadSelected: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleLoaded: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleUnloaded: return "="; case CMICmnMIOutOfBandRecord::eOutOfBand_TargetStreamOutput: return "@"; case CMICmnMIOutOfBandRecord::eOutOfBand_ConsoleStreamOutput: return "~"; case CMICmnMIOutOfBandRecord::eOutOfBand_LogStreamOutput: return "&"; } assert(false && "unknown CMICmnMIOutofBandRecord::OutOfBand_e"); return NULL; } //++ //------------------------------------------------------------------------------------ // Details: Build the Out-of-band record's mandatory data part. The part up to // the first // (additional) result i.e. async-record ==> "*" type. // Args: veType - (R) A MI Out-of-Band enumeration. // Return: CMIUtilString - The async record text. // Throws: None. //-- static CMIUtilString BuildAsyncRecord(CMICmnMIOutOfBandRecord::OutOfBand_e veType) { return CMIUtilString::Format("%s%s", MapOutOfBandToToken(veType), MapOutOfBandToText(veType)); } //++ //------------------------------------------------------------------------------------ // Details: CMICmnMIOutOfBandRecord constructor. // Type: Method. // Args: None. // Return: None. // Throws: None. //-- CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord() : m_strAsyncRecord(MIRSRC(IDS_CMD_ERR_EVENT_HANDLED_BUT_NO_ACTION)) {} //++ //------------------------------------------------------------------------------------ // Details: CMICmnMIOutOfBandRecord constructor. // Type: Method. // Args: veType - (R) A MI Out-of-Bound enumeration. // Return: None. // Throws: None. //-- CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord(OutOfBand_e veType) : m_strAsyncRecord(BuildAsyncRecord(veType)) {} //++ //------------------------------------------------------------------------------------ // Details: CMICmnMIOutOfBandRecord constructor. // Type: Method. // Args: veType - (R) A MI Out-of-Bound enumeration. // vConst - (R) A MI const object. // Return: None. // Throws: None. //-- CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord( OutOfBand_e veType, const CMICmnMIValueConst &vConst) : m_strAsyncRecord(BuildAsyncRecord(veType)) { m_strAsyncRecord += vConst.GetString(); } //++ //------------------------------------------------------------------------------------ // Details: CMICmnMIOutOfBandRecord constructor. // Type: Method. // Args: veType - (R) A MI Out-of-Bound enumeration. // vResult - (R) A MI result object. // Return: None. // Throws: None. //-- CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord( OutOfBand_e veType, const CMICmnMIValueResult &vResult) : m_strAsyncRecord(BuildAsyncRecord(veType)) { Add(vResult); } //++ //------------------------------------------------------------------------------------ // Details: CMICmnMIOutOfBandRecord destructor. // Type: Overrideable. // Args: None. // Return: None. // Throws: None. //-- CMICmnMIOutOfBandRecord::~CMICmnMIOutOfBandRecord() {} //++ //------------------------------------------------------------------------------------ // Details: Return the MI Out-of-band record as a string. The string is a direct // result of // work done on *this Out-of-band record so if not enough data is added // then it is // possible to return a malformed Out-of-band record. If nothing has // been set or // added to *this MI Out-of-band record object then text "<Invalid>" // will be returned. // Type: Method. // Args: None. // Return: CMIUtilString & - MI output text. // Throws: None. //-- const CMIUtilString &CMICmnMIOutOfBandRecord::GetString() const { return m_strAsyncRecord; } //++ //------------------------------------------------------------------------------------ // Details: Add to *this Out-of-band record additional information. // Type: Method. // Args: vResult - (R) A MI result object. // Return: None. // Throws: None. //-- void CMICmnMIOutOfBandRecord::Add(const CMICmnMIValueResult &vResult) { m_strAsyncRecord += ","; m_strAsyncRecord += vResult.GetString(); }
{ "content_hash": "e94e91f34457c632716b7ee8ffc93f5d", "timestamp": "", "source": "github", "line_count": 192, "max_line_length": 86, "avg_line_length": 36.057291666666664, "alnum_prop": 0.6443738263758486, "repo_name": "youtube/cobalt", "id": "029f76e65a856e1ea1720946e12df2c663aa7369", "size": "7415", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "third_party/llvm-project/lldb/tools/lldb-mi/MICmnMIOutOfBandRecord.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
namespace FlatRedBall.Glue.CodeGeneration.CodeBuilder { public class CodeBlockIf : CodeBlockBase { public CodeBlockIf(ICodeBlock pParent, string pCondition) : base(pParent) { PreCodeLines.Add(new CodeLine("if (" + (string.IsNullOrEmpty(pCondition) ? "" : pCondition) + ")")); PreCodeLines.Add(new CodeLine("{")); PostCodeLines.Add(new CodeLine("}")); } } public class CodeBlockElseIf : CodeBlockBase { public CodeBlockElseIf(ICodeBlock pParent, string pCondition) : base(pParent) { PreCodeLines.Add(new CodeLine("else if (" + (string.IsNullOrEmpty(pCondition) ? "" : pCondition) + ")")); PreCodeLines.Add(new CodeLine("{")); PostCodeLines.Add(new CodeLine("}")); } } public class CodeBlockElse : CodeBlockBase { public CodeBlockElse(ICodeBlock pParent) : base(pParent) { PreCodeLines.Add(new CodeLine("else")); PreCodeLines.Add(new CodeLine("{")); PostCodeLines.Add(new CodeLine("}")); } } public static class CodeBlockIfExtensions { public static ICodeBlock If(this ICodeBlock pCodeBlock, string pCondition) { return new CodeBlockIf(pCodeBlock, pCondition); } public static ICodeBlock ElseIf(this ICodeBlock pCodeBlock, string pCondition) { return new CodeBlockElseIf(pCodeBlock, pCondition); } public static ICodeBlock Else(this ICodeBlock pCodeBlock) { return new CodeBlockElse(pCodeBlock); } } }
{ "content_hash": "f4d747c32026d4d8eae32050354dd430", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 117, "avg_line_length": 32.84, "alnum_prop": 0.6065773447015834, "repo_name": "GorillaOne/FlatRedBall", "id": "0274277f0b1216ddfd3134d1a0bb53672fdeef36", "size": "1644", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FRBDK/Glue/Glue/CodeGeneration/CodeBuilder/CodeBlockIf.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1314" }, { "name": "C", "bytes": "335451" }, { "name": "C#", "bytes": "16797833" }, { "name": "C++", "bytes": "321530" }, { "name": "CSS", "bytes": "6282" }, { "name": "HLSL", "bytes": "66557" }, { "name": "HTML", "bytes": "56466" }, { "name": "Logos", "bytes": "167589" }, { "name": "Objective-C", "bytes": "361" }, { "name": "Smalltalk", "bytes": "12" }, { "name": "XSLT", "bytes": "24694" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2011 ArtiVisi Intermedia <info@artivisi.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d %-5level %logger{35} - %msg %n</pattern> </encoder> </appender> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${catalina.home:-.}/logs/training-${stage:-development}.log</file> <encoder> <pattern>%d %-5level %logger{35} - %msg %n</pattern> </encoder> </appender> <include resource="logback-${stage:-development}.xml"/> </configuration>
{ "content_hash": "a3f59e0833bfe2b4c7514fef836927c1", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 80, "avg_line_length": 40.42857142857143, "alnum_prop": 0.7226148409893993, "repo_name": "sulistionoadi/belajar-springmvc-dojo", "id": "79872d723d82161519cb53073503b934323fbda2", "size": "1132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "training-config/src/main/resources/logback.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "21071" }, { "name": "Groovy", "bytes": "64" }, { "name": "Java", "bytes": "159748" }, { "name": "JavaScript", "bytes": "11238911" }, { "name": "PHP", "bytes": "560785" }, { "name": "Perl", "bytes": "282741" }, { "name": "Racket", "bytes": "156311" }, { "name": "Ruby", "bytes": "911" }, { "name": "Scala", "bytes": "1257" }, { "name": "Shell", "bytes": "14241" }, { "name": "XQuery", "bytes": "798" } ], "symlink_target": "" }
package org.apache.jena.rdf.model.test; import java.io.FileNotFoundException ; import java.io.InputStream ; import java.net.URISyntaxException ; import java.net.URL ; import junit.framework.TestCase ; import org.apache.jena.rdf.model.Model ; import org.apache.jena.rdf.model.test.helpers.TestingModelFactory ; /** * Base for all test cases. * * All derived classes will use the getModel to get the model created in the * setUp method. * * createModel will create a model using the TestingModelFactory methods. */ public abstract class AbstractModelTestBase extends TestCase { protected static String getFileName( final String fn ) { URL u = AbstractModelTestBase.class.getClassLoader().getResource( fn ); if (u == null) { throw new RuntimeException( new FileNotFoundException( fn )); } try { return u.toURI().toString(); } catch (URISyntaxException e) { throw new RuntimeException( e ); } } protected InputStream getInputStream( final String fn ) { ClassLoader loader = AbstractModelTestBase.class.getClassLoader(); if (loader == null) throw new SecurityException("Cannot access class loader"); final InputStream in = loader.getResourceAsStream(fn); if (in == null) throw new IllegalArgumentException("Resource: " + fn + " not found on class path."); return in; } public static class LitTestObj { protected long content; public LitTestObj( final long l ) { content = l; } public LitTestObj( final String s ) { content = Long.parseLong(s.substring(1, s.length() - 1)); } @Override public boolean equals( final Object o ) { return (o instanceof LitTestObj) && (content == ((LitTestObj) o).content); } @Override public int hashCode() { return (int) (content ^ (content >> 32)); } @Override public String toString() { return "[" + Long.toString(content) + "]"; } } protected static final boolean tvBoolean = true; protected static final byte tvByte = 1; protected static final short tvShort = 2; protected static final int tvInt = -1; protected static final long tvLong = -2; protected static final char tvChar = '!'; protected static final float tvFloat = (float) 123.456; protected static final double tvDouble = -123.456; protected static final String tvString = "test 12 string"; protected static final Object tvLitObj = new LitTestObj(1234); protected static final LitTestObj tvObject = new LitTestObj(12345); protected static final double dDelta = 0.000000005; protected static final float fDelta = 0.000005f; protected Model model; protected TestingModelFactory modelFactory; public AbstractModelTestBase( final TestingModelFactory modelFactory, final String name ) { super(name); this.modelFactory = modelFactory; } /** * Create a new model. * * @return A new model from the modelFactory. */ public final Model createModel() { return modelFactory.createModel(); } /** * Do not call this. * * This is here to make modification of legacy tests easier. * * @Throws RuntimeException ALWAYS */ public final Model getModel() { throw new RuntimeException( "Do not call getModel() in tests either use model instance variable or call createModel()"); } /** * sets the model instance variable */ @Override public void setUp() { model = createModel(); } /** * Closes the model instance variable and shuts it down. */ @Override public void tearDown() { model.close(); model = null; } }
{ "content_hash": "e0b1ab5c58fcfbeee3f92452cffdbd49", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 96, "avg_line_length": 23.626666666666665, "alnum_prop": 0.6969525959367946, "repo_name": "apache/jena", "id": "4c0b9639bfcddaf3bdd77db555a9c977f0c6d221", "size": "4344", "binary": false, "copies": "16", "ref": "refs/heads/main", "path": "jena-core/src/test/java/org/apache/jena/rdf/model/test/AbstractModelTestBase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "22246" }, { "name": "C++", "bytes": "5877" }, { "name": "CSS", "bytes": "3241" }, { "name": "Dockerfile", "bytes": "3341" }, { "name": "Elixir", "bytes": "2548" }, { "name": "HTML", "bytes": "69029" }, { "name": "Haml", "bytes": "30030" }, { "name": "Java", "bytes": "35185092" }, { "name": "JavaScript", "bytes": "72788" }, { "name": "Lex", "bytes": "82672" }, { "name": "Makefile", "bytes": "198" }, { "name": "Perl", "bytes": "35662" }, { "name": "Python", "bytes": "416" }, { "name": "Ruby", "bytes": "216471" }, { "name": "SCSS", "bytes": "4242" }, { "name": "Shell", "bytes": "264124" }, { "name": "Thrift", "bytes": "3755" }, { "name": "Vue", "bytes": "104702" }, { "name": "XSLT", "bytes": "65126" } ], "symlink_target": "" }
package ch.hearc.corporations.controller; /** * @author Alexandre * */ public final class DataLoaderUtil { public static final class RequestParameters { public static class All { public static final String KEY_WHAT = "what"; public static final String KEY_IDENTIFIER = "identifier"; } public static final class Leaderboard extends All { public static final String WHAT = "leaderboard"; public static final String KEY_START = "start"; public static final String KEY_LIMIT = "limit"; } public static class Profile extends All { public static final String WHAT = "profile"; } public static final class Trips extends All { public static final String WHAT = "trips"; public static final String KEY_LIMIT = "limit"; } public static final class Territories extends All { public static final String WHAT = "territories"; public static final String KEY_LATITUDE = "lat"; public static final String KEY_LONGITUDE = "lng"; public static final String KEY_LIMIT = "limit"; } public static class PurchaseTerritory extends All { public static final String WHAT = "purchaseTerritory"; public static final String KEY_LATITUDE = "lat"; public static final String KEY_LONGITUDE = "lng"; public static final String KEY_OWNER = "owner"; public static final String KEY_PRICE = "price"; } public static final class CaptureTerritory extends All { public static final String WHAT = "captureTerritory"; public static final String KEY_LATITUDE = "lat"; public static final String KEY_LONGITUDE = "lng"; public static final String KEY_OWNER = "owner"; } public static final class Connection extends All { public static final String WHAT = "connection"; public static final String KEY_USER_ID = "user_id"; public static final String KEY_TOKEN = "token"; public static final String KEY_HOME_LATITUDE = "lat"; public static final String KEY_HOME_LONGITUDE = "lng"; } public static final class UpdateProfile extends All { public static final String WHAT = "updateProfile"; public static final String KEY_EXPERIENCE_POINTS_PRICE = "experiencePointsPrice"; public static final String KEY_PURCHASE_PRICE_SKILL_LEVEL = "purchasePriceSkillLevel"; public static final String KEY_PURCHASE_DISTANCE_SKILL_LEVEL = "purchaseDistanceSkillLevel"; public static final String KEY_EXPERIENCE_LIMIT_SKILL_LEVEL = "experienceLimitSkillLevel"; public static final String KEY_MONEY_LIMIT_SKILL_LEVEL = "moneyLimitSkillLevel"; public static final String KEY_EXPERIENCE_QUANTITY_FOUND_SKILL_LEVEL = "experienceQuantityFoundSkillLevel"; public static final String KEY_ALLIANCE_PRICE_SKILL_LEVEL = "alliancePriceSkillLevel"; } public static final class UpdateAlliance extends All { public static final String WHAT = "updateAlliance"; public static final String KEY_ALLY = "ally"; public static final String KEY_CREATE_OR_DELETE = "createOrDelete"; } public static final class UploadTrip extends All { public static final String WHAT = "uploadTrip"; public static final String KEY_DISTANCE = "distance"; public static final String KEY_TIME = "secondes"; public static final String KEY_DATE = "date"; } public static final class ChangePrice extends All { public static final String WHAT = "changePrice"; public static final String KEY_NEW_PRICE = "newPrice"; public static final String KEY_LATITUDE = "lat"; public static final String KEY_LONGITUDE = "lng"; } public static final class StatusKey { public static final int OK = 0; public static final int UNKNOW_IDENTIFIER = 1; public static final int UNKNOW_REQUEST = 2; public static final int INVALID_PARAMETER = 3; public static final int UNKNOWN_ERROR = 4; public static final int OWNER_CHANGE = 5; public static final int NOT_ENOUGTH_MONEY = 6; public static final int PRICE_CHANGE = 7; public static final int ALREADY_EXISTS = 8; public static final int DONT_EXISTS = 9; } } public static final class ResultKeys { public static final class Leaderboard { public static final String USER_ID = "id"; public static final String ALLY = "a"; public static final String NUMBER_OF_TERRITORIES = "nt"; public static final String RANK = "r"; } public static class Profile { public static final String USER_ID = "id"; public static final String NUMBER_OF_ALLIANCE = "na"; public static final String NUMBER_OF_TERRITORIES = "nt"; public static final String RANK = "r"; public static final String CURRENT_MONEY = "cm"; public static final String CURRENT_REVENUE = "cr"; public static final String TRIP_MONEY_EARNED = "tme"; public static final String TOTAL_GAIN = "tg"; public static final String EXPERIENCE_POINTS = "ep"; public static final String HOME_LAT = "hlat"; public static final String HOME_LNG = "hlng"; public static final String PPL = "ppl"; public static final String PDL = "pdl"; public static final String ELL = "ell"; public static final String MLL = "mll"; public static final String EQFL = "eqfl"; public static final String APL = "apl"; } public static final class Trips { public static final String DATE = "da"; public static final String DISTANCE = "d"; public static final String TIME = "t"; public static final String MONEY = "m"; public static final String EXPERIENCE = "e"; } public static class Territories { public static final String OWNER = "o"; public static final String ALLY = "a"; public static final String REVENUE = "r"; public static final String SPECIAL = "s"; public static final String PURCHASE_PRICE = "pp"; public static final String SALE_PRICE = "sp"; public static final String OWNED_TIME = "t"; public static final String LATITUDE = "la"; public static final String LONGITUDE = "lo"; } public static final class PurchaseTerritory extends Territories { } public static final class CaptureTerritory extends Territories { } public static final class Connection extends Profile { } public static final class UpdateProfile extends Profile { } public static final class UpdateAlliance { } public static final class UploadTrip { } public static final String STATUS = "status"; public static final String RESULTS = "results"; public static final class StatusKey { public static final int OK = 0; public static final int UNKNOW_IDENTIFIER = 1; public static final int UNKNOW_REQUEST = 2; public static final int INVALID_PARAMETER = 3; public static final int UNKNOWN_ERROR = 4; public static final int OWNER_CHANGE = 5; public static final int NOT_ENOUGTH_MONEY = 6; public static final int PRICE_CHANGE = 7; public static final int ALREADY_EXISTS = 8; public static final int DONT_EXISTS = 9; } } }
{ "content_hash": "73d04dcaab7b5b7e06ad28851cac100b", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 110, "avg_line_length": 32.87906976744186, "alnum_prop": 0.7005234120809167, "repo_name": "awph/Corporations", "id": "6331cb57e1f29d2ef6670036291b0e6417e9ecbc", "size": "7483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ch/hearc/corporations/controller/DataLoaderUtil.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "211321" } ], "symlink_target": "" }
package com.crowleysimon.cookbook; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import com.crashlytics.android.Crashlytics; import com.readystatesoftware.systembartint.SystemBarTintManager; public class MainActivity extends Activity implements SortFragment.OnFragmentInteractionListener, ResultsFragment.OnFragmentInteractionListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Crashlytics.start(this); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.sort, new SortFragment()) .add(R.id.recipes, new ResultsFragment()) .commit(); } // create our manager instance after the content view is set SystemBarTintManager tintManager = new SystemBarTintManager(this); // enable status bar tint tintManager.setStatusBarTintEnabled(true); tintManager.setStatusBarTintResource(R.color.main_colour_shading); } @Override public void onFragmentInteraction(Uri uri) { } @Override public void newRecipe() { Intent intent = new Intent(this, AddActivity.class); startActivity(intent); } }
{ "content_hash": "e2ebde4922dd79986e8f1a152b21ae3f", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 101, "avg_line_length": 32.63636363636363, "alnum_prop": 0.6692200557103064, "repo_name": "RyanTech/Cookbook-1", "id": "8eaaf2f53d45c63eb33b234bdc3a8f773d430f4c", "size": "1436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/crowleysimon/cookbook/MainActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "30767" } ], "symlink_target": "" }
vizmap = [{"selector":"node","style": {"text-valign":"center", "text-halign":"center", "content": "", "background-color":"rgb(240, 240, 240)", "border-color":"gray", "border-width":"1px", "width":"mapData(degree, 0.0, 100.0, 20.0, 100.0)", "height":"mapData(degree, 0.0, 100.0, 20.0, 100.0)", "font-size":"12px"}}, {selector:"node:selected", css: { "border-color": "gold", "border-width": "3px", }}, {"selector":"node[label='Mesenchymal']", "style":{"font-size":"80px", "width":"0px"}}, {"selector":"node[label='Mesenchymal']", "style":{"font-size":"80px", "width":"0px"}}, {"selector":"node[canonicalName='Molecular Markers']", "style":{"font-size":"80px", "width":"0px"}}, {"selector":"node[label='Proneural']", "style":{"font-size":"80px", "width":"0px"}}, {"selector":"node[label='Proneural G-CIMP']", "style":{"font-size":"80px", "width":"0px"}}, {"selector":"node[label='Neural']", "style":{"font-size":"80px", "width":"0px"}}, {"selector":"node[label='Classical']", "style":{"font-size":"80px", "width":"0px"}}, {"selector":"node[subType='Proneural']", "style":{"border-color":"darkgreen"}}, {"selector":"node[subType='Neural']", "style":{"border-color":"turquoise"}}, {"selector":"node[subType='Mesenchymal']", "style":{"border-color":"blue"}}, {"selector":"node[subType='Classical']", "style":{"border-color":"red"}}, {"selector":"node[subType='G-CIMP']", "style":{"border-color":"purple"}}, {"selector":"node[subType='lgg']", "style":{"border-color":"orange"}}, {"selector":"node[subType='1']", "style":{"border-color":"darkred"}}, {"selector":"node[subType='2']", "style":{"border-color":"red"}}, {"selector":"node[subType='3']", "style":{"border-color":"orange"}}, {"selector":"node[subType='4']", "style":{"border-color":"magenta"}}, {"selector":"node[subType='5']", "style":{"border-color":"blue"}}, {"selector":"node[subType='6']", "style":{"border-color":"cyan"}}, {"selector":"node[subType='7']", "style":{"border-color":"green"}}, {"selector":"node[subType='8']", "style":{"border-color":"yellow"}}, {"selector":"node[subType='high']", "style":{"border-color":"blue"}}, {"selector":"node[subType='low']", "style":{"border-color":"red"}}, {"selector":"node[subType='G2']", "style":{"border-color":"green"}}, {"selector":"node[subType='G3']", "style":{"border-color":"blue"}}, {"selector":"node[subType='G4']", "style":{"border-color":"red"}}, {"selector":"node[subType='NA']", "style":{"border-color":"gray"}}, {"selector":"node[nodeType='chromosome']", style: {"shape":"roundrectangle", "width":"60px", "height":"30px", "content":"data(id)", "border-color":"green", "font-size":"18px" }}, {"selector":"node[nodeType='telomere']", "style":{"shape":"octagon"}}, {selector: "node[cluster='G-CIMP']", style: {"border-color": "purple"}}, {selector: "node[cluster='Classical']", style: {"border-color": "red"}}, {selector: "node[cluster='Proneural']", style: {"border-color": "green"}}, {selector: "node[cluster='Neural']", style: {"border-color": "turquoise"}}, {selector: "node[cluster='Mesenchymal']", style: {"border-color": "blue"}}, {selector: "node[cluster='1']", style: {"border-color": "darkred"}}, {selector: "node[cluster='2']", style: {"border-color": "red"}}, {selector: "node[cluster='3']", style: {"border-color": "orange"}}, {selector: "node[cluster='4']", style: {"border-color": "magenta"}}, {selector: "node[cluster='5']", style: {"border-color": "blue"}}, {selector: "node[cluster='6']", style: {"border-color": "cyan"}}, {selector: "node[cluster='7']", style: {"border-color": "gree"}}, {selector: "node[cluster='8']", style: {"border-color": "forestgreen"}}, {"selector":"edge", "style":{"display":"none", "line-color":"green", "curve-style":"haystack", "source-arrow-shape":"none", "source-arrow-color":"red", "target-arrow-shape":"none"}}, {"selector":"edge[edgeType='chromosome']", "style":{"line-color":"rgb(0,0,128)", "line-style":"solid", "width":"1px", "curve-style": "bezier"}}, {"selector":"edge[edgeType='mutation']", "style":{"line-color":"black", "line-style":"dashed", "width":"1px"}}, {"selector":"edge[edgeType='cnLoss.2']", "style":{"line-color":"rgb(0,100,0)", }}, {"selector":"edge[edgeType='cnGain.2']", "style":{"line-color":"rgb(255,0,0)" }}, {"selector":"edge:selected", "style":{"line-color":"rgb(255,0,0)", "width":"8px"}}];
{ "content_hash": "36d7c4c8ab33fa89305ad5ceb1a41a99", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 81, "avg_line_length": 29.13609467455621, "alnum_prop": 0.5387896019496344, "repo_name": "LisaMc/Oncoscape", "id": "0407224c3f3feb17606b9094740b2602ff4620e9", "size": "4924", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "dataPackages/networks/TCGAbrainMarkersAndTissues/prep/style.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "477" }, { "name": "HTML", "bytes": "1470640" }, { "name": "JavaScript", "bytes": "4564865" }, { "name": "Makefile", "bytes": "13241" }, { "name": "Python", "bytes": "159722" }, { "name": "R", "bytes": "1699435" }, { "name": "Shell", "bytes": "1608" }, { "name": "TeX", "bytes": "8554" } ], "symlink_target": "" }
FOUNDATION_EXPORT double PinkyPromise_tvOSVersionNumber; //! Project version string for PinkyPromise_tvOS. FOUNDATION_EXPORT const unsigned char PinkyPromise_tvOSVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <PinkyPromise_tvOS/PublicHeader.h>
{ "content_hash": "1d0de484055e944d5fbbb886552aa133", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 142, "avg_line_length": 40.75, "alnum_prop": 0.8190184049079755, "repo_name": "willowtreeapps/PinkyPromise", "id": "ac4fa7008015eec48b0247b80a61934e0dac252d", "size": "1677", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "PinkyPromise_tvOS/PinkyPromise_tvOS.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "5029" }, { "name": "Ruby", "bytes": "2333" }, { "name": "Swift", "bytes": "100438" } ], "symlink_target": "" }
/*! * # Semantic UI 2.4.0 - Site * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { $.site = $.fn.site = function(parameters) { var time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.site.settings, parameters) : $.extend({}, $.site.settings), namespace = settings.namespace, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $document = $(document), $module = $document, element = this, instance = $module.data(moduleNamespace), module, returnedValue ; module = { initialize: function() { module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of site', module); instance = module; $module .data(moduleNamespace, module) ; }, normalize: function() { module.fix.console(); module.fix.requestAnimationFrame(); }, fix: { console: function() { module.debug('Normalizing window.console'); if (console === undefined || console.log === undefined) { module.verbose('Console not available, normalizing events'); module.disable.console(); } if (typeof console.group == 'undefined' || typeof console.groupEnd == 'undefined' || typeof console.groupCollapsed == 'undefined') { module.verbose('Console group not available, normalizing events'); window.console.group = function() {}; window.console.groupEnd = function() {}; window.console.groupCollapsed = function() {}; } if (typeof console.markTimeline == 'undefined') { module.verbose('Mark timeline not available, normalizing events'); window.console.markTimeline = function() {}; } }, consoleClear: function() { module.debug('Disabling programmatic console clearing'); window.console.clear = function() {}; }, requestAnimationFrame: function() { module.debug('Normalizing requestAnimationFrame'); if(window.requestAnimationFrame === undefined) { module.debug('RequestAnimationFrame not available, normalizing event'); window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); } ; } } }, moduleExists: function(name) { return ($.fn[name] !== undefined && $.fn[name].settings !== undefined); }, enabled: { modules: function(modules) { var enabledModules = [] ; modules = modules || settings.modules; $.each(modules, function(index, name) { if(module.moduleExists(name)) { enabledModules.push(name); } }); return enabledModules; } }, disabled: { modules: function(modules) { var disabledModules = [] ; modules = modules || settings.modules; $.each(modules, function(index, name) { if(!module.moduleExists(name)) { disabledModules.push(name); } }); return disabledModules; } }, change: { setting: function(setting, value, modules, modifyExisting) { modules = (typeof modules === 'string') ? (modules === 'all') ? settings.modules : [modules] : modules || settings.modules ; modifyExisting = (modifyExisting !== undefined) ? modifyExisting : true ; $.each(modules, function(index, name) { var namespace = (module.moduleExists(name)) ? $.fn[name].settings.namespace || false : true, $existingModules ; if(module.moduleExists(name)) { module.verbose('Changing default setting', setting, value, name); $.fn[name].settings[setting] = value; if(modifyExisting && namespace) { $existingModules = $(':data(module-' + namespace + ')'); if($existingModules.length > 0) { module.verbose('Modifying existing settings', $existingModules); $existingModules[name]('setting', setting, value); } } } }); }, settings: function(newSettings, modules, modifyExisting) { modules = (typeof modules === 'string') ? [modules] : modules || settings.modules ; modifyExisting = (modifyExisting !== undefined) ? modifyExisting : true ; $.each(modules, function(index, name) { var $existingModules ; if(module.moduleExists(name)) { module.verbose('Changing default setting', newSettings, name); $.extend(true, $.fn[name].settings, newSettings); if(modifyExisting && namespace) { $existingModules = $(':data(module-' + namespace + ')'); if($existingModules.length > 0) { module.verbose('Modifying existing settings', $existingModules); $existingModules[name]('setting', newSettings); } } } }); } }, enable: { console: function() { module.console(true); }, debug: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Enabling debug for modules', modules); module.change.setting('debug', true, modules, modifyExisting); }, verbose: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Enabling verbose debug for modules', modules); module.change.setting('verbose', true, modules, modifyExisting); } }, disable: { console: function() { module.console(false); }, debug: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Disabling debug for modules', modules); module.change.setting('debug', false, modules, modifyExisting); }, verbose: function(modules, modifyExisting) { modules = modules || settings.modules; module.debug('Disabling verbose debug for modules', modules); module.change.setting('verbose', false, modules, modifyExisting); } }, console: function(enable) { if(enable) { if(instance.cache.console === undefined) { module.error(error.console); return; } module.debug('Restoring console function'); window.console = instance.cache.console; } else { module.debug('Disabling console function'); instance.cache.console = window.console; window.console = { clear : function(){}, error : function(){}, group : function(){}, groupCollapsed : function(){}, groupEnd : function(){}, info : function(){}, log : function(){}, markTimeline : function(){}, warn : function(){} }; } }, destroy: function() { module.verbose('Destroying previous site for', $module); $module .removeData(moduleNamespace) ; }, cache: {}, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Element' : element, 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { module.destroy(); } module.initialize(); } return (returnedValue !== undefined) ? returnedValue : this ; }; $.site.settings = { name : 'Site', namespace : 'site', error : { console : 'Console cannot be restored, most likely it was overwritten outside of module', method : 'The method you called is not defined.' }, debug : false, verbose : false, performance : true, modules: [ 'accordion', 'api', 'checkbox', 'dimmer', 'dropdown', 'embed', 'form', 'modal', 'nag', 'popup', 'rating', 'shape', 'sidebar', 'state', 'sticky', 'tab', 'transition', 'visit', 'visibility' ], siteNamespace : 'site', namespaceStub : { cache : {}, config : {}, sections : {}, section : {}, utilities : {} } }; // allows for selection of elements with data attributes $.extend($.expr[ ":" ], { data: ($.expr.createPseudo) ? $.expr.createPseudo(function(dataName) { return function(elem) { return !!$.data(elem, dataName); }; }) : function(elem, i, match) { // support: jQuery < 1.8 return !!$.data(elem, match[ 3 ]); } }); })( jQuery, window, document );
{ "content_hash": "a221f0c177e7926e23e43b41e7dd42e9", "timestamp": "", "source": "github", "line_count": 487, "max_line_length": 140, "avg_line_length": 28.987679671457904, "alnum_prop": 0.5315576963944181, "repo_name": "cdnjs/cdnjs", "id": "3321d7280de30f50f3f2b0cf91ddc8e058ff2b1c", "size": "14117", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "ajax/libs/fomantic-ui/2.4.0/components/site.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
title: asl9 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: l9 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
{ "content_hash": "69e7f7dac6d933915aa5b2708cee5c85", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 22.2, "alnum_prop": 0.6636636636636637, "repo_name": "pblack/kaldi-hugo-cms-template", "id": "1a3e9d17abcf087fb93c64797cee2dc35679c77e", "size": "337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/content/pages2/asl9.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "94394" }, { "name": "HTML", "bytes": "18889" }, { "name": "JavaScript", "bytes": "10014" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Class Alcys\Core\Db\Expression\Builder\JoinBuilder</title> <link rel="stylesheet" href="resources/bootstrap.min.css?08b23951ef4599ca9cbf1f902d0e8290c9653ddd"> <link rel="stylesheet" href="resources/style.css?062e9e59e0b8c44fbaaded5b7ffc21f907b78669"> </head> <body> <div id="navigation" class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a href="index.html" class="brand">Overview</a> <div class="nav-collapse"> <ul class="nav"> <li> <a href="namespace-Alcys.Core.Db.Expression.Builder.html" title="Summary of Alcys\Core\Db\Expression\Builder"><span>Namespace</span></a> </li> <li class="active"> <span>Class</span> </li> <li class="divider-vertical"></li> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> <li> <a href="todo.html" title="Todo list"><span>Todo</span></a> </li> <li class="divider-vertical"></li> <li> <a href="API-documentation.zip" title="Download documentation as ZIP archive"><span>Download</span></a> </li> </ul> </div> </div> </div> </div> <div id="left"> <div id="menu"> <form id="search" class="form-search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="search-query" placeholder="Search"> </form> <div id="groups"> <h3>Namespaces</h3> <ul> <li class="active"> <a href="namespace-Alcys.html"> Alcys<span></span> </a> <ul> <li class="active"> <a href="namespace-Alcys.Core.html"> Core<span></span> </a> <ul> <li class="active"> <a href="namespace-Alcys.Core.Db.html"> Db<span></span> </a> <ul> <li class="active"> <a href="namespace-Alcys.Core.Db.Expression.html"> Expression<span></span> </a> <ul> <li class="active"> <a href="namespace-Alcys.Core.Db.Expression.Builder.html"> Builder </a> </li> </ul></li> <li> <a href="namespace-Alcys.Core.Db.Facade.html"> Facade </a> </li> <li> <a href="namespace-Alcys.Core.Db.Factory.html"> Factory </a> </li> <li> <a href="namespace-Alcys.Core.Db.QueryBuilder.html"> QueryBuilder<span></span> </a> <ul> <li> <a href="namespace-Alcys.Core.Db.QueryBuilder.MySql.html"> MySql </a> </li> </ul></li> <li> <a href="namespace-Alcys.Core.Db.References.html"> References<span></span> </a> <ul> <li> <a href="namespace-Alcys.Core.Db.References.MySql.html"> MySql </a> </li> </ul></li> <li> <a href="namespace-Alcys.Core.Db.Service.html"> Service </a> </li> <li> <a href="namespace-Alcys.Core.Db.Statement.html"> Statement </a> </li> </ul></li> <li> <a href="namespace-Alcys.Core.Types.html"> Types </a> </li> </ul></li></ul></li> </ul> </div> <div id="elements"> <h3>Classes</h3> <ul> <li><a href="class-Alcys.Core.Db.Expression.Builder.ConditionBuilder.html">ConditionBuilder</a></li> <li class="active"><a href="class-Alcys.Core.Db.Expression.Builder.JoinBuilder.html">JoinBuilder</a></li> <li><a href="class-Alcys.Core.Db.Expression.Builder.NullBuilder.html">NullBuilder</a></li> </ul> <h3>Interfaces</h3> <ul> <li><a href="class-Alcys.Core.Db.Expression.Builder.ExpressionBuilderInterface.html">ExpressionBuilderInterface</a></li> <li><a href="class-Alcys.Core.Db.Expression.Builder.MultipleExpressionBuilderInterface.html">MultipleExpressionBuilderInterface</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <div id="content" class="class"> <h1>Class JoinBuilder</h1> <div class="description"> <p>Class JoinBuilder</p> </div> <dl class="tree well"> <dd style="padding-left:0px"> <b><span>Alcys\Core\Db\Expression\Builder\JoinBuilder</span></b> implements <a href="class-Alcys.Core.Db.Expression.Builder.ExpressionBuilderInterface.html"><span>Alcys\Core\Db\Expression\Builder\ExpressionBuilderInterface</span></a>, <a href="class-Alcys.Core.Db.Expression.Builder.MultipleExpressionBuilderInterface.html"><span>Alcys\Core\Db\Expression\Builder\MultipleExpressionBuilderInterface</span></a> </dd> </dl> <div class="alert alert-info"> <b>Namespace:</b> <a href="namespace-Alcys.html">Alcys</a>\<a href="namespace-Alcys.Core.html">Core</a>\<a href="namespace-Alcys.Core.Db.html">Db</a>\<a href="namespace-Alcys.Core.Db.Expression.html">Expression</a>\<a href="namespace-Alcys.Core.Db.Expression.Builder.html">Builder</a><br> <b>Package:</b> Alcys\Core\Db\Expression<br> <b>Located at</b> <a href="source-class-Alcys.Core.Db.Expression.Builder.JoinBuilder.html#31-179" title="Go to source code">Core/Db/Expression/Builder/JoinBuilder.php</a> <br> </div> <h2>Methods summary</h2> <table class="summary table table-bordered table-striped methods" id="methods"> <tr data-order="__construct" id="___construct"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#___construct">#</a> <code><a href="source-class-Alcys.Core.Db.Expression.Builder.JoinBuilder.html#63-71" title="Go to source code">__construct</a>( <span><code><a href="class-Alcys.Core.Db.Expression.JoinInterface.html">Alcys\Core\Db\Expression\JoinInterface</a></code> <var>$join</var></span> )</code> <div class="description short"> <p>Initialization of the join builder.</p> </div> <div class="description detailed hidden"> <p>Initialization of the join builder.</p> <h4>Parameters</h4> <div class="list"><dl> <dt><var>$join</var></dt> <dd></dd> </dl></div> </div> </div></td> </tr> <tr data-order="build" id="_build"> <td class="attributes"><code> public string </code> </td> <td class="name"><div> <a class="anchor" href="#_build">#</a> <code><a href="source-class-Alcys.Core.Db.Expression.Builder.JoinBuilder.html#74-104" title="Go to source code">build</a>( )</code> <div class="description short"> <p>Build the join expression string. Processing the passed join expression and return it in form of a string.</p> </div> <div class="description detailed hidden"> <p>Build the join expression string. Processing the passed join expression and return it in form of a string.</p> <h4>Returns</h4> <div class="list"> string<br>The join expression as a string. </div> <h4>Throws</h4> <div class="list"> Exception<br>When the join expression has an invalid format. </div> <h4>See</h4> <div class="list"> JoinBuilder::_checkJoinArray<br> JoinBuilder::_prepareJoinTable<br> JoinBuilder::_prepareJoinCondition<br> </div> <h4>Implementation of</h4> <div class="list"><code><a href="class-Alcys.Core.Db.Expression.Builder.ExpressionBuilderInterface.html#_build">Alcys\Core\Db\Expression\Builder\ExpressionBuilderInterface::build()</a></code></div> </div> </div></td> </tr> <tr data-order="rebuild" id="_rebuild"> <td class="attributes"><code> public string </code> </td> <td class="name"><div> <a class="anchor" href="#_rebuild">#</a> <code><a href="source-class-Alcys.Core.Db.Expression.Builder.JoinBuilder.html#107-127" title="Go to source code">rebuild</a>( <span><code><a href="class-Alcys.Core.Db.Expression.ReBuildableExpressionInterface.html">Alcys\Core\Db\Expression\ReBuildableExpressionInterface</a></code> <var>$join</var></span> )</code> <div class="description short"> <p>Build the join expression string. Processing the passed join expression and return it in form of a string.</p> </div> <div class="description detailed hidden"> <p>Build the join expression string. Processing the passed join expression and return it in form of a string.</p> <h4>Parameters</h4> <div class="list"><dl> <dt><var>$join</var></dt> <dd></dd> </dl></div> <h4>Returns</h4> <div class="list"> string<br>The join expression as a string.<br> string </div> <h4>Throws</h4> <div class="list"> Exception<br>When the join expression has an invalid format. </div> <h4>See</h4> <div class="list"> JoinBuilder::_checkJoinArray<br> JoinBuilder::_prepareJoinTable<br> JoinBuilder::_prepareJoinCondition<br> </div> <h4>Implementation of</h4> <div class="list"><code><a href="class-Alcys.Core.Db.Expression.Builder.MultipleExpressionBuilderInterface.html#_rebuild">Alcys\Core\Db\Expression\Builder\MultipleExpressionBuilderInterface::rebuild()</a></code></div> </div> </div></td> </tr> </table> <h3>Magic methods summary</h3> </div> </div> <div id="footer"> API documentation generated by <a href="http://apigen.org">ApiGen</a> </div> </div> <script src="resources/combined.js"></script> <script src="elementlist.js"></script> </body> </html>
{ "content_hash": "5208f9aac1994e2a4146965196f8def0", "timestamp": "", "source": "github", "line_count": 352, "max_line_length": 317, "avg_line_length": 27.022727272727273, "alnum_prop": 0.6207947855340622, "repo_name": "AlcyZ/Alcys-ORM", "id": "3440c542ab8eebea0c5a9b8562d71f2286b28435", "size": "9512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/APIDocs/class-Alcys.Core.Db.Expression.Builder.JoinBuilder.html", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "255492" } ], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var operators_1 = require("rxjs/operators"); exports.repeatWhen = operators_1.repeatWhen; //# sourceMappingURL=repeatWhen.js.map
{ "content_hash": "ff7f784b87864c59ff23a7e5d110eaaa", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 62, "avg_line_length": 41, "alnum_prop": 0.751219512195122, "repo_name": "friendsofagape/mt2414ui", "id": "bd6050c93293578a3291d1673413a2f21854090b", "size": "205", "binary": false, "copies": "1", "ref": "refs/heads/AMTv2", "path": "node_modules/rxjs-compat/operators/repeatWhen.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10242" }, { "name": "HTML", "bytes": "142509" }, { "name": "JavaScript", "bytes": "2159" }, { "name": "TypeScript", "bytes": "331761" } ], "symlink_target": "" }
import { Breadcrumbs } from "@blueprintjs/core"; import { shell } from "electron"; import React from "react"; import styled from "styled-components"; const Spacer = styled.div` height: 30px; `; const NoWrap = styled.div` white-space: nowrap; position: absolute; width: 250px; * { font-size: 14px !important; background: transparent !important; } li::after { margin: 0 3px !important; } `; // Show the user the most important parts of the file path, as much as // they have space in the message. export const FilePathMessage = (props: { filepath: string }) => <> <NoWrap> <Breadcrumbs items={props.filepath.split("/").map((each, i) => ({ text: each, icon: i === props.filepath.split("/").length - 1 ? "document" : "folder-close", onClick: i === props.filepath.split("/").length - 1 ? () => shell.openItem(props.filepath) : undefined }))}/> </NoWrap> <Spacer/> </>;
{ "content_hash": "dde124678a3c8330cbbe556cb6f2b9b0", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 71, "avg_line_length": 25.333333333333332, "alnum_prop": 0.5951417004048583, "repo_name": "nteract/composition", "id": "de806bf79bb95b0da6c0523d2ebfdf4cbf0dd679", "size": "988", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "applications/desktop/src/common/commands/utils/notifications.tsx", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4743" }, { "name": "HTML", "bytes": "752" }, { "name": "JavaScript", "bytes": "59859" }, { "name": "Jupyter Notebook", "bytes": "4732" }, { "name": "Shell", "bytes": "1020" } ], "symlink_target": "" }
package com.myrunning.leaderboard.web; /** * File: EditCompetitorFormController.java * Author: Joshua Forester * Date: 2009/08/23 * Description: Controller object for the competitor app. **/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.validation.BindException; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import com.myrunning.leaderboard.global.Constants; import com.myrunning.leaderboard.model.Admin; import com.myrunning.leaderboard.model.DataResource; import com.myrunning.leaderboard.model.Identity; import com.myrunning.leaderboard.model.Competitor; import com.myrunning.leaderboard.model.stats.DataCorrelator; import com.myrunning.leaderboard.db.DataAccessFilter; import com.myrunning.leaderboard.db.dao.ifacedao.DataResourceDao; import com.myrunning.leaderboard.db.dao.ifacedao.LastInsertIdDao; import com.myrunning.leaderboard.db.dao.ifacedao.IdentityDao; import com.myrunning.leaderboard.db.dao.ifacedao.CompetitorDao; import com.myrunning.leaderboard.db.dao.ifacedao.PersonDao; public class EditCompetitorFormController extends CompetitorFormController { static Logger logger = Logger.getLogger(EditCompetitorFormController.class); private DataResourceDao dataResourceDao; private LastInsertIdDao lastInsertIdDao; private IdentityDao identityDao; private CompetitorDao competitorDao; private PersonDao personDao; public EditCompetitorFormController() { // empty } protected Object formBackingObject (HttpServletRequest request) throws Exception { Competitor competitor = new Competitor(); long competitor_id = ServletRequestUtils.getLongParameter(request, "competitor_id", 0); Admin admin = (Admin) request.getSession().getAttribute(Constants.ADMIN_SESSION_KEY); if (admin == null) { return competitor; } if (DataAccessFilter.filterDataResourceById(competitor_id, admin.getId()) == null) { return competitor; } if (competitor_id != 0) { WebApplicationContext wac = getWebApplicationContext(); competitorDao = (CompetitorDao) wac.getBean("competitorDao"); competitor = competitorDao.getCompetitorById(competitor_id); } return competitor; } public ModelAndView onSubmit (HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { MDC.put("Session", request.getSession().getId()); logger.debug("handling request"); WebApplicationContext wac = getWebApplicationContext(); dataResourceDao = (DataResourceDao) wac.getBean("dataResourceDao"); lastInsertIdDao = (LastInsertIdDao) wac.getBean("lastInsertIdDao"); identityDao = (IdentityDao) wac.getBean("identityDao"); competitorDao = (CompetitorDao) wac.getBean("competitorDao"); personDao = (PersonDao) wac.getBean("personDao"); Competitor competitor = (Competitor) command; Admin admin = (Admin) request.getSession().getAttribute(Constants.ADMIN_SESSION_KEY); if (admin == null) { return new ModelAndView(Constants.OWNERSHIP_ERROR); } if (DataAccessFilter.filterDataResourceById(competitor, admin.getId()) == null) { return new ModelAndView(Constants.OWNERSHIP_ERROR); } // this is where we need to ensure that someone isn't attempting // to escalate privileges by editing an admin's competitor object // and adding roles to it. get the existing persons roles, add them // here. they should be preserved. not added to. Competitor existingCompetitor = competitorDao.getCompetitorById(competitor.getId()); competitor.setIdentityId(existingCompetitor.getIdentityId()); competitor.setAuthorities(existingCompetitor.getAuthorities()); // set identity here, adding one (and associated DATA_RESOURCE // if it doesn't exist. this means doing vetting to ensure it // is a duplicate if it does exist. this is global and should // go beyond the scope of the RD's data, whereas validation // should only be scoped for the RD's data. Identity identity = DataCorrelator.correlateIdentity(competitor); long identityId = competitor.getIdentityId(); boolean identityChanged = false; if (identity == null) { identity = new Identity(); DataResource dataResource = new DataResource(); dataResource.setAdminId(admin.getId()); dataResourceDao.insertDataResource(dataResource); identity.setId(lastInsertIdDao.getLastInsertId()); identityDao.insertIdentity(identity); competitor.setIdentityId(identity.getId()); identityChanged = true; } else if (identity.getId() != identityId) { competitor.setIdentityId(identity.getId()); identityChanged = true; } competitorDao.updateCompetitor(competitor); // now get rid of old identity if it is orphaned if (identityChanged) { if (personDao.getPersonsByIdentityId(identityId, null, false).isEmpty()) { identityDao.deleteIdentityById(identityId); dataResourceDao.deleteDataResourceById(identityId); } } return new ModelAndView(this.getSuccessView()); } }
{ "content_hash": "914230422430f030941485c49c8f88b9", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 88, "avg_line_length": 33.60897435897436, "alnum_prop": 0.7673087926759489, "repo_name": "joshforester/rdboard", "id": "17b283886bfd8547e3ede0b6e1123bacc161b5c2", "size": "5243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/com/myrunning/leaderboard/web/EditCompetitorFormController.java", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "792" }, { "name": "CSS", "bytes": "181787" }, { "name": "HTML", "bytes": "47328" }, { "name": "Java", "bytes": "790065" }, { "name": "JavaScript", "bytes": "2586273" }, { "name": "PHP", "bytes": "32890" }, { "name": "Shell", "bytes": "3626" } ], "symlink_target": "" }
import unittest from conans import tools from conans.test.utils.tools import TestClient, TestServer from conans.model.ref import ConanFileReference, PackageReference import os from conans.paths import EXPORT_SOURCES_TGZ_NAME, EXPORT_TGZ_NAME, EXPORT_SRC_FOLDER from parameterized.parameterized import parameterized from conans.util.files import load, save, md5sum from conans.model.manifest import FileTreeManifest from collections import OrderedDict from conans.test.utils.test_files import scan_folder conanfile_py = """ from conans import ConanFile class HelloConan(ConanFile): name = "Hello" version = "0.1" exports = "*.h", "*.cpp" def package(self): self.copy("*.h", "include") """ combined_conanfile = """ from conans import ConanFile class HelloConan(ConanFile): name = "Hello" version = "0.1" exports_sources = "*.h", "*.cpp" exports = "*.txt" def package(self): self.copy("*.h", "include") self.copy("data.txt", "docs") """ nested_conanfile = """ from conans import ConanFile class HelloConan(ConanFile): name = "Hello" version = "0.1" exports_sources = "src/*.h", "src/*.cpp" exports = "src/*.txt" def package(self): self.copy("*.h", "include") self.copy("*data.txt", "docs") """ overlap_conanfile = """ from conans import ConanFile class HelloConan(ConanFile): name = "Hello" version = "0.1" exports_sources = "src/*.h", "*.txt" exports = "src/*.txt", "*.h" def package(self): self.copy("*.h", "include") self.copy("*data.txt", "docs") """ class ExportsSourcesTest(unittest.TestCase): def setUp(self): self.server = TestServer() self.other_server = TestServer() servers = OrderedDict([("default", self.server), ("other", self.other_server)]) client = TestClient(servers=servers, users={"default": [("lasote", "mypass")], "other": [("lasote", "mypass")]}) self.client = client self.reference = ConanFileReference.loads("Hello/0.1@lasote/testing") self.package_reference = PackageReference(self.reference, "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9") self.source_folder = self.client.client_cache.source(self.reference) self.package_folder = self.client.client_cache.package(self.package_reference) self.export_folder = self.client.client_cache.export(self.reference) self.export_sources_folder = self.client.client_cache.export_sources(self.reference) def _check_source_folder(self, mode): """ Source folder MUST be always the same """ expected_sources = ["hello.h"] if mode == "both": expected_sources.append("data.txt") if mode == "nested" or mode == "overlap": expected_sources = ["src/hello.h", "src/data.txt"] expected_sources = sorted(expected_sources) self.assertEqual(scan_folder(self.source_folder), expected_sources) def _check_package_folder(self, mode): """ Package folder must be always the same (might have tgz after upload) """ if mode in ["exports", "exports_sources"]: expected_package = ["conaninfo.txt", "conanmanifest.txt", "include/hello.h"] if mode == "both": expected_package = ["conaninfo.txt", "conanmanifest.txt", "include/hello.h", "docs/data.txt"] if mode == "nested" or mode == "overlap": expected_package = ["conaninfo.txt", "conanmanifest.txt", "include/src/hello.h", "docs/src/data.txt"] self.assertEqual(scan_folder(self.package_folder), sorted(expected_package)) def _check_server_folder(self, mode, server=None): if mode == "exports_sources": expected_server = [EXPORT_SOURCES_TGZ_NAME, 'conanfile.py', 'conanmanifest.txt'] if mode == "exports": expected_server = [EXPORT_TGZ_NAME, 'conanfile.py', 'conanmanifest.txt'] if mode == "both" or mode == "nested" or mode == "overlap": expected_server = [EXPORT_TGZ_NAME, EXPORT_SOURCES_TGZ_NAME, 'conanfile.py', 'conanmanifest.txt'] server = server or self.server self.assertEqual(scan_folder(server.paths.export(self.reference)), expected_server) def _check_export_folder(self, mode, export_folder=None, export_src_folder=None): if mode == "exports_sources": expected_src_exports = ["hello.h"] expected_exports = ['conanfile.py', 'conanmanifest.txt'] if mode == "exports": expected_src_exports = [] expected_exports = ["hello.h", 'conanfile.py', 'conanmanifest.txt'] if mode == "both": expected_src_exports = ["hello.h"] expected_exports = ['conanfile.py', 'conanmanifest.txt', "data.txt"] if mode == "nested": expected_src_exports = ["src/hello.h"] expected_exports = ["src/data.txt", 'conanfile.py', 'conanmanifest.txt'] if mode == "overlap": expected_src_exports = ["src/hello.h", "src/data.txt"] expected_exports = ["src/data.txt", "src/hello.h", 'conanfile.py', 'conanmanifest.txt'] self.assertEqual(scan_folder(export_folder or self.export_folder), sorted(expected_exports)) self.assertEqual(scan_folder(export_src_folder or self.export_sources_folder), sorted(expected_src_exports)) def _check_export_installed_folder(self, mode, reuploaded=False, updated=False): """ Just installed, no EXPORT_SOURCES_DIR is present """ if mode == "exports_sources": expected_exports = ['conanfile.py', 'conanmanifest.txt'] if mode == "both": expected_exports = ['conanfile.py', 'conanmanifest.txt', "data.txt"] if reuploaded: expected_exports.append("conan_export.tgz") if mode == "exports": expected_exports = ['conanfile.py', 'conanmanifest.txt', "hello.h"] if reuploaded: expected_exports.append("conan_export.tgz") if mode == "nested": expected_exports = ['conanfile.py', 'conanmanifest.txt', "src/data.txt"] if reuploaded: expected_exports.append("conan_export.tgz") if mode == "overlap": expected_exports = ['conanfile.py', 'conanmanifest.txt', "src/data.txt", "src/hello.h"] if reuploaded: expected_exports.append("conan_export.tgz") if updated: expected_exports.append("license.txt") self.assertEqual(scan_folder(self.export_folder), sorted(expected_exports)) self.assertFalse(os.path.exists(self.export_sources_folder)) def _check_export_uploaded_folder(self, mode, export_folder=None, export_src_folder=None): if mode == "exports_sources": expected_src_exports = ["hello.h"] expected_exports = ['conanfile.py', 'conanmanifest.txt', EXPORT_SOURCES_TGZ_NAME] if mode == "exports": expected_src_exports = [] expected_exports = ["hello.h", 'conanfile.py', 'conanmanifest.txt', EXPORT_TGZ_NAME] if mode == "both": expected_src_exports = ["hello.h"] expected_exports = ['conanfile.py', 'conanmanifest.txt', "data.txt", EXPORT_TGZ_NAME, EXPORT_SOURCES_TGZ_NAME] if mode == "nested": expected_src_exports = ["src/hello.h"] expected_exports = ["src/data.txt", 'conanfile.py', 'conanmanifest.txt', EXPORT_TGZ_NAME, EXPORT_SOURCES_TGZ_NAME] if mode == "overlap": expected_src_exports = ["src/hello.h", "src/data.txt"] expected_exports = ["src/data.txt", "src/hello.h", 'conanfile.py', 'conanmanifest.txt', EXPORT_TGZ_NAME, EXPORT_SOURCES_TGZ_NAME] export_folder = export_folder or self.export_folder self.assertEqual(scan_folder(export_folder), sorted(expected_exports)) self.assertEqual(scan_folder(export_src_folder or self.export_sources_folder), sorted(expected_src_exports)) def _check_manifest(self, mode): manifest = load(os.path.join(self.client.current_folder, ".conan_manifests/Hello/0.1/lasote/testing/export/" "conanmanifest.txt")) if mode == "exports_sources": self.assertIn("%s/hello.h: 5d41402abc4b2a76b9719d911017c592" % EXPORT_SRC_FOLDER, manifest.splitlines()) elif mode == "exports": self.assertIn("hello.h: 5d41402abc4b2a76b9719d911017c592", manifest.splitlines()) elif mode == "both": self.assertIn("data.txt: 8d777f385d3dfec8815d20f7496026dc", manifest.splitlines()) self.assertIn("%s/hello.h: 5d41402abc4b2a76b9719d911017c592" % EXPORT_SRC_FOLDER, manifest.splitlines()) elif mode == "nested": self.assertIn("src/data.txt: 8d777f385d3dfec8815d20f7496026dc", manifest.splitlines()) self.assertIn("%s/src/hello.h: 5d41402abc4b2a76b9719d911017c592" % EXPORT_SRC_FOLDER, manifest.splitlines()) else: assert mode == "overlap" self.assertIn("src/data.txt: 8d777f385d3dfec8815d20f7496026dc", manifest.splitlines()) self.assertIn("src/hello.h: 5d41402abc4b2a76b9719d911017c592", manifest.splitlines()) self.assertIn("%s/src/hello.h: 5d41402abc4b2a76b9719d911017c592" % EXPORT_SRC_FOLDER, manifest.splitlines()) self.assertIn("%s/src/data.txt: 8d777f385d3dfec8815d20f7496026dc" % EXPORT_SRC_FOLDER, manifest.splitlines()) def _create_code(self, mode): if mode == "exports": conanfile = conanfile_py elif mode == "exports_sources": conanfile = conanfile_py.replace("exports", "exports_sources") elif mode == "both": conanfile = combined_conanfile elif mode == "nested": conanfile = nested_conanfile elif mode == "overlap": conanfile = overlap_conanfile if mode in ["nested", "overlap"]: self.client.save({"conanfile.py": conanfile, "src/hello.h": "hello", "src/data.txt": "data"}) else: self.client.save({"conanfile.py": conanfile, "hello.h": "hello", "data.txt": "data"}) @parameterized.expand([("exports", ), ("exports_sources", ), ("both", ), ("nested", ), ("overlap", )]) def copy_test(self, mode): # https://github.com/conan-io/conan/issues/943 self._create_code(mode) self.client.run("export . lasote/testing") self.client.run("install Hello/0.1@lasote/testing --build=missing") self.client.run("upload Hello/0.1@lasote/testing --all") self.client.run('remove Hello/0.1@lasote/testing -f') self.client.run("install Hello/0.1@lasote/testing") # new copied package data reference = ConanFileReference.loads("Hello/0.1@lasote/stable") source_folder = self.client.client_cache.source(reference) export_folder = self.client.client_cache.export(reference) self.client.run("copy Hello/0.1@lasote/testing lasote/stable") self._check_export_folder(mode, export_folder) self.client.run("upload Hello/0.1@lasote/stable") self.assertFalse(os.path.exists(source_folder)) self._check_export_uploaded_folder(mode, export_folder) self._check_server_folder(mode) @parameterized.expand([("exports", ), ("exports_sources", ), ("both", ), ("nested", ), ("overlap", )]) def export_test(self, mode): self._create_code(mode) self.client.run("export . lasote/testing") self._check_export_folder(mode) # now build package self.client.run("install Hello/0.1@lasote/testing --build=missing") # Source folder and package should be exatly the same self._check_export_folder(mode) self._check_source_folder(mode) self._check_package_folder(mode) # upload to remote self.client.run("upload Hello/0.1@lasote/testing --all") self._check_export_uploaded_folder(mode) self._check_server_folder(mode) # remove local self.client.run('remove Hello/0.1@lasote/testing -f') self.assertFalse(os.path.exists(self.export_folder)) # install from remote self.client.run("install Hello/0.1@lasote/testing") self.assertFalse(os.path.exists(self.source_folder)) self._check_export_installed_folder(mode) self._check_package_folder(mode) # Manifests must work too! self.client.run("install Hello/0.1@lasote/testing --manifests") self.assertFalse(os.path.exists(self.source_folder)) # The manifests retrieve the normal state, as it retrieves sources self._check_export_folder(mode) self._check_package_folder(mode) self._check_manifest(mode) # lets try to verify self.client.run('remove Hello/0.1@lasote/testing -f') self.assertFalse(os.path.exists(self.export_folder)) self.client.run("install Hello/0.1@lasote/testing --verify") self.assertFalse(os.path.exists(self.source_folder)) # The manifests retrieve the normal state, as it retrieves sources self._check_export_folder(mode) self._check_package_folder(mode) self._check_manifest(mode) @parameterized.expand([("exports", ), ("exports_sources", ), ("both", ), ("nested", ), ("overlap", )]) def export_upload_test(self, mode): self._create_code(mode) self.client.run("export . lasote/testing") self.client.run("upload Hello/0.1@lasote/testing") self.assertFalse(os.path.exists(self.source_folder)) self._check_export_uploaded_folder(mode) self._check_server_folder(mode) # remove local self.client.run('remove Hello/0.1@lasote/testing -f') self.assertFalse(os.path.exists(self.export_folder)) # install from remote self.client.run("install Hello/0.1@lasote/testing --build") self._check_export_folder(mode) self._check_source_folder(mode) self._check_package_folder(mode) # Manifests must work too! self.client.run("install Hello/0.1@lasote/testing --manifests") # The manifests retrieve the normal state, as it retrieves sources self._check_export_folder(mode) self._check_package_folder(mode) self._check_manifest(mode) @parameterized.expand([("exports", ), ("exports_sources", ), ("both", ), ("nested", ), ("overlap", )]) def reupload_test(self, mode): """ try to reupload to same and other remote """ self._create_code(mode) self.client.run("export . lasote/testing") self.client.run("install Hello/0.1@lasote/testing --build=missing") self.client.run("upload Hello/0.1@lasote/testing --all") self.client.run('remove Hello/0.1@lasote/testing -f') self.client.run("install Hello/0.1@lasote/testing") # upload to remote again, the folder remains as installed self.client.run("upload Hello/0.1@lasote/testing --all") self._check_export_installed_folder(mode, reuploaded=True) self._check_server_folder(mode) self.client.run("upload Hello/0.1@lasote/testing --all -r=other") self._check_export_uploaded_folder(mode) self._check_server_folder(mode, self.other_server) @parameterized.expand([("exports", ), ("exports_sources", ), ("both", ), ("nested", ), ("overlap", )]) def update_test(self, mode): self._create_code(mode) self.client.run("export . lasote/testing") self.client.run("install Hello/0.1@lasote/testing --build=missing") self.client.run("upload Hello/0.1@lasote/testing --all") self.client.run('remove Hello/0.1@lasote/testing -f') self.client.run("install Hello/0.1@lasote/testing") # upload to remote again, the folder remains as installed self.client.run("install Hello/0.1@lasote/testing --update") self.assertIn("Hello/0.1@lasote/testing: Already installed!", self.client.user_io.out) self._check_export_installed_folder(mode) server_path = self.server.paths.export(self.reference) save(os.path.join(server_path, "license.txt"), "mylicense") manifest = FileTreeManifest.load(server_path) manifest.time += 1 manifest.file_sums["license.txt"] = md5sum(os.path.join(server_path, "license.txt")) manifest.save(server_path) self.client.run("install Hello/0.1@lasote/testing --update") self._check_export_installed_folder(mode, updated=True) def exports_sources_old_c_src_test(self): conanfile = """ import os from conans import ConanFile class HelloConan(ConanFile): exports_sources = "*" def build(self): # won't be run in create but in the install from remote, we are emulating old .c_src # in the package if not os.environ.get("SKIP_THIS"): # This dir has to exists after the install assert(os.path.exists("modules/Hello/projects/Hello/myfile.txt")) """ # Fake old package layout with .c_src self.client.save({"conanfile.py": conanfile, ".c_src/modules/Hello/projects/Hello/myfile.txt": "contents"}) with tools.environment_append({"SKIP_THIS": "1"}): self.client.run("create . Hello/0.1@lasote/channel") self.client.run("upload Hello/0.1@lasote/channel --all") self.client.run('remove "*" -f') self.client.run("install Hello/0.1@lasote/channel --build")
{ "content_hash": "43bc353bd806db69ce346041df3456bf", "timestamp": "", "source": "github", "line_count": 425, "max_line_length": 99, "avg_line_length": 43.510588235294115, "alnum_prop": 0.6009625784122864, "repo_name": "birsoyo/conan", "id": "1145b0059c3b602c0f09fa277b8d723a32f1ec93", "size": "18492", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "conans/test/integration/export_sources_test.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1100" }, { "name": "Groovy", "bytes": "6251" }, { "name": "Python", "bytes": "3101477" }, { "name": "Shell", "bytes": "1864" } ], "symlink_target": "" }
module Fayde.Controls.Internal { export class BindingSourceEvaluator<T> extends FrameworkElement { static ValueProperty = DependencyProperty.Register("Value", () => Object, BindingSourceEvaluator); Value: T; private _ValueBinding: Data.Binding = null; get ValueBinding(): Data.Binding { return this._ValueBinding; } constructor(binding:Data.Binding) { super(); this._ValueBinding = binding; } GetDynamicValue(source: any): T { var vb = this._ValueBinding; var binding1 = new Data.Binding(); binding1.BindsDirectlyToSource = vb.BindsDirectlyToSource; binding1.Converter = vb.Converter; binding1.ConverterCulture = vb.ConverterCulture; binding1.ConverterParameter = vb.ConverterParameter; binding1.FallbackValue = vb.FallbackValue; binding1.Mode = vb.Mode; binding1.NotifyOnValidationError = vb.NotifyOnValidationError; binding1.Path = vb.Path; binding1.StringFormat = vb.StringFormat; binding1.TargetNullValue = vb.TargetNullValue; binding1.UpdateSourceTrigger = vb.UpdateSourceTrigger; binding1.ValidatesOnDataErrors = vb.ValidatesOnDataErrors; binding1.ValidatesOnExceptions = vb.ValidatesOnExceptions; binding1.ValidatesOnNotifyDataErrors = vb.ValidatesOnNotifyDataErrors; binding1.Source = source; this.SetBinding(BindingSourceEvaluator.ValueProperty, binding1); var obj = <T>this.Value; this.ClearValue(BindingSourceEvaluator.ValueProperty); return obj; } } }
{ "content_hash": "255675a9883ca6e576911c7c22d79c48", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 106, "avg_line_length": 43.146341463414636, "alnum_prop": 0.6302996042962126, "repo_name": "BlokDust/BlokDust", "id": "58ad09a352f7ce78eb70803e96b96369789136aa", "size": "1769", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/lib/fayde.controls/src/Internal/BindingSourceEvaluator.ts", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "11956" }, { "name": "CoffeeScript", "bytes": "92" }, { "name": "HTML", "bytes": "59905" }, { "name": "JavaScript", "bytes": "5801102" }, { "name": "Makefile", "bytes": "135" }, { "name": "Python", "bytes": "981" }, { "name": "Shell", "bytes": "2275" }, { "name": "TypeScript", "bytes": "3047228" } ], "symlink_target": "" }
#include "ncurses/window/window_agent.h" #include <curses.h> /********************************************************************/ /** Agent Commands **/ /********************************************************************/ static TACommandVerdict copywin_cmd(TAThread thread,TAInputStream stream) { WINDOW* srcwin, *dstwin; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol, overlay, res; srcwin = readPointer(&stream); dstwin = readPointer(&stream); sminrow = readInt(&stream); smincol = readInt(&stream); dminrow = readInt(&stream); dmincol = readInt(&stream); dmaxrow = readInt(&stream); dmaxcol = readInt(&stream); overlay = readInt(&stream); START_TARGET_OPERATION(thread); res = copywin(srcwin, dstwin, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol, overlay); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict curs_set_cmd(TAThread thread,TAInputStream stream) { int res, visibility; visibility = readInt(&stream); START_TARGET_OPERATION(thread); res = curs_set(visibility); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict delwin_cmd(TAThread thread,TAInputStream stream) { WINDOW* win; int res; win = readPointer(&stream); START_TARGET_OPERATION(thread); res = delwin(win); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict derwin_cmd(TAThread thread,TAInputStream stream) { WINDOW* orig, *res; int nlines, ncols, begin_y, begin_x; orig = readPointer(&stream); nlines = readInt(&stream); ncols = readInt(&stream); begin_y = readInt(&stream); begin_x = readInt(&stream); START_TARGET_OPERATION(thread); res = derwin(orig, nlines, ncols, begin_y, begin_x); END_TARGET_OPERATION(thread); writePointer(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict dupwin_cmd(TAThread thread,TAInputStream stream) { WINDOW* win, *res; win = readPointer(&stream); START_TARGET_OPERATION(thread); res = dupwin(win); END_TARGET_OPERATION(thread); writePointer(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict getwin_cmd(TAThread thread,TAInputStream stream) { char* filename; FILE* filep; WINDOW *res; filename = readString(&stream); filep = fopen(filename, "r+"); START_TARGET_OPERATION(thread); res = getwin(filep); END_TARGET_OPERATION(thread); fclose(filep); writePointer(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict intrflush_cmd(TAThread thread,TAInputStream stream) { WINDOW* win; int res, bf; win = readPointer(&stream); bf = readInt(&stream); START_TARGET_OPERATION(thread); res = intrflush(win, bf); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict keypad_cmd(TAThread thread,TAInputStream stream) { WINDOW* win; int res, bf; win = readPointer(&stream); bf = readInt(&stream); START_TARGET_OPERATION(thread); res = keypad(win, bf); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict meta_cmd(TAThread thread,TAInputStream stream) { WINDOW* win; int res, bf; win = readPointer(&stream); bf = readInt(&stream); START_TARGET_OPERATION(thread); res = meta(win, bf); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict mvderwin_cmd(TAThread thread,TAInputStream stream) { WINDOW* win; int res, y, x; win = readPointer(&stream); y = readInt(&stream); x = readInt(&stream); START_TARGET_OPERATION(thread); res = mvderwin(win, y, x); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict mvwin_cmd(TAThread thread,TAInputStream stream) { WINDOW* win; int y, x, res; win = readPointer(&stream); y = readInt(&stream); x = readInt(&stream); START_TARGET_OPERATION(thread); res = mvwin(win, y, x); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict newwin_cmd(TAThread thread,TAInputStream stream) { WINDOW* res; int nlines, ncols, begin_y, begin_x, lines, cols; ta_debug_printf("NewWin!\n"); nlines=readInt(&stream); ncols=readInt(&stream); begin_y=readInt(&stream); begin_x=readInt(&stream); START_TARGET_OPERATION(thread); res = newwin(nlines, ncols, begin_y, begin_x); END_TARGET_OPERATION(thread); writePointer(thread, res); getmaxyx(res, lines, cols); writeInt(thread, cols); writeInt(thread, lines); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict nodelay_cmd(TAThread thread,TAInputStream stream) { WINDOW* win; int res, bf; win = readPointer(&stream); bf = readInt(&stream); START_TARGET_OPERATION(thread); res = nodelay(win, bf); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict overlay_cmd(TAThread thread,TAInputStream stream) { WINDOW* srcwin, *dstwin; int res; srcwin = readPointer(&stream); dstwin = readPointer(&stream); START_TARGET_OPERATION(thread); res = overlay(srcwin, dstwin); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict overwrite_cmd(TAThread thread,TAInputStream stream) { WINDOW* srcwin, *dstwin; int res; srcwin = readPointer(&stream); dstwin = readPointer(&stream); START_TARGET_OPERATION(thread); res = overwrite(srcwin, dstwin); END_TARGET_OPERATION(thread); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict putwin_cmd(TAThread thread,TAInputStream stream) { char* filename; FILE* filep; WINDOW *win; int res; win = readPointer(&stream); filename = readString(&stream); filep = fopen(filename, "w+"); START_TARGET_OPERATION(thread); res = putwin(win, filep); END_TARGET_OPERATION(thread); fclose(filep); writeInt(thread, res); sendResponse(thread); return taDefaultVerdict; } static TACommandVerdict subwin_cmd(TAThread thread,TAInputStream stream) { WINDOW* orig, *res; int nlines, ncols, begin_y, begin_x; orig = readPointer(&stream); nlines = readInt(&stream); ncols = readInt(&stream); begin_y = readInt(&stream); begin_x = readInt(&stream); START_TARGET_OPERATION(thread); res = subwin(orig, nlines, ncols, begin_y, begin_x); END_TARGET_OPERATION(thread); writePointer(thread, res); sendResponse(thread); return taDefaultVerdict; } /********************************************************************/ /** Agent Initialization **/ /********************************************************************/ void register_ncurses_window_window_commands(void) { ta_register_command("copywin",copywin_cmd); ta_register_command("curs_set",curs_set_cmd); ta_register_command("delwin",delwin_cmd); ta_register_command("derwin",derwin_cmd); ta_register_command("dupwin",dupwin_cmd); ta_register_command("getwin",getwin_cmd); ta_register_command("intrflush",intrflush_cmd); ta_register_command("keypad",keypad_cmd); ta_register_command("meta",meta_cmd); ta_register_command("mvderwin",mvderwin_cmd); ta_register_command("mvwin",mvwin_cmd); ta_register_command("newwin",newwin_cmd); ta_register_command("nodelay",nodelay_cmd); ta_register_command("overlay",overlay_cmd); ta_register_command("overwrite",overwrite_cmd); ta_register_command("putwin",putwin_cmd); ta_register_command("subwin",subwin_cmd); }
{ "content_hash": "bb111f4fee977a86411f8ec2444aa181", "timestamp": "", "source": "github", "line_count": 373, "max_line_length": 78, "avg_line_length": 23.289544235924932, "alnum_prop": 0.6337055370093243, "repo_name": "levenkov/olver", "id": "b7893f141889c9da7fc5c4ba7127579e51026bee", "size": "8923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/agent/ncurses/window/window_agent.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "603" }, { "name": "C", "bytes": "2083994" }, { "name": "C++", "bytes": "129137" }, { "name": "GAP", "bytes": "8091" }, { "name": "Objective-C", "bytes": "6840" }, { "name": "Shell", "bytes": "28776" } ], "symlink_target": "" }
<?php namespace Magento\Theme\Block\Html; use Magento\Framework\View\Element\Template; /** * Html page title block * * @method $this setTitleId($titleId) * @method $this setTitleClass($titleClass) * @method string getTitleId() * @method string getTitleClass() */ class Title extends \Magento\Framework\View\Element\Template { /** * Own page title to display on the page * * @var string */ protected $pageTitle; /** * Provide own page title or pick it from Head Block * * @return string */ public function getPageTitle() { if (!empty($this->pageTitle)) { return $this->pageTitle; } return __($this->pageConfig->getTitle()->getShort()); } /** * Provide own page content heading * * @return string */ public function getPageHeading() { if (!empty($this->pageTitle)) { return __($this->pageTitle); } return __($this->pageConfig->getTitle()->getShortHeading()); } /** * Set own page title * * @param string $pageTitle * @return void */ public function setPageTitle($pageTitle) { $this->pageTitle = $pageTitle; } }
{ "content_hash": "563e9e5421bd4c2b1a2ed21ee6f57687", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 68, "avg_line_length": 20.716666666666665, "alnum_prop": 0.5711987127916331, "repo_name": "j-froehlich/magento2_wk", "id": "45f5e56dca0958742657c3566ed06c6286dc6aca", "size": "1351", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/magento/module-theme/Block/Html/Title.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
Usage: python benchmark/run.py structured_data_classification report.csv
{ "content_hash": "368f4169b24b32e43f34a1ff6e74101f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 72, "avg_line_length": 73, "alnum_prop": 0.8493150684931506, "repo_name": "keras-team/autokeras", "id": "ebf58d24fb1005a624e43b5f7db36d809add385a", "size": "73", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "benchmark/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1005" }, { "name": "JavaScript", "bytes": "307" }, { "name": "Makefile", "bytes": "704" }, { "name": "Python", "bytes": "548809" }, { "name": "Shell", "bytes": "2084" } ], "symlink_target": "" }
package sun.jvm.hotspot.types.basic; import sun.jvm.hotspot.debugger.*; import sun.jvm.hotspot.types.*; /** A specialization of BasicField adding typechecked getValue() routines returning ints. */ public class BasicCIntegerField extends BasicField implements CIntegerField { private CIntegerType intType; public BasicCIntegerField(BasicTypeDataBase db, Type containingType, String name, Type type, boolean isStatic, long offset, Address staticFieldAddress) { super(db, containingType, name, type, isStatic, offset, staticFieldAddress); if (!(type instanceof CIntegerType)) { throw new WrongTypeException("Type of a BasicCIntegerField must be a CIntegerType"); } intType = (CIntegerType) type; } public boolean isUnsigned() { return intType.isUnsigned(); } /** The field must be nonstatic and of integer type, or a WrongTypeException will be thrown. */ public long getValue(Address addr) throws UnmappedAddressException, UnalignedAddressException, WrongTypeException { return getCInteger(addr, intType); } /** The field must be static and of integer type, or a WrongTypeException will be thrown. */ public long getValue() throws UnmappedAddressException, UnalignedAddressException, WrongTypeException { return getCInteger(intType); } }
{ "content_hash": "35fe0557d6249f62d01ba01b6b2c0026", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 117, "avg_line_length": 33.65, "alnum_prop": 0.736998514115899, "repo_name": "rokn/Count_Words_2015", "id": "e8dd91290aa319939e0ffba423c9f8ea09b6a2d8", "size": "2405", "binary": false, "copies": "106", "ref": "refs/heads/master", "path": "testing/openjdk/hotspot/agent/src/share/classes/sun/jvm/hotspot/types/basic/BasicCIntegerField.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
FROM debian_base # https://hub.docker.com/_/debian/ LABEL MAINTAINER="WaterBolik@163.com" # 安装Docker CE # ARG APT_MIRROR=download.docker.com ARG APT_MIRROR=mirrors.aliyun.com/docker-ce RUN set -eux \ && apt-get update -y --fix-missing \ && apt-get install -y \ apt-transport-https \ ca-certificates \ curl \ gnupg2 \ software-properties-common \ && curl -fsSL https://${APT_MIRROR}/linux/debian/gpg \ | apt-key add - \ && apt-key fingerprint 0EBFCD88 \ && add-apt-repository \ "deb [arch=amd64] https://${APT_MIRROR}/linux/debian \ $(lsb_release -cs) \ stable" \ && apt-get update -y --fix-missing \ && apt-get install -y --no-install-recommends \ docker-ce \ && apt-get autoclean \ && apt-get autoremove \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /etc/docker \ && { \ echo '{'; \ echo ' "registry-mirrors": ['; \ echo ' "https://registry.docker-cn.com"'; \ echo ' ]'; \ echo '}'; \ } > /etc/docker/daemon.json \ && systemctl enable docker \ && echo "end" # && curl -fsSL get.docker.com -o get-docker.sh \ # && sh get-docker.sh \ # 显示可安装稳定版Docker # apt-cache madison docker-ce # && pip install docker-compose \ # && apt-get -y install \ # docker-compose \ # 安装Docker CE # RUN set -euxo pipefail \ # && curl -fsSL get.docker.com -o get-docker.sh \ # && sh get-docker.sh \ # && yum clean all \ # && systemctl enable docker \ # && echo "end" # $ docker build -t dockerindebian /Volumes/Work/OpenSource/WaterBolik/prestudy/bdocker/docker/dockerindebian/ # $ docker build -t dockerindebian ~/OpenSource/WaterBolik/prestudy/bdocker/docker/dockerindebian/ # $ docker build -t dockerindebian B:/OpenSource/WaterBolik/prestudy/bdocker/docker/dockerindebian/ # $ docker run -it --rm --name dockerindebian --privileged=true -d dockerindebian # $ docker exec -it dockerindebian bash # $ docker stop dockerindebian
{ "content_hash": "c4437a539b079a4b34c3fef80d4444a0", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 110, "avg_line_length": 33.935483870967744, "alnum_prop": 0.5903041825095057, "repo_name": "waterbolik/prestudy", "id": "7e99c528544655c860f08399954ee5cf5bf52210", "size": "2128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bdocker/Docker/dockerindebian/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "5775" }, { "name": "Awk", "bytes": "11528" }, { "name": "Batchfile", "bytes": "39539" }, { "name": "C", "bytes": "11942178" }, { "name": "C++", "bytes": "12015954" }, { "name": "CMake", "bytes": "45024" }, { "name": "CSS", "bytes": "234890" }, { "name": "CoffeeScript", "bytes": "1656" }, { "name": "Go", "bytes": "522" }, { "name": "HTML", "bytes": "15857725" }, { "name": "Java", "bytes": "137764" }, { "name": "JavaScript", "bytes": "433952" }, { "name": "M4", "bytes": "250490" }, { "name": "Makefile", "bytes": "1091030" }, { "name": "PHP", "bytes": "2407" }, { "name": "Perl", "bytes": "33243" }, { "name": "PowerShell", "bytes": "24877" }, { "name": "Python", "bytes": "510239" }, { "name": "QMake", "bytes": "4125" }, { "name": "Roff", "bytes": "33580" }, { "name": "Scheme", "bytes": "1570" }, { "name": "Shell", "bytes": "1151730" }, { "name": "TypeScript", "bytes": "12747" }, { "name": "XSLT", "bytes": "9232" } ], "symlink_target": "" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsBIG5ToUnicode.h" #include "nsUCvTWDll.h" #include "nsUCConstructors.h" //---------------------------------------------------------------------- // Global functions and data [declaration] static const uScanClassID g_BIG5ScanClassIDs[] = { u1ByteCharset, u2BytesCharset }; static const uint16_t *g_BIG5MappingTableSet [] ={ g_ASCIIMapping, g_utBIG5Mapping }; static const uRange g_BIG5Ranges[] = { { 0x00, 0x7E }, { 0x81, 0xFE } }; nsresult nsBIG5ToUnicodeConstructor(nsISupports *aOuter, REFNSIID aIID, void **aResult) { return CreateMultiTableDecoder(2, (const uRange* ) &g_BIG5Ranges, (uScanClassID*) &g_BIG5ScanClassIDs, (uMappingTable**) &g_BIG5MappingTableSet, 1, aOuter, aIID, aResult); }
{ "content_hash": "338a499e8a39fed18c573fcd7d12acab", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 79, "avg_line_length": 30.076923076923077, "alnum_prop": 0.5703324808184144, "repo_name": "sergecodd/FireFox-OS", "id": "a931958095dd30f6f44dbf523989bab97194ff12", "size": "1173", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "B2G/gecko/intl/uconv/ucvtw/nsBIG5ToUnicode.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "443" }, { "name": "ApacheConf", "bytes": "85" }, { "name": "Assembly", "bytes": "5123438" }, { "name": "Awk", "bytes": "46481" }, { "name": "Batchfile", "bytes": "56250" }, { "name": "C", "bytes": "101720951" }, { "name": "C#", "bytes": "38531" }, { "name": "C++", "bytes": "148896543" }, { "name": "CMake", "bytes": "23541" }, { "name": "CSS", "bytes": "2758664" }, { "name": "DIGITAL Command Language", "bytes": "56757" }, { "name": "Emacs Lisp", "bytes": "12694" }, { "name": "Erlang", "bytes": "889" }, { "name": "FLUX", "bytes": "34449" }, { "name": "GLSL", "bytes": "26344" }, { "name": "Gnuplot", "bytes": "710" }, { "name": "Groff", "bytes": "447012" }, { "name": "HTML", "bytes": "43343468" }, { "name": "IDL", "bytes": "1455122" }, { "name": "Java", "bytes": "43261012" }, { "name": "JavaScript", "bytes": "46646658" }, { "name": "Lex", "bytes": "38358" }, { "name": "Logos", "bytes": "21054" }, { "name": "Makefile", "bytes": "2733844" }, { "name": "Matlab", "bytes": "67316" }, { "name": "Max", "bytes": "3698" }, { "name": "NSIS", "bytes": "421625" }, { "name": "Objective-C", "bytes": "877657" }, { "name": "Objective-C++", "bytes": "737713" }, { "name": "PHP", "bytes": "17415" }, { "name": "Pascal", "bytes": "6780" }, { "name": "Perl", "bytes": "1153180" }, { "name": "Perl6", "bytes": "1255" }, { "name": "PostScript", "bytes": "1139" }, { "name": "PowerShell", "bytes": "8252" }, { "name": "Protocol Buffer", "bytes": "26553" }, { "name": "Python", "bytes": "8453201" }, { "name": "Ragel in Ruby Host", "bytes": "3481" }, { "name": "Ruby", "bytes": "5116" }, { "name": "Scilab", "bytes": "7" }, { "name": "Shell", "bytes": "3383832" }, { "name": "SourcePawn", "bytes": "23661" }, { "name": "TeX", "bytes": "879606" }, { "name": "WebIDL", "bytes": "1902" }, { "name": "XSLT", "bytes": "13134" }, { "name": "Yacc", "bytes": "112744" } ], "symlink_target": "" }
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dfp.axis.v201502.audiencesegmentservice; import com.google.api.ads.common.lib.auth.OfflineCredentials; import com.google.api.ads.common.lib.auth.OfflineCredentials.Api; import com.google.api.ads.dfp.axis.factory.DfpServices; import com.google.api.ads.dfp.axis.utils.v201502.StatementBuilder; import com.google.api.ads.dfp.axis.v201502.AudienceSegment; import com.google.api.ads.dfp.axis.v201502.AudienceSegmentPage; import com.google.api.ads.dfp.axis.v201502.AudienceSegmentServiceInterface; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.api.client.auth.oauth2.Credential; /** * This example gets all audience segments. To create audience segments, run * CreateAudienceSegments.java. * * Credentials and properties in {@code fromFile()} are pulled from the * "ads.properties" file. See README for more info. * * Tags: AudienceSegmentService.getAudienceSegmentsByStatement * * @author Adam Rogal */ public class GetAllAudienceSegments { public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception { // Get the AudienceSegmentService. AudienceSegmentServiceInterface audienceSegmentService = dfpServices.get(session, AudienceSegmentServiceInterface.class); // Create a statement to select all audience segments. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get audience segments by statement. AudienceSegmentPage page = audienceSegmentService.getAudienceSegmentsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (AudienceSegment audienceSegment : page.getResults()) { System.out.printf( "%d) Audience segment with ID \"%d\" and name \"%s\" of size " + "\"%d\" was found.%n", i++, audienceSegment.getId(), audienceSegment.getName(), audienceSegment.getSize()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); } public static void main(String[] args) throws Exception { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.DFP) .fromFile() .build() .generateCredential(); // Construct a DfpSession. DfpSession session = new DfpSession.Builder() .fromFile() .withOAuth2Credential(oAuth2Credential) .build(); DfpServices dfpServices = new DfpServices(); runExample(dfpServices, session); } }
{ "content_hash": "6d21ee510ac39b354585e08521d6bff0", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 96, "avg_line_length": 37.447916666666664, "alnum_prop": 0.7143254520166898, "repo_name": "andyj24/googleads-java-lib", "id": "3ca833a78ed490faea00ce5ec0a3635fdb4d2f56", "size": "3595", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "examples/dfp_axis/src/main/java/dfp/axis/v201502/audiencesegmentservice/GetAllAudienceSegments.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "89458532" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fr-FR"> <title>Linux WebDrivers</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
{ "content_hash": "9067a8509d2bad0969a902147f302709", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 184, "avg_line_length": 25.289473684210527, "alnum_prop": 0.6389177939646202, "repo_name": "denniskniep/zap-extensions", "id": "32c59f921fffff97621f2c31073885824aa91d51", "size": "961", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "addOns/webdrivers/webdriverlinux/src/main/javahelp/org/zaproxy/zap/extension/webdriverlinux/resources/help_fr_FR/helpset_fr_FR.hs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "50766" }, { "name": "Groovy", "bytes": "29975" }, { "name": "HTML", "bytes": "14402916" }, { "name": "Haskell", "bytes": "2591946" }, { "name": "Java", "bytes": "15880552" }, { "name": "JavaScript", "bytes": "220737" }, { "name": "Kotlin", "bytes": "120709" }, { "name": "Python", "bytes": "27312" }, { "name": "Ruby", "bytes": "16548" }, { "name": "XSLT", "bytes": "9433" } ], "symlink_target": "" }
(function () { 'use strict'; angular .module('flexget.components', []); })();
{ "content_hash": "82513a156bdb830b4f394bb27e00d976", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 42, "avg_line_length": 13.714285714285714, "alnum_prop": 0.4895833333333333, "repo_name": "qvazzler/Flexget", "id": "eeb5b6a50c21786b7f48ee8c6c6f30224640fb96", "size": "96", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "flexget/ui/src/components/components.module.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5275" }, { "name": "HTML", "bytes": "33930" }, { "name": "JavaScript", "bytes": "58811" }, { "name": "Python", "bytes": "2428468" } ], "symlink_target": "" }
$(document).ready(function() { $('a.blog-button').click(function() { if ($('.panel-cover').hasClass('panel-cover--collapsed')) return; currentWidth = $('.panel-cover').width(); $('.panel-cover').addClass('animated panel-cover--collapsed slideInLeft'); $('.content-wrapper').addClass('animated slideInLeft'); }); if (window.location.hash && window.location.hash == "#blog") { $('.panel-cover').addClass('panel-cover--collapsed'); } if (window.location.pathname != "/") { // if hexo in subdir of site, should change this line $('.panel-cover').addClass('panel-cover--collapsed'); } $('.btn-mobile-menu').click(function() { $('.navigation-wrapper').toggleClass('visible animated bounceInDown'); $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn'); }); $('.navigation-wrapper .blog-button').click(function() { // $('.navigation-wrapper').toggleClass('visible'); $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn'); }); });
{ "content_hash": "829b92b6424ace4b898c8249c6fb1f3a", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 100, "avg_line_length": 37.607142857142854, "alnum_prop": 0.6381766381766382, "repo_name": "wqo/wqo.github.io", "id": "67c893303f5039f446890d6b755adc143c490261", "size": "1053", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "js/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "87323" }, { "name": "HTML", "bytes": "226201" }, { "name": "JavaScript", "bytes": "17664" } ], "symlink_target": "" }
Common exception reporting for a variety of services Libraries are automatically detected. Supports: - [Airbrake](https://airbrake.io/) - [Appsignal](https://appsignal.com/) - [Bugsnag](https://bugsnag.com/) - [Exception Notification](https://github.com/smartinez87/exception_notification) - [Google Stackdriver](https://cloud.google.com/stackdriver/) - [Honeybadger](https://www.honeybadger.io/) - [New Relic](https://newrelic.com/) - [Raygun](https://raygun.io/) - [Rollbar](https://rollbar.com/) - [Scout APM](https://scoutapm.com/) - [Sentry](https://getsentry.com/) ```ruby begin # code rescue => e Errbase.report(e) end ``` You can add extra context with: ```ruby Errbase.report(e, {username: "hello"}) ``` > Context is not supported for Google Stackdriver [![Build Status](https://github.com/ankane/errbase/workflows/build/badge.svg?branch=master)](https://github.com/ankane/errbase/actions) ## Installation Errbase is designed to be used as a dependency. Add this line to your gemspec: ```ruby spec.add_dependency "errbase" ``` ## Contributing Everyone is encouraged to help improve this project. Here are a few ways you can help: - [Report bugs](https://github.com/ankane/errbase/issues) - Fix bugs and [submit pull requests](https://github.com/ankane/errbase/pulls) - Write, clarify, or fix documentation - Suggest or add new features To get started with development: ```sh git clone https://github.com/ankane/errbase.git cd errbase bundle install bundle exec rake test ```
{ "content_hash": "2527b670ca5b745ebb984323ac310e9e", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 135, "avg_line_length": 24.65573770491803, "alnum_prop": 0.7320478723404256, "repo_name": "ankane/errbase", "id": "3a51fd962be6af266d88ae8f172ff6e50da1f5e3", "size": "1515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3063" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Sentir, Responsive admin and dashboard UI kits template"> <meta name="keywords" content="admin,bootstrap,template,responsive admin,dashboard template,web apps template"> <meta name="author" content="Ari Rusmanto, Isoh Design Studio, Warung Themes"> <title>Default Widget | SENTIR - Responsive admin and dashboard UI kits template</title> <!-- BOOTSTRAP CSS (REQUIRED ALL PAGE)--> <link href="assets/css/bootstrap.min.css" rel="stylesheet"> <!-- PLUGINS CSS --> <link href="assets/plugins/weather-icon/css/weather-icons.min.css" rel="stylesheet"> <link href="assets/plugins/prettify/prettify.min.css" rel="stylesheet"> <link href="assets/plugins/magnific-popup/magnific-popup.min.css" rel="stylesheet"> <link href="assets/plugins/owl-carousel/owl.carousel.min.css" rel="stylesheet"> <link href="assets/plugins/owl-carousel/owl.theme.min.css" rel="stylesheet"> <link href="assets/plugins/owl-carousel/owl.transitions.min.css" rel="stylesheet"> <link href="assets/plugins/chosen/chosen.min.css" rel="stylesheet"> <link href="assets/plugins/icheck/skins/all.css" rel="stylesheet"> <link href="assets/plugins/datepicker/datepicker.min.css" rel="stylesheet"> <link href="assets/plugins/timepicker/bootstrap-timepicker.min.css" rel="stylesheet"> <link href="assets/plugins/validator/bootstrapValidator.min.css" rel="stylesheet"> <link href="assets/plugins/summernote/summernote.min.css" rel="stylesheet"> <link href="assets/plugins/markdown/bootstrap-markdown.min.css" rel="stylesheet"> <link href="assets/plugins/datatable/css/bootstrap.datatable.min.css" rel="stylesheet"> <link href="assets/plugins/morris-chart/morris.min.css" rel="stylesheet"> <link href="assets/plugins/c3-chart/c3.min.css" rel="stylesheet"> <link href="assets/plugins/slider/slider.min.css" rel="stylesheet"> <link href="assets/plugins/salvattore/salvattore.css" rel="stylesheet"> <link href="assets/plugins/toastr/toastr.css" rel="stylesheet"> <link href="assets/plugins/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet"> <link href="assets/plugins/fullcalendar/fullcalendar/fullcalendar.print.css" rel="stylesheet" media="print"> <!-- MAIN CSS (REQUIRED ALL PAGE)--> <link href="assets/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="assets/css/style.css" rel="stylesheet"> <link href="assets/css/style-responsive.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="tooltips"> <!-- BEGIN PANEL DEMO --> <div class="box-demo"> <div class="inner-panel"> <div class="cog-panel" id="demo-panel"><i class="fa fa-cog fa-spin"></i></div> <p class="text-muted small text-center">35 COLOR SCHEMES</p> <div class="row text-center"> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Default" id="color-reset"> <div class="half-tiles bg-white"></div> <div class="half-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Primary dark" id="change-primary-dark"> <div class="quarter-tiles bg-primary"></div> <div class="tigaperempat-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Info dark" id="change-info-dark"> <div class="quarter-tiles bg-info"></div> <div class="tigaperempat-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Success dark" id="change-success-dark"> <div class="quarter-tiles bg-success"></div> <div class="tigaperempat-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Danger dark" id="change-danger-dark"> <div class="quarter-tiles bg-danger"></div> <div class="tigaperempat-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Warning dark" id="change-warning-dark"> <div class="quarter-tiles bg-warning"></div> <div class="tigaperempat-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Primary light" id="change-primary-light"> <div class="quarter-tiles bg-primary"></div> <div class="tigaperempat-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Info light" id="change-info-light"> <div class="quarter-tiles bg-info"></div> <div class="tigaperempat-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Success light" id="change-success-light"> <div class="quarter-tiles bg-success"></div> <div class="tigaperempat-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Danger light" id="change-danger-light"> <div class="quarter-tiles bg-danger"></div> <div class="tigaperempat-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Warning light" id="change-warning-light"> <div class="quarter-tiles bg-warning"></div> <div class="tigaperempat-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Dark light" id="change-dark-light"> <div class="quarter-tiles bg-dark"></div> <div class="tigaperempat-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav primary light" id="change-full-primary-light"> <div class="half-tiles bg-primary"></div> <div class="half-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav info light" id="change-full-info-light"> <div class="half-tiles bg-info"></div> <div class="half-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav success light" id="change-full-success-light"> <div class="half-tiles bg-success"></div> <div class="half-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav danger light" id="change-full-danger-light"> <div class="half-tiles bg-danger"></div> <div class="half-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav warning light" id="change-full-warning-light"> <div class="half-tiles bg-warning"></div> <div class="half-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav dark light" id="change-full-dark-light"> <div class="half-tiles bg-dark"></div> <div class="half-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Sidebar primary light" id="change-sidebar-primary-light"> <div class="half-tiles bg-white"></div> <div class="half-tiles bg-primary"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Sidebar info light" id="change-sidebar-info-light"> <div class="half-tiles bg-white"></div> <div class="half-tiles bg-info"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Sidebar success light" id="change-sidebar-success-light"> <div class="half-tiles bg-white"></div> <div class="half-tiles bg-success"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Sidebar danger light" id="change-sidebar-danger-light"> <div class="half-tiles bg-white"></div> <div class="half-tiles bg-danger"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Sidebar warning light" id="change-sidebar-warning-light"> <div class="half-tiles bg-white"></div> <div class="half-tiles bg-warning"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav primary dark" id="change-full-primary-dark"> <div class="half-tiles bg-primary"></div> <div class="half-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav info dark" id="change-full-info-dark"> <div class="half-tiles bg-info"></div> <div class="half-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav success dark" id="change-full-success-dark"> <div class="half-tiles bg-success"></div> <div class="half-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Nav danger dark" id="change-full-danger-dark"> <div class="half-tiles bg-danger"></div> <div class="half-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="nav warning dark" id="change-full-warning-dark"> <div class="half-tiles bg-warning"></div> <div class="half-tiles bg-dark"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Light" id="change-color-light"> <div class="quarter-tiles bg-white"></div> <div class="tigaperempat-tiles bg-white"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Full rimary" id="change-full-primary"> <div class="half-tiles bg-primary"></div> <div class="half-tiles bg-primary"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Full info" id="change-full-info"> <div class="half-tiles bg-info"></div> <div class="half-tiles bg-info"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Full success" id="change-full-success"> <div class="half-tiles bg-success"></div> <div class="half-tiles bg-success"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Full danger" id="change-full-danger"> <div class="half-tiles bg-danger"></div> <div class="half-tiles bg-danger"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Full warning" id="change-full-warning"> <div class="half-tiles bg-warning"></div> <div class="half-tiles bg-warning"></div> </div> </div> <div class="col-xs-3"> <div class="xs-tiles" data-toggle="tooltip" title="Full dark" id="change-full-dark"> <div class="half-tiles bg-dark"></div> <div class="half-tiles bg-dark"></div> </div> </div> </div> <button class="btn btn-block btn-primary btn-sm" id="btn-reset">Reset to default</button> <a href="http://themeforest.net/item/sentir-responsive-admin-and-dashboard-ui-kits/7700260?ref=arirusmanto" class="btn btn-block btn-danger btn-sm" id="btn-reset"><i class="fa fa-shopping-cart"></i> Buy this template</a> </div> </div> <!-- END PANEL DEMO --> <!-- =========================================================== BEGIN PAGE =========================================================== --> <div class="wrapper"> <!-- BEGIN TOP NAV --> <div class="top-navbar"> <div class="top-navbar-inner"> <!-- Begin Logo brand --> <div class="logo-brand"> <a href="index.html"><img src="assets/img/sentir-logo-primary.png" alt="Sentir logo"></a> </div><!-- /.logo-brand --> <!-- End Logo brand --> <div class="top-nav-content"> <!-- Begin button sidebar left toggle --> <div class="btn-collapse-sidebar-left"> <i class="fa fa-bars"></i> </div><!-- /.btn-collapse-sidebar-left --> <!-- End button sidebar left toggle --> <!-- Begin button sidebar right toggle --> <div class="btn-collapse-sidebar-right"> <i class="fa fa-bullhorn"></i> </div><!-- /.btn-collapse-sidebar-right --> <!-- End button sidebar right toggle --> <!-- Begin button nav toggle --> <div class="btn-collapse-nav" data-toggle="collapse" data-target="#main-fixed-nav"> <i class="fa fa-plus icon-plus"></i> </div><!-- /.btn-collapse-sidebar-right --> <!-- End button nav toggle --> <!-- Begin user session nav --> <ul class="nav-user navbar-right"> <li class="dropdown"> <a href="#fakelink" class="dropdown-toggle" data-toggle="dropdown"> <img src="assets/img/avatar/avatar-1.jpg" class="avatar img-circle" alt="Avatar"> Hi, <strong>Paris Hawker</strong> </a> <ul class="dropdown-menu square primary margin-list-rounded with-triangle"> <li><a href="#fakelink">Account setting</a></li> <li><a href="#fakelink">Payment setting</a></li> <li><a href="#fakelink">Change password</a></li> <li><a href="#fakelink">My public profile</a></li> <li class="divider"></li> <li><a href="lock-screen.html">Lock screen</a></li> <li><a href="login.html">Log out</a></li> </ul> </li> </ul> <!-- End user session nav --> <!-- Begin Collapse menu nav --> <div class="collapse navbar-collapse" id="main-fixed-nav"> <!-- Begin nav search form --> <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> </form> <!-- End nav search form --> <ul class="nav navbar-nav navbar-left"> <!-- Begin nav notification --> <li class="dropdown"> <a href="#fakelink" class="dropdown-toggle" data-toggle="dropdown"> <span class="badge badge-danger icon-count">7</span> <i class="fa fa-bell"></i> </a> <ul class="dropdown-menu square with-triangle"> <li> <div class="nav-dropdown-heading"> Notifications </div><!-- /.nav-dropdown-heading --> <div class="nav-dropdown-content scroll-nav-dropdown"> <ul> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-2.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Thomas White</strong> posted on your profile page <span class="small-caps">17 seconds ago</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-3.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Doina Slaivici</strong> uploaded photo <span class="small-caps">10 minutes ago</span> </a></li> <li><a href="#fakelink"> <img src="assets/img/avatar/avatar-4.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Harry Nichols</strong> commented on your post <span class="small-caps">40 minutes ago</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-5.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Mihaela Cihac</strong> send you a message <span class="small-caps">2 hours ago</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-6.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Harold Chavez</strong> change his avatar <span class="small-caps">Yesterday</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-7.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Elizabeth Owens</strong> posted on your profile page <span class="small-caps">Yesterday</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-8.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Frank Oliver</strong> commented on your post <span class="small-caps">A week ago</span> </a></li> <li><a href="#fakelink"> <img src="assets/img/avatar/avatar-9.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Mya Weastell</strong> send you a message <span class="small-caps">April 15, 2014</span> </a></li> <li><a href="#fakelink"> <img src="assets/img/avatar/avatar-10.jpg" class="absolute-left-content img-circle" alt="Avatar"> <strong>Carl Rodriguez</strong> joined your weekend party <span class="small-caps">April 01, 2014</span> </a></li> </ul> </div><!-- /.nav-dropdown-content scroll-nav-dropdown --> <button class="btn btn-primary btn-square btn-block">See all notifications</button> </li> </ul> </li> <!-- End nav notification --> <!-- Begin nav task --> <li class="dropdown"> <a href="#fakelink" class="dropdown-toggle" data-toggle="dropdown"> <span class="badge badge-warning icon-count">3</span> <i class="fa fa-tasks"></i> </a> <ul class="dropdown-menu square margin-list-rounded with-triangle"> <li> <div class="nav-dropdown-heading"> Tasks </div><!-- /.nav-dropdown-heading --> <div class="nav-dropdown-content scroll-nav-dropdown"> <ul> <li class="unread"><a href="#fakelink"> <i class="fa fa-check-circle-o absolute-left-content icon-task completed"></i> Creating documentation <span class="small-caps">Completed : Yesterday</span> </a></li> <li><a href="#fakelink"> <i class="fa fa-clock-o absolute-left-content icon-task progress"></i> Eating sands <span class="small-caps">Deadline : Tomorrow</span> </a></li> <li><a href="#fakelink"> <i class="fa fa-clock-o absolute-left-content icon-task progress"></i> Sending payment <span class="small-caps">Deadline : Next week</span> </a></li> <li><a href="#fakelink"> <i class="fa fa-exclamation-circle absolute-left-content icon-task uncompleted"></i> Uploading new version <span class="small-caps">Deadline: 2 seconds ago</span> </a></li> <li><a href="#fakelink"> <i class="fa fa-exclamation-circle absolute-left-content icon-task uncompleted"></i> Drinking coffee <span class="small-caps">Deadline : 2 hours ago</span> </a></li> <li class="unread"><a href="#fakelink"> <i class="fa fa-check-circle-o absolute-left-content icon-task completed"></i> Walking to nowhere <span class="small-caps">Completed : over a year ago</span> </a></li> <li class="unread"><a href="#fakelink"> <i class="fa fa-check-circle-o absolute-left-content icon-task completed"></i> Sleeping under bridge <span class="small-caps">Completed : Dec 31, 2013</span> </a></li> <li class="unread"><a href="#fakelink"> <i class="fa fa-check-circle-o absolute-left-content icon-task completed"></i> Buying some cigarettes <span class="small-caps">Completed : 2 days ago</span> </a></li> </ul> </div><!-- /.nav-dropdown-content scroll-nav-dropdown --> <button class="btn btn-primary btn-square btn-block">See all notifications</button> </li> </ul> </li> <!-- End nav task --> <!-- Begin nav message --> <li class="dropdown"> <a href="#fakelink" class="dropdown-toggle" data-toggle="dropdown"> <span class="badge badge-success icon-count">9</span> <i class="fa fa-envelope"></i> </a> <ul class="dropdown-menu square margin-list-rounded with-triangle"> <li> <div class="nav-dropdown-heading"> Messages </div><!-- /.nav-dropdown-heading --> <div class="nav-dropdown-content scroll-nav-dropdown"> <ul> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-25.jpg" class="absolute-left-content img-circle" alt="Avatar"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit <span class="small-caps">17 seconds ago</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-24.jpg" class="absolute-left-content img-circle" alt="Avatar"> Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat <span class="small-caps">10 minutes ago</span> </a></li> <li><a href="#fakelink"> <img src="assets/img/avatar/avatar-23.jpg" class="absolute-left-content img-circle" alt="Avatar"> I think so <span class="small-caps">40 minutes ago</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-22.jpg" class="absolute-left-content img-circle" alt="Avatar"> Yes, I'll be waiting <span class="small-caps">2 hours ago</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-21.jpg" class="absolute-left-content img-circle" alt="Avatar"> Thank you! <span class="small-caps">Yesterday</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-20.jpg" class="absolute-left-content img-circle" alt="Avatar"> No problem! I will never remember that <span class="small-caps">Yesterday</span> </a></li> <li class="unread"><a href="#fakelink"> <img src="assets/img/avatar/avatar-19.jpg" class="absolute-left-content img-circle" alt="Avatar"> Tak gepuk ndasmu sisan lho dab! <span class="small-caps">A week ago</span> </a></li> <li><a href="#fakelink"> <img src="assets/img/avatar/avatar-18.jpg" class="absolute-left-content img-circle" alt="Avatar"> Sorry bro, aku or atau sing jenenge ngono kui <span class="small-caps">April 15, 2014</span> </a></li> <li><a href="#fakelink"> <img src="assets/img/avatar/avatar-17.jpg" class="absolute-left-content img-circle" alt="Avatar"> Will you send me an invitation for your weeding party? <span class="small-caps">April 01, 2014</span> </a></li> </ul> </div><!-- /.nav-dropdown-content scroll-nav-dropdown --> <button class="btn btn-primary btn-square btn-block">See all message</button> </li> </ul> </li> <!-- End nav message --> <!-- Begin nav friend requuest --> <li class="dropdown"> <a href="#fakelink" class="dropdown-toggle" data-toggle="dropdown"> <span class="badge badge-info icon-count">2</span> <i class="fa fa-users"></i> </a> <ul class="dropdown-menu square margin-list-rounded with-triangle"> <li> <div class="nav-dropdown-heading"> Friend requests </div><!-- /.nav-dropdown-heading --> <div class="nav-dropdown-content static-list scroll-nav-dropdown"> <ul> <li> <img src="assets/img/avatar/avatar-12.jpg" class="absolute-left-content img-circle" alt="Avatar"> <div class="row"> <div class="col-xs-6"> <strong>Craig Dixon</strong> <span class="small-caps">2 murtual friends</span> </div> <div class="col-xs-6 text-right btn-action"> <button class="btn btn-success btn-xs">Accept</button><button class="btn btn-danger btn-xs">Ignore</button> </div><!-- /.col-xs-5 text-right btn-cation --> </div><!-- /.row --> </li> <li> <img src="assets/img/avatar/avatar-13.jpg" class="absolute-left-content img-circle" alt="Avatar"> <div class="row"> <div class="col-xs-6"> <strong>Mikayla King</strong> <span class="small-caps">20 murtual friends</span> </div> <div class="col-xs-6 text-right btn-action"> <button class="btn btn-success btn-xs">Accept</button><button class="btn btn-danger btn-xs">Ignore</button> </div><!-- /.col-xs-5 text-right btn-cation --> </div><!-- /.row --> </li> <li> <img src="assets/img/avatar/avatar-14.jpg" class="absolute-left-content img-circle" alt="Avatar"> <div class="row"> <div class="col-xs-6"> <strong>Richard Dixon</strong> <span class="small-caps">1 murtual friend</span> </div> <div class="col-xs-6 text-right btn-action"> <button class="btn btn-success btn-xs">Accept</button><button class="btn btn-danger btn-xs">Ignore</button> </div><!-- /.col-xs-5 text-right btn-cation --> </div><!-- /.row --> </li> <li> <img src="assets/img/avatar/avatar-15.jpg" class="absolute-left-content img-circle" alt="Avatar"> <div class="row"> <div class="col-xs-6"> <strong>Brenda Fuller</strong> <span class="small-caps">8 murtual friends</span> </div> <div class="col-xs-6 text-right btn-action"> <button class="btn btn-success btn-xs">Accept</button><button class="btn btn-danger btn-xs">Ignore</button> </div><!-- /.col-xs-5 text-right btn-cation --> </div><!-- /.row --> </li> <li> <img src="assets/img/avatar/avatar-16.jpg" class="absolute-left-content img-circle" alt="Avatar"> <div class="row"> <div class="col-xs-6"> <strong>Ryan Ortega</strong> <span class="small-caps">122 murtual friends</span> </div> <div class="col-xs-6 text-right btn-action"> <button class="btn btn-success btn-xs">Accept</button><button class="btn btn-danger btn-xs">Ignore</button> </div><!-- /.col-xs-5 text-right btn-cation --> </div><!-- /.row --> </li> <li> <img src="assets/img/avatar/avatar-17.jpg" class="absolute-left-content img-circle" alt="Avatar"> <div class="row"> <div class="col-xs-6"> <strong>Jessica Gutierrez</strong> <span class="small-caps">45 murtual friends</span> </div> <div class="col-xs-6 text-right btn-action"> <button class="btn btn-success btn-xs">Accept</button><button class="btn btn-danger btn-xs">Ignore</button> </div><!-- /.col-xs-5 text-right btn-cation --> </div><!-- /.row --> </li> </ul> </div><!-- /.nav-dropdown-content scroll-nav-dropdown --> <button class="btn btn-primary btn-square btn-block">See all request</button> </li> </ul> </li> <!-- End nav friend requuest --> </ul> </div><!-- /.navbar-collapse --> <!-- End Collapse menu nav --> </div><!-- /.top-nav-content --> </div><!-- /.top-navbar-inner --> </div><!-- /.top-navbar --> <!-- END TOP NAV --> <!-- BEGIN SIDEBAR LEFT --> <div class="sidebar-left sidebar-nicescroller"> <ul class="sidebar-menu"> <li> <a href="index.html"> <i class="fa fa-dashboard icon-sidebar"></i> Dashboard </a> </li> <li> <a href="front-end.html"> <i class="fa fa-bomb icon-sidebar"></i> Web templates </a> </li> <li> <a href="#fakelink"> <i class="fa fa-desktop icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Layout template <span class="badge badge-warning span-sidebar">9</span> </a> <ul class="submenu"> <li><a href="#fakelink">Default layout<span class="label label-success span-sidebar">CURRENT</span></a></li> <li><a href="layout-no-sidebar-right.html">No sidebar right</a></li> <li><a href="layout-profile-left.html">Profile summary left</a></li> <li><a href="layout-no-sidebar-left.html">No sidebar left</a></li> <li><a href="layout-shrink-navbar.html">Shrink navbar</a></li> <li><a href="layout-top-navigation.html">Top navigation</a></li> <li><a href="layout-tour.html">Tour layout</a></li> <li><a href="layout-hidden-sidebar-left.html">Hidden sidebar left</a></li> <li><a href="layout-top-notification.html">Top notification</a></li> </ul> </li> <li class="active selected"> <a href="#fakelink"> <i class="fa fa-flask icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Widget UI kits </a> <ul class="submenu visible"> <li class="active selected"><a href="widget-default.html">Default</a></li> <li><a href="widget-store.html">Store</a></li> <li><a href="widget-real-estate.html">Real estate <span class="label label-warning span-sidebar">HOT</span></a></li> <li><a href="widget-blog.html">Blog</a></li> <li><a href="widget-social.html">Social <span class="label label-warning span-sidebar">HOT</span></a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-folder icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Basic elements <span class="label label-info span-sidebar">BS3</span> </a> <ul class="submenu"> <li><a href="element-typography.html">Typography</a></li> <li><a href="element-form.html">Form element</a></li> <li><a href="element-form-example.html">Form example</a></li> <li><a href="element-wyswyg.html">Form WYSWYG</a></li> <li><a href="element-validation.html">Form validation</a></li> <li><a href="element-button.html">Button</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-folder-open icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> More elements </a> <ul class="submenu"> <li><a href="element-icon.html">Icons <span class="badge badge-info span-sidebar">3</span></a></li> <li><a href="element-box-panel.html">Box &amp; panel</a></li> <li><a href="element-nav-dropdown.html">Nav &amp; dropdown</a></li> <li><a href="element-breadcrumb-pagination.html">Breadcrumb &amp; pagination</a></li> <li><a href="element-thumbnail-jumbotron.html">Jumbotron &amp; thumbnail</a></li> <li><a href="element-alert-progress-bar.html">Alert &amp; progress</a></li> <li><a href="element-list-media.html">List group &amp; media object</a></li> <li><a href="element-collapse.html">Collapse</a></li> <li><a href="element-grid-masonry.html">Grid &amp; masonry</a></li> <li><a href="element-masonry-js.html">Masonry JS</a></li> <li><a href="element-toastr.html">Toastr notifications</a></li> <li><a href="element-carousel.html">Carousel</a></li> <li><a href="element-calendar.html">Calendar</a></li> <li><a href="element-extra.html">Extra elements</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-table icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Tables </a> <ul class="submenu"> <li><a href="table-static.html">Static table</a></li> <li><a href="table-color.html">Table color</a></li> <li><a href="table-datatable.html">Jquery datatable</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-bar-chart-o icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Chart or Graph </a> <ul class="submenu"> <li><a href="chart-morris.html">Morris chart</a></li> <li><a href="chart-c3.html">C3 chart</a></li> <li><a href="chart-flot.html">Flot chart</a></li> <li><a href="chart-easy-knob.html">Easy pie chart &amp; knob</a></li> </ul> </li> <li class="static">EXTRA DESIGNS</li> <li> <a href="#fakelink"> <i class="fa fa-envelope icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Mail apps <span class="label label-warning span-sidebar">HOT</span> </a> <ul class="submenu"> <li><a href="mail-inbox.html">Inbox <span class="badge badge-success span-sidebar">6</span></a></li> <li><a href="mail-send.html">Sent mail</a></li> <li><a href="mail-new.html">New mail</a></li> <li><a href="mail-contact.html">Mail contact</a></li> <li><a href="mail-read.html">Read mail</a></li> <li><a href="mail-reply.html">Reply mail</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-shopping-cart icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Store apps </a> <ul class="submenu"> <li><a href="store-product-list.html">Product list</a></li> <li><a href="store-product-column.html">Product column</a></li> <li><a href="store-product-masonry.html">Product masonry</a></li> <li><a href="store-product-detail.html">Product detail</a></li> <li><a href="store-shopping-cart.html">Shopping cart</a></li> <li><a href="store-checkout.html">Checkout</a></li> <li><a href="store-new-product.html">Add new product</a></li> <li><a href="store-orderlist.html">Order list</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-home icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Real estate apps </a> <ul class="submenu"> <li><a href="real-estate-property-list.html">Property list</a></li> <li><a href="real-estate-property-column.html">Property column</a></li> <li><a href="real-estate-property-masonry.html">Property masonry</a></li> <li><a href="real-estate-property-detail.html">Property detail</a></li> <li><a href="real-estate-property-search.html">Search property</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-comment icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> <span class="label label-success span-sidebar">TOP</span> Blog apps </a> <ul class="submenu"> <li><a href="blog-list.html">Blog list</a></li> <li><a href="blog-column.html">Blog column</a></li> <li><a href="blog-masonry.html">Blog masonry</a></li> <li><a href="blog-detail.html">Blog detail</a></li> <li><a href="blog-home.html">Featured home</a></li> <li><a href="blog-new.html">Add new blog</a></li> <li><a href="blog-comments.html">Comments</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-users icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Social apps </a> <ul class="submenu"> <li><a href="social-home.html">Home activity</a></li> <li><a href="social-my-profile.html">My profile</a></li> <li><a href="social-friendlist.html">Friend list <span class="badge badge-info span-sidebar">5</span></a></li> <li><a href="social-timeline.html">Timeline</a></li> <li><a href="social-photos.html">Photos</a></li> </ul> </li> <li> <a href="#fakelink"> <i class="fa fa-heart icon-sidebar"></i> <i class="fa fa-angle-right chevron-icon-sidebar"></i> Example pages </a> <ul class="submenu"> <li><a href="login.html">Login</a></li> <li><a href="lock-screen.html">Lock screen</a></li> <li><a href="forgot-password.html">Forgot password</a></li> <li><a href="register.html">Register</a></li> <li><a href="example-pricing-table.html">Pricing table</a></li> <li><a href="example-invoice.html">Invoice</a></li> <li><a href="example-faq.html">FAQ</a></li> <li><a href="example-search.html">Search page</a></li> <li><a href="example-media-library.html">Media library</a></li> <li><a href="404.html">404</a></li> <li><a href="blank.html">Blank page</a></li> </ul> </li> <li class="static">SYSTEM SETTING</li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="alertme" checked> <label class="onoffswitch-label" for="alertme"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Alert me when system down </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="autoupdate"> <label class="onoffswitch-label" for="autoupdate"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Automatic update </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="dailyreport"> <label class="onoffswitch-label" for="dailyreport"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Daily task report </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="remembercomputer" checked> <label class="onoffswitch-label" for="remembercomputer"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Remember this computer </li> </ul> </div><!-- /.sidebar-left --> <!-- END SIDEBAR LEFT --> <!-- BEGIN SIDEBAR RIGHT HEADING --> <div class="sidebar-right-heading"> <ul class="nav nav-tabs square nav-justified"> <li class="active"><a href="#online-user-sidebar" data-toggle="tab"><i class="fa fa-comments"></i></a></li> <li><a href="#notification-sidebar" data-toggle="tab"><i class="fa fa-bell"></i></a></li> <li><a href="#task-sidebar" data-toggle="tab"><i class="fa fa-tasks"></i></a></li> <li><a href="#setting-sidebar" data-toggle="tab"><i class="fa fa-cogs"></i></a></li> </ul> </div><!-- /.sidebar-right-heading --> <!-- END SIDEBAR RIGHT HEADING --> <!-- BEGIN SIDEBAR RIGHT --> <div class="sidebar-right right-sidebar-nicescroller"> <div class="tab-content"> <div class="tab-pane fade in active" id="online-user-sidebar"> <ul class="sidebar-menu online-user"> <li class="static">ONLINE USERS</li> <li><a href="#fakelink"> <span class="user-status success"></span> <img src="assets/img/avatar/avatar-2.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-mobile-phone device-status"></i> Thomas White <span class="small-caps">Lorem ipsum dolor sit amet, consectetuer adipiscing elit</span> </a></li> <li><a href="#fakelink"> <span class="user-status success"></span> <img src="assets/img/avatar/avatar-3.jpg" class="ava-sidebar img-circle" alt="Avatar"> Doina Slaivici <span class="small-caps">Duis autem vel eum iriure dolor in hendrerit in </span> </a></li> <li><a href="#fakelink"> <span class="user-status success"></span> <img src="assets/img/avatar/avatar-4.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-android device-status"></i> Harry Nichols <span class="small-caps">I think so</span> </a></li> <li><a href="#fakelink"> <span class="user-status success"></span> <img src="assets/img/avatar/avatar-5.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-mobile-phone device-status"></i> Mihaela Cihac <span class="small-caps">Yes, I'll be waiting</span> </a></li> <li><a href="#fakelink"> <span class="user-status success"></span> <img src="assets/img/avatar/avatar-6.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-apple device-status"></i> Harold Chavez <span class="small-caps">Thank you!</span> </a></li> <li class="static">IDLE USERS</li> <li><a href="#fakelink"> <span class="user-status warning"></span> <img src="assets/img/avatar/avatar-7.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-windows device-status"></i> Elizabeth Owens <span class="small-caps">2 hours</span> </a></li> <li><a href="#fakelink"> <span class="user-status warning"></span> <img src="assets/img/avatar/avatar-8.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-apple device-status"></i> Frank Oliver <span class="small-caps">4 hours</span> </a></li> <li><a href="#fakelink"> <span class="user-status warning"></span> <img src="assets/img/avatar/avatar-9.jpg" class="ava-sidebar img-circle" alt="Avatar"> Mya Weastell <span class="small-caps">15 minutes</span> </a></li> <li><a href="#fakelink"> <span class="user-status warning"></span> <img src="assets/img/avatar/avatar-10.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-mobile-phone device-status"></i> Carl Rodriguez <span class="small-caps">20 hours</span> </a></li> <li><a href="#fakelink"> <span class="user-status warning"></span> <img src="assets/img/avatar/avatar-11.jpg" class="ava-sidebar img-circle" alt="Avatar"> <i class="fa fa-mobile-phone device-status"></i> Nikita Carter <span class="small-caps">2 minutes</span> </a></li> <li class="static">OFFLINE USERS</li> <li><a href="#fakelink"> <span class="user-status danger"></span> <img src="assets/img/avatar/avatar-12.jpg" class="ava-sidebar img-circle" alt="Avatar"> Craig Dixon <span class="small-caps">Last seen 2 hours ago</span> </a></li> <li><a href="#fakelink"> <span class="user-status danger"></span> <img src="assets/img/avatar/avatar-13.jpg" class="ava-sidebar img-circle" alt="Avatar"> Mikayla King <span class="small-caps">Last seen yesterday</span> </a></li> <li><a href="#fakelink"> <span class="user-status danger"></span> <img src="assets/img/avatar/avatar-14.jpg" class="ava-sidebar img-circle" alt="Avatar"> Richard Dixon <span class="small-caps">Last seen Feb 20, 2014 05:45:50</span> </a></li> <li><a href="#fakelink"> <span class="user-status danger"></span> <img src="assets/img/avatar/avatar-15.jpg" class="ava-sidebar img-circle" alt="Avatar"> Brenda Fuller <span class="small-caps">Last seen Feb 15, 2014 11:35:50</span> </a></li> <li><a href="#fakelink"> <span class="user-status danger"></span> <img src="assets/img/avatar/avatar-16.jpg" class="ava-sidebar img-circle" alt="Avatar"> Ryan Ortega <span class="small-caps">Last seen Jan 20, 2014 03:45:50</span> </a></li> </ul> </div> <div class="tab-pane fade" id="notification-sidebar"> <ul class="sidebar-menu sidebar-notification"> <li class="static">TODAY</li> <li><a href="#fakelink" data-toggle="tooltip" title="Karen Wallace" data-placement="left"> <img src="assets/img/avatar/avatar-25.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Posted something on your profile page</span> <span class="small-caps">17 seconds ago</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Phillip Lucas" data-placement="left"> <img src="assets/img/avatar/avatar-24.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Uploaded a photo</span> <span class="small-caps">2 hours ago</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Sandra Myers" data-placement="left"> <img src="assets/img/avatar/avatar-23.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Commented on your post</span> <span class="small-caps">5 hours ago</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Charles Guerrero" data-placement="left"> <img src="assets/img/avatar/avatar-22.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Send you a message</span> <span class="small-caps">17 hours ago</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Maria Simpson" data-placement="left"> <img src="assets/img/avatar/avatar-21.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Change her avatar</span> <span class="small-caps">20 hours ago</span> </a></li> <li class="static">YESTERDAY</li> <li><a href="#fakelink" data-toggle="tooltip" title="Jason Crawford" data-placement="left"> <img src="assets/img/avatar/avatar-20.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Posted something on your profile page</span> <span class="small-caps">Yesterday 10:45:12</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Cynthia Mendez" data-placement="left"> <img src="assets/img/avatar/avatar-19.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Uploaded a photo</span> <span class="small-caps">Yesterday 08:00:05</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Peter Ramirez" data-placement="left"> <img src="assets/img/avatar/avatar-18.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Commented on your post</span> <span class="small-caps">Yesterday 07:49:08</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Jessica Gutierrez" data-placement="left"> <img src="assets/img/avatar/avatar-17.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Send you a message</span> <span class="small-caps">Yesterday 07:35:19</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="Ryan Ortega" data-placement="left"> <img src="assets/img/avatar/avatar-16.jpg" class="ava-sidebar img-circle" alt="Avatar"> <span class="activity">Change her avatar</span> <span class="small-caps">Yesterday 06:00:00</span> </a></li> <li class="static text-center"><button class="btn btn-primary btn-sm">See all notifications</button></li> </ul> </div> <div class="tab-pane fade" id="task-sidebar"> <ul class="sidebar-menu sidebar-task"> <li class="static">UNCOMPLETED</li> <li><a href="#fakelink" data-toggle="tooltip" title="in progress" data-placement="left"> <i class="fa fa-clock-o icon-task-sidebar progress"></i> Creating documentation <span class="small-caps">Deadline : Next week</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="uncompleted" data-placement="left"> <i class="fa fa-exclamation-circle icon-task-sidebar uncompleted"></i> Eating sand <span class="small-caps">Deadline : 2 hours ago</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="uncompleted" data-placement="left"> <i class="fa fa-exclamation-circle icon-task-sidebar uncompleted"></i> Sending payment <span class="small-caps">Deadline : 2 seconds ago</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="in progress" data-placement="left"> <i class="fa fa-clock-o icon-task-sidebar progress"></i> Uploading new version <span class="small-caps">Deadline : Tomorrow</span> </a></li> <li class="static">COMPLETED</li> <li><a href="#fakelink" data-toggle="tooltip" title="completed" data-placement="left"> <i class="fa fa-check-circle-o icon-task-sidebar completed"></i> Drinking coffee <span class="small-caps">Completed : 10 hours ago</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="completed" data-placement="left"> <i class="fa fa-check-circle-o icon-task-sidebar completed"></i> Walking to nowhere <span class="small-caps">Completed : Yesterday</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="completed" data-placement="left"> <i class="fa fa-check-circle-o icon-task-sidebar completed"></i> Sleeping under bridge <span class="small-caps">Completed : Feb 10 2014</span> </a></li> <li><a href="#fakelink" data-toggle="tooltip" title="completed" data-placement="left"> <i class="fa fa-check-circle-o icon-task-sidebar completed"></i> Buying some cigarettes <span class="small-caps">Completed : Jan 15 2014</span> </a></li> <li class="static text-center"><button class="btn btn-success btn-sm">See all tasks</button></li> </ul> </div><!-- /#task-sidebar --> <div class="tab-pane fade" id="setting-sidebar"> <ul class="sidebar-menu"> <li class="static">ACCOUNT SETTING</li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="onlinestatus" checked> <label class="onoffswitch-label" for="onlinestatus"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Online status </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="offlinecontact" checked> <label class="onoffswitch-label" for="offlinecontact"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Show offline contact </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="invisiblemode"> <label class="onoffswitch-label" for="invisiblemode"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Invisible mode </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="personalstatus" checked> <label class="onoffswitch-label" for="personalstatus"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Show my personal status </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="deviceicon"> <label class="onoffswitch-label" for="deviceicon"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Show my device icon </li> <li class="text-content"> <div class="switch"> <div class="onoffswitch blank"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="logmessages"> <label class="onoffswitch-label" for="logmessages"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> </div> Log all message </li> </ul> </div><!-- /#setting-sidebar --> </div><!-- /.tab-content --> </div><!-- /.sidebar-right --> <!-- END SIDEBAR RIGHT --> <!-- BEGIN PAGE CONTENT --> <div class="page-content"> <div class="container-fluid"> <!-- Begin page heading --> <h1 class="page-heading">Default widget <small>Sub heading here</small></h1> <!-- End page heading --> <!-- Begin breadcrumb --> <ol class="breadcrumb default square rsaquo sm"> <li><a href="index.html"><i class="fa fa-home"></i></a></li> <li><a href="#fakelink">Widgets UI kits</a></li> <li class="active">Default</li> </ol> <!-- End breadcrumb --> <div class="row"> <div class="col-lg-6 col-md-12 col-sm-12"> <!-- BEGIN NEWS TICKER WIDGET --> <div class="the-box no-border full"> <button class="btn btn-block btn-primary btn-square" id="w-newsticker-next"><i class="fa fa-chevron-up"></i></button> <ul class="widget-newsticker media-list"> <li class="media"> <div class="media-left"> <img class="media-object" src="assets/img/photo/small/img-1.jpg" alt="Image"> </div> <div class="media-body"> <h4 class="media-heading"><a href="#fakelink">Duis autem vel eum iriure dolor in hendrerit in vulputate</a></h4> <p class="text-muted"><small>Posted on August 17, 2014</small></p> <p> Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut... </p> </div> </li> <li class="media"> <div class="media-left" href="#fakelink"> <img class="media-object" src="assets/img/photo/small/img-2.jpg" alt="Image"> </div> <div class="media-body"> <h4 class="media-heading"><a href="#fakelink">Lorem ipsum dolor sit amet, consectetuer</a></h4> <p class="text-muted"><small>Posted on August 17, 2014</small></p> <p> Ut wisi enim ad minim veniam, quis nostrud exerci tation... </p> </div> </li> <li class="media"> <div class="media-left" href="#fakelink"> <img class="media-object" src="assets/img/photo/small/img-3.jpg" alt="Image"> </div> <div class="media-body"> <h4 class="media-heading"><a href="#fakelink">Ut wisi enim ad minim veniam</a></h4> <p class="text-muted"><small>Posted on August 17, 2014</small></p> <p> Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper... </p> </div> </li> <li class="media"> <div class="media-left" href="#fakelink"> <img class="media-object" src="assets/img/photo/small/img-4.jpg" alt="Image"> </div> <div class="media-body"> <h4 class="media-heading"><a href="#fakelink">Typi non habent</a></h4> <p class="text-muted"><small>Posted on August 17, 2014</small></p> <p> Ut wisi enim ad minim veniam, quis nostrud exerci... </p> </div> </li> <li class="media"> <div class="media-left" href="#fakelink"> <img class="media-object" src="assets/img/photo/small/img-5.jpg" alt="Image"> </div> <div class="media-body"> <h4 class="media-heading"><a href="#fakelink">Claritas est etiam processus</a></h4> <p class="text-muted"><small>Posted on August 17, 2014</small></p> <p> Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit... </p> </div> </li> <li class="media"> <div class="media-left" href="#fakelink"> <img class="media-object" src="assets/img/photo/small/img-6.jpg" alt="Image"> </div> <div class="media-body"> <h4 class="media-heading"><a href="#fakelink">Eodem modo typi, qui nunc nobis</a></h4> <p class="text-muted"><small>Posted on August 17, 2014</small></p> <p> Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper... </p> </div> </li> </ul> <button class="btn btn-block btn-primary btn-square" id="w-newsticker-prev"><i class="fa fa-chevron-down"></i></button> </div><!-- /.the-box no-border --> <!-- END NEWS TICKER WIDGET --> </div><!-- /.col-lg-6 col-md-12 col-sm-12 --> <div class="col-lg-6 col-md-12 col-sm-12"> <!-- BEGIN PERCENTAGE MONITOR --> <div class="panel panel-default panel-square panel-no-border text-center"> <div class="panel-heading"> <h3 class="panel-title">PERCENTAGE MONITOR</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-sm-4 text-center"> <h4 class="small-heading">Sales</h4> <span class="chart chart-widget-pie widget-easy-pie-1" data-percent="45"> <span class="percent"></span> </span> </div><!-- /.col-sm-4 --> <div class="col-sm-4 text-center"> <h4 class="small-heading">Visitor</h4> <span class="chart chart-widget-pie widget-easy-pie-2" data-percent="85"> <span class="percent"></span> </span> </div><!-- /.col-sm-4 --> <div class="col-sm-4 text-center"> <h4 class="small-heading">Reach</h4> <span class="chart chart-widget-pie widget-easy-pie-3" data-percent="25"> <span class="percent"></span> </span> </div><!-- /.col-sm-4 --> </div><!-- /.row --> </div><!-- /.panel-body --> </div><!-- /.panel panel-success panel-block-color --> <!-- END PERCENTAGE MONITOR --> <!-- BEGIN HEADLINE NEWS TILES --> <div class="the-box no-border bg-warning full"> <div id="tiles-slide-4" class="owl-carousel tiles-carousel-color-2"> <div class="item full"> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome life story title</a></h4> <p class="small">02 MAY, 2014</p> <p class="small">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <button class="btn btn-warning btn-sm">Read more</button> </div> </div><!-- /.item full --> <div class="item full"> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome life story title</a></h4> <p class="small">01 MAY, 2014</p> <p class="small">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <button class="btn btn-warning btn-sm">Read more</button> </div> </div><!-- /.item full --> <div class="item full"> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome life story title</a></h4> <p class="small">29 APRIL, 2014</p> <p class="small">Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p> <button class="btn btn-warning btn-sm">Read more</button> </div> </div><!-- /.item full --> </div><!-- /#tiles-slide-2 --> </div><!-- /.the-box no-border full --> <!-- END HEADLINE NEWS TILES --> </div><!-- /.col-lg-6 col-md-12 col-sm-12 --> </div><!-- /.row --> <div class="row"> <div class="col-lg-4"> <!-- BEGIN CURRENCY RATES --> <div class="panel panel-primary panel-square panel-no-border"> <div class="panel-heading"> <h3 class="panel-title">CURRENCY RATES</h3> </div> <ul class="list-group currency-rates widget-currency-ticker"> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">EUR / USD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">1.36786</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">USD / JPY</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">101.538</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">GBP / USD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">1.71523</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">USD / CHF</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">0.88748</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-down text-danger"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">USD / CAD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">1.06365</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">EUR / JPY</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">138.890</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">AUD / USD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">0.94975</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-down text-danger"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">EUR / USD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">1.36786</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">USD / JPY</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">101.538</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">GBP / USD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">1.71523</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">USD / CHF</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">0.88748</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-down text-danger"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">USD / CAD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">1.06365</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">EUR / JPY</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">138.890</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-up text-success"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> <li class="list-group-item"> <div class="row"> <div class="col-xs-5"><a href="#fakelink">AUD / USD</a></div><!-- /.col-cs-4 --> <div class="col-xs-5">0.94975</div><!-- /.col-cs-4 --> <div class="col-xs-2"><i class="fa fa-caret-down text-danger"></i></div><!-- /.col-cs-4 --> </div><!-- /.row --> </li> </ul> </div><!-- /.panel panel-default panel-square panel-no-border --> <!-- END CURRENCY RATES --> </div><!-- /.col-sm-4 --> <div class="col-lg-3"> <!-- BEGIN TODAY VISITOR TILES --> <div class="panel panel-danger panel-square panel-no-border text-center"> <div class="panel-heading"> <h3 class="panel-title">TODAY VISITOR</h3> </div> <div class="panel-body"> <h1 class="bolded tiles-number text-danger">25,057</h1> <p class="text-muted"><small>UNIQUE VISITOR <strong>957</strong></small></p> <p class="text-muted"><small>TOTAL REACH <strong>25%</strong></small></p> </div><!-- /.panel-body --> </div><!-- /.panel panel-danger panel-square panel-no-border text-center --> <!-- END TODAY VISITOR TILES --> <!-- BEGIN TODAY VIEWS TILES --> <div class="panel panel-info panel-square panel-no-border text-center"> <div class="panel-heading"> <h3 class="panel-title">TODAY VIEWS</h3> </div> <div class="panel-body"> <h1 class="bolded tiles-number text-info">125K</h1> <p class="text-muted"><small>UNIQUE VISITOR <strong>957</strong></small></p> <p class="text-muted"><small>AVERAGE <strong>3 MINUNTES</strong></small></p> </div><!-- /.panel-body --> </div><!-- /.panel panel-info panel-square panel-no-border text-center --> <!-- END TODAY VIEWS TILES --> </div><!-- /.col-sm-6 --> <div class="col-lg-3"> <!-- BEGIN TODAY SALES TILES --> <div class="panel panel-warning panel-square panel-no-border text-center"> <div class="panel-heading"> <h3 class="panel-title">TODAY SALES</h3> </div> <div class="panel-body"> <h1 class="bolded tiles-number text-warning">245</h1> <p class="text-muted"><small>LAST SALE <strong>2 HOURS AGO</strong></small></p> <p class="text-muted"><small>SALE AVERAGE <strong>221</strong></small></p> </div><!-- /.panel-body --> </div><!-- /.panel panel-warning panel-square panel-no-border text-center --> <!-- END TODAY SALES TILES --> <!-- BEGIN TODAY VISITOR TILES --> <div class="panel panel-success panel-square panel-no-border text-center"> <div class="panel-heading"> <h3 class="panel-title">TODAY FEEDBACK</h3> </div> <div class="panel-body"> <h1 class="bolded tiles-number text-success">117</h1> <p class="text-muted"><small>LAST FEEDBACK <strong>16 MIN AGO</strong></small></p> <p class="text-muted"><small>OVERALL <strong>EXCELLENT</strong></small></p> </div><!-- /.panel-body --> </div><!-- /.panel panel-success panel-square panel-no-border text-center --> <!-- END TODAY VISITOR TILES --> </div><!-- /.col-sm-6 --> <div class="col-sm-2"> <!-- BEGIN SOCIAL TILES --> <div class="row"> <div class="col-sm-12 col-xs-6"> <div class="tiles facebook-tile text-center"> <i class="fa fa-facebook icon-lg-size"></i> <h4><a href="#fakelink">10K likes</a></h4> </div><!-- /.tiles .facebook-tile --> </div><!-- /.col-sm-12 col-xs-6 --> <div class="col-sm-12 col-xs-6"> <div class="tiles twitter-tile text-center"> <i class="fa fa-twitter icon-lg-size"></i> <h4><a href="#fakelink">10K followers</a></h4> </div><!-- /.tiles .twitter-tile --> </div><!-- /.col-sm-12 col-xs-6 --> <div class="col-sm-12 col-xs-6"> <div class="tiles dribbble-tile text-center"> <i class="fa fa-dribbble icon-lg-size"></i> <h4><a href="#fakelink">1K followers</a></h4> </div><!-- /.tiles .dribbble-tile --> </div><!-- /.col-sm-12 col-xs-6 --> </div><!-- /.row --> <!-- END SOCIAL TILES --> </div><!-- /.col-sm-2 --> </div><!-- /.row --> <div class="row"> <div class="col-sm-12 col-md-8"> <!-- BEGIN SERVER STATUS WIDGET --> <div class="panel panel-success panel-square panel-no-border"> <div class="panel-heading lg"> <div class="right-content"> <button class="btn btn-success to-collapse" data-toggle="collapse" data-target="#panel-chart-widget-1"><i class="fa fa-chevron-up"></i></button> </div> <h3 class="panel-title"><strong>YOUR SERVER STATUS</strong></h3> </div> <div id="panel-chart-widget-1" class="collapse in"> <div class="the-box no-border full bg-success no-margin"> <div id="realtime-chart-widget"> <div id="realtime-chart-container-widget"></div> </div><!-- /.realtime-chart --> </div><!-- /.the-box .no-border --> <div class="the-box no-border"> <div class="row"> <div class="col-sm-6"> <div class="row"> <div class="col-xs-6 text-center"> <h4 class="small-heading">Kernel memory</h4> <span class="chart chart-widget-pie widget-easy-pie-1" data-percent="45"> <span class="percent"></span> </span> </div><!-- /.col-xs-6 --> <div class="col-xs-6 text-center"> <h4 class="small-heading">Physical memory</h4> <span class="chart chart-widget-pie widget-easy-pie-2" data-percent="85"> <span class="percent"></span> </span> </div><!-- /.col-xs-6 --> </div><!-- /.row --> <hr /> <button class="btn btn-block btn-danger"><i class="fa fa-cogs"></i> Resource monitor</button> </div><!-- /.col-sm-6 --> <div class="col-sm-6"> <h4 class="small-heading">System status</h4> <p class="small">Handles - <span class="text-danger">80%</span></p> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> </div><!-- /.progress-bar .progress-bar-danger --> </div><!-- /.progress .no-rounded --> <p class="small">Threads - <span class="text-warning">65%</span></p> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100" style="width: 65%"> </div><!-- /.progress-bar .progress-bar-warning --> </div><!-- /.progress .no-rounded --> <p class="small">Proccess - <span class="text-success">40%</span></p> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> </div><!-- /.progress-bar .progress-bar-success --> </div><!-- /.progress .no-rounded --> <p class="small">Cached - <span class="text-info">70%</span></p> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 70%"> </div><!-- /.progress-bar .progress-bar-info --> </div><!-- /.progress .no-rounded --> </div><!-- /.col-sm-6 --> </div><!-- /.row --> </div><!-- /.the-box .no-border --> </div><!-- /#panel-chart-widget-1 --> </div><!-- /.the-box .no-border --> <!-- END SERVER STATUS WIDGET --> <!-- BEGIN CHART WIDGET 1 --> <div class="the-box no-border full"> <div class="the-box no-border bg-info no-margin full"> <div id="morris-widget-1" style="height: 250px;"></div> </div><!-- the-box no-border bg-info no-margin full --> <div class="the-box no-border bg-dark no-margin chart-des"> <div class="row"> <div class="col-xs-7"> <h3 class="bolded">LAST YEAR</h3> <p>Today May 20 2014</p> </div><!-- /.col-xs-7 --> <div class="col-xs-5 text-right"> <h3 class="bolded text-success">+805.00</h3> <p>-10,1(11%)</p> </div><!-- /.col-xs-5 --> </div><!-- /.row --> </div><!-- the-box no-border bg-dark no-margin --> <div class="the-box no-border no-margin"> <div class="row"> <div class="col-xs-5"> <h1 class="bolded">50,024K</h1> <p class="text-muted">Lifetime earnings</p> </div><!-- /.col-xs-5 --> <div class="col-xs-7"> <div id="morris-widget-2" style="height: 120px;"></div> </div><!-- /.col-xs-5 --> </div><!-- /.row --> </div><!-- the-box no-border no-margin --> </div><!-- /.the-box no-border .full --> <!-- END CHART WIDGET 1 --> </div><!-- /.col-sm-12 col-md-8 --> <div class="col-sm-12 col-md-4"> <div class="row"> <div class="col-sm-6 col-md-12"> <!-- BEGIN HEADLINE NEWS TILES --> <div class="the-box no-border full"> <div id="tiles-slide-2" class="owl-carousel tiles-carousel"> <div class="item full"> <img src="assets/img/avatar/avatar-1.jpg" class="avatar img-circle has-white-shadow" alt="avatar"> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome headline news title</a></h4> <p class="small">02 MAY, 2014</p> <p class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh</p> </div> <img src="assets/img/photo/medium/img-12.jpg" alt="Image"> </div><!-- /.item full --> <div class="item full"> <img src="assets/img/avatar/avatar-2.jpg" class="avatar img-circle has-white-shadow" alt="avatar"> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome headline news title</a></h4> <p class="small">01 MAY, 2014</p> <p class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh</p> </div> <img src="assets/img/photo/medium/img-13.jpg" alt="Image"> </div><!-- /.item full --> <div class="item full"> <img src="assets/img/avatar/avatar-3.jpg" class="avatar img-circle has-white-shadow" alt="avatar"> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome headline news title</a></h4> <p class="small">29 APRIL, 2014</p> <p class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh</p> </div> <img src="assets/img/photo/medium/img-14.jpg" alt="Image"> </div><!-- /.item full --> </div><!-- /#tiles-slide-2 --> </div><!-- /.the-box no-border full --> <!-- END HEADLINE NEWS TILES --> </div><!-- /.col-sm-6 col-md-12 --> <div class="col-sm-6 col-md-12"> <!-- BEGIN HEADLINE NEWS TILES --> <div class="the-box no-border bg-warning full"> <div id="tiles-slide-3" class="owl-carousel tiles-carousel-color"> <div class="item full"> <div class="avatar-wrap"> <div class="media"> <a class="pull-left" href="#fakelink"> <img src="assets/img/avatar/avatar-1.jpg" class="avatar img-circle has-white-shadow media-object" alt="avatar"> </a> <div class="media-body"> <h4 class="media-heading">@parishawker</h4> </div><!-- /.media-body --> </div><!-- /.media --> </div><!-- /.avatar-wrap --> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome life story title</a></h4> <p class="small">02 MAY, 2014</p> <p class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh</p> <button class="btn btn-warning btn-sm">Read more</button> </div> </div><!-- /.item full --> <div class="item full"> <div class="avatar-wrap"> <div class="media"> <a class="pull-left" href="#fakelink"> <img src="assets/img/avatar/avatar-2.jpg" class="avatar img-circle has-white-shadow media-object" alt="avatar"> </a> <div class="media-body"> <h4 class="media-heading">@thomaswhite</h4> </div><!-- /.media-body --> </div><!-- /.media --> </div><!-- /.avatar-wrap --> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome life story title</a></h4> <p class="small">01 MAY, 2014</p> <p class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh</p> <button class="btn btn-warning btn-sm">Read more</button> </div> </div><!-- /.item full --> <div class="item full"> <div class="avatar-wrap"> <div class="media"> <a class="pull-left" href="#fakelink"> <img src="assets/img/avatar/avatar-3.jpg" class="avatar img-circle has-white-shadow media-object" alt="avatar"> </a> <div class="media-body"> <h4 class="media-heading">@doinaslaivici</h4> </div><!-- /.media-body --> </div><!-- /.media --> </div><!-- /.avatar-wrap --> <div class="des"> <h4 class="bolded"><a href="#fakelink">Awesome life story title</a></h4> <p class="small">29 APRIL, 2014</p> <p class="small">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh</p> <button class="btn btn-warning btn-sm">Read more</button> </div> </div><!-- /.item full --> </div><!-- /#tiles-slide-2 --> </div><!-- /.the-box no-border full --> <!-- END HEADLINE NEWS TILES --> </div><!-- /.col-sm-6 col-md-12 --> </div><!-- /.row --> <!-- BEGIN TASK LIST --> <div class="panel panel-success panel-no-border task-list-wrap"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-check-square-o"></i> Your current tasks</h3> </div> <ul class="list-group"> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-1"> <label for="task-1">Eating woods</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-2" checked /> <label for="task-2">Washing my pets</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-3" checked /> <label for="task-3">Uploading selfie photos</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-4" checked /> <label for="task-4">Downloading movie</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-5"> <label for="task-5">Updating my <i>alay</i> status</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-6" checked /> <label for="task-6">Hunting cabe-cabean</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-7"> <label for="task-7">Creating web template</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-8" checked /> <label for="task-8">Walking to Malioboro</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-9" checked /> <label for="task-9">Listening Alay songs</label> </div><!-- /.checkbox --> </li> <li class="list-group-item"> <div class="checkbox"> <input type="checkbox" id="task-10" /> <label for="task-10">Being an elite author</label> </div><!-- /.checkbox --> </li> </ul> <div class="panel-footer"> <p><button class="btn btn-danger btn-perspective btn-block">See all tasks</button></p> </div> </div><!-- /.panel panel-success --> <!-- END TASK LIST --> </div><!-- /.col-sm-4 --> </div><!-- /.the-box .no-border --> <!-- BEGIN SiTE INFORMATIONS --> <div class="row"> <div class="col-sm-3"> <div class="the-box no-border bg-success rounded tiles-information"> <i class="fa fa-users icon-bg"></i> <div class="tiles-inner text-center"> <p>TODAY VISITORS</p> <h1 class="bolded">12,254K</h1> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> </div><!-- /.progress-bar .progress-bar-success --> </div><!-- /.progress .no-rounded --> <p><small>Better than yesterday ( 7,5% )</small></p> </div><!-- /.tiles-inner --> </div><!-- /.the-box no-border --> </div><!-- /.col-sm-3 --> <div class="col-sm-3"> <div class="the-box no-border bg-warning rounded tiles-information"> <i class="fa fa-shopping-cart icon-bg"></i> <div class="tiles-inner text-center"> <p>TODAY SALES</p> <h1 class="bolded">521</h1> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> </div><!-- /.progress-bar .progress-bar-warning --> </div><!-- /.progress .no-rounded --> <p><small>Better than yesterday ( 10,5% )</small></p> </div><!-- /.tiles-inner --> </div><!-- /.the-box no-border --> </div><!-- /.col-sm-3 --> <div class="col-sm-3"> <div class="the-box no-border bg-danger rounded tiles-information"> <i class="fa fa-comments icon-bg"></i> <div class="tiles-inner text-center"> <p>TODAY FEEDBACK</p> <h1 class="bolded">124</h1> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> </div><!-- /.progress-bar .progress-bar-danger --> </div><!-- /.progress .no-rounded --> <p><small>Less than yesterday ( <span class="text-danger">-7,5%</span> )</small></p> </div><!-- /.tiles-inner --> </div><!-- /.the-box no-border --> </div><!-- /.col-sm-3 --> <div class="col-sm-3"> <div class="the-box no-border bg-info rounded tiles-information"> <i class="fa fa-money icon-bg"></i> <div class="tiles-inner text-center"> <p>TODAY EARNINGS</p> <h1 class="bolded">10,241</h1> <div class="progress no-rounded progress-xs"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> </div><!-- /.progress-bar .progress-bar-info --> </div><!-- /.progress .no-rounded --> <p><small>Better than yesterday ( 2,5% )</small></p> </div><!-- /.tiles-inner --> </div><!-- /.the-box no-border --> </div><!-- /.col-sm-3 --> </div><!-- /.row --> <!-- END SITE INFORMATIONS --> <div class="row"> <div class="col-sm-4"> <!-- BEGIN WEATHER WIDGET 1 --> <div class="the-box bg-info no-border"> <h4 class="text-center bolded">YOGYAKARTA, ID</h4> <p class="text-center">April 27, 2014</p> <div class="weather-widget"> <div class="row"> <div class="col-xs-6 text-center"> <canvas id="rain" width="120" height="120"></canvas> </div><!-- /.col-sm-6 --> <div class="col-xs-6"> <h1 class="bolded degrees">29<i class="wi-degrees"></i></h1> <p>and falling</p> </div><!-- /.col-sm-6 --> </div><!-- /.row --> <h4 class="text-center bolded">Day rain</h4> <p class="text-center">Wind: 3 mph (E)</p> </div><!-- /.weather-widget --> <div class="row"> <div class="col-xs-2 text-center"> <p><small>Sa</small></p> <i class="wi-day-cloudy-gusts icon-weather"></i> <p class="no-margin"><small>27<i class="wi-degrees"></i></small></p> </div><!-- /.col-xs-2 --> <div class="col-xs-2 text-center"> <p><small>Su</small></p> <i class="wi-day-cloudy-gusts icon-weather"></i> <p class="no-margin"><small>22<i class="wi-degrees"></i></small></p> </div><!-- /.col-xs-2 --> <div class="col-xs-2 text-center"> <p><small>Mo</small></p> <i class="wi-day-cloudy-gusts icon-weather"></i> <p class="no-margin"><small>31<i class="wi-degrees"></i></small></p> </div><!-- /.col-xs-2 --> <div class="col-xs-2 text-center"> <p><small>Tu</small></p> <i class="wi-day-cloudy-gusts icon-weather"></i> <p class="no-margin"><small>23<i class="wi-degrees"></i></small></p> </div><!-- /.col-xs-2 --> <div class="col-xs-2 text-center"> <p><small>We</small></p> <i class="wi-day-cloudy-gusts icon-weather"></i> <p class="no-margin"><small>25<i class="wi-degrees"></i></small></p> </div><!-- /.col-xs-2 --> <div class="col-xs-2 text-center"> <p><small>Th</small></p> <i class="wi-day-cloudy-gusts icon-weather"></i> <p class="no-margin"><small>24<i class="wi-degrees"></i></small></p> </div><!-- /.col-xs-2 --> </div><!-- /.row --> </div><!-- /.the-box bg-info no-border --> <!-- END WEATHER WIDGET 1 --> </div><!-- /.col-sm-4 --> <div class="col-sm-4"> <!-- BEGIN WEATHER WIDGET 2 --> <div class="the-box bg-success no-border"> <h4 class="text-center bolded">YOGYAKARTA, ID</h4> <p class="text-center">TODAY</p> <div class="weather-widget"> <div class="row"> <div class="col-xs-6 text-center"> <canvas id="partly-cloudy-day" width="140" height="140"></canvas> </div><!-- /.col-xs-6 --> <div class="col-xs-6"> <h1 class="bolded degrees">32<i class="wi-degrees"></i></h1> <p>Partly cloudy day</p> </div><!-- /.col-xs-6 --> </div><!-- /.row --> </div><!-- /.weather-widget --> <div class="row"> <div class="col-xs-4 text-center"> <h4>SAT</h4> <canvas id="cloudy" width="50" height="50"></canvas> <h4 class="bolded">30<i class="wi-degrees"></i></h4> </div><!-- /.col-xs-4 --> <div class="col-xs-4 text-center"> <h4>SUN</h4> <canvas id="wind" width="50" height="50"></canvas> <h4 class="bolded">28<i class="wi-degrees"></i></h4> </div><!-- /.col-xs-4 --> <div class="col-xs-4 text-center"> <h4>MON</h4> <canvas id="clear-day" width="50" height="50"></canvas> <h4 class="bolded">33<i class="wi-degrees"></i></h4> </div><!-- /.col-xs-4 --> </div><!-- /.row --> </div><!-- /.the-box bg-info no-border --> <!-- END WEATHER WIDGET 2 --> </div><!-- /.col-sm-4 --> <div class="col-sm-4"> <!-- BEGIN WEATHER WIDGET 3 --> <div class="the-box no-border" id="weather-widget-2"> <h4 class="text-center bolded white-text">YOGYAKARTA, ID</h4> <p class="text-center white-text">TONIGHT</p> <div class="weather-widget"> <div class="row"> <div class="col-xs-6 text-center"> <canvas id="partly-cloudy-night" width="140" height="140"></canvas> </div><!-- /.col-xs-6 --> <div class="col-xs-6"> <h1 class="bolded degrees white-text">32<i class="wi-degrees"></i></h1> <p class="white-text">Partly cloudy night</p> </div><!-- /.col-xs-6 --> </div><!-- /.row --> </div><!-- /.weather-widget --> <div class="row"> <div class="col-xs-4 text-center"> <h4 class="white-text">SAT</h4> <canvas id="clear-night" width="50" height="50"></canvas> <h4 class="bolded white-text">27<i class="wi-degrees"></i></h4> </div><!-- /.col-xs-4 --> <div class="col-xs-4 text-center"> <h4 class="white-text">SUN</h4> <canvas id="fog" width="50" height="50"></canvas> <h4 class="bolded white-text">26<i class="wi-degrees"></i></h4> </div><!-- /.col-xs-4 --> <div class="col-xs-4 text-center"> <h4 class="white-text">MON</h4> <canvas id="snow" width="50" height="50"></canvas> <h4 class="bolded white-text">15<i class="wi-degrees"></i></h4> </div><!-- /.col-xs-4 --> </div><!-- /.row --> </div><!-- /.the-box bg-info no-border --> <!-- END WEATHER WIDGET 2 --> </div><!-- /.col-sm-4 --> </div><!-- /.row --> <div class="row"> <div class="col-sm-3"> <!-- BEGIN WEATHER WIDGET 4 --> <div class="the-box no-border full text-center"> <div class="the-box no-border bg-warning no-margin"> <canvas id="sleet" width="140" height="140"></canvas> <h1 class="bolded less-distance">27<i class="wi-degrees"></i></h1> <h4>It's raining</h4> </div><!-- /.the-box no-border bg-warning no-margin --> <div class="the-box no-border no-margin"> <h4 class="bolded less-distance">JAKARTA, ID</h4> <p class="small text-muted">Today, 04:42 PM</p> </div><!-- /.the-box no-border no-margin --> </div><!-- /.the-box .no-border .full --> <!-- END WEATHER WIDGET 4 --> <!-- BEGIN WEATHER WIDGET 5 --> <div class="the-box no-border full text-center"> <div class="the-box no-border bg-primary no-margin"> <i class="wi-sunrise icon-xl-size"></i> <h1 class="bolded less-distance">31<i class="wi-degrees"></i></h1> </div><!-- /.the-box no-border bg-primary no-margin --> <div class="the-box no-border no-margin"> <h4 class="bolded less-distance">SURAKARTA</h4> <p class="small text-muted">Today, 06:00 AM</p> </div><!-- /.the-box no-border no-margin --> </div><!-- /.the-box .no-border .full --> <!-- BEGIN WEATHER WIDGET 5 --> </div><!-- /.col-sm-3 --> <div class="col-sm-4"> <!-- BEGIN REMINDER WIDGET --> <div class="the-box no-border full"> <div class="the-box bg-dark no-border no-margin"> <p class="text-center"><i class="fa fa-clock-o icon-lg"></i></p> <h4 class="bolded less-distance text-danger text-center">My personal reminder</h4> </div><!-- /.the-box no-border no-margin --> <div class="the-box no-border bg-danger no-margin"> <h4>Next week agenda</h4> <hr /> <div id="tiles-slide-1" class="owl-carousel my-reminder"> <div class="item full text-left"> <p> Eating some sand and listening alay songs in the small hole under bridge </p> <p class="small">Wrote about a month ago</p> </div> <div class="item full"> <p> Go to school again, do homework again, meet some best friends again </p> <p class="small">Wrote about a week ago</p> </div> <div class="item full"> <p> Finishing all my works, time to vacation, spending time with family and friends </p> <p class="small">Wrote 2 days ago</p> </div> </div><!-- /#tiles-slide-1 --> </div><!-- /.the-box no-border bg-danger no-margin --> </div><!-- /.the-box .no-border .full --> <!-- END REMINDER WIDGET --> </div><!-- /.col-sm-4 --> <div class="col-sm-5"> <!-- BEGIN PHOTO COLLECTION WIDGET --> <div class="the-box no-border full"> <div class="the-box no-border bg-warning no-margin full"> <div id="photo-collection-1" class="owl-carousel"> <div class="item full"><img src="assets/img/photo/medium/img-1.jpg" alt="Image"></div> <div class="item full"><img src="assets/img/photo/medium/img-2.jpg" alt="Image"></div> <div class="item full"><img src="assets/img/photo/medium/img-3.jpg" alt="Image"></div> </div> </div><!-- /.the-box no-border bg-warning no-margin --> <div class="the-box no-border no-margin"> <h4 class="bolded">My photo collection</h4> <p class="text-muted"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </p> <p> <button class="btn btn-default btn-rounded-lg btn-sm"><i class="fa fa-heart text-danger"></i> 1,254</button> <button class="btn btn-success btn-rounded-lg btn-sm"><i class="fa fa-reply"></i> 204</button> </p> </div><!-- /.the-box no-border no-margin --> </div><!-- /.the-box .no-border .full --> <!-- END PHOTO COLLECTION WIDGET --> </div><!-- /.col-sm-5 --> </div><!-- /.row --> </div><!-- /.container-fluid --> <!-- BEGIN FOOTER --> <footer> &copy; 2014 <a href="#fakelink">Your company</a><br /> Design by <a href="http://isohdesign.com" target="_blank">ids</a>. Purchase this item at <a href="http://goo.gl/wSCjxD" target="_blank">Themeforest</a> </footer> <!-- END FOOTER --> </div><!-- /.page-content --> </div><!-- /.wrapper --> <!-- END PAGE CONTENT --> <!-- BEGIN BACK TO TOP BUTTON --> <div id="back-top"> <a href="#top"><i class="fa fa-chevron-up"></i></a> </div> <!-- END BACK TO TOP --> <!-- =========================================================== END PAGE =========================================================== --> <!-- =========================================================== Placed at the end of the document so the pages load faster =========================================================== --> <!-- MAIN JAVASRCIPT (REQUIRED ALL PAGE)--> <script src="assets/js/jquery.min.js"></script> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/plugins/retina/retina.min.js"></script> <script src="assets/plugins/nicescroll/jquery.nicescroll.js"></script> <script src="assets/plugins/slimscroll/jquery.slimscroll.min.js"></script> <script src="assets/plugins/backstretch/jquery.backstretch.min.js"></script> <!-- PLUGINS --> <script src="assets/plugins/skycons/skycons.js"></script> <script src="assets/plugins/prettify/prettify.js"></script> <script src="assets/plugins/magnific-popup/jquery.magnific-popup.min.js"></script> <script src="assets/plugins/owl-carousel/owl.carousel.min.js"></script> <script src="assets/plugins/chosen/chosen.jquery.min.js"></script> <script src="assets/plugins/icheck/icheck.min.js"></script> <script src="assets/plugins/datepicker/bootstrap-datepicker.js"></script> <script src="assets/plugins/timepicker/bootstrap-timepicker.js"></script> <script src="assets/plugins/mask/jquery.mask.min.js"></script> <script src="assets/plugins/validator/bootstrapValidator.min.js"></script> <script src="assets/plugins/datatable/js/jquery.dataTables.min.js"></script> <script src="assets/plugins/datatable/js/bootstrap.datatable.js"></script> <script src="assets/plugins/summernote/summernote.min.js"></script> <script src="assets/plugins/markdown/markdown.js"></script> <script src="assets/plugins/markdown/to-markdown.js"></script> <script src="assets/plugins/markdown/bootstrap-markdown.js"></script> <script src="assets/plugins/slider/bootstrap-slider.js"></script> <script src="assets/plugins/toastr/toastr.js"></script> <script src="assets/plugins/newsticker/jquery.newsTicker.min.js"></script> <!-- FULL CALENDAR JS --> <script src="assets/plugins/fullcalendar/lib/jquery-ui.custom.min.js"></script> <script src="assets/plugins/fullcalendar/fullcalendar/fullcalendar.min.js"></script> <script src="assets/js/full-calendar.js"></script> <!-- EASY PIE CHART JS --> <script src="assets/plugins/easypie-chart/easypiechart.min.js"></script> <script src="assets/plugins/easypie-chart/jquery.easypiechart.min.js"></script> <!-- KNOB JS --> <!--[if IE]> <script type="text/javascript" src="assets/plugins/jquery-knob/excanvas.js"></script> <![endif]--> <script src="assets/plugins/jquery-knob/jquery.knob.js"></script> <script src="assets/plugins/jquery-knob/knob.js"></script> <!-- FLOT CHART JS --> <script src="assets/plugins/flot-chart/jquery.flot.js"></script> <script src="assets/plugins/flot-chart/jquery.flot.tooltip.js"></script> <script src="assets/plugins/flot-chart/jquery.flot.resize.js"></script> <script src="assets/plugins/flot-chart/jquery.flot.selection.js"></script> <script src="assets/plugins/flot-chart/jquery.flot.stack.js"></script> <script src="assets/plugins/flot-chart/jquery.flot.time.js"></script> <!-- MORRIS JS --> <script src="assets/plugins/morris-chart/raphael.min.js"></script> <script src="assets/plugins/morris-chart/morris.min.js"></script> <!-- C3 JS --> <script src="assets/plugins/c3-chart/d3.v3.min.js" charset="utf-8"></script> <script src="assets/plugins/c3-chart/c3.min.js"></script> <!-- MAIN APPS JS --> <script src="assets/js/apps.js"></script><script src="assets/js/demo-panel.js"></script> </body> </html>
{ "content_hash": "bbe3bf8482040a3f6cae1ca2f88acdcf", "timestamp": "", "source": "github", "line_count": 2282, "max_line_length": 301, "avg_line_length": 45.707712532865905, "alnum_prop": 0.5525046737932027, "repo_name": "project-store/theme", "id": "1fb067bbee38380385c62ccd759a8fbd9689bbca", "size": "104305", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "backend/Sentir/widget-default.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "27940912" }, { "name": "CoffeeScript", "bytes": "16726" }, { "name": "HTML", "bytes": "231766282" }, { "name": "JavaScript", "bytes": "81504306" }, { "name": "PHP", "bytes": "417111" }, { "name": "Ruby", "bytes": "902" }, { "name": "Shell", "bytes": "616" } ], "symlink_target": "" }
var Footer = require('./Footer.react'); var Header = require('./Header.react'); var MainSection = require('./MainSection.react'); var React = require('react'); var TodoStore = require('../stores/TodoStore'); var Router = require('react-router'); var Link = Router.Link; var AboutPage = React.createClass({ render: function() { return ( <div>ABOUT BIAATCHES <Link to="/todo">Todos</Link> </div> ); }, }); module.exports = AboutPage;
{ "content_hash": "9d1de1e3e87a8c9843f1a0475c908643", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 49, "avg_line_length": 21.272727272727273, "alnum_prop": 0.6367521367521367, "repo_name": "donbonifacio/flux-playground", "id": "46bdd1024b4f37e78cafa551c22e8a0f00e05bdb", "size": "468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/components/AboutPage.react.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10321" }, { "name": "JavaScript", "bytes": "23962" }, { "name": "Shell", "bytes": "1148" } ], "symlink_target": "" }
// // typica - A client library for Amazon Web Services // Copyright (C) 2008 Xerox Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.xerox.amazonws.common; import com.xerox.amazonws.fps.FPSError; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * A wrapper exception to simplify catching errors related to AWS activity. * * @author D. Kavanagh * @author developer@dotech.com */ public class AWSException extends Exception { private static final String UNKNOWN_REQUEST = "Unknown Request"; private final String requestId; private final List<AWSError> errors = new ArrayList<AWSError>(); public AWSException(String s) { super(s); requestId = UNKNOWN_REQUEST; } public AWSException(String s, Throwable cause) { super(s, cause); requestId = UNKNOWN_REQUEST; } public AWSException(@NotNull String message, @NotNull final String requestId, @NotNull AWSError... errors) { this(message, requestId, Arrays.asList(errors)); } public AWSException(String s, String requestId, List<? extends AWSError> errors) { super(s); this.requestId = requestId; this.errors.addAll(errors); } protected AWSException(AWSException ex) { // copy constructor super(ex.getMessage(), ex.getCause()); this.requestId = ex.getRequestId(); this.errors.addAll(ex.errors); } @Nullable public String getRequestId() { return requestId; } @NotNull public List<? extends AWSError> getErrors() { return errors; } protected static String concatenateErrors(List<FPSError> errors) { final StringBuilder buffer = new StringBuilder(); for (FPSError error : errors) buffer.append(error.getCode()).append(": ").append(error.getMessage()).append('.'); return buffer.toString(); } }
{ "content_hash": "cafbbce8d1bc6288ab5efc7b478be6e7", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 89, "avg_line_length": 29.693181818181817, "alnum_prop": 0.6850363566781478, "repo_name": "cadams500/typica-clone", "id": "ee242c59c1eae5f0cf0ce71f61869f96d35966a7", "size": "2613", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "java/com/xerox/amazonws/common/AWSException.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "813092" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://www.activiti.org/schema/spring/components" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"> <property name="targetDataSource"> <bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource"> <property name="driverClass" value="org.h2.Driver"/> <property name="url" value="jdbc:h2:mem:activiti;DB_CLOSE_DELAY=1000"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="processEngineConfiguration" class="org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration"> <property name="processEngineName" value="default" /> <property name="dataSource" ref="dataSource"/> <property name="transactionManager" ref="transactionManager"/> <property name="databaseSchemaUpdate" value="true"/> <property name="jobExecutorActivate" value="false"/> </bean> <!-- using ManagedProcessEngineFactoryBean allows registering the ProcessEngine with the BpmPlatform --> <bean id="processEngine" class="org.camunda.bpm.engine.spring.container.ManagedProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"/> </bean> <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/> <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/> <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/> <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/> <bean id="managementService" factory-bean="processEngine" factory-method="getManagementService"/> </beans>
{ "content_hash": "4f606485c2ddc9c52d9923c930cb018c", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 135, "avg_line_length": 56.333333333333336, "alnum_prop": 0.7037193575655114, "repo_name": "tkaefer/camunda-bpm-platform", "id": "3179b936dd484ef92c0a42084832c2408cbd82fa", "size": "2366", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "engine-spring/src/test/resources/org/camunda/bpm/engine/spring/test/container/ManagedProcessEngineFactoryBean-context.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>org.scalatest.prop.TableFor11</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" rel="stylesheet" type="text/css" media="screen" /> <script type="text/javascript" src="../../../lib/jquery.js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <!-- gtag [javascript] --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-71294502-1"></script> <script defer> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-71294502-1'); </script> </head> <body class="value" onload="windowTitle();"> <p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.prop">prop</a></p> <div id="definition"> <img src="../../../lib/object_big.png" /> <h1>TableFor11</h1> </div> <h4 class="signature" id="signature"> <span class="kind">object</span> <span class="symbol"> <span class="name">TableFor11</span> <span class="result"> extends AnyRef</span> </span> </h4> <div class="fullcomment" id="comment"><div class="comment cmt"><p>Companion object for class <code>TableFor11</code> that provides an implicit <code>canBuildFrom</code> method that enables higher order functions defined on <code>TableFor11</code> to return another <code>TableFor11</code>. </p></div><div class="block"> go to: <a href="TableFor11.html">companion</a> </div><div class="block"> linear super types: AnyRef, <span class="extype" name="scala.Any">Any</span> </div> </div> <div id="template"> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input accesskey="/" type="text" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol><li class="alpha in">Alphabetic</li><li class="inherit out">By inheritance</li></ol> </div> <div id="ancestors"> <span class="filtertype">Inherited</span> <ol><li class="hideall">Hide All</li><li class="showall">Show all</li></ol> <ol id="linearization"><li class="in" name="org.scalatest.prop.TableFor11">TableFor11</li><li class="in" name="scala.AnyRef">AnyRef</li><li class="in" name="scala.Any">Any</li></ol> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in">Public</li><li class="all out">All</li></ol> </div> <div id="impl"> <span class="filtertype">Impl.</span> <ol><li class="concrete in">Concrete</li><li class="abstract in">Abstract</li></ol> </div> </div> <div class="values members" id="values"> <h3>Value Members</h3> <ol><li visbl="pub" data-isabs="false" name="scala.AnyRef#!="> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">!=</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div></div> </li><li visbl="pub" data-isabs="false" name="scala.Any#!="> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">!=</span> <span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt"><code>o != arg0</code> is the same as <code>!(o == (arg0))</code>.</p> <div class="fullcomment"><div class="comment cmt"><p><code>o != arg0</code> is the same as <code>!(o == (arg0))</code>. </p></div><dl class="paramcmts block"><dt class="param">arg0</dt><dd class="cmt"><p>the object to compare against this object for dis-equality.</p></dd><dt>returns</dt><dd class="cmt"><p><code>false</code> if the receiver object is equivalent to the argument; <code>true</code> otherwise.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: Any </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef###"> <a id="##():Int"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">##</span> <span class="params">()</span> <span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef → Any </div></div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#$asInstanceOf"> <a id="$asInstanceOf[T0]():T0"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">$asInstanceOf</span> <span class="tparams">[<span name="T0">T0</span>]</span> <span class="params">()</span> <span class="result">: T0</span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div></div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#$isInstanceOf"> <a id="$isInstanceOf[T0]():Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">$isInstanceOf</span> <span class="tparams">[<span name="T0">T0</span>]</span> <span class="params">()</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div></div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#=="> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">==</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt"><code>o == arg0</code> is the same as <code>if (o eq null) arg0 eq null else o.equals(arg0)</code>.</p> <div class="fullcomment"><div class="comment cmt"><p><code>o == arg0</code> is the same as <code>if (o eq null) arg0 eq null else o.equals(arg0)</code>. </p></div><dl class="paramcmts block"><dt class="param">arg0</dt><dd class="cmt"><p>the object to compare against this object for equality.</p></dd><dt>returns</dt><dd class="cmt"><p><code>true</code> if the receiver object is equivalent to the argument; <code>false</code> otherwise.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.Any#=="> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">==</span> <span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt"><code>o == arg0</code> is the same as <code>o.equals(arg0)</code>.</p> <div class="fullcomment"><div class="comment cmt"><p><code>o == arg0</code> is the same as <code>o.equals(arg0)</code>. </p></div><dl class="paramcmts block"><dt class="param">arg0</dt><dd class="cmt"><p>the object to compare against this object for equality.</p></dd><dt>returns</dt><dd class="cmt"><p><code>true</code> if the receiver object is equivalent to the argument; <code>false</code> otherwise.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: Any </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.Any#asInstanceOf"> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">asInstanceOf</span> <span class="tparams">[<span name="T0">T0</span>]</span> <span class="result">: T0</span> </span> </h4> <p class="shortcomment cmt">This method is used to cast the receiver object to be of type <code>T0</code>.</p> <div class="fullcomment"><div class="comment cmt"><p>This method is used to cast the receiver object to be of type <code>T0</code>.</p><p>Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression<code>1.asInstanceOf[String]</code> will throw a <code>ClassCastException</code> at runtime, while the expression<code>List(1).asInstanceOf[List[String]]</code> will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested typed. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>the receiver object.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: Any </div> </div> </li><li visbl="pub" data-isabs="false" name="org.scalatest.prop.TableFor11#canBuildFrom"> <a id="canBuildFrom[A, B, C, D, E, F, G, H, I, J, K]:CanBuildFrom[TableFor11[A, B, C, D, E, F, G, H, I, J, K], (A, B, C, D, E, F, G, H, I, J, K), TableFor11[A, B, C, D, E, F, G, H, I, J, K]]"></a> <h4 class="signature"> <span class="kind">implicit def</span> <span class="symbol"> <span class="name">canBuildFrom</span> <span class="tparams">[<span name="A">A</span>, <span name="B">B</span>, <span name="C">C</span>, <span name="D">D</span>, <span name="E">E</span>, <span name="F">F</span>, <span name="G">G</span>, <span name="H">H</span>, <span name="I">I</span>, <span name="J">J</span>, <span name="K">K</span>]</span> <span class="result">: <span class="extype" name="scala.collection.generic.CanBuildFrom">CanBuildFrom</span>[<a href="TableFor11.html" class="extype" name="org.scalatest.prop.TableFor11">TableFor11</a>[A, B, C, D, E, F, G, H, I, J, K], (A, B, C, D, E, F, G, H, I, J, K), <a href="TableFor11.html" class="extype" name="org.scalatest.prop.TableFor11">TableFor11</a>[A, B, C, D, E, F, G, H, I, J, K]]</span> </span> </h4> <p class="shortcomment cmt">Implicit method enabling higher order functions of <code>TableFor11</code> to return sequences of type <code>TableFor11</code>.</p> <div class="fullcomment"><div class="comment cmt"><p>Implicit method enabling higher order functions of <code>TableFor11</code> to return sequences of type <code>TableFor11</code>. </p></div><div class="block"> attributes: implicit </div> </div> </li><li visbl="prt" data-isabs="false" name="scala.AnyRef#clone"> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">clone</span> <span class="params">()</span> <span class="result">: AnyRef</span> </span> </h4> <p class="shortcomment cmt">This method creates and returns a copy of the receiver object.</p> <div class="fullcomment"><div class="comment cmt"><p>This method creates and returns a copy of the receiver object.</p><p>The default implementation of the <code>clone</code> method is platform dependent. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>a copy of the receiver object.</p></dd></dl><div class="block"> attributes: protected </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#eq"> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">eq</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt">This method is used to test whether the argument (<code>arg0</code>) is a reference to the receiver object (<code>this</code>).</p> <div class="fullcomment"><div class="comment cmt"><p>This method is used to test whether the argument (<code>arg0</code>) is a reference to the receiver object (<code>this</code>).</p><p>The <code>eq</code> method implements an [http://en.wikipedia.org/wiki/Equivalence_relation equivalence relation] on non-null instances of <code>AnyRef</code>: * It is reflexive: for any non-null instance <code>x</code> of type <code>AnyRef</code>, <code>x.eq(x)</code> returns <code>true</code>. * It is symmetric: for any non-null instances <code>x</code> and <code>y</code> of type <code>AnyRef</code>, <code>x.eq(y)</code> returns <code>true</code> if and only if <code>y.eq(x)</code> returns <code>true</code>. * It is transitive: for any non-null instances <code>x</code>, <code>y</code>, and <code>z</code> of type <code>AnyRef</code> if <code>x.eq(y)</code> returns <code>true</code> and <code>y.eq(z)</code> returns <code>true</code>, then <code>x.eq(z)</code> returns <code>true</code>.</p><p>Additionally, the <code>eq</code> method has three other properties. * It is consistent: for any non-null instances <code>x</code> and <code>y</code> of type <code>AnyRef</code>, multiple invocations of <code>x.eq(y)</code> consistently returns <code>true</code> or consistently returns <code>false</code>. * For any non-null instance <code>x</code> of type <code>AnyRef</code>, <code>x.eq(null)</code> and <code>null.eq(x)</code> returns <code>false</code>. * <code>null.eq(null)</code> returns <code>true</code>.</p><p>When overriding the <code>equals</code> or <code>hashCode</code> methods, it is important to ensure that their behavior is consistent with reference equality. Therefore, if two objects are references to each other (<code>o1 eq o2</code>), they should be equal to each other (<code>o1 == o2</code>) and they should hash to the same value (<code>o1.hashCode == o2.hashCode</code>). </p></div><dl class="paramcmts block"><dt class="param">arg0</dt><dd class="cmt"><p>the object to compare against this object for reference equality.</p></dd><dt>returns</dt><dd class="cmt"><p><code>true</code> if the argument is a reference to the receiver object; <code>false</code> otherwise.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#equals"> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">equals</span> <span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt">This method is used to compare the receiver object (<code>this</code>) with the argument object (<code>arg0</code>) for equivalence.</p> <div class="fullcomment"><div class="comment cmt"><p>This method is used to compare the receiver object (<code>this</code>) with the argument object (<code>arg0</code>) for equivalence.</p><p>The default implementations of this method is an [http://en.wikipedia.org/wiki/Equivalence_relation equivalence relation]: * It is reflexive: for any instance <code>x</code> of type <code>Any</code>, <code>x.equals(x)</code> should return <code>true</code>. * It is symmetric: for any instances <code>x</code> and <code>y</code> of type <code>Any</code>, <code>x.equals(y)</code> should return <code>true</code> if and only if <code>y.equals(x)</code> returns <code>true</code>. * It is transitive: for any instances <code>x</code>, <code>y</code>, and <code>z</code> of type <code>AnyRef</code> if <code>x.equals(y)</code> returns <code>true</code> and <code>y.equals(z)</code> returns <code>true</code>, then <code>x.equals(z)</code> should return <code>true</code>.</p><p>If you override this method, you should verify that your implementation remains an equivalence relation. Additionally, when overriding this method it is often necessary to override <code>hashCode</code> to ensure that objects that are &quot;equal&quot; (<code>o1.equals(o2)</code> returns <code>true</code>) hash to the same scala.Int (<code>o1.hashCode.equals(o2.hashCode)</code>). </p></div><dl class="paramcmts block"><dt class="param">arg0</dt><dd class="cmt"><p>the object to compare against this object for equality.</p></dd><dt>returns</dt><dd class="cmt"><p><code>true</code> if the receiver object is equivalent to the argument; <code>false</code> otherwise.</p></dd></dl><div class="block"> definition classes: AnyRef → Any </div> </div> </li><li visbl="prt" data-isabs="false" name="scala.AnyRef#finalize"> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">finalize</span> <span class="params">()</span> <span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <p class="shortcomment cmt">This method is called by the garbage collector on the receiver object when garbage collection determines that there are no more references to the object.</p> <div class="fullcomment"><div class="comment cmt"><p>This method is called by the garbage collector on the receiver object when garbage collection determines that there are no more references to the object.</p><p>The details of when and if the <code>finalize</code> method are invoked, as well as the interaction between <code>finalize</code>and non-local returns and exceptions, are all platform dependent.</p></div><div class="block"> attributes: protected </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#getClass"> <a id="getClass():java.lang.Class[_]"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">getClass</span> <span class="params">()</span> <span class="result">: java.lang.Class[_]</span> </span> </h4> <p class="shortcomment cmt">Returns a representation that corresponds to the dynamic class of the receiver object.</p> <div class="fullcomment"><div class="comment cmt"><p>Returns a representation that corresponds to the dynamic class of the receiver object.</p><p>The nature of the representation is platform dependent. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>a representation that corresponds to the dynamic class of the receiver object.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#hashCode"> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">hashCode</span> <span class="params">()</span> <span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <p class="shortcomment cmt">Returns a hash code value for the object.</p> <div class="fullcomment"><div class="comment cmt"><p>Returns a hash code value for the object.</p><p>The default hashing algorithm is platform dependent.</p><p>Note that it is allowed for two objects to have identical hash codes (<code>o1.hashCode.equals(o2.hashCode)</code>) yet not be equal (<code>o1.equals(o2)</code> returns <code>false</code>). A degenerate implementation could always return <code>0</code>. However, it is required that if two objects are equal (<code>o1.equals(o2)</code> returns <code>true</code>) that they have identical hash codes (<code>o1.hashCode.equals(o2.hashCode)</code>). Therefore, when overriding this method, be sure to verify that the behavior is consistent with the <code>equals</code> method. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>the hash code value for the object.</p></dd></dl><div class="block"> definition classes: AnyRef → Any </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.Any#isInstanceOf"> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">isInstanceOf</span> <span class="tparams">[<span name="T0">T0</span>]</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt">This method is used to test whether the dynamic type of the receiver object is <code>T0</code>.</p> <div class="fullcomment"><div class="comment cmt"><p>This method is used to test whether the dynamic type of the receiver object is <code>T0</code>.</p><p>Note that the test result of the test is modulo Scala's erasure semantics. Therefore the expression<code>1.isInstanceOf[String]</code> will return <code>false</code>, while the expression <code>List(1).isInstanceOf[List[String]]</code> will return <code>true</code>. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested typed. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p><code>true</code> if the receiver object is an instance of erasure of type <code>T0</code>; <code>false</code> otherwise.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: Any </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#ne"> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">ne</span> <span class="params">(<span name="arg0">arg0: AnyRef</span>)</span> <span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt"><code>o.ne(arg0)</code> is the same as <code>!(o.eq(arg0))</code>.</p> <div class="fullcomment"><div class="comment cmt"><p><code>o.ne(arg0)</code> is the same as <code>!(o.eq(arg0))</code>. </p></div><dl class="paramcmts block"><dt class="param">arg0</dt><dd class="cmt"><p>the object to compare against this object for reference dis-equality.</p></dd><dt>returns</dt><dd class="cmt"><p><code>false</code> if the argument is not a reference to the receiver object; <code>true</code> otherwise.</p></dd></dl><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#notify"> <a id="notify():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">notify</span> <span class="params">()</span> <span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Wakes up a single thread that is waiting on the receiver object's monitor.</p> <div class="fullcomment"><div class="comment cmt"><p>Wakes up a single thread that is waiting on the receiver object's monitor.</p></div><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#notifyAll"> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">notifyAll</span> <span class="params">()</span> <span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <p class="shortcomment cmt">Wakes up all threads that are waiting on the receiver object's monitor.</p> <div class="fullcomment"><div class="comment cmt"><p>Wakes up all threads that are waiting on the receiver object's monitor.</p></div><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#synchronized"> <a id="synchronized[T0](T0):T0"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">synchronized</span> <span class="tparams">[<span name="T0">T0</span>]</span> <span class="params">(<span name="arg0">arg0: T0</span>)</span> <span class="result">: T0</span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div></div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#toString"> <a id="toString():String"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">toString</span> <span class="params">()</span> <span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <p class="shortcomment cmt">Returns a string representation of the object.</p> <div class="fullcomment"><div class="comment cmt"><p>Returns a string representation of the object.</p><p>The default representation is platform dependent. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>a string representation of the object.</p></dd></dl><div class="block"> definition classes: AnyRef → Any </div> </div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#wait"> <a id="wait():Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">wait</span> <span class="params">()</span> <span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div></div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#wait"> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">wait</span> <span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span> <span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div></div> </li><li visbl="pub" data-isabs="false" name="scala.AnyRef#wait"> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="kind">def</span> <span class="symbol"> <span class="name">wait</span> <span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span> <span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><div class="block"> attributes: final </div><div class="block"> definition classes: AnyRef </div></div> </li></ol> </div> <div class="parent" name="scala.AnyRef"> <h3>Inherited from AnyRef</h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="tooltip"></div> </body> </html>
{ "content_hash": "7491ba5baefd8352ff2741d00fce3066", "timestamp": "", "source": "github", "line_count": 661, "max_line_length": 488, "avg_line_length": 48.636913767019664, "alnum_prop": 0.5815421941584498, "repo_name": "scalatest/scalatest-website", "id": "171be6b5ff79ff543f8053512cb4db6b56382e4d", "size": "32157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/scaladoc/1.5/org/scalatest/prop/TableFor11$.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8401192" }, { "name": "HTML", "bytes": "4508833233" }, { "name": "JavaScript", "bytes": "12256885" }, { "name": "Procfile", "bytes": "62" }, { "name": "Scala", "bytes": "136544" } ], "symlink_target": "" }
<?php declare(strict_types = 1); namespace gears\conf; /** * Class Settings is for global static configuration key-value pairs. * @package gears\conf */ final class Settings { /** * Settings constructor. Seals this class. */ private function __construct() { } public static $DB_NAME = 'gears'; public static $DB_DRIVER = 'mysql'; public static $DB_HOST = 'localhost'; public static $DB_PORT = '3306'; public static $DB_USER = ''; public static $DB_PASSWORD = ''; /** * Construct a database connection string with the static setting values. * @return string The database connection string. */ public static function getDBConnString() { return self::$DB_DRIVER . ':host=' . self::$DB_HOST . ':' . self::$DB_PORT . ';dbname=' . self::$DB_NAME; } public static $CURR_USER_SESS_KEY = 'current_user_object'; /** * @var int Site session time out duration. 1800 === 30 minutes */ public static $SESSION_TIMEOUT = 1800; public static $MYSQL_DATETIME_FORMAT = 'Y-m-d H:i:s'; /** * Get the default time zone for all DateTime creation/calculation * @return \DateTimeZone The default time zone */ public static function timeZone() : \DateTimeZone { return new \DateTimeZone('America/New_York'); } }
{ "content_hash": "2fa737fe5bbbf3fe15fbb734c4c73e5a", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 113, "avg_line_length": 27.346938775510203, "alnum_prop": 0.6246268656716418, "repo_name": "sacrefies/csc621-code-gears", "id": "83c7add31c71873363b14c73dd172f7421d0e2c7", "size": "1945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/conf/Settings.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "36399" }, { "name": "HTML", "bytes": "28332" }, { "name": "JavaScript", "bytes": "384997" }, { "name": "PHP", "bytes": "344173" } ], "symlink_target": "" }
import layoutTemplate from '../view/layout.html'; import dashboardTemplate from '../view/dashboard.html'; import errorTemplate from '../view/404.html'; import Entry from 'ng-admin-config/src/Entry'; function dataStoreProvider() { return ['AdminDescription', function (AdminDescription) { return AdminDescription.getDataStore(); }]; } function entryConstructorProvider() { return ['AdminDescription', function (AdminDescription) { return AdminDescription.getEntryConstructor(); }]; } function routing($stateProvider, $urlRouterProvider) { $stateProvider.state('ng-admin', { abstract: true, views: { 'ng-admin': { controller: 'AppController', controllerAs: 'appController', templateProvider: ['NgAdminConfiguration', function(Configuration) { return Configuration().layout() || layoutTemplate; }] } } }); $stateProvider.state('dashboards', { parent: 'ng-admin', url: '/dashboards/:name', params: { name: null, }, controller: 'DashboardController', controllerAs: 'dashboardController', resolve: { dataStore: dataStoreProvider(), Entry: entryConstructorProvider(), hasEntities: ['NgAdminConfiguration', function(Configuration) { return Configuration().entities.length > 0; }], dashboard: ['$stateParams', 'NgAdminConfiguration', function($stateParams, Configuration) { try { return Configuration().getDashboard($stateParams.name); } catch (e) { var error404 = new Error('Unknown dashboard name'); error404.status = 404; // trigger the 404 error throw error404; } }], widgets: ['dashboard', function(dashboard) { return dashboard.widgets; }], responses: ['$stateParams', '$q', 'widgets', 'dataStore', 'Entry', 'ReadQueries', function($stateParams, $q, widgets, dataStore, Entry, ReadQueries) { var sortField = 'sortField' in $stateParams ? $stateParams.sortField : null; var sortDir = 'sortDir' in $stateParams ? $stateParams.sortDir : null; var promises = {}, widget, widgetSortField, widgetSortDir, widgetName; for (widgetName in widgets) { widget = widgets[widgetName]; widgetSortField = widget.getSortFieldName(); widgetSortDir = widget.sortDir(); if (sortField && sortField.split('.')[0] === widget.name()) { widgetSortField = sortField; widgetSortDir = sortDir; } promises[widgetName] = (function (widget, widgetSortField, widgetSortDir) { var rawEntries; return ReadQueries .getAll(widget, 1, {}, widgetSortField, widgetSortDir) .then(response => { rawEntries = response.data; return rawEntries; }) .then(rawEntries => ReadQueries.getReferenceData(widget.fields(), rawEntries)) .then(referenceData => { const references = widget.getReferences(); for (var name in referenceData) { Entry.createArrayFromRest( referenceData[name], [references[name].targetField()], references[name].targetEntity().name(), references[name].targetEntity().identifier().name() ).map(entry => dataStore.addEntry(references[name].targetEntity().uniqueId + '_values', entry)); } }) .then(() => { var entries = widget.mapEntries(rawEntries); // shortcut to display widget of entry with included referenced values dataStore.fillReferencesValuesFromCollection(entries, widget.getReferences(), true); return entries; }); })(widget, widgetSortField, widgetSortDir); } return $q.all(promises); }], entries: ['responses', 'widgets', function(responses, widgets) { var widgetName, entries = {}; for (widgetName in responses) { entries[widgets[widgetName].name()] = responses[widgetName]; } return entries; }], prepare: ['dashboard', '$stateParams', 'dataStore', 'entries', 'widgets', '$window', '$injector', function(dashboard, $stateParams, dataStore, entries, widgets, $window, $injector) { return dashboard.prepare() && $injector.invoke(dashboard.prepare(), dashboard, { query: $stateParams, datastore: dataStore, dashboard, Entry, entries, widgets, window: $window }); }], }, templateProvider: ['dashboard', function(dashboard) { return dashboard.template() || dashboardTemplate; }], }); $stateProvider.state('ma-404', { parent: 'ng-admin', template: errorTemplate }); $urlRouterProvider.when('', 'dashboards/primary'); $urlRouterProvider.otherwise(function($injector, $location) { var state = $injector.get('$state'); state.go('ma-404'); return $location.path(); }); } routing.$inject = ['$stateProvider', '$urlRouterProvider']; export default routing;
{ "content_hash": "1b9cdcfac067099d3dba4ec8f35dac63", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 194, "avg_line_length": 41.435064935064936, "alnum_prop": 0.4923993104529071, "repo_name": "ulrobix/ng-admin", "id": "e5c9ffd0bea6b08244986b0970772a013fa23f4e", "size": "6381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/javascripts/ng-admin/Main/config/routing.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12417" }, { "name": "HTML", "bytes": "15668" }, { "name": "JavaScript", "bytes": "346734" }, { "name": "Makefile", "bytes": "2111" }, { "name": "Shell", "bytes": "786" } ], "symlink_target": "" }
import { KeysPipePipe } from './keys-pipe.pipe'; describe('KeysPipePipe', () => { it('create an instance', () => { const pipe = new KeysPipePipe(); expect(pipe).toBeTruthy(); }); });
{ "content_hash": "d61e72a738732f23c1d86aa87b14195d", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 48, "avg_line_length": 24.5, "alnum_prop": 0.5918367346938775, "repo_name": "friendsofagape/mt2414ui", "id": "af5ebaad255b3c9df853179b6254af8442fd945c", "size": "196", "binary": false, "copies": "2", "ref": "refs/heads/AMTv2", "path": "src/app/keys-pipe.pipe.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10242" }, { "name": "HTML", "bytes": "142509" }, { "name": "JavaScript", "bytes": "2159" }, { "name": "TypeScript", "bytes": "331761" } ], "symlink_target": "" }
<?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <!-- <parameters> <parameter key="php_schulung_de_config_demo.example.class">PhpSchulungDe\ConfigDemoBundle\Example</parameter> </parameters> <services> <service id="php_schulung_de_config_demo.example" class="%php_schulung_de_config_demo.example.class%"> <argument type="service" id="service_id" /> <argument>plain_value</argument> <argument>%parameter_name%</argument> </service> </services> --> </container>
{ "content_hash": "d4404ba5f5ad4f0ecf14deb7a6dd6812", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 120, "avg_line_length": 37.9, "alnum_prop": 0.6569920844327177, "repo_name": "timon-schroeter/PHP-Schulung-Demos", "id": "8c834f8a3e89810d62a411e46cd43c220cfb5a5f", "size": "758", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/Symfony-2.3/src/PhpSchulungDe/ConfigDemoBundle/Resources/config/services.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2204" }, { "name": "PHP", "bytes": "86360" }, { "name": "Puppet", "bytes": "3653" }, { "name": "Ruby", "bytes": "585" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <config> <subConfigs> <!-- --> <!-- article idxs --> <!-- keyword --> <subConfig type="index" id="chapter-austen-idx"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="chapterXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="WordNamedNormalizer"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> </options> </subConfig> <subConfig type="index" id="chapter-austen-idx-case"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="chapterXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="PosNamedNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> </options> </subConfig> <!-- end chapter idxs --> <!-- paragraph idxs --> <!-- keyword --> <subConfig type="index" id="paragraph-austen-idx"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="paragraphXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="WordNamedNormalizer"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> </options> </subConfig> <subConfig type="index" id="paragraph-austen-idx-case"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="paragraphXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="PosNamedNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> </options> </subConfig> <!-- end paragraph idxs --> <!-- sentence idxs --> <!-- keyword --> <subConfig type="index" id="sentence-austen-idx"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="sentenceXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="WordNamedNormalizer"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> <subConfig type="index" id="sentence-austen-idx-case"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="sentenceXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="PosNamedNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> </options> </subConfig> <subConfig type="index" id="5gram-austen-idx"> <objectType>cheshire3.index.SimpleIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="sentenceXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="RegexpSubTokenizer"/> <object type="tokenMerger" ref="5GramTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> </process> </source> <options> <setting type="termIds">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> <!--end sentence idxs --> <!-- Quote Index --> <subConfig type="index" id="quote-austen-idx"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="quoteXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> <subConfig type="index" id="quote-5gram-austen-idx"> <objectType>cheshire3.index.SimpleIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="quoteXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="5GramTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpSubTokenizer"/> <object type="tokenMerger" ref="5GramTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> </process> </source> <options> <setting type="termIds">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> <subConfig type="index" id="longsus-austen-idx"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="longsusXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> <subConfig type="index" id="longsus-5gram-austen-idx"> <objectType>cheshire3.index.SimpleIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="longsusXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="5GramTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpSubTokenizer"/> <object type="tokenMerger" ref="5GramTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> </process> </source> <options> <setting type="termIds">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> <subConfig type="index" id="shortsus-austen-idx"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="shortsusXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="5GramTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpSubTokenizer"/> <object type="tokenMerger" ref="5GramTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> <subConfig type="index" id="book-austen-idx"> <objectType>cheshire3.index.SimpleIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="bookXPath"/> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="SimpleTokenizer"/> <object type="tokenMerger" ref="SimpleTokenMerger"/> </process> </source> </subConfig> <subConfig type="index" id="subCorpus-austen-idx"> <objectType>cheshire3.index.SimpleIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="bookXPath"/> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="SimpleTokenizer"/> <object type="tokenMerger" ref="SimpleTokenMerger"/> <object type="normalizer" ref="SubCorpusNormalizer"/> </process> </source> </subConfig> <subConfig type="index" id="non-quote-austen-idx"> <objectType>cheshire3.index.ProximityIndex</objectType> <paths> <object type="indexStore" ref="indexStore"/> </paths> <source> <xpath ref="nonQuoteXPath"/> <process> <object type="extractor" ref="TaggedTermExtractor"/> <object type="tokenizer" ref="SuppliedOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <source mode="any|all|=|exact|window"> <process> <object type="extractor" ref="SimpleExtractor"/> <object type="tokenizer" ref="RegexpFindOffsetTokenizer"/> <object type="tokenMerger" ref="OffsetProxTokenMerger"/> <object type="normalizer" ref="CaseNormalizer"/> <object type="normalizer" ref="PossessiveNormalizer"/> </process> </source> <options> <setting type="nProxInts">3</setting> <setting type="proxVectors">1</setting> <setting type="vectors">1</setting> <setting type="freqList">rec occ</setting> </options> </subConfig> </subConfigs> </config>
{ "content_hash": "f74f05c1d18912c0366782c1410e6da7", "timestamp": "", "source": "github", "line_count": 451, "max_line_length": 63, "avg_line_length": 33.44345898004435, "alnum_prop": 0.6553072996088312, "repo_name": "CentreForCorpusResearch/clic", "id": "854710757f5a9cdfe195ed7b0ed28a1e006d2e10", "size": "15083", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "dbs/dickens/austenConfigs.d/austenIdxs.xml", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "4441" }, { "name": "HTML", "bytes": "192883" }, { "name": "JavaScript", "bytes": "45975" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "186759" }, { "name": "XSLT", "bytes": "12605" } ], "symlink_target": "" }
package dmytro.service.linkedin; /** * Not implemented * @author Dmytro_Plekhotkin * */ public class LinkedinException extends RuntimeException{ }
{ "content_hash": "d5ec67fdd31f5e1851d729d47b2ed2e1", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 56, "avg_line_length": 15.4, "alnum_prop": 0.7467532467532467, "repo_name": "plekhotkindmytro/Linkedin-oAuth2.0", "id": "ac7dee4b19f63096aa314ca8e9c665a3bf818ce2", "size": "154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/dmytro/service/linkedin/LinkedinException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9506" } ], "symlink_target": "" }
from io import StringIO from .output import Output from .section_output import SectionOutput class BufferedOutput(Output): def __init__(self, decorated: bool = False, supports_utf8: bool = True) -> None: super().__init__(decorated=decorated) self._buffer = StringIO() self._supports_utf8 = supports_utf8 def fetch(self) -> str: """ Empties the buffer and returns its content. """ content = self._buffer.getvalue() self._buffer = StringIO() return content def clear(self) -> None: """ Empties the buffer. """ self._buffer = StringIO() def supports_utf8(self) -> bool: return self._supports_utf8 def set_supports_utf8(self, supports_utf8: bool) -> None: self._supports_utf8 = supports_utf8 def section(self) -> SectionOutput: return SectionOutput( self._buffer, self._section_outputs, verbosity=self.verbosity, decorated=self.is_decorated(), formatter=self.formatter, ) def _write(self, message: str, new_line: bool = False) -> None: self._buffer.write(message) if new_line: self._buffer.write("\n")
{ "content_hash": "91f3f9dab70eeb658d79944eb5fcb463", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 84, "avg_line_length": 26.291666666666668, "alnum_prop": 0.5800316957210776, "repo_name": "sdispater/cleo", "id": "e0c14bef9ec6395eec893fbf9e3f3d98fcae9e6b", "size": "1262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cleo/io/outputs/buffered_output.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "335366" } ], "symlink_target": "" }
"""Geometric transforms (e.g. rigid transformation).""" import dataclasses from typing import Union import numpy as np @dataclasses.dataclass class Isometry: """3D transform object used to represent an SE(3) (isometric) transform. Underneath this class stores the transform [R|t] composed of rotation (R) and translation (t). Usage example: ```python frameB_from_frameA = Isometry(R=np.eye(3), t=np.ones(3)) pointA = np.random.rand(3) pointB = frameB_from_frameA * pointA pointA = frameB_from_frameA.inverse() * pointB # Compose multiple transforms: frameA_to_frameB = Isometry(...) frameB_to_frameC = Isometry(...) frameA_to_frameC = frameB_to_frameC * frameA_to_frameB # Apply transform on single point: pointB = frameA_to_frameB * np.array([4.0, 2.0, 1.0]) # Apply transform on a pointcloud (Nx3): pointcloudC = frameA_to_frameC * np.random.rand(1000, 3) ``` """ # Rotation component with tensor shape (3, 3) R: np.ndarray = dataclasses.field(default_factory=lambda: np.eye(3)) # pylint: disable=invalid-name # Translation component with tensor shape (3,) t: np.ndarray = dataclasses.field(default_factory=lambda: np.zeros(3)) @classmethod def from_matrix(cls, matrix: np.ndarray) -> 'Isometry': """Constructs from a 3x4 or 4x4 transform matrix.""" if matrix.shape not in [(3, 4), (4, 4)]: raise ValueError('invalid matrix.shape={}'.format(matrix.shape)) return cls(R=matrix[:3, :3], t=matrix[:3, 3]) def matrix3x4(self) -> np.ndarray: """Returns as 3x4 matrix. Returns a matrix [R|t] of shape (3, 4) """ return np.hstack((self.R, self.t.reshape((3, 1)))) def matrix4x4(self) -> np.ndarray: """Returns as 4x4 matrix. Returns a matrix [R|t] of shape (4, 4) [0|1] """ matrix = np.eye(4) matrix[:3, :3] = self.R matrix[:3, 3] = self.t return matrix def inverse(self) -> 'Isometry': """Returns the inverse of self. Usage example: frameB_from_frameA = Isometry(R=np.eye(3), t=np.ones(3)) frameA_from_frameB = frameB_from_frameA.inverse() Returns: Inverse transform of self. """ return Isometry(self.R.T, -self.R.T.dot(self.t)) def compose(self, other: 'Isometry') -> 'Isometry': """Returns the composite transform equal to self * other. This function is used to compose multiple transforms together. This can alternatively be achieved via `*` operator. Usage example: frameB_from_frameA = Isometry(R=..., t=...) frameC_from_frameB = Isometry(R=..., t=...) frameC_from_frameA = frameC_from_frameB.compose(frameB_from_frameA) Args: other: Another transform to compose with. Returns: Composite transform equal to self * other. """ return Isometry(self.R.dot(other.R), self.R.dot(other.t) + self.t) def transform_points(self, points: np.ndarray) -> np.ndarray: """Computes the transformation of a set of points. frameA_to_frameB = Isometry() pointsA = np.random.rand(1000, 3) pointsB = frameA_to_frameB.transform_points(pointsA) Args: points: Tensor containing point positions of shape (N, 3) or a single point vector of shape (3,). Returns: Transformed points. """ projected = np.einsum('ij,nj->ni', self.R, points.reshape(-1, 3)) + self.t return np.squeeze(projected) def __mul__( self, other: Union['Isometry', np.ndarray] ) -> Union['Isometry', np.ndarray]: """Returns the product of self with other i.e. `out = self * other`. This function can be used to transform point(s) or compose multiple transforms together. Compose multiple transforms: frameA_to_frameB = Isometry(...) frameB_to_frameC = Isometry(...) frameA_to_frameC = frameB_to_frameC * frameA_to_frameB Apply transform on single point: pointB = frameA_to_frameB * np.array([4.0, 2.0, 1.0]) Apply transform on a pointcloud (Nx3): pointcloudC = frameA_to_frameC * np.random.rand(1000, 3) Args: other: Either 3D point(s) or vector(s) to transform or other transform to compose with. Returns: When multiplying with another Isometry object `other`, the composite transform equal to `(this * other)` is returned. When other is point with shape (3,) or a pointcloud of shape (N, 3), the output is the transformed point or pointcloud. """ if isinstance(other, np.ndarray): return self.transform_points(other) elif isinstance(other, Isometry): return self.compose(other) raise TypeError('Unsupported type')
{ "content_hash": "5cc07c6ab0ca4aecc0548c531d84c9a8", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 102, "avg_line_length": 30.36842105263158, "alnum_prop": 0.654896013864818, "repo_name": "google-research/sunds", "id": "a5fa41a921133d285a7ac0eda09ba23ec9ae82c6", "size": "5199", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sunds/core/np_geometry/isometry.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "202324" } ], "symlink_target": "" }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new AppBundle\AppBundle(), new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(), ]; if (in_array($this->getEnvironment(), ['dev', 'test'], true)) { $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function getRootDir() { return __DIR__; } public function getCacheDir() { return dirname(__DIR__).'/var/cache/'.$this->getEnvironment(); } public function getLogDir() { return dirname(__DIR__).'/var/logs'; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml'); } }
{ "content_hash": "1a89ade45519af6c65acfa9a32adb083", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 92, "avg_line_length": 32.12, "alnum_prop": 0.6400996264009963, "repo_name": "wslomczynski/myshop", "id": "65d04535e01f345ab94009fe690cb5ce2030dfe4", "size": "1606", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/AppKernel.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "CSS", "bytes": "867" }, { "name": "HTML", "bytes": "6145" }, { "name": "JavaScript", "bytes": "940" }, { "name": "PHP", "bytes": "76869" } ], "symlink_target": "" }
use futures::channel::mpsc; use iml_tracing::tracing; use iml_wire_types::{ApiList, Command, EndpointName as _}; use std::{collections::HashSet, iter, time::Duration}; use tokio::time::delay_for; #[derive(Debug, thiserror::Error)] pub enum CmdUtilError { #[error(transparent)] ImlManagerClientError(#[from] iml_manager_client::ImlManagerClientError), #[error("Failed commands: {0:?}")] FailedCommandError(Vec<Command>), } impl From<Vec<Command>> for CmdUtilError { fn from(xs: Vec<Command>) -> Self { CmdUtilError::FailedCommandError(xs) } } pub enum Progress { Update(i32), Complete(Command), } pub async fn wait_for_cmds_progress( cmds: &[Command], tx: Option<mpsc::UnboundedSender<Progress>>, ) -> Result<Vec<Command>, CmdUtilError> { let mut state: HashSet<_> = cmds.iter().map(|x| x.id).collect(); let mut settled_commands = vec![]; loop { if state.is_empty() { tracing::debug!("All commands complete. Returning"); return Ok(settled_commands); } delay_for(Duration::from_millis(1000)).await; let query: Vec<_> = state .iter() .map(|x| ["id__in".into(), x.to_string()]) .chain(iter::once(["limit".into(), "0".into()])) .collect(); let client = iml_manager_client::get_client()?; let cmds: ApiList<Command> = iml_manager_client::get(client, Command::endpoint_name(), query).await?; for cmd in cmds.objects { if cmd_finished(&cmd) { state.remove(&cmd.id); if let Some(tx) = tx.as_ref() { let _ = tx.unbounded_send(Progress::Complete(cmd.clone())); } settled_commands.push(cmd); } else if let Some(tx) = tx.as_ref() { let _ = tx.unbounded_send(Progress::Update(cmd.id)); } } } } /// Waits for command completion and prints progress messages. /// This will error on command failure and print failed commands in the error message. pub async fn wait_for_cmds_success( cmds: &[Command], tx: Option<mpsc::UnboundedSender<Progress>>, ) -> Result<Vec<Command>, CmdUtilError> { let cmds = wait_for_cmds_progress(cmds, tx).await?; let (failed, passed): (Vec<_>, Vec<_>) = cmds.into_iter().partition(|x| x.errored || x.cancelled); if !failed.is_empty() { Err(failed.into()) } else { Ok(passed) } } fn cmd_finished(cmd: &Command) -> bool { cmd.complete }
{ "content_hash": "5e042ea56c29b9a6f480d56053987bb7", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 86, "avg_line_length": 29.147727272727273, "alnum_prop": 0.5828460038986355, "repo_name": "intel-hpdd/intel-manager-for-lustre", "id": "dbbf85142ee5029570b83554eab3436368ef72ed", "size": "2718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iml-command-utils/src/lib.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "20532" }, { "name": "Makefile", "bytes": "20966" }, { "name": "Python", "bytes": "6527307" }, { "name": "Roff", "bytes": "1415" }, { "name": "Ruby", "bytes": "27697" }, { "name": "Shell", "bytes": "127203" } ], "symlink_target": "" }
#define GENUS X(rdft_r2r_genus) extern const kr2r_genus GENUS;
{ "content_hash": "7fac282143ebf7be5944853f73bdb896", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 31, "avg_line_length": 13.2, "alnum_prop": 0.7424242424242424, "repo_name": "abrahamneben/orbcomm_beam_mapping", "id": "614427cd110a2a596726b304340dc7b828776194", "size": "886", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "daq/Sat1/fftw-3.0.1/rdft/codelets/r2r.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1707832" }, { "name": "C", "bytes": "7887268" }, { "name": "C++", "bytes": "99788" }, { "name": "Fortran", "bytes": "10088" }, { "name": "Gnuplot", "bytes": "98" }, { "name": "Go", "bytes": "1781" }, { "name": "Groff", "bytes": "126621" }, { "name": "HTML", "bytes": "796465" }, { "name": "M", "bytes": "582" }, { "name": "MATLAB", "bytes": "96993" }, { "name": "Makefile", "bytes": "1409220" }, { "name": "OCaml", "bytes": "1302732" }, { "name": "Objective-C", "bytes": "1007" }, { "name": "OpenEdge ABL", "bytes": "102236" }, { "name": "Perl", "bytes": "84319" }, { "name": "Python", "bytes": "97265" }, { "name": "Shell", "bytes": "814165" }, { "name": "Standard ML", "bytes": "23914" }, { "name": "TeX", "bytes": "438992" }, { "name": "Visual Basic", "bytes": "7441" }, { "name": "Yacc", "bytes": "8370" } ], "symlink_target": "" }
from masseuse.core import massage from masseuse.cli import argparser from masseuse.kernels import kernels import datetime as dt import re def makeparser(form): def parse(astring): return dt.datetime.strptime(astring, form).date() return parse def lintimes(times, lpad=0, rpad=0, step=1): minday,maxday = min(times),max(times) tdelta = (maxday - minday).days return [minday + dt.timedelta(days) for days in xrange(0-lpad, tdelta+rpad, step)] def main(args): parser = makeparser(args.format) kernel = kernels(args.kernel, args.parameter) otimes = [parser(line.split()[0]) for line in args.infile if not line.startswith("#")] ntimes = lintimes(otimes, args.step) args.infile.seek(0) massage(parser, kernel, ntimes, args.infile, args.outfile) if __name__ == "__main__": main(argparser().parse_args())
{ "content_hash": "6d3cf8800dc1013b98b032f36c28e88e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 62, "avg_line_length": 30.93103448275862, "alnum_prop": 0.6633221850613155, "repo_name": "triposorbust/masseuse", "id": "f98ef4312bcd2fa9fb1c9d971d74aa803db0de2f", "size": "920", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "massage.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "4833" } ], "symlink_target": "" }
namespace net { class ClientSocketPoolManager; class HttpStreamFactory; class NET_EXPORT_PRIVATE HttpNetworkSessionPeer { public: // |session| should outlive the HttpNetworkSessionPeer. explicit HttpNetworkSessionPeer(HttpNetworkSession* session); ~HttpNetworkSessionPeer(); void SetClientSocketPoolManager( std::unique_ptr<ClientSocketPoolManager> socket_pool_manager); void SetHttpStreamFactory( std::unique_ptr<HttpStreamFactory> http_stream_factory); HttpNetworkSession::Params* params(); private: HttpNetworkSession* const session_; DISALLOW_COPY_AND_ASSIGN(HttpNetworkSessionPeer); }; } // namespace net #endif // NET_HTTP_HTTP_NETWORK_SESSION_PEER_H_
{ "content_hash": "41b565e73a8b3d6331a40df3965fc7ca", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 68, "avg_line_length": 24.964285714285715, "alnum_prop": 0.7753934191702432, "repo_name": "endlessm/chromium-browser", "id": "b173f5de684e5e3f8c89176134d00746a9f2c438", "size": "1120", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "net/http/http_network_session_peer.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
require 'cucumber/formatter/progress' module Cucumber module Formatter class Profile < Progress NUMBER_OF_STEP_DEFINITONS_TO_SHOW = 10 NUMBER_OF_STEP_INVOCATIONS_TO_SHOW = 5 def initialize(step_mother, io, options) super @step_definition_durations = Hash.new { |h,step_definition| h[step_definition] = [] } end def visit_step(step) @step_duration = Time.now @step = step super end def visit_step_name(keyword, step_name, status, step_definition, source_indent) duration = Time.now - @step_duration super if step_definition # nil for outline steps description = format_step(keyword, step_name, status, step_definition, nil) @step_definition_durations[step_definition] << [duration, description, @step.file_line] end end def print_summary(features) super @io.puts "\n\nTop #{NUMBER_OF_STEP_DEFINITONS_TO_SHOW} average slowest steps with #{NUMBER_OF_STEP_INVOCATIONS_TO_SHOW} slowest matches:\n" mean_durations = map_to_mean_durations(@step_definition_durations) mean_durations = mean_durations.sort_by do |duration_description_location, step_definition, mean_duration| mean_duration end.reverse mean_durations[0...NUMBER_OF_STEP_DEFINITONS_TO_SHOW].each do |duration_description_location, step_definition, mean_duration| print_step_definition(step_definition, mean_duration) duration_description_location = duration_description_location.sort_by do |duration, description, location| duration end.reverse print_step_definitions(duration_description_location, step_definition) end end private def map_to_mean_durations(step_definition_durations) mean_durations = [] step_definition_durations.each do |step_definition, duration_description_location| total_duration = duration_description_location.inject(0) { |sum, step_details| step_details[0] + sum } mean_duration = total_duration / duration_description_location.length mean_durations << [duration_description_location, step_definition, mean_duration] end mean_durations end def print_step_definition(step_definition, mean_duration) duration = sprintf("%.7f", mean_duration) @io.puts format_string("#{duration} #{step_definition.to_backtrace_line}", :failed) end def print_step_definitions(duration_description_location, step_definition) max_length = duration_description_location[0...NUMBER_OF_STEP_INVOCATIONS_TO_SHOW].map{|_, d, _| d.jlength}.max duration_description_location[0...NUMBER_OF_STEP_INVOCATIONS_TO_SHOW].each do |duration, description, location| @io.print format_string(" #{sprintf("%.7f", duration)}", :pending) @io.print " #{description}" @io.print format_string(" # #{location}".indent(max_length - description.jlength), :comment) @io.puts end end end end end
{ "content_hash": "85c99cb3332671ac222a9b56abf949c8", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 147, "avg_line_length": 40.41558441558441, "alnum_prop": 0.6584190231362468, "repo_name": "fastingrobot/planet", "id": "c0c43c38d970d0807041ba81f61bd879c6420602", "size": "3112", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/plugins/cucumber/lib/cucumber/formatter/profile.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "148" }, { "name": "Ruby", "bytes": "50295" } ], "symlink_target": "" }
$.counter.addEventListener('click', function() { var widget = Alloy.createWidget('com.r3mobile.counter'); widget.complete = function(){ $.win.remove(widget.getView()); }; $.win.add(widget.getView()); widget.start(); }); $.maskTextbox.addEventListener('click', function() { var widget = Alloy.createWidget('com.r3mobile.maskTextbox'); $.win.add(widget.getView()); }); $.iconicLabel.addEventListener('click', function() { var widget = Alloy.createWidget('com.r3mobile.iconicLabel'); $.win.add(widget.getView()); }); $.loading.addEventListener('click', function() { var widget = Alloy.createWidget('com.r3mobile.loading'); $.win.add(widget.getView()); }); $.win.open(); // function IndexOpen(e) { // $.logo.init({ image: '/appicon.png', width: 216, height: 200 }); // } // $.drawer.init({ // mainWindow : $.index, // buttons : [{ // id : 'One', // title : 'One', // backgroundColor : 'red', // click : function(e) { // alert("One"); // } // }, { // id : 'Two', // title : 'Two', // backgroundColor : 'yellow', // click : function(e) { // alert("Two"); // } // }, { // id : 'Three', // title : 'Three', // backgroundColor : 'orange', // color : 'white', // click : function(e) { // alert("Three"); // } // }], // autoClose : true, // gutter : 5 // }); // //SOME SAMPLE DATA // var items = [ // {title:'sample 1', image:'http://www.lorempixel.com/700/600/'}, // {title:'sample 2', image:'http://www.lorempixel.com/900/1200/'}, // {title:'sample 3', image:'http://www.lorempixel.com/400/300/'}, // {title:'sample 4', image:'http://www.lorempixel.com/600/600/'}, // {title:'sample 5', image:'http://www.lorempixel.com/400/310/'}, // {title:'sample 6', image:'http://www.lorempixel.com/410/300/'}, // {title:'sample 7', image:'http://www.lorempixel.com/500/300/'}, // {title:'sample 8', image:'http://www.lorempixel.com/300/300/'}, // {title:'sample 9', image:'http://www.lorempixel.com/450/320/'}, // {title:'sample 10', image:'http://www.lorempixel.com/500/400/'}, // {title:'sample 11', image:'http://www.lorempixel.com/500/560/'}, // {title:'sample 12', image:'http://www.lorempixel.com/700/400/'}, // {title:'sample 13', image:'http://www.lorempixel.com/300/400/'}, // {title:'sample 14', image:'http://www.lorempixel.com/500/500/'}, // {title:'sample 15', image:'http://www.lorempixel.com/700/390/'} // ]; // // $.fg.createGrid({ // columns:2, //NUMBER OF COLUMNS. DEFAULT IS 4. // space:10, //SPACE BETWEEN EACH ELEMENT. DEFAULT IS 5. // data:items, //ARRAY WITH THE DATA TO DISPLAY. SEE SAMPLE DATA ABOVE. // layout:'gallery', //LAYOUT TYPE: gallery or customView. DEFAULT IS gallery. // params:{ // padding:5, //GALLERY ONLY. // showTitle:false, //GALLERY ONLY. True or False // handleRotate : true, //GALLERY ONLY. True or False // backgroundColor: '#eee', // gridColor: '#ccc' // } // //width: 320 //OPTIONAL. SCREEN'S WIDTH TO ADJUST GRID. // }); //var Font = require('/lib/FontAwesome'); //var font = new Font(); // var imageView = Ti.UI.createLabel({ // text : 'test', // id : 'move', // //text : font.getText('icon-anchor'), // // font : { // // fontFamily : font.fontfamily, // // fontSize : '50sp' // // }, // color : 'white', // top : Ti.Platform.displayCaps.platformHeight / 2, // left : Ti.Platform.displayCaps.platformWidth / 2 // }); // $.win.add(imageView); // var touchMoveBase = { // set: function(point) { // this.x = point.x; // this.y = point.y; // } // }; // var position = {top: imageView.top, left: imageView.left}; // var olt = Titanium.UI.create3DMatrix(), curX, curY; // imageView.addEventListener('touchstart', function(e) { // curX = e.x; // curY = e.y; // }); // imageView.addEventListener('touchmove', function(e) { // var deltaX = e.x - curX, deltaY = e.y - curY; // olt = olt.translate(deltaX, deltaY, 0); // imageView.animate({ // transform : olt, // duration : 100 // }); // }); // $.win.addEventListener('touchmove', function(e) { // Ti.API.info(e.source.id + ' - ' + e.x); // return; // if (e.source.id == 'win'){ // // //Ti.API.info(e.source.id + ' - ' + e.x); // }else{ // //run move code? // } // // }); // var view = Ti.UI.createView({ // top : 0, // left : 0, // width : '50dp', // height : '50dp', // borderColor : 'white', // borderRadius : 0, // borderWidth : 1, // touchEnabled : false // }); // $.index.add(view); // var icon = Alloy.createWidget('com.r3mobile.iconicLabel','',{ // icon:"icon-save", // color : 'yellow', // fontSize : '100sp' // }); // var img = Ti.UI.createImageView({ // image : icon.createIconFile(), // top : 20 // }); // $.index.add(img); // // icon.setIcon('icon-home'); // icon.setColor('red'); // icon.setFontSize('50sp'); // // var img2 = Ti.UI.createImageView({ // image : icon.createIconFile(), // top : 200, // }); // $.index.add(img2); // setTimeout(function() { // $.loading.init($.loading.types.DARK); // $.loading.start(); // //$.drawer.jiggle(); // }, 2000);
{ "content_hash": "5627860ed98a5445c5fa7a25216cbcc5", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 92, "avg_line_length": 27.5, "alnum_prop": 0.5963636363636363, "repo_name": "rollsroyc3/Alloy-Testbed", "id": "296b98eaff7d1c331bd3a667c9d136d1016b21c9", "size": "4950", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/index.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2552" }, { "name": "JavaScript", "bytes": "338299" }, { "name": "Python", "bytes": "5251" } ], "symlink_target": "" }
/** * */ package org.pos2d.webapi.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.pos2d.webapi.entities.City; import org.pos2d.webapi.entities.UrbanArea; import org.springframework.transaction.annotation.Transactional; /** * @author soumik * */ public class UrbanAreaDAOImpl implements UrbanAreaDAO { private SessionFactory sessionFactory; public UrbanAreaDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override @Transactional public UrbanArea getByName(String name, String city) { String hql = "FROM UrbanArea as ua where ua.name = :subUrbName and ua.city = :cityName"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("subUrbName", name); query.setParameter("cityName", city); return (UrbanArea) query.list().get(0); } @SuppressWarnings("unchecked") @Override @Transactional public List<UrbanArea> getAllForCity(String city) { String hql = "select ua.name FROM UrbanArea as ua where ua.city = :cityName"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setParameter("cityName", city); return (List<UrbanArea>) query.list(); } }
{ "content_hash": "56a49de4ec847bbddee9ef2537f86076", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 90, "avg_line_length": 27.043478260869566, "alnum_prop": 0.7483922829581994, "repo_name": "soumik-mukherjee/PositioningDemo2D", "id": "1a5f95c38e1136286ef091861a9b4a3b8da2fa50", "size": "1244", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/java/WebApi/src/main/java/org/pos2d/webapi/dao/UrbanAreaDAOImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "13459" }, { "name": "C", "bytes": "1303" }, { "name": "C++", "bytes": "1312" }, { "name": "CSS", "bytes": "1648" }, { "name": "HTML", "bytes": "9283" }, { "name": "Java", "bytes": "59663" }, { "name": "JavaScript", "bytes": "12555" }, { "name": "PLpgSQL", "bytes": "6721" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WriteableBitmapExBlitAlphaRepro.WinRT")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WriteableBitmapExBlitAlphaRepro.WinRT")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
{ "content_hash": "e4f1e7ce41a3c2e0ff38a7809681cc5c", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 84, "avg_line_length": 38.58620689655172, "alnum_prop": 0.7327971403038427, "repo_name": "teichgraf/WriteableBitmapEx", "id": "b834c4fc466b73305496c3814a0f79410c2d6396", "size": "1122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/WriteableBitmapExBlitAlphaRepro.WinRT/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "3436" }, { "name": "Batchfile", "bytes": "443" }, { "name": "C#", "bytes": "573620" }, { "name": "HTML", "bytes": "6056" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Sideritis guillonii Timb. ### Remarks null
{ "content_hash": "acb9a30d7dba5d3ca86f58885dcfe706", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 11.307692307692308, "alnum_prop": 0.7278911564625851, "repo_name": "mdoering/backbone", "id": "ab8648a2542e7137a83ac240f1d1bb5bfcc6b216", "size": "231", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Sideritis/Sideritis peyrei/Sideritis peyrei guillonii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; using System.Linq; using LibGit2Sharp; public class MockBranch : Branch, ICollection<Commit> { public MockBranch(string name) { this.name = name; } public MockBranch(string name, string canonicalName) { this.name = name; this.canonicalName = canonicalName; } public MockBranch() { } MockCommitLog commits = new MockCommitLog(); string name; string canonicalName; public override string Name { get { return name; } } public override ICommitLog Commits { get { return commits; } } public override Commit Tip { get { return commits.First(); } } public override string CanonicalName { get { return canonicalName; } } public IEnumerator<Commit> GetEnumerator() { return commits.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(Commit item) { commits.Add(item); } public void Clear() { commits.Clear(); } public bool Contains(Commit item) { return commits.Contains(item); } public void CopyTo(Commit[] array, int arrayIndex) { commits.CopyTo(array, arrayIndex); } public bool Remove(Commit item) { return commits.Remove(item); } public int Count{get{return commits.Count;}} public bool IsReadOnly { get{return false;} } }
{ "content_hash": "cbf28f27e18a9d55d65655afbcc78277", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 66, "avg_line_length": 21.140845070422536, "alnum_prop": 0.6229180546302465, "repo_name": "potherca-contrib/GitVersion", "id": "920682eb1e68022978e5b9ab8114af2068d2ff84", "size": "1501", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/Mocks/MockBranch.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
There are some special issues that you have to deal with when you’re trying to ship on mobile or embedded devices, and you’ll need to think about these as you’re developing your model. These issues are: - Model and Binary Size - App speed and model loading speed - Performance and threading We'll discuss a few of these below. ## What are the minimum device requirements for TensorFlow? You need at least one megabyte of program memory and several megabytes of RAM to run the base TensorFlow runtime, so it’s not suitable for DSPs or microcontrollers. Other than those, the biggest constraint is usually the calculation speed of the device, and whether you can run the model you need for your application with a low enough latency. You can use the benchmarking tools in [How to Profile your Model](#how_to_profile_your_model) to get an idea of how many FLOPs are required for a model, and then use that to make rule-of-thumb estimates of how fast they will run on different devices. For example, a modern smartphone might be able to run 10 GFLOPs per second, so the best you could hope for from a 5 GFLOP model is two frames per second, though you may do worse depending on what the exact computation patterns are. This model dependence means that it’s possible to run TensorFlow even on very old or constrained phones, as long as you optimize your network to fit within the latency budget and possibly within limited RAM too. For memory usage, you mostly need to make sure that the intermediate buffers that TensorFlow creates aren’t too large, which you can examine in the benchmark output too. ## Speed One of the highest priorities of most model deployments is figuring out how to run the inference fast enough to give a good user experience. The first place to start is by looking at the total number of floating point operations that are required to execute the graph. You can get a very rough estimate of this by using the `benchmark_model` tool: bazel build -c opt tensorflow/tools/benchmark:benchmark_model && \ bazel-bin/tensorflow/tools/benchmark/benchmark_model \ --graph=/tmp/inception_graph.pb --input_layer="Mul:0" \ --input_layer_shape="1,299,299,3" --input_layer_type="float" \ --output_layer="softmax:0" --show_run_order=false --show_time=false \ --show_memory=false --show_summary=true --show_flops=true --logtostderr This should show you an estimate of how many operations are needed to run the graph. You can then use that information to figure out how feasible your model is to run on the devices you’re targeting. For an example, a high-end phone from 2016 might be able to do 20 billion FLOPs per second, so the best speed you could hope for from a model that requires 10 billion FLOPs is around 500ms. On a device like the Raspberry Pi 3 that can do about 5 billion FLOPs, you may only get one inference every two seconds. Having this estimate helps you plan for what you’ll be able to realistically achieve on a device. If the model is using too many ops, then there are a lot of opportunities to optimize the architecture to reduce that number. Advanced techniques include [SqueezeNet](https://arxiv.org/abs/1602.07360) and [MobileNet](https://arxiv.org/abs/1704.04861), which are architectures designed to produce models for mobile -- lean and fast but with a small accuracy cost. You can also just look at alternative models, even older ones, which may be smaller. For example, Inception v1 only has around 7 million parameters, compared to Inception v3’s 24 million, and requires only 3 billion FLOPs rather than 9 billion for v3. ## Model Size Models that run on a device need to be stored somewhere on the device, and very large neural networks can be hundreds of megabytes. Most users are reluctant to download very large app bundles from app stores, so you want to make your model as small as possible. Furthermore, smaller neural networks can persist in and out of a mobile device's memory faster. To understand how large your network will be on disk, start by looking at the size on disk of your `GraphDef` file after you’ve run `freeze_graph` and `strip_unused_nodes` on it (see @{$mobile/prepare_models$Preparing models} for more details on these tools), since then it should only contain inference-related nodes. To double-check that your results are as expected, run the `summarize_graph` tool to see how many parameters are in constants: bazel build tensorflow/tools/graph_transforms:summarize_graph && \ bazel-bin/tensorflow/tools/graph_transforms/summarize_graph \ --in_graph=/tmp/tensorflow_inception_graph.pb That command should give you output that looks something like this: No inputs spotted. Found 1 possible outputs: (name=softmax, op=Softmax) Found 23885411 (23.89M) const parameters, 0 (0) variable parameters, and 99 control_edges Op types used: 489 Const, 99 CheckNumerics, 99 Identity, 94 BatchNormWithGlobalNormalization, 94 Conv2D, 94 Relu, 11 Concat, 9 AvgPool, 5 MaxPool, 1 Sub, 1 Softmax, 1 ResizeBilinear, 1 Reshape, 1 Mul, 1 MatMul, 1 ExpandDims, 1 DecodeJpeg, 1 Cast, 1 BiasAdd The important part for our current purposes is the number of const parameters. In most models these will be stored as 32-bit floats to start, so if you multiply the number of const parameters by four, you should get something that’s close to the size of the file on disk. You can often get away with only eight-bits per parameter with very little loss of accuracy in the final result, so if your file size is too large you can try using @{$performance/quantization$quantize_weights} to transform the parameters down. bazel build tensorflow/tools/graph_transforms:transform_graph && \ bazel-bin/tensorflow/tools/graph_transforms/transform_graph \ --in_graph=/tmp/tensorflow_inception_optimized.pb \ --out_graph=/tmp/tensorflow_inception_quantized.pb \ --inputs='Mul:0' --outputs='softmax:0' --transforms='quantize_weights' If you look at the resulting file size, you should see that it’s about a quarter of the original at 23MB. Another transform is `round_weights`, which doesn't make the file smaller, but it makes the file compressible to about the same size as when `quantize_weights` is used. This is particularly useful for mobile development, taking advantage of the fact that app bundles are compressed before they’re downloaded by consumers. The original file does not compress well with standard algorithms, because the bit patterns of even very similar numbers can be very different. The `round_weights` transform keeps the weight parameters stored as floats, but rounds them to a set number of step values. This means there are a lot more repeated byte patterns in the stored model, and so compression can often bring the size down dramatically, in many cases to near the size it would be if they were stored as eight bit. Another advantage of `round_weights` is that the framework doesn’t have to allocate a temporary buffer to unpack the parameters into, as we have to when we just use `quantize_weights`. This saves a little bit of latency (though the results should be cached so it’s only costly on the first run) and makes it possible to use memory mapping, as described later. ## Binary Size One of the biggest differences between mobile and server development is the importance of binary size. On desktop machines it’s not unusual to have executables that are hundreds of megabytes on disk, but for mobile and embedded apps it’s vital to keep the binary as small as possible so that user downloads are easy. As mentioned above, TensorFlow only includes a subset of op implementations by default, but this still results in a 12 MB final executable. To reduce this, you can set up the library to only include the implementations of the ops that you actually need, based on automatically analyzing your model. To use it: - Run `tools/print_required_ops/print_selective_registration_header.py` on your model to produce a header file that only enables the ops it uses. - Place the `ops_to_register.h` file somewhere that the compiler can find it. This can be in the root of your TensorFlow source folder. - Build TensorFlow with `SELECTIVE_REGISTRATION` defined, for example by passing in `--copts=”-DSELECTIVE_REGISTRATION”` to your Bazel build command. This process recompiles the library so that only the needed ops and types are included, which can dramatically reduce the executable size. For example, with Inception v3, the new size is only 1.5MB. ## How to Profile your Model Once you have an idea of what your device's peak performance range is, it’s worth looking at its actual current performance. Using a standalone TensorFlow benchmark, rather than running it inside a larger app, helps isolate just the Tensorflow contribution to the latency. The [tensorflow/tools/benchmark](https://www.tensorflow.org/code/tensorflow/tools/benchmark/) tool is designed to help you do this. To run it on Inception v3 on your desktop machine, build this benchmark model: bazel build -c opt tensorflow/tools/benchmark:benchmark_model && \ bazel-bin/tensorflow/tools/benchmark/benchmark_model \ --graph=/tmp/tensorflow_inception_graph.pb --input_layer="Mul" \ --input_layer_shape="1,299,299,3" --input_layer_type="float" \ --output_layer="softmax:0" --show_run_order=false --show_time=false \ --show_memory=false --show_summary=true --show_flops=true --logtostderr You should see output that looks something like this: <pre> ============================== Top by Computation Time ============================== [node type] [start] [first] [avg ms] [%] [cdf%] [mem KB] [Name] Conv2D 22.859 14.212 13.700 4.972% 4.972% 3871.488 conv_4/Conv2D Conv2D 8.116 8.964 11.315 4.106% 9.078% 5531.904 conv_2/Conv2D Conv2D 62.066 16.504 7.274 2.640% 11.717% 443.904 mixed_3/conv/Conv2D Conv2D 2.530 6.226 4.939 1.792% 13.510% 2765.952 conv_1/Conv2D Conv2D 55.585 4.605 4.665 1.693% 15.203% 313.600 mixed_2/tower/conv_1/Conv2D Conv2D 127.114 5.469 4.630 1.680% 16.883% 81.920 mixed_10/conv/Conv2D Conv2D 47.391 6.994 4.588 1.665% 18.548% 313.600 mixed_1/tower/conv_1/Conv2D Conv2D 39.463 7.878 4.336 1.574% 20.122% 313.600 mixed/tower/conv_1/Conv2D Conv2D 127.113 4.192 3.894 1.413% 21.535% 114.688 mixed_10/tower_1/conv/Conv2D Conv2D 70.188 5.205 3.626 1.316% 22.850% 221.952 mixed_4/conv/Conv2D ============================== Summary by node type ============================== [Node type] [count] [avg ms] [avg %] [cdf %] [mem KB] Conv2D 94 244.899 88.952% 88.952% 35869.953 BiasAdd 95 9.664 3.510% 92.462% 35873.984 AvgPool 9 7.990 2.902% 95.364% 7493.504 Relu 94 5.727 2.080% 97.444% 35869.953 MaxPool 5 3.485 1.266% 98.710% 3358.848 Const 192 1.727 0.627% 99.337% 0.000 Concat 11 1.081 0.393% 99.730% 9892.096 MatMul 1 0.665 0.242% 99.971% 4.032 Softmax 1 0.040 0.015% 99.986% 4.032 <> 1 0.032 0.012% 99.997% 0.000 Reshape 1 0.007 0.003% 100.000% 0.000 Timings (microseconds): count=50 first=330849 curr=274803 min=232354 max=415352 avg=275563 std=44193 Memory (bytes): count=50 curr=128366400(all same) 514 nodes defined 504 nodes observed </pre> This is the summary view, which is enabled by the show_summary flag. To interpret it, the first table is a list of the nodes that took the most time, in order by how long they took. From left to right, the columns are: - Node type, what kind of operation this was. - Start time of the op, showing where it falls in the sequence of operations. - First time in milliseconds. This is how long the operation took on the first run of the benchmark, since by default 20 runs are executed to get more reliable statistics. The first time is useful to spot which ops are doing expensive calculations on the first run, and then caching the results. - Average time for the operation across all runs, in milliseconds. - What percentage of the total time for one run the op took. This is useful to understand where the hotspots are. - The cumulative total time of this and the previous ops in the table. This is handy for understanding what the distribution of work is across the layers, to see if just a few of the nodes are taking up most of the time. - Name of the node. The second table is similar, but instead of breaking down the timings by particular named nodes, it groups them by the kind of op. This is very useful to understand which op implementations you might want to optimize or eliminate from your graph. The table is arranged with the most costly operations at the start, and only shows the top ten entries, with a placeholder for other nodes. The columns from left to right are: - Type of the nodes being analyzed. - Accumulated average time taken by all nodes of this type, in milliseconds. - What percentage of the total time was taken by this type of operation. - Cumulative time taken by this and op types higher in the table, so you can understand the distribution of the workload. - How much memory the outputs of this op type took up. Both of these tables are set up so that you can easily copy and paste their results into spreadsheet documents, since they are output with tabs as separators between the columns. The summary by node type can be the most useful when looking for optimization opportunities, since it’s a pointer to the code that’s taking the most time. In this case, you can see that the Conv2D ops are almost 90% of the execution time. This is a sign that the graph is pretty optimal, since convolutions and matrix multiplies are expected to be the bulk of a neural network’s computing workload. As a rule of thumb, it’s more worrying if you see a lot of other operations taking up more than a small fraction of the time. For neural networks, the ops that don’t involve large matrix multiplications should usually be dwarfed by the ones that do, so if you see a lot of time going into those it’s a sign that either your network is non-optimally constructed, or the code implementing those ops is not as optimized as it could be. [Performance bugs](https://github.com/tensorflow/tensorflow/issues) or patches are always welcome if you do encounter this situation, especially if they include an attached model exhibiting this behavior and the command line used to run the benchmark tool on it. The run above was on your desktop, but the tool also works on Android, which is where it’s most useful for mobile development. Here’s an example command line to run it on a 64-bit ARM device: bazel build -c opt --config=android_arm64 \ tensorflow/tools/benchmark:benchmark_model adb push bazel-bin/tensorflow/tools/benchmark/benchmark_model /data/local/tmp adb push /tmp/tensorflow_inception_graph.pb /data/local/tmp/ adb shell '/data/local/tmp/benchmark_model \ --graph=/data/local/tmp/tensorflow_inception_graph.pb --input_layer="Mul" \ --input_layer_shape="1,299,299,3" --input_layer_type="float" \ --output_layer="softmax:0" --show_run_order=false --show_time=false \ --show_memory=false --show_summary=true' You can interpret the results in exactly the same way as the desktop version above. If you have any trouble figuring out what the right input and output names and types are, take a look at the @{$mobile/prepare_models$Preparing models} page for details about detecting these for your model, and look at the `summarize_graph` tool which may give you helpful information. There isn’t good support for command line tools on iOS, so instead there’s a separate example at [tensorflow/examples/ios/benchmark](https://www.tensorflow.org/code/tensorflow/examples/ios/benchmark) that packages the same functionality inside a standalone app. This outputs the statistics to both the screen of the device and the debug log. If you want on-screen statistics for the Android example apps, you can turn them on by pressing the volume-up button. ## Profiling within your own app The output you see from the benchmark tool is generated from modules that are included as part of the standard TensorFlow runtime, which means you have access to them within your own applications too. You can see an example of how to do that [here](https://www.tensorflow.org/code/tensorflow/examples/ios/benchmark/BenchmarkViewController.mm?l=139). The basic steps are: 1. Create a StatSummarizer object: tensorflow::StatSummarizer stat_summarizer(tensorflow_graph); 2. Set up the options: tensorflow::RunOptions run_options; run_options.set_trace_level(tensorflow::RunOptions::FULL_TRACE); tensorflow::RunMetadata run_metadata; 3. Run the graph: run_status = session->Run(run_options, inputs, output_layer_names, {}, output_layers, &run_metadata); 4. Calculate the results and print them out: assert(run_metadata.has_step_stats()); const tensorflow::StepStats& step_stats = run_metadata.step_stats(); stat_summarizer->ProcessStepStats(step_stats); stat_summarizer->PrintStepStats(); ## Visualizing Models The most effective way to speed up your code is by altering your model so it does less work. To do that, you need to understand what your model is doing, and visualizing it is a good first step. To get a high-level overview of your graph, use [TensorBoard](https://github.com/tensorflow/tensorboard). ## Threading The desktop version of TensorFlow has a sophisticated threading model, and will try to run multiple operations in parallel if it can. In our terminology this is called “inter-op parallelism” (though to avoid confusion with “intra-op”, you could think of it as “between-op” instead), and can be set by specifying `inter_op_parallelism_threads` in the session options. By default, mobile devices run operations serially; that is, `inter_op_parallelism_threads` is set to 1. Mobile processors usually have few cores and a small cache, so running multiple operations accessing disjoint parts of memory usually doesn’t help performance. “Intra-op parallelism” (or “within-op”) can be very helpful though, especially for computation-bound operations like convolutions where different threads can feed off the same small set of memory. On mobile, how many threads an op will use is set to the number of cores by default, or 2 when the number of cores can't be determined. You can override the default number of threads that ops are using by setting `intra_op_parallelism_threads` in the session options. It’s a good idea to reduce the default if your app has its own threads doing heavy processing, so that they don’t interfere with each other. To see more details on session options, look at [ConfigProto](https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto). ## Retrain with mobile data The biggest cause of accuracy problems when running models on mobile apps is unrepresentative training data. For example, most of the Imagenet photos are well-framed so that the object is in the center of the picture, well-lit, and shot with a normal lens. Photos from mobile devices are often poorly framed, badly lit, and can have fisheye distortions, especially selfies. The solution is to expand your training set with data actually captured from your application. This step can involve extra work, since you’ll have to label the examples yourself, but even if you just use it to expand your original training data, it can help the training set dramatically. Improving the training set by doing this, and by fixing other quality issues like duplicates or badly labeled examples is the single best way to improve accuracy. It’s usually a bigger help than altering your model architecture or using different techniques. ## Reducing model loading time and/or memory footprint Most operating systems allow you to load a file using memory mapping, rather than going through the usual I/O APIs. Instead of allocating an area of memory on the heap and then copying bytes from disk into it, you simply tell the operating system to make the entire contents of a file appear directly in memory. This has several advantages: * Speeds loading * Reduces paging (increases performance) * Does not count towards RAM budget for your app TensorFlow has support for memory mapping the weights that form the bulk of most model files. Because of limitations in the `ProtoBuf` serialization format, we have to make a few changes to our model loading and processing code. The way memory mapping works is that we have a single file where the first part is a normal `GraphDef` serialized into the protocol buffer wire format, but then the weights are appended in a form that can be directly mapped. To create this file, run the `tensorflow/contrib/util:convert_graphdef_memmapped_format` tool. This takes in a `GraphDef` file that’s been run through `freeze_graph` and converts it to the format that has the weights appended at the end. Since that file’s no longer a standard `GraphDef` protobuf, you then need to make some changes to the loading code. You can see an example of this in the [iOS Camera demo app](https://www.tensorflow.org/code/tensorflow/examples/ios/camera/tensorflow_utils.mm?l=147), in the `LoadMemoryMappedModel()` function. The same code (with the Objective C calls for getting the filenames substituted) can be used on other platforms too. Because we’re using memory mapping, we need to start by creating a special TensorFlow environment object that’s set up with the file we’ll be using: std::unique_ptr<tensorflow::MemmappedEnv> memmapped_env; memmapped_env->reset( new tensorflow::MemmappedEnv(tensorflow::Env::Default())); tensorflow::Status mmap_status = (memmapped_env->get())->InitializeFromFile(file_path); You then need to pass in this environment to subsequent calls, like this one for loading the graph: tensorflow::GraphDef tensorflow_graph; tensorflow::Status load_graph_status = ReadBinaryProto( memmapped_env->get(), tensorflow::MemmappedFileSystem::kMemmappedPackageDefaultGraphDef, &tensorflow_graph); You also need to create the session with a pointer to the environment you’ve created: tensorflow::SessionOptions options; options.config.mutable_graph_options() ->mutable_optimizer_options() ->set_opt_level(::tensorflow::OptimizerOptions::L0); options.env = memmapped_env->get(); tensorflow::Session* session_pointer = nullptr; tensorflow::Status session_status = tensorflow::NewSession(options, &session_pointer); One thing to notice here is that we’re also disabling automatic optimizations, since in some cases these will fold constant sub-trees, and so create copies of tensor values that we don’t want and use up more RAM. Once you’ve gone through these steps, you can use the session and graph as normal, and you should see a reduction in loading time and memory usage. ## Protecting model files from easy copying By default, your models will be stored in the standard serialized protobuf format on disk. In theory this means that anybody can copy your model, which you may not want. However, in practice, most models are so application-specific and obfuscated by optimizations that the risk is similar to that of competitors disassembling and reusing your code, but if you do want to make it tougher for casual users to access your files it is possible to take some basic steps. Most of our examples use the [ReadBinaryProto()](https://www.tensorflow.org/code/tensorflow/core/platform/env.cc?q=core/platform/env.cc&l=409) convenience call to load a `GraphDef` from disk. This does require an unencrypted protobuf on disk. Luckily though, the implementation of the call is pretty straightforward and it should be easy to write an equivalent that can decrypt in memory. Here's some code that shows how you can read and decrypt a protobuf using your own decryption routine: Status ReadEncryptedProto(Env* env, const string& fname, ::tensorflow::protobuf::MessageLite* proto) { string data; TF_RETURN_IF_ERROR(ReadFileToString(env, fname, &data)); DecryptData(&data); // Your own function here. if (!proto->ParseFromString(&data)) { TF_RETURN_IF_ERROR(stream->status()); return errors::DataLoss("Can't parse ", fname, " as binary proto"); } return Status::OK(); } To use this you’d need to define the DecryptData() function yourself. It could be as simple as something like: void DecryptData(string* data) { for (int i = 0; i < data.size(); ++i) { data[i] = data[i] ^ 0x23; } } You may want something more complex, but exactly what you’ll need is outside the current scope here.
{ "content_hash": "b374865bd4f98ffaff3f9e58aac6cd4b", "timestamp": "", "source": "github", "line_count": 495, "max_line_length": 133, "avg_line_length": 50.74949494949495, "alnum_prop": 0.7506070618207874, "repo_name": "guschmue/tensorflow", "id": "5abc68bb61b4b24a16045a6ed31446bd54c1bd82", "size": "25258", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tensorflow/docs_src/mobile/optimizing.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8535" }, { "name": "C", "bytes": "314452" }, { "name": "C++", "bytes": "34310628" }, { "name": "CMake", "bytes": "211937" }, { "name": "Go", "bytes": "1012495" }, { "name": "Java", "bytes": "533607" }, { "name": "Jupyter Notebook", "bytes": "1940884" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "44807" }, { "name": "Objective-C", "bytes": "12460" }, { "name": "Objective-C++", "bytes": "94483" }, { "name": "PHP", "bytes": "1429" }, { "name": "Perl", "bytes": "6186" }, { "name": "Perl 6", "bytes": "1360" }, { "name": "PureBasic", "bytes": "24932" }, { "name": "Python", "bytes": "30064150" }, { "name": "Ruby", "bytes": "547" }, { "name": "Shell", "bytes": "402121" } ], "symlink_target": "" }
var Morf = function(elem, css, opts) { var from = {}, to = {}, fromElem = document.createElement('div'), toElem = document.createElement('div'), options = { timingFunction: 'ease', duration: null, increment: 0.01, debug: false, optimise: true, // Whether the outputted CSS should be optimised decimalPlaces: 5 // How many decimal places to optimise the WebKitCSSMatrix output to }, // Define all other var's used in the function i = rule = ruleName = camel = m1 = m2 = progress = frame = rule = transEvent = val = null, cacheKey = '', // Setup a scoped reference to ourselves _this = this, keyframes = {}, // Create a unique name for this animation animName = 'anim'+(new Date().getTime()), /* --- Helper Functions ------------------------------------------------------------------- */ // Event listener for the webkitAnimationEnd Event animationEndListener = function(event){ elem.removeEventListener('webkitAnimationEnd', animationEndListener, true); // Dispatch a faux webkitTransitionEnd event to complete the appearance of this being a transition rather than an animation // TODO: Should we throw an event for each property changed? (event.propertyName = 'opacity' etc) transEvent = document.createEvent("Event"); transEvent.initEvent("webkitTransitionEnd", true, true); elem.dispatchEvent(transEvent); // Reset transition effects after use elem.style.webkitTransitionTimingFunction = null; elem.style.webkitTransitionDuration = 0; if (options.callback) { options.callback(elem); } }, // Adds the CSS to the current page addKeyframeRule = function(rule) { if (document.styleSheets && document.styleSheets.length) document.styleSheets[0].insertRule(rule, 0); else { var style = document.createElement('style'); style.innerHTML = rule; document.head.appendChild(style); } }, // Produces a CSS string representation of the Keyframes createAnimationCSS = function(kf, name) { var str = '@-webkit-keyframes '+name+' {\n', f = pos = rule = null, fStr = ''; for(pos in kf) { f = kf[pos]; fStr = '\t'+pos+' {\n'; for(rule in f) fStr += '\t\t'+_this.util.toDash(rule)+': '+f[rule]+';\n'; fStr += "\t}\n\n"; str += fStr; } return options.optimise ? optimiseCSS(str+' }') : str+' }'; }, // Replaces scale(0) with 0.0001 to get around the inability to these decompose matrix sanityCheckTransformString = function(str) { var scale = str.match(/scale[Y|X|Z]*\([0-9, ]*0[,0-9 ]*\)/g), i = 0; if(scale) { // There might be multiple scale() properties in the string for(i = 0; i < scale.length; i++) str = str.replace(scale[i], scale[i].replace(/([^0-9])0([^0.9])/g, "$10.0001$2")); } return str; }, // WebKitCSSMatrix toString() ALWAYS outputs numbers to 5 decimal places - this helps optimise the string optimiseCSS = function(str, decimalPlaces) { decimalPlaces = typeof options.decimalPlaces == 'number' ? options.decimalPlaces : 5; var matches = str.match(/[0-9\.]+/gm), i = 0; if(matches) { for(i = 0; i < matches.length; i++) str = str.replace(matches[i], parseFloat( parseFloat(matches[i]).toFixed(decimalPlaces))); } return str; }; /* --- Helper Functions End --------------------------------------------------------------- */ // Import the options for(i in opts) options[i] = opts[i]; // If timingFunction is a natively supported function then just trigger normal transition if( options.timingFunction === 'ease' || options.timingFunction === 'linear' || options.timingFunction === 'ease-in' || options.timingFunction === 'ease-out' || options.timingFunction === 'ease-in-out' || /^cubic-bezier/.test(options.timingFunction)) { elem.style.webkitTransitionDuration = options.duration; elem.style.webkitTransitionTimingFunction = options.timingFunction; // Listen for the transitionEnd event to fire the callback if needed var transitionEndListener = function(event) { elem.removeEventListener('webkitTransitionEnd', transitionEndListener, true); // Clean up after ourself elem.style.webkitTransitionDuration = 0; elem.style.webkitTransitionTimingFunction = null; if (options.callback) { // Delay execution to ensure the clean up CSS has taken effect setTimeout(function() { options.callback(elem); }, 10); } }; elem.addEventListener('webkitTransitionEnd', transitionEndListener, true); setTimeout(function() { for(rule in css) { camel = _this.util.toCamel(rule); elem.style[camel] = css[rule]; } }, 10); this.css = ''; return; } else { // Reset transition properties for this element elem.style.webkitTransitionTimingFunction = null; elem.style.webkitTransitionDuration = 0; } // Create the key used to cache this animation cacheKey += options.timingFunction; // Setup the start and end CSS state for(rule in css) { camel = this.util.toCamel(rule); toElem.style[camel] = css[rule]; // Set the from/start state from[rule] = (camel == 'WebkitTransform') ? new WebKitCSSMatrix( sanityCheckTransformString( window.getComputedStyle(elem)['-webkit-transform'] ) ) : window.getComputedStyle(elem)[rule]; // Set the to/end state to[rule] = (camel == 'WebkitTransform') ? new WebKitCSSMatrix( sanityCheckTransformString( toElem.style.WebkitTransform ) ) : toElem.style[camel]; // Shifty requires numeric values to be a number rather than a string (e.g. for opacity) from[rule] = from[rule] == (val = parseInt(from[rule], 10)) ? val : from[rule]; to[rule] = to[rule] == (val = parseInt(from[rule], 10)) ? val : to[rule]; // Update the cacheKey cacheKey += ';' + rule + ':' + from[rule] + '->' + to[rule]; } // Check the cache to save expensive calculations if(Morf.cache[cacheKey]) { this.css = Morf.cache[cacheKey].css; animName = Morf.cache[cacheKey].name; } else { // Produce decompositions of matrices here so we don't have to redo it on each iteration // Decomposing the matrix is expensive so we need to minimise these requests if(from['-webkit-transform']) { m1 = from['-webkit-transform'].decompose(); m2 = to['-webkit-transform'].decompose(); } // Produce style keyframes for(progress = 0; progress <= 1; progress += options.increment) { // Use Shifty.js to work out the interpolated CSS state frame = Tweenable.util.interpolate(from, to, progress, options.timingFunction); // Work out the interpolated matrix transformation if(m1 !== null && m2 !== null) frame['-webkit-transform'] = m1.tween(m2, progress, Tweenable.prototype.formula[options.timingFunction]); keyframes[parseInt(progress*100, 10)+'%'] = frame; } // Ensure the last frame has been added keyframes['100%'] = to; // Add the new animation to the document this.css = createAnimationCSS(keyframes, animName); addKeyframeRule(this.css); Morf.cache[cacheKey] = {css: this.css, name: animName}; } // Set the final position state as this should be a transition not an animation & the element should end in the 'to' state for(rule in to) elem.style[this.util.toCamel(rule)] = to[rule]; // Trigger the animation elem.addEventListener('webkitAnimationEnd', animationEndListener, true); elem.style.webkitAnimationDuration = options.duration; elem.style.webkitAnimationTimingFunction = 'linear'; elem.style.webkitAnimationName = animName; // Print the animation to the console if the debug switch is given if(options.debug && window.console && window.console.log) console.log(this.css); }; /** * Convenience function for triggering a transition * @param {HTMLDom} elem The element to apply the transition to * @param {Object} css Key value pair of CSS properties * @param {Object} opts Additional configuration options * * Configuration options * - timingFunction: {String} Name of the easing function to perform * - duration: {integer} Duration in ms * - increment: {float} How frequently to generate keyframes (Defaults to 0.01, which is every 1%) * - debug: {Boolean} Should the generated CSS Animation be printed to the console * * @returns {Morf} An instance of the Morf object */ Morf.transition = function(elem, css, opts){ return new Morf(elem, css, opts); }; /** * Object to cache generated animations */ Morf.cache = {}; /** * Current version */ Morf.version = '0.1.5'; // Utilities Placeholder Morf.prototype.util = {}; /** * Converts a DOM style string to CSS property name * @param {String} str A DOM style string * @returns {String} CSS property name */ Morf.prototype.util.toDash = function(str){ str = str.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();}); return /^webkit/.test(str) ? '-'+str : str; }; /** * Converts a CSS property name to DOM style string * @param {String} str A CSS property name * @returns {String} DOM style string */ Morf.prototype.util.toCamel = function(str){ return str.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');}); }; /** * WebKitCSSMatrix Extensions * * Copyright 2011, Joe Lambert (http://www.joelambert.co.uk) * Free to use under the MIT license. * http://joelambert.mit-license.org/ */ // Wrap this functionality up to prevent poluting the global namespace (function(){ /** * A 4 dimensional vector * @author Joe Lambert * @constructor */ var Vector4 = function(x, y, z, w) { this.x = x ? x : 0; this.y = y ? y : 0; this.z = z ? z : 0; this.w = w ? w : 0; /** * Ensure that values are not undefined * @author Joe Lambert * @returns null */ this.checkValues = function() { this.x = this.x ? this.x : 0; this.y = this.y ? this.y : 0; this.z = this.z ? this.z : 0; this.w = this.w ? this.w : 0; }; /** * Get the length of the vector * @author Joe Lambert * @returns {float} */ this.length = function() { this.checkValues(); return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); }; /** * Get a normalised representation of the vector * @author Joe Lambert * @returns {Vector4} */ this.normalise = function() { var len = this.length(), v = new Vector4(this.x / len, this.y / len, this.z / len); return v; }; /** * Vector Dot-Product * @param {Vector4} v The second vector to apply the product to * @author Joe Lambert * @returns {float} The Dot-Product of this and v. */ this.dot = function(v) { return this.x*v.x + this.y*v.y + this.z*v.z + this.w*v.w; }; /** * Vector Cross-Product * @param {Vector4} v The second vector to apply the product to * @author Joe Lambert * @returns {Vector4} The Cross-Product of this and v. */ this.cross = function(v) { return new Vector4(this.y*v.z - this.z*v.y, this.z*v.x - this.x*v.z, this.x*v.y - this.y*v.x); }; /** * Helper function required for matrix decomposition * A Javascript implementation of pseudo code available from http://www.w3.org/TR/css3-2d-transforms/#matrix-decomposition * @param {Vector4} aPoint A 3D point * @param {float} ascl * @param {float} bscl * @author Joe Lambert * @returns {Vector4} */ this.combine = function(aPoint, ascl, bscl) { return new Vector4( (ascl * this.x) + (bscl * aPoint.x), (ascl * this.y) + (bscl * aPoint.y), (ascl * this.z) + (bscl * aPoint.z) ); } }; /** * Object containing the decomposed components of a matrix * @author Joe Lambert * @constructor */ var CSSMatrixDecomposed = function(obj) { obj === undefined ? obj = {} : null; var components = {perspective: null, translate: null, skew: null, scale: null, rotate: null}; for(var i in components) this[i] = obj[i] ? obj[i] : new Vector4(); /** * Tween between two decomposed matrices * @param {CSSMatrixDecomposed} dm The destination decomposed matrix * @param {float} progress A float value between 0-1, representing the percentage of completion * @param {function} fn An easing function following the prototype function(pos){} * @author Joe Lambert * @returns {WebKitCSSMatrix} A new matrix for the tweened state */ this.tween = function(dm, progress, fn) { if(fn === undefined) fn = function(pos) {return pos;}; // Default to a linear easing if(!dm) dm = new CSSMatrixDecomposed(new WebKitCSSMatrix().decompose()); var r = new CSSMatrixDecomposed(), i = index = null, trans = ''; progress = fn(progress); for(index in components) for(i in {x:'x', y:'y', z:'z', w:'w'}) r[index][i] = (this[index][i] + (dm[index][i] - this[index][i]) * progress ).toFixed(5); trans = 'matrix3d(1,0,0,0, 0,1,0,0, 0,0,1,0, '+r.perspective.x+', '+r.perspective.y+', '+r.perspective.z+', '+r.perspective.w+') ' + 'translate3d('+r.translate.x+'px, '+r.translate.y+'px, '+r.translate.z+'px) ' + 'rotateX('+r.rotate.x+'rad) rotateY('+r.rotate.y+'rad) rotateZ('+r.rotate.z+'rad) ' + 'matrix3d(1,0,0,0, 0,1,0,0, 0,'+r.skew.z+',1,0, 0,0,0,1) ' + 'matrix3d(1,0,0,0, 0,1,0,0, '+r.skew.y+',0,1,0, 0,0,0,1) ' + 'matrix3d(1,0,0,0, '+r.skew.x+',1,0,0, 0,0,1,0, 0,0,0,1) ' + 'scale3d('+r.scale.x+', '+r.scale.y+', '+r.scale.z+')'; try { r = new WebKitCSSMatrix(trans); return r; } catch(e) { console.error('Invalid matrix string: '+trans); return '' }; }; }; /** * Tween between two matrices * @param {WebKitCSSMatrix} matrix The destination matrix * @param {float} progress A float value between 0-1, representing the percentage of completion * @param {function} fn An easing function following the prototype function(pos){} * @author Joe Lambert * @returns {WebKitCSSMatrix} A new matrix for the tweened state */ WebKitCSSMatrix.prototype.tween = function(matrix, progress, fn) { if(fn === undefined) fn = function(pos) {return pos;}; // Default to a linear easing var m = new WebKitCSSMatrix, m1 = this.decompose(), m2 = matrix.decompose(), r = m.decompose() trans = '', index = i = null; // Tween between the two decompositions return m1.tween(m2, progress, fn); }; /** * Transform a Vector4 object using the current matrix * @param {Vector4} v The vector to transform * @author Joe Lambert * @returns {Vector4} The transformed vector */ WebKitCSSMatrix.prototype.transformVector = function(v) { // TODO: Do we need to mod this for Vector4? return new Vector4( this.m11*v.x + this.m12*v.y + this.m13*v.z, this.m21*v.x + this.m22*v.y + this.m23*v.z, this.m31*v.x + this.m32*v.y + this.m33*v.z ); }; /** * Transposes the matrix * @author Joe Lambert * @returns {WebKitCSSMatrix} The transposed matrix */ WebKitCSSMatrix.prototype.transpose = function() { var matrix = new WebKitCSSMatrix(), n = m = 0; for (n = 0; n <= 4-2; n++) { for (m = n + 1; m <= 4-1; m++) { matrix['m'+(n+1)+(m+1)] = this['m'+(m+1)+(n+1)]; matrix['m'+(m+1)+(n+1)] = this['m'+(n+1)+(m+1)]; } } return matrix; }; /** * Calculates the determinant * @author Joe Lambert * @returns {float} The determinant of the matrix */ WebKitCSSMatrix.prototype.determinant = function() { return this.m14 * this.m23 * this.m32 * this.m41-this.m13 * this.m24 * this.m32 * this.m41 - this.m14 * this.m22 * this.m33 * this.m41+this.m12 * this.m24 * this.m33 * this.m41 + this.m13 * this.m22 * this.m34 * this.m41-this.m12 * this.m23 * this.m34 * this.m41 - this.m14 * this.m23 * this.m31 * this.m42+this.m13 * this.m24 * this.m31 * this.m42 + this.m14 * this.m21 * this.m33 * this.m42-this.m11 * this.m24 * this.m33 * this.m42 - this.m13 * this.m21 * this.m34 * this.m42+this.m11 * this.m23 * this.m34 * this.m42 + this.m14 * this.m22 * this.m31 * this.m43-this.m12 * this.m24 * this.m31 * this.m43 - this.m14 * this.m21 * this.m32 * this.m43+this.m11 * this.m24 * this.m32 * this.m43 + this.m12 * this.m21 * this.m34 * this.m43-this.m11 * this.m22 * this.m34 * this.m43 - this.m13 * this.m22 * this.m31 * this.m44+this.m12 * this.m23 * this.m31 * this.m44 + this.m13 * this.m21 * this.m32 * this.m44-this.m11 * this.m23 * this.m32 * this.m44 - this.m12 * this.m21 * this.m33 * this.m44+this.m11 * this.m22 * this.m33 * this.m44; }; /** * Decomposes the matrix into its component parts. * A Javascript implementation of the pseudo code available from http://www.w3.org/TR/css3-2d-transforms/#matrix-decomposition * @author Joe Lambert * @returns {Object} An object with each of the components of the matrix (perspective, translate, skew, scale, rotate) or identity matrix on failure */ WebKitCSSMatrix.prototype.decompose = function() { var matrix = new WebKitCSSMatrix(this.toString()), perspectiveMatrix = rightHandSide = inversePerspectiveMatrix = transposedInversePerspectiveMatrix = perspective = translate = row = i = scale = skew = pdum3 = rotate = null; if (matrix.m33 == 0) return new CSSMatrixDecomposed(new WebKitCSSMatrix().decompose()); // Return the identity matrix // Normalize the matrix. for (i = 1; i <= 4; i++) for (j = 1; j <= 4; j++) matrix['m'+i+j] /= matrix.m44; // perspectiveMatrix is used to solve for perspective, but it also provides // an easy way to test for singularity of the upper 3x3 component. perspectiveMatrix = matrix; for (i = 1; i <= 3; i++) perspectiveMatrix['m'+i+'4'] = 0; perspectiveMatrix.m44 = 1; if (perspectiveMatrix.determinant() == 0) return new CSSMatrixDecomposed(new WebKitCSSMatrix().decompose()); // Return the identity matrix // First, isolate perspective. if (matrix.m14 != 0 || matrix.m24 != 0 || matrix.m34 != 0) { // rightHandSide is the right hand side of the equation. rightHandSide = new Vector4(matrix.m14, matrix.m24, matrix.m34, matrix.m44); // Solve the equation by inverting perspectiveMatrix and multiplying // rightHandSide by the inverse. inversePerspectiveMatrix = perspectiveMatrix.inverse(); transposedInversePerspectiveMatrix = inversePerspectiveMatrix.transpose(); perspective = transposedInversePerspectiveMatrix.transformVector(rightHandSide); // Clear the perspective partition matrix.m14 = matrix.m24 = matrix.m34 = 0; matrix.m44 = 1; } else { // No perspective. perspective = new Vector4(0,0,0,1); } // Next take care of translation translate = new Vector4(matrix.m41, matrix.m42, matrix.m43); matrix.m41 = 0; matrix.m42 = 0; matrix.m43 = 0; // Now get scale and shear. 'row' is a 3 element array of 3 component vectors row = [ new Vector4(), new Vector4(), new Vector4() ]; for (i = 1; i <= 3; i++) { row[i-1].x = matrix['m'+i+'1']; row[i-1].y = matrix['m'+i+'2']; row[i-1].z = matrix['m'+i+'3']; } // Compute X scale factor and normalize first row. scale = new Vector4(); skew = new Vector4(); scale.x = row[0].length(); row[0] = row[0].normalise(); // Compute XY shear factor and make 2nd row orthogonal to 1st. skew.x = row[0].dot(row[1]); row[1] = row[1].combine(row[0], 1.0, -skew.x); // Now, compute Y scale and normalize 2nd row. scale.y = row[1].length(); row[1] = row[1].normalise(); skew.x /= scale.y; // Compute XZ and YZ shears, orthogonalize 3rd row skew.y = row[0].dot(row[2]); row[2] = row[2].combine(row[0], 1.0, -skew.y); skew.z = row[1].dot(row[2]); row[2] = row[2].combine(row[1], 1.0, -skew.z); // Next, get Z scale and normalize 3rd row. scale.z = row[2].length(); row[2] = row[2].normalise(); skew.y /= scale.z; skew.y /= scale.z; // At this point, the matrix (in rows) is orthonormal. // Check for a coordinate system flip. If the determinant // is -1, then negate the matrix and the scaling factors. pdum3 = row[1].cross(row[2]) if (row[0].dot(pdum3) < 0) { for (i = 0; i < 3; i++) { scale.x *= -1; row[i].x *= -1; row[i].y *= -1; row[i].z *= -1; } } // Now, get the rotations out rotate = new Vector4(); rotate.y = Math.asin(-row[0].z); if (Math.cos(rotate.y) != 0) { rotate.x = Math.atan2(row[1].z, row[2].z); rotate.z = Math.atan2(row[0].y, row[0].x); } else { rotate.x = Math.atan2(-row[2].x, row[1].y); rotate.z = 0; } return new CSSMatrixDecomposed({ perspective: perspective, translate: translate, skew: skew, scale: scale, rotate: rotate }); }; })(); /** Mifty - A custom build of Shifty for use with Morf.js. By Jeremy Kahn - jeremyckahn@gmail.com v0.4.1 For instructions on how to use Shifty, please consult the README: https://github.com/jeremyckahn/shifty/blob/master/README.md MIT Lincense. This code free to use, modify, distribute and enjoy. */ (function(e){function a(){return+new Date}function b(a,c){for(var j in a)a.hasOwnProperty(j)&&c(a,j)}function h(a,c){b(c,function(c,f){a[f]=c[f]});return a}function k(a,c){b(c,function(c,f){typeof a[f]==="undefined"&&(a[f]=c[f])});return a}function i(a,c,j){var f,a=(a-c.timestamp)/c.duration;for(f in j.current)j.current.hasOwnProperty(f)&&c.to.hasOwnProperty(f)&&(j.current[f]=c.originalState[f]+(c.to[f]-c.originalState[f])*c.easingFunc(a));return j.current}function n(a,c,j,f){var b;for(b=0;b<c[a].length;b++)c[a][b].apply(j, f)}function l(a,c,j){b(e.Tweenable.prototype.filter,function(b,e){b[e][a]&&b[e][a].apply(c,j)})}function m(d,c){var b;b=a();b<d.timestamp+d.duration&&c.isAnimating?(l("beforeTween",d.owner,[c.current,d.originalState,d.to]),i(b,d,c),l("afterTween",d.owner,[c.current,d.originalState,d.to]),d.hook.step&&n("step",d.hook,d.owner,[c.current]),d.step.call(c.current),c.loopId=setTimeout(function(){m(d,c)},1E3/d.owner.fps)):d.owner.stop(!0)}function g(a){a=a||{};this._hook={};this._tweenParams={owner:this, hook:this._hook};this._state={};this._state.current=a.initialState||{};this.fps=a.fps||30;this.easing=a.easing||"linear";this.duration=a.duration||500;return this}g.prototype.tween=function(d,c,b,e,g){var i=this;if(!this._state.isAnimating)return this._state.loopId=0,this._state.pausedAtTime=null,c?(this._tweenParams.step=function(){},this._state.current=d||{},this._tweenParams.to=c||{},this._tweenParams.duration=b||this.duration,this._tweenParams.callback=e||function(){},this._tweenParams.easing= g||this.easing):(this._tweenParams.step=d.step||function(){},this._tweenParams.callback=d.callback||function(){},this._state.current=d.from||{},this._tweenParams.to=d.to||d.target||{},this._tweenParams.duration=d.duration||this.duration,this._tweenParams.easing=d.easing||this.easing),this._tweenParams.timestamp=a(),this._tweenParams.easingFunc=this.formula[this._tweenParams.easing]||this.formula.linear,k(this._state.current,this._tweenParams.to),k(this._tweenParams.to,this._state.current),l("tweenCreated", this._tweenParams.owner,[this._state.current,this._tweenParams.originalState,this._tweenParams.to]),this._tweenParams.originalState=h({},this._state.current),this._state.isAnimating=!0,setTimeout(function(){m(i._tweenParams,i._state)},1E3/this.fps),this};g.prototype.to=function(a,c,b,e){typeof c==="undefined"?(a.from=this.get(),this.tween(a)):this.tween(this.get(),a,c,b,e);return this};g.prototype.get=function(){return this._state.current};g.prototype.set=function(a){this._state.current=a||{};return this}; g.prototype.stop=function(a){clearTimeout(this._state.loopId);this._state.isAnimating=!1;a&&(h(this._state.current,this._tweenParams.to),this._tweenParams.callback.call(this._state.current));return this};g.prototype.pause=function(){clearTimeout(this._state.loopId);this._state.pausedAtTime=a();this._state.isPaused=!0;return this};g.prototype.resume=function(){var a=this;this._state.isPaused&&(this._tweenParams.timestamp+=this._state.pausedAtTime-this._tweenParams.timestamp);setTimeout(function(){m(a._tweenParams, a._state)},1E3/this.fps);return this};g.prototype.hookAdd=function(a,c){this._hook.hasOwnProperty(a)||(this._hook[a]=[]);this._hook[a].push(c)};g.prototype.hookRemove=function(a,c){var b;if(this._hook.hasOwnProperty(a))if(c)for(b=this._hook[a].length;b>=0;b++)this._hook[a][b]===c&&this._hook[a].splice(b,1);else this._hook[a]=[]};g.prototype.filter={};g.util={now:a,each:b,tweenProps:i,applyFilter:l,simpleCopy:h};g.prototype.formula={linear:function(a){return a}};e.Tweenable=g})(this); (function(e){e.Tweenable.util.simpleCopy(e.Tweenable.prototype.formula,{easeInQuad:function(a){return Math.pow(a,2)},easeOutQuad:function(a){return-(Math.pow(a-1,2)-1)},easeInOutQuad:function(a){if((a/=0.5)<1)return 0.5*Math.pow(a,2);return-0.5*((a-=2)*a-2)},easeInCubic:function(a){return Math.pow(a,3)},easeOutCubic:function(a){return Math.pow(a-1,3)+1},easeInOutCubic:function(a){if((a/=0.5)<1)return 0.5*Math.pow(a,3);return 0.5*(Math.pow(a-2,3)+2)},easeInQuart:function(a){return Math.pow(a,4)},easeOutQuart:function(a){return-(Math.pow(a- 1,4)-1)},easeInOutQuart:function(a){if((a/=0.5)<1)return 0.5*Math.pow(a,4);return-0.5*((a-=2)*Math.pow(a,3)-2)},easeInQuint:function(a){return Math.pow(a,5)},easeOutQuint:function(a){return Math.pow(a-1,5)+1},easeInOutQuint:function(a){if((a/=0.5)<1)return 0.5*Math.pow(a,5);return 0.5*(Math.pow(a-2,5)+2)},easeInSine:function(a){return-Math.cos(a*(Math.PI/2))+1},easeOutSine:function(a){return Math.sin(a*(Math.PI/2))},easeInOutSine:function(a){return-0.5*(Math.cos(Math.PI*a)-1)},easeInExpo:function(a){return a== 0?0:Math.pow(2,10*(a-1))},easeOutExpo:function(a){return a==1?1:-Math.pow(2,-10*a)+1},easeInOutExpo:function(a){if(a==0)return 0;if(a==1)return 1;if((a/=0.5)<1)return 0.5*Math.pow(2,10*(a-1));return 0.5*(-Math.pow(2,-10*--a)+2)},easeInCirc:function(a){return-(Math.sqrt(1-a*a)-1)},easeOutCirc:function(a){return Math.sqrt(1-Math.pow(a-1,2))},easeInOutCirc:function(a){if((a/=0.5)<1)return-0.5*(Math.sqrt(1-a*a)-1);return 0.5*(Math.sqrt(1-(a-=2)*a)+1)},easeOutBounce:function(a){return a<1/2.75?7.5625* a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375},easeInBack:function(a){return a*a*(2.70158*a-1.70158)},easeOutBack:function(a){return(a-=1)*a*(2.70158*a+1.70158)+1},easeInOutBack:function(a){var b=1.70158;if((a/=0.5)<1)return 0.5*a*a*(((b*=1.525)+1)*a-b);return 0.5*((a-=2)*a*(((b*=1.525)+1)*a+b)+2)},elastic:function(a){return-1*Math.pow(4,-8*a)*Math.sin((a*6-1)*2*Math.PI/2)+1},swingFromTo:function(a){var b=1.70158;return(a/=0.5)< 1?0.5*a*a*(((b*=1.525)+1)*a-b):0.5*((a-=2)*a*(((b*=1.525)+1)*a+b)+2)},swingFrom:function(a){return a*a*(2.70158*a-1.70158)},swingTo:function(a){return(a-=1)*a*(2.70158*a+1.70158)+1},bounce:function(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375},bouncePast:function(a){return a<1/2.75?7.5625*a*a:a<2/2.75?2-(7.5625*(a-=1.5/2.75)*a+0.75):a<2.5/2.75?2-(7.5625*(a-=2.25/2.75)*a+0.9375):2-(7.5625*(a-=2.625/2.75)* a+0.984375)},easeFromTo:function(a){if((a/=0.5)<1)return 0.5*Math.pow(a,4);return-0.5*((a-=2)*Math.pow(a,3)-2)},easeFrom:function(a){return Math.pow(a,4)},easeTo:function(a){return Math.pow(a,0.25)}})})(this); (function(e){if(e.Tweenable)e.Tweenable.util.interpolate=function(a,b,h,k){var i;if(a&&a.from)b=a.to,h=a.position,k=a.easing,a=a.from;i=e.Tweenable.util.simpleCopy({},a);e.Tweenable.util.applyFilter("tweenCreated",i,[i,a,b]);e.Tweenable.util.applyFilter("beforeTween",i,[i,a,b]);h=e.Tweenable.util.tweenProps(h,{originalState:a,to:b,timestamp:0,duration:1,easingFunc:e.Tweenable.prototype.formula[k]||e.Tweenable.prototype.formula.linear},{current:i});e.Tweenable.util.applyFilter("afterTween",h,[h,a, b]);return h},e.Tweenable.prototype.interpolate=function(a,b,h){a=e.Tweenable.util.interpolate(this.get(),a,b,h);this.set(a);return a}})(this); /** * @preserve * Extra easing functions borrowed from scripty2 (c) 2005-2010 Thomas Fuchs (MIT Licence) * https://raw.github.com/madrobby/scripty2/master/src/effects/transitions/transitions.js */ (function(){ var scripty2 = { spring: function(pos) { return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); }, sinusoidal: function(pos) { return (-Math.cos(pos*Math.PI)/2) + 0.5; } }; // Load the Scripty2 functions for(var t in scripty2) Tweenable.prototype.formula[t] = scripty2[t]; })();
{ "content_hash": "cb82a8c74bce1341054d92c39f71c7d5", "timestamp": "", "source": "github", "line_count": 738, "max_line_length": 544, "avg_line_length": 38.17886178861789, "alnum_prop": 0.6631175468483816, "repo_name": "joelambert/morf", "id": "6a968f22c5007bc1b9558fc047f8cca30d22b70c", "size": "28371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/morf.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5318" }, { "name": "JavaScript", "bytes": "113535" }, { "name": "PHP", "bytes": "1513" } ], "symlink_target": "" }
using System.Linq; using System.Web.Mvc; using Xero.ScreencastWeb.Services; namespace Xero.ScreencastWeb.Controllers { [InitServiceProvider] public class InvoicesController : ControllerBase { // // GET: /Invoices/ public ActionResult Index() { var repository = ServiceProvider.GetCurrentRepository(); return View(repository.Invoices.ToList()); } } }
{ "content_hash": "b34d0e1cbea3fb543cfdfec461979f30", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 68, "avg_line_length": 19.772727272727273, "alnum_prop": 0.6367816091954023, "repo_name": "XeroAPI/XeroAPI.Net", "id": "9c3f0f597018b213cc74eb7ed0ff6297638f65e8", "size": "435", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "source/XeroApi.MvcWebApp/Controllers/InvoicesController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "7689" }, { "name": "C#", "bytes": "463635" }, { "name": "CSS", "bytes": "4635" }, { "name": "Visual Basic", "bytes": "14298" } ], "symlink_target": "" }
package org.apache.solr.schema; /** * A numeric field that can contain 32-bit signed two's complement integer values. * * <ul> * <li>Min Value Allowed: -2147483648</li> * <li>Max Value Allowed: 2147483647</li> * </ul> * * @see Integer */ public class TrieIntField extends TrieField implements IntValueFieldType { { type=TrieTypes.INTEGER; } @Override public Object toNativeType(Object val) { if(val==null) return null; if (val instanceof Number) return ((Number) val).intValue(); try { if (val instanceof String) return Integer.parseInt((String) val); } catch (NumberFormatException e) { Float v = Float.parseFloat((String) val); return v.intValue(); } return super.toNativeType(val); } }
{ "content_hash": "2cb51c3b19286ac995f73befe0b9ba95", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 82, "avg_line_length": 23.78125, "alnum_prop": 0.6636005256241787, "repo_name": "cscorley/solr-only-mirror", "id": "ffa33815ef51077ed6db7fc4e81157d6b8666ef0", "size": "1562", "binary": false, "copies": "5", "ref": "refs/heads/trunk", "path": "core/src/java/org/apache/solr/schema/TrieIntField.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "133214" }, { "name": "Java", "bytes": "13653420" }, { "name": "JavaScript", "bytes": "1023076" }, { "name": "Shell", "bytes": "148719" }, { "name": "XSLT", "bytes": "134072" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ConsotoUniversity.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
{ "content_hash": "db1adbda03563598c918d49b9205f918", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 67, "avg_line_length": 19.466666666666665, "alnum_prop": 0.5684931506849316, "repo_name": "codinghouselondon/ContosoUniversity", "id": "20cd4b12760383f7c58ddf9844379f0dea67fef2", "size": "586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ConsotoUniversity/ConsotoUniversity/Controllers/HomeController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "108" }, { "name": "C#", "bytes": "27043" }, { "name": "CSS", "bytes": "513" }, { "name": "JavaScript", "bytes": "21032" }, { "name": "PowerShell", "bytes": "101111" } ], "symlink_target": "" }
<?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: header-name'); if (isset($_GET['redirected'])) { return; } if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { header('HTTP/1.0 302 Found'); header('Location: ./cors-preflight-redirect.php?redirected=true'); } else { echo 'OK'; } ?>
{ "content_hash": "f6ba261c5c620ec9bd2e66e6d12333eb", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 68, "avg_line_length": 24.666666666666668, "alnum_prop": 0.6621621621621622, "repo_name": "scheib/chromium", "id": "07adc539ad9ad2d4bef28d327ab61a995d314e78", "size": "370", "binary": false, "copies": "9", "ref": "refs/heads/main", "path": "third_party/blink/web_tests/http/tests/inspector-protocol/network/resources/cors-preflight-redirect.php", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package polardb //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // StartSqlLogTrail invokes the polardb.StartSqlLogTrail API synchronously func (client *Client) StartSqlLogTrail(request *StartSqlLogTrailRequest) (response *StartSqlLogTrailResponse, err error) { response = CreateStartSqlLogTrailResponse() err = client.DoAction(request, response) return } // StartSqlLogTrailWithChan invokes the polardb.StartSqlLogTrail API asynchronously func (client *Client) StartSqlLogTrailWithChan(request *StartSqlLogTrailRequest) (<-chan *StartSqlLogTrailResponse, <-chan error) { responseChan := make(chan *StartSqlLogTrailResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.StartSqlLogTrail(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // StartSqlLogTrailWithCallback invokes the polardb.StartSqlLogTrail API asynchronously func (client *Client) StartSqlLogTrailWithCallback(request *StartSqlLogTrailRequest, callback func(response *StartSqlLogTrailResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *StartSqlLogTrailResponse var err error defer close(result) response, err = client.StartSqlLogTrail(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // StartSqlLogTrailRequest is the request struct for api StartSqlLogTrail type StartSqlLogTrailRequest struct { *requests.RpcRequest ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` SecurityToken string `position:"Query" name:"SecurityToken"` DBInstanceId string `position:"Query" name:"DBInstanceId"` ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` OwnerAccount string `position:"Query" name:"OwnerAccount"` OwnerId requests.Integer `position:"Query" name:"OwnerId"` } // StartSqlLogTrailResponse is the response struct for api StartSqlLogTrail type StartSqlLogTrailResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` DBInstanceID int `json:"DBInstanceID" xml:"DBInstanceID"` OpenTrail string `json:"OpenTrail" xml:"OpenTrail"` DBInstanceName string `json:"DBInstanceName" xml:"DBInstanceName"` } // CreateStartSqlLogTrailRequest creates a request to invoke StartSqlLogTrail API func CreateStartSqlLogTrailRequest() (request *StartSqlLogTrailRequest) { request = &StartSqlLogTrailRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("polardb", "2017-08-01", "StartSqlLogTrail", "polardb", "openAPI") request.Method = requests.POST return } // CreateStartSqlLogTrailResponse creates a response to parse from StartSqlLogTrail response func CreateStartSqlLogTrailResponse() (response *StartSqlLogTrailResponse) { response = &StartSqlLogTrailResponse{ BaseResponse: &responses.BaseResponse{}, } return }
{ "content_hash": "f9d12ec050771ceb13b0e0b13948db1a", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 159, "avg_line_length": 37.18691588785047, "alnum_prop": 0.7582307112339783, "repo_name": "aliyun/alibaba-cloud-sdk-go", "id": "3415b33218fbcb070c724c8edfe5788dc88cd8fe", "size": "3979", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/polardb/start_sql_log_trail.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "734307" }, { "name": "Makefile", "bytes": "183" } ], "symlink_target": "" }
static int fatal_error_handler_nesting_depth = 0; // Contains protection against recursive calls (faults while handling faults). extern "C" void V8_Fatal(const char* file, int line, const char* format, ...) { fflush(stdout); fflush(stderr); fatal_error_handler_nesting_depth++; // First time we try to print an error message if (fatal_error_handler_nesting_depth < 2) { i::OS::PrintError("\n\n#\n# Fatal error in %s, line %d\n# ", file, line); va_list arguments; va_start(arguments, format); i::OS::VPrintError(format, arguments); va_end(arguments); i::OS::PrintError("\n#\n\n"); } // First two times we may try to print a stack dump. if (fatal_error_handler_nesting_depth < 3) { if (i::FLAG_stack_trace_on_abort) { // Call this one twice on double fault i::Top::PrintStack(); } } i::OS::Abort(); } void CheckEqualsHelper(const char* file, int line, const char* expected_source, v8::Handle<v8::Value> expected, const char* value_source, v8::Handle<v8::Value> value) { if (!expected->Equals(value)) { v8::String::Utf8Value value_str(value); v8::String::Utf8Value expected_str(expected); V8_Fatal(file, line, "CHECK_EQ(%s, %s) failed\n# Expected: %s\n# Found: %s", expected_source, value_source, *expected_str, *value_str); } } void CheckNonEqualsHelper(const char* file, int line, const char* unexpected_source, v8::Handle<v8::Value> unexpected, const char* value_source, v8::Handle<v8::Value> value) { if (unexpected->Equals(value)) { v8::String::Utf8Value value_str(value); V8_Fatal(file, line, "CHECK_NE(%s, %s) failed\n# Value: %s", unexpected_source, value_source, *value_str); } } void API_Fatal(const char* location, const char* format, ...) { i::OS::PrintError("\n#\n# Fatal error in %s\n# ", location); va_list arguments; va_start(arguments, format); i::OS::VPrintError(format, arguments); va_end(arguments); i::OS::PrintError("\n#\n\n"); i::OS::Abort(); }
{ "content_hash": "633b7f249eea50055f67d0ffaeef3696", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 79, "avg_line_length": 34.36363636363637, "alnum_prop": 0.5771604938271605, "repo_name": "sinisterchipmunk/tomato", "id": "b5df316d0f736a38bf11cd0ccea90bcaa742635e", "size": "3949", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ext/tomato/external/v8/src/checks.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2815122" }, { "name": "C++", "bytes": "19935082" }, { "name": "JavaScript", "bytes": "4019959" }, { "name": "Python", "bytes": "1833190" }, { "name": "Ruby", "bytes": "245959" }, { "name": "Scheme", "bytes": "10604" } ], "symlink_target": "" }
package org.apache.camel.model.language; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.CamelContext; import org.apache.camel.Expression; import org.apache.camel.Predicate; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.Metadata; import org.apache.camel.util.ObjectHelper; /** * To use XQuery (XML) in Camel expressions or predicates. */ @Metadata(firstVersion = "1.0.0", label = "language,xml", title = "XQuery") @XmlRootElement(name = "xquery") @XmlAccessorType(XmlAccessType.FIELD) public class XQueryExpression extends NamespaceAwareExpression { @XmlAttribute private String type; @XmlTransient private Class<?> resultType; @XmlAttribute private String headerName; public XQueryExpression() { } public XQueryExpression(String expression) { super(expression); } public String getLanguage() { return "xquery"; } public String getType() { return type; } /** * Sets the class name of the result type (type from output) * <p/> * The default result type is NodeSet */ public void setType(String type) { this.type = type; } public Class<?> getResultType() { return resultType; } /** * Sets the class of the result type (type from output). * <p/> * The default result type is NodeSet */ public void setResultType(Class<?> resultType) { this.resultType = resultType; } public String getHeaderName() { return headerName; } /** * Name of header to use as input, instead of the message body */ public void setHeaderName(String headerName) { this.headerName = headerName; } @Override public Expression createExpression(CamelContext camelContext) { if (resultType == null && type != null) { try { resultType = camelContext.getClassResolver().resolveMandatoryClass(type); } catch (ClassNotFoundException e) { throw RuntimeCamelException.wrapRuntimeCamelException(e); } } return super.createExpression(camelContext); } @Override protected void configureExpression(CamelContext camelContext, Expression expression) { if (resultType != null) { setProperty(expression, "resultType", resultType); } if (ObjectHelper.isNotEmpty(getHeaderName())) { setProperty(expression, "headerName", getHeaderName()); } super.configureExpression(camelContext, expression); } @Override protected void configurePredicate(CamelContext camelContext, Predicate predicate) { if (resultType != null) { setProperty(predicate, "resultType", resultType); } if (ObjectHelper.isNotEmpty(getHeaderName())) { setProperty(predicate, "headerName", getHeaderName()); } super.configurePredicate(camelContext, predicate); } }
{ "content_hash": "62fe0cf14bec80c39b537b9a056d80be", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 90, "avg_line_length": 28.280701754385966, "alnum_prop": 0.6591191066997518, "repo_name": "punkhorn/camel-upstream", "id": "2e631ed10e1a352c75d370090f3938ddc8b8ea45", "size": "4027", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/camel-core/src/main/java/org/apache/camel/model/language/XQueryExpression.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6519" }, { "name": "Batchfile", "bytes": "1518" }, { "name": "CSS", "bytes": "16394" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "14490" }, { "name": "HTML", "bytes": "896075" }, { "name": "Java", "bytes": "70312352" }, { "name": "JavaScript", "bytes": "90399" }, { "name": "Makefile", "bytes": "513" }, { "name": "Shell", "bytes": "17108" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "270186" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "c09a54b3437b08aa7f454bcef8e7f8d7", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "ab200d4fd3e76def46fce7b592a6b91a1a877cf2", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Sorghum/Sorghum bicolor/ Syn. Agrostis nigricans/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using GuildedRose.Web.App_Start; using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace GuildedRose.Web { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //config.Filters.Add(new HardcodedAuthorizationFilterAttribute()); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html")); } } }
{ "content_hash": "e3843bd1ac508981541294c864c403c0", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 28.82758620689655, "alnum_prop": 0.631578947368421, "repo_name": "cgleadall/GuildedRoseKata", "id": "d7b86e466a9533e34eba7f77db2efbfbf1e9bf03", "size": "838", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/GuildedRose/GuildedRose.Web/App_Start/WebApiConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "C#", "bytes": "175452" }, { "name": "CSS", "bytes": "2626" }, { "name": "HTML", "bytes": "5069" }, { "name": "JavaScript", "bytes": "10918" } ], "symlink_target": "" }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/local/syncable_file_operation_runner.h" #include <stddef.h> #include <stdint.h> #include <memory> #include <string> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/sync_file_system/local/canned_syncable_file_system.h" #include "chrome/browser/sync_file_system/local/local_file_change_tracker.h" #include "chrome/browser/sync_file_system/local/local_file_sync_context.h" #include "chrome/browser/sync_file_system/local/local_file_sync_status.h" #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h" #include "chrome/browser/sync_file_system/local/syncable_file_system_operation.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/file_system/file_system_context.h" #include "storage/browser/file_system/file_system_operation_runner.h" #include "storage/browser/test/mock_blob_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/leveldb_chrome.h" using base::File; using storage::FileSystemOperation; using storage::FileSystemURL; using storage::ScopedTextBlob; namespace sync_file_system { namespace { const std::string kParent = "foo"; const std::string kFile = "foo/file"; const std::string kDir = "foo/dir"; const std::string kChild = "foo/dir/bar"; const std::string kOther = "bar"; } // namespace class SyncableFileOperationRunnerTest : public testing::Test { protected: typedef FileSystemOperation::StatusCallback StatusCallback; // Use the current thread as IO thread so that we can directly call // operations in the tests. SyncableFileOperationRunnerTest() : task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP), in_memory_env_( leveldb_chrome::NewMemEnv("SyncableFileOperationRunnerTest")), file_system_(GURL("http://example.com"), in_memory_env_.get(), base::ThreadTaskRunnerHandle::Get().get(), base::ThreadTaskRunnerHandle::Get().get()), callback_count_(0), write_status_(File::FILE_ERROR_FAILED), write_bytes_(0), write_complete_(false) {} void SetUp() override { ASSERT_TRUE(dir_.CreateUniqueTempDir()); file_system_.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), base::ThreadTaskRunnerHandle::Get().get(), base::ThreadTaskRunnerHandle::Get().get()); ASSERT_EQ( SYNC_STATUS_OK, file_system_.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(File::FILE_OK, file_system_.OpenFileSystem()); ASSERT_EQ(File::FILE_OK, file_system_.CreateDirectory(URL(kParent))); } void TearDown() override { if (sync_context_.get()) sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system_.TearDown(); RevokeSyncableFileSystem(); } FileSystemURL URL(const std::string& path) { return file_system_.URL(path); } LocalFileSyncStatus* sync_status() { return file_system_.backend()->sync_context()->sync_status(); } void ResetCallbackStatus() { write_status_ = File::FILE_ERROR_FAILED; write_bytes_ = 0; write_complete_ = false; callback_count_ = 0; } StatusCallback ExpectStatus(const base::Location& location, File::Error expect) { return base::BindOnce(&SyncableFileOperationRunnerTest::DidFinish, weak_factory_.GetWeakPtr(), location, expect); } FileSystemOperation::WriteCallback GetWriteCallback( const base::Location& location) { return base::Bind(&SyncableFileOperationRunnerTest::DidWrite, weak_factory_.GetWeakPtr(), location); } void DidWrite(const base::Location& location, File::Error status, int64_t bytes, bool complete) { SCOPED_TRACE(testing::Message() << location.ToString()); write_status_ = status; write_bytes_ += bytes; write_complete_ = complete; ++callback_count_; } void DidFinish(const base::Location& location, File::Error expect, File::Error status) { SCOPED_TRACE(testing::Message() << location.ToString()); EXPECT_EQ(expect, status); ++callback_count_; } bool CreateTempFile(base::FilePath* path) { return base::CreateTemporaryFileInDir(dir_.GetPath(), path); } content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir dir_; std::unique_ptr<leveldb::Env> in_memory_env_; CannedSyncableFileSystem file_system_; scoped_refptr<LocalFileSyncContext> sync_context_; int callback_count_; File::Error write_status_; size_t write_bytes_; bool write_complete_; storage::BlobStorageContext blob_storage_context_; private: base::WeakPtrFactory<SyncableFileOperationRunnerTest> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SyncableFileOperationRunnerTest); }; TEST_F(SyncableFileOperationRunnerTest, SimpleQueue) { sync_status()->StartSyncing(URL(kFile)); ASSERT_FALSE(sync_status()->IsWritable(URL(kFile))); // The URL is in syncing so the write operations won't run. ResetCallbackStatus(); file_system_.operation_runner()->CreateFile( URL(kFile), false /* exclusive */, ExpectStatus(FROM_HERE, File::FILE_OK)); file_system_.operation_runner()->Truncate( URL(kFile), 1, ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(0, callback_count_); // Read operations are not blocked (and are executed before queued ones). file_system_.operation_runner()->FileExists( URL(kFile), ExpectStatus(FROM_HERE, File::FILE_ERROR_NOT_FOUND)); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // End syncing (to enable write). sync_status()->EndSyncing(URL(kFile)); ASSERT_TRUE(sync_status()->IsWritable(URL(kFile))); ResetCallbackStatus(); content::RunAllTasksUntilIdle(); EXPECT_EQ(2, callback_count_); // Now the file must have been created and updated. ResetCallbackStatus(); file_system_.operation_runner()->FileExists( URL(kFile), ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); } TEST_F(SyncableFileOperationRunnerTest, WriteToParentAndChild) { // First create the kDir directory and kChild in the dir. EXPECT_EQ(File::FILE_OK, file_system_.CreateDirectory(URL(kDir))); EXPECT_EQ(File::FILE_OK, file_system_.CreateFile(URL(kChild))); // Start syncing the kDir directory. sync_status()->StartSyncing(URL(kDir)); ASSERT_FALSE(sync_status()->IsWritable(URL(kDir))); // Writes to kParent and kChild should be all queued up. ResetCallbackStatus(); file_system_.operation_runner()->Truncate( URL(kChild), 1, ExpectStatus(FROM_HERE, File::FILE_OK)); file_system_.operation_runner()->Remove( URL(kParent), true /* recursive */, ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(0, callback_count_); // Read operations are not blocked (and are executed before queued ones). file_system_.operation_runner()->DirectoryExists( URL(kDir), ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // Writes to unrelated files must succeed as well. ResetCallbackStatus(); file_system_.operation_runner()->CreateDirectory( URL(kOther), false /* exclusive */, false /* recursive */, ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // End syncing (to enable write). sync_status()->EndSyncing(URL(kDir)); ASSERT_TRUE(sync_status()->IsWritable(URL(kDir))); ResetCallbackStatus(); content::RunAllTasksUntilIdle(); EXPECT_EQ(2, callback_count_); } TEST_F(SyncableFileOperationRunnerTest, CopyAndMove) { // First create the kDir directory and kChild in the dir. EXPECT_EQ(File::FILE_OK, file_system_.CreateDirectory(URL(kDir))); EXPECT_EQ(File::FILE_OK, file_system_.CreateFile(URL(kChild))); // Start syncing the kParent directory. sync_status()->StartSyncing(URL(kParent)); // Copying kDir to other directory should succeed, while moving would fail // (since the source directory is in syncing). ResetCallbackStatus(); file_system_.operation_runner()->Copy( URL(kDir), URL("dest-copy"), storage::FileSystemOperation::OPTION_NONE, storage::FileSystemOperation::ERROR_BEHAVIOR_ABORT, storage::FileSystemOperationRunner::CopyProgressCallback(), ExpectStatus(FROM_HERE, File::FILE_OK)); file_system_.operation_runner()->Move( URL(kDir), URL("dest-move"), storage::FileSystemOperation::OPTION_NONE, ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // Only "dest-copy1" should exist. EXPECT_EQ(File::FILE_OK, file_system_.DirectoryExists(URL("dest-copy"))); EXPECT_EQ(File::FILE_ERROR_NOT_FOUND, file_system_.DirectoryExists(URL("dest-move"))); // Start syncing the "dest-copy2" directory. sync_status()->StartSyncing(URL("dest-copy2")); // Now the destination is also locked copying kDir should be queued. ResetCallbackStatus(); file_system_.operation_runner()->Copy( URL(kDir), URL("dest-copy2"), storage::FileSystemOperation::OPTION_NONE, storage::FileSystemOperation::ERROR_BEHAVIOR_ABORT, storage::FileSystemOperationRunner::CopyProgressCallback(), ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(0, callback_count_); // Finish syncing the "dest-copy2" directory to unlock Copy. sync_status()->EndSyncing(URL("dest-copy2")); ResetCallbackStatus(); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // Now we should have "dest-copy2". EXPECT_EQ(File::FILE_OK, file_system_.DirectoryExists(URL("dest-copy2"))); // Finish syncing the kParent to unlock Move. sync_status()->EndSyncing(URL(kParent)); ResetCallbackStatus(); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // Now we should have "dest-move". EXPECT_EQ(File::FILE_OK, file_system_.DirectoryExists(URL("dest-move"))); } TEST_F(SyncableFileOperationRunnerTest, Write) { EXPECT_EQ(File::FILE_OK, file_system_.CreateFile(URL(kFile))); const std::string kData("Lorem ipsum."); ScopedTextBlob blob(&blob_storage_context_, "blob:foo", kData); sync_status()->StartSyncing(URL(kFile)); ResetCallbackStatus(); file_system_.operation_runner()->Write( URL(kFile), blob.GetBlobDataHandle(), 0, GetWriteCallback(FROM_HERE)); content::RunAllTasksUntilIdle(); EXPECT_EQ(0, callback_count_); sync_status()->EndSyncing(URL(kFile)); ResetCallbackStatus(); while (!write_complete_) content::RunAllTasksUntilIdle(); EXPECT_EQ(File::FILE_OK, write_status_); EXPECT_EQ(kData.size(), write_bytes_); EXPECT_TRUE(write_complete_); } TEST_F(SyncableFileOperationRunnerTest, QueueAndCancel) { sync_status()->StartSyncing(URL(kFile)); ASSERT_FALSE(sync_status()->IsWritable(URL(kFile))); ResetCallbackStatus(); file_system_.operation_runner()->CreateFile( URL(kFile), false /* exclusive */, ExpectStatus(FROM_HERE, File::FILE_ERROR_ABORT)); file_system_.operation_runner()->Truncate( URL(kFile), 1, ExpectStatus(FROM_HERE, File::FILE_ERROR_ABORT)); content::RunAllTasksUntilIdle(); EXPECT_EQ(0, callback_count_); ResetCallbackStatus(); // This shouldn't crash nor leak memory. sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; content::RunAllTasksUntilIdle(); EXPECT_EQ(2, callback_count_); } // Test if CopyInForeignFile runs cooperatively with other Sync operations. TEST_F(SyncableFileOperationRunnerTest, CopyInForeignFile) { const std::string kTestData("test data"); base::FilePath temp_path; ASSERT_TRUE(CreateTempFile(&temp_path)); ASSERT_EQ(static_cast<int>(kTestData.size()), base::WriteFile( temp_path, kTestData.data(), kTestData.size())); sync_status()->StartSyncing(URL(kFile)); ASSERT_FALSE(sync_status()->IsWritable(URL(kFile))); // The URL is in syncing so CopyIn (which is a write operation) won't run. ResetCallbackStatus(); file_system_.operation_runner()->CopyInForeignFile( temp_path, URL(kFile), ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(0, callback_count_); // End syncing (to enable write). sync_status()->EndSyncing(URL(kFile)); ASSERT_TRUE(sync_status()->IsWritable(URL(kFile))); ResetCallbackStatus(); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // Now the file must have been created and have the same content as temp_path. // TODO(mek): AdaptCallbackForRepeating is needed here because // CannedSyncableFileSystem hasn't switched to OnceCallback yet. ResetCallbackStatus(); file_system_.DoVerifyFile( URL(kFile), kTestData, base::AdaptCallbackForRepeating(ExpectStatus(FROM_HERE, File::FILE_OK))); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); } TEST_F(SyncableFileOperationRunnerTest, Cancel) { // Prepare a file. file_system_.operation_runner()->CreateFile( URL(kFile), false /* exclusive */, ExpectStatus(FROM_HERE, File::FILE_OK)); content::RunAllTasksUntilIdle(); EXPECT_EQ(1, callback_count_); // Run Truncate and immediately cancel. This shouldn't crash. ResetCallbackStatus(); storage::FileSystemOperationRunner::OperationID id = file_system_.operation_runner()->Truncate( URL(kFile), 10, ExpectStatus(FROM_HERE, File::FILE_OK)); file_system_.operation_runner()->Cancel( id, ExpectStatus(FROM_HERE, File::FILE_ERROR_INVALID_OPERATION)); content::RunAllTasksUntilIdle(); EXPECT_EQ(2, callback_count_); } } // namespace sync_file_system
{ "content_hash": "accf6bc947b9a6758f08c4d2af61f6c4", "timestamp": "", "source": "github", "line_count": 417, "max_line_length": 81, "avg_line_length": 35.139088729016784, "alnum_prop": 0.6963761687026547, "repo_name": "endlessm/chromium-browser", "id": "04f649de45b98c2f3ae22cd3044adcc49fd32167", "size": "14653", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/browser/sync_file_system/local/syncable_file_operation_runner_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants_test.projects.base_project_integration_test import ProjectIntegrationTest class ExamplesIntegrationTest(ProjectIntegrationTest): def tests_examples(self): # TODO: Remove the --exclude-target-regexp once we're on Java 8 everywhere. pants_run = self.pants_test(['examples::', '--exclude-target-regexp=examples/src/java/org/pantsbuild/example/plugin']) self.assert_success(pants_run)
{ "content_hash": "63ca9fc03d58d6d72519057bdc4901ff", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 108, "avg_line_length": 49.5, "alnum_prop": 0.702020202020202, "repo_name": "gmalmquist/pants", "id": "db8913867f06de7c24d7e914c6f29f3be03faca8", "size": "741", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/python/pants_test/projects/test_examples_integration.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "781" }, { "name": "CSS", "bytes": "9444" }, { "name": "Cucumber", "bytes": "919" }, { "name": "GAP", "bytes": "2459" }, { "name": "Go", "bytes": "1746" }, { "name": "HTML", "bytes": "79866" }, { "name": "Java", "bytes": "437330" }, { "name": "JavaScript", "bytes": "29992" }, { "name": "Protocol Buffer", "bytes": "3783" }, { "name": "Python", "bytes": "5053630" }, { "name": "Scala", "bytes": "84585" }, { "name": "Shell", "bytes": "58748" }, { "name": "Thrift", "bytes": "1966" } ], "symlink_target": "" }
require 'rubygems' require 'rubygems/user_interaction' require 'fileutils' ## # Gem::YARDoc provides methods to generate YARDoc and yri data for installed gems # upon gem installation. # # This file is automatically required by RubyGems 1.9 and newer. module YARD class RubygemsHook include Gem::UserInteraction extend Gem::UserInteraction @yard_version = nil ## # Force installation of documentation? attr_accessor :force ## # Generate yard? attr_accessor :generate_yard ## # Generate yri data? attr_accessor :generate_yri class << self ## # Loaded version of YARD. Set by ::load_yard attr_reader :yard_version end ## # Post installs hook that generates documentation for each specification in # +specs+ def self.generation_hook(installer, specs) start = Time.now types = installer.document generate_yard = types.include?('yardoc') || types.include?('yard') generate_yri = types.include? 'yri' specs.each do |spec| gen_yard = generate_yard gen_yri = generate_yri gen_yri = false if gen_yard # never generate both, no need unless types.empty? # --no-document is not in effect # look at spec.metadata['yard.run'] for override run_yard = spec.metadata['yard.run'] gen_yard = true if run_yard && run_yard != 'yri' gen_yri = true if run_yard == 'yri' end new(spec, gen_yard, gen_yri).generate end return unless generate_yard || generate_yri duration = (Time.now - start).to_i names = specs.map(&:name).join ', ' say "Done installing documentation for #{names} after #{duration} seconds" end ## # Pre uninstalls hook that removes documentation # def self.removal_hook(uninstaller) new(uninstaller.spec).remove end ## # Loads the YARD generator def self.load_yard return if @yard_version require 'yard' @yard_version = Gem::Version.new ::YARD::VERSION end def initialize(spec, generate_yard = false, generate_yri = true) @doc_dir = spec.doc_dir @force = false @spec = spec @generate_yard = generate_yard @generate_yri = generate_yri @yard_dir = spec.doc_dir('yard') @yri_dir = spec.doc_dir('.yardoc') end def run_yardoc(*args) args << '--quiet' unless Gem.configuration.really_verbose args << '--backtrace' if Gem.configuration.backtrace unless File.file?(File.join(@spec.full_gem_path, '.yardopts')) args << @spec.require_paths unless @spec.extra_rdoc_files.empty? args << '-' args += @spec.extra_rdoc_files end end args = args.flatten.map(&:to_s) Dir.chdir(@spec.full_gem_path) do YARD::CLI::Yardoc.run(*args) end rescue Errno::EACCES => e dirname = File.dirname e.message.split("-")[1].strip raise Gem::FilePermissionError, dirname rescue => ex alert_error "While generating documentation for #{@spec.full_name}" ui.errs.puts "... MESSAGE: #{ex}" ui.errs.puts "... YARDOC args: #{args.join(' ')}" ui.errs.puts "\t#{ex.backtrace.join("\n\t")}" if Gem.configuration.backtrace ui.errs.puts "(continuing with the rest of the installation)" end def install_yard FileUtils.rm_rf @yard_dir say "Installing YARD documentation for #{@spec.full_name}..." run_yardoc '--no-progress', '--db', @yri_dir, '-o', @yard_dir end def install_yri FileUtils.rm_rf @yri_dir say "Building YARD (yri) index for #{@spec.full_name}..." run_yardoc '--no-progress', '-c', '-n', '--db', @yri_dir end ## # Generates YARD and yri data def generate return if @spec.default_gem? return unless @generate_yri || @generate_yard setup install_yri if @generate_yri && (@force || !File.exist?(@yri_dir)) install_yard if @generate_yard && (@force || !File.exist?(@yard_dir)) end ## # Prepares the spec for documentation generation def setup self.class.load_yard if File.exist?(@doc_dir) raise Gem::FilePermissionError, @doc_dir unless File.writable?(@doc_dir) else FileUtils.mkdir_p @doc_dir end end def uninstall_yard if File.exist?(@yard_dir) raise Gem::FilePermissionError, @yard_dir unless File.writable?(@yard_dir) FileUtils.rm_rf @yard_dir end end def uninstall_yri if File.exist?(@yri_dir) raise Gem::FilePermissionError, @yri_dir unless File.writable?(@yri_dir) FileUtils.rm_rf @yri_dir end end ## # Removes YARD and yri data def remove uninstall_yri uninstall_yard end end end Gem.done_installing(&YARD::RubygemsHook.method(:generation_hook)) Gem.pre_uninstall(&YARD::RubygemsHook.method(:removal_hook))
{ "content_hash": "9ed095b8fc6b0dac44582c28ee2f82f8", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 82, "avg_line_length": 25.413265306122447, "alnum_prop": 0.613531419393696, "repo_name": "thomthom/yard", "id": "4f1e0162f2220294846a994456c68871baa5bb03", "size": "5011", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "lib/yard/rubygems/hook.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34869" }, { "name": "HTML", "bytes": "80916" }, { "name": "JavaScript", "bytes": "16458" }, { "name": "Ruby", "bytes": "1444214" } ], "symlink_target": "" }
#ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <sstream> #include <inttypes.h> #include <map> #include <vector> #include "astutil.h" #include "build.h" #include "caches.h" #include "callInfo.h" #include "expr.h" #include "iterator.h" #include "passes.h" #include "resolution.h" #include "scopeResolve.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "../ifa/prim_data.h" // Allow disambiguation tracing to be controlled by the command-line option // --explain-verbose. #define ENABLE_TRACING_OF_DISAMBIGUATION 1 #ifdef ENABLE_TRACING_OF_DISAMBIGUATION #define TRACE_DISAMBIGUATE_BY_MATCH(...) \ if (developer && DC.explain) fprintf(stderr, __VA_ARGS__) #else #define TRACE_DISAMBIGUATE_BY_MATCH(...) #endif /** Contextual info used by the disambiguation process. * * This class wraps information that is used by multiple functions during the * function disambiguation process. */ class DisambiguationContext { public: /// The actual arguments from the call site. Vec<Symbol*>* actuals; /// The scope in which the call is made. Expr* scope; /// Whether or not to print out tracing information. bool explain; /// Indexes used when printing out tracing information. int i, j; /** A simple constructor that initializes all of the values except i and j. * * \param actuals The actual arguments from the call site. * \param scope A block representing the scope the call was made in. * \param explain Whether or not a trace of this disambiguation process should * be printed for the developer. */ DisambiguationContext(Vec<Symbol*>* actuals, Expr* scope, bool explain) : actuals(actuals), scope(scope), explain(explain), i(-1), j(-1) {} /** A helper function used to set the i and j members. * * \param i The index of the left-hand side of the comparison. * \param j The index of the right-hand side of the comparison. * * \return A constant reference to this disambiguation context. */ const DisambiguationContext& forPair(int newI, int newJ) { this->i = newI; this->j = newJ; return *this; } }; /** A wrapper for candidates for function call resolution. * * If a best candidate was found than the function member will point to it. */ class ResolutionCandidate { public: /// A pointer to the best candidate function. FnSymbol* fn; /** The actual arguments for the candidate, aligned so that they have the same * index as their corresponding formal argument in alignedFormals. */ Vec<Symbol*> alignedActuals; /** The formal arguments for the candidate, aligned so that they have the same * index as their corresponding actual argument in alignedActuals. */ Vec<ArgSymbol*> alignedFormals; /// A symbol map for substitutions that were made during the copying process. SymbolMap substitutions; /** The main constructor. * * \param fn A function that is a candidate for the resolution process. */ ResolutionCandidate(FnSymbol* function) : fn(function) {} /** Compute the alignment of actual and formal arguments for the wrapped * function and the current call site. * * \param info The CallInfo object corresponding to the call site. * * \return If a valid alignment was found. */ bool computeAlignment(CallInfo& info); /// Compute substitutions for wrapped function that is generic. void computeSubstitutions(); }; /// State information used during the disambiguation process. class DisambiguationState { public: /// Is fn1 more specific than fn2? bool fn1MoreSpecific; /// Is fn2 more specific than fn1? bool fn2MoreSpecific; /// Does fn1 require promotion? bool fn1Promotes; /// Does fn2 require promotion? bool fn2Promotes; /// 1 == fn1, 2 == fn2, -1 == conflicting signals int paramPrefers; /// Initialize the state to the starting values. DisambiguationState() : fn1MoreSpecific(false), fn2MoreSpecific(false), fn1Promotes(false), fn2Promotes(false), paramPrefers(0) {} /** Prints out information for tracing of the disambiguation process. * * \param DBMLoc A string representing the location in the DBM process the * message is coming from. * \param DC The disambiguation context. */ void printSummary(const char* DBMLoc, const DisambiguationContext& DC) { if (this->fn1MoreSpecific) { TRACE_DISAMBIGUATE_BY_MATCH("\n%s: Fn %d is more specific than Fn %d\n", DBMLoc, DC.i, DC.j); } else { TRACE_DISAMBIGUATE_BY_MATCH("\n%s: Fn %d is NOT more specific than Fn %d\n", DBMLoc, DC.i, DC.j); } if (this->fn2MoreSpecific) { TRACE_DISAMBIGUATE_BY_MATCH("%s: Fn %d is more specific than Fn %d\n", DBMLoc, DC.j, DC.i); } else { TRACE_DISAMBIGUATE_BY_MATCH("%s: Fn %d is NOT more specific than Fn %d\n", DBMLoc, DC.j, DC.i); } } }; //# //# Global Variables //# bool resolved = false; bool inDynamicDispatchResolution = false; SymbolMap paramMap; //# //# Static Variables //# static int explainCallLine; static ModuleSymbol* explainCallModule; static Vec<CallExpr*> inits; static Vec<FnSymbol*> resolvedFormals; Vec<CallExpr*> callStack; static Vec<CondStmt*> tryStack; static bool tryFailure = false; static Map<Type*,Type*> runtimeTypeMap; // map static types to runtime types // e.g. array and domain runtime types static Map<Type*,FnSymbol*> valueToRuntimeTypeMap; // convertValueToRuntimeType static Map<Type*,FnSymbol*> runtimeTypeToValueMap; // convertRuntimeTypeToValue static std::map<std::string, std::pair<AggregateType*, FnSymbol*> > functionTypeMap; // lookup table/cache for function types and their representative parents static std::map<FnSymbol*, FnSymbol*> functionCaptureMap; //loopup table/cache for function captures // map of compiler warnings that may need to be reissued for repeated // calls; the inner compiler warning map is from the compilerWarning // function; the outer compiler warning map is from the function // containing the compilerWarning function // to do: this needs to be a map from functions to multiple strings in // order to support multiple compiler warnings are allowed to // be in a single function static Map<FnSymbol*,const char*> innerCompilerWarningMap; static Map<FnSymbol*,const char*> outerCompilerWarningMap; Map<Type*,FnSymbol*> autoCopyMap; // type to chpl__autoCopy function Map<Type*,FnSymbol*> autoDestroyMap; // type to chpl__autoDestroy function Map<FnSymbol*,FnSymbol*> iteratorLeaderMap; // iterator->leader map for promotion Map<FnSymbol*,FnSymbol*> iteratorFollowerMap; // iterator->leader map for promotion //# //# Static Function Declarations //# static bool hasRefField(Type *type); static bool typeHasRefField(Type *type); static FnSymbol* resolveUninsertedCall(Type* type, CallExpr* call); static void makeRefType(Type* type); static void resolveAutoCopy(Type* type); static void resolveAutoDestroy(Type* type); static void resolveOther(); static FnSymbol* protoIteratorMethod(IteratorInfo* ii, const char* name, Type* retType); static void protoIteratorClass(FnSymbol* fn); static bool isInstantiatedField(Symbol* field); static Symbol* determineQueriedField(CallExpr* call); static void resolveSpecifiedReturnType(FnSymbol* fn); static bool fits_in_int(int width, Immediate* imm); static bool fits_in_uint(int width, Immediate* imm); static bool canInstantiate(Type* actualType, Type* formalType); static bool canParamCoerce(Type* actualType, Symbol* actualSym, Type* formalType); static bool moreSpecific(FnSymbol* fn, Type* actualType, Type* formalType); static bool computeActualFormalAlignment(FnSymbol* fn, Vec<Symbol*>& alignedActuals, Vec<ArgSymbol*>& alignedFormals, CallInfo& info); static Type* getInstantiationType(Type* actualType, Type* formalType); static void computeGenericSubs(SymbolMap &subs, FnSymbol* fn, Vec<Symbol*>& alignedActuals); static FnSymbol* expandVarArgs(FnSymbol* origFn, int numActuals); static void filterCandidate(Vec<ResolutionCandidate*>& candidates, ResolutionCandidate* currCandidate, CallInfo& info); static void filterCandidate(Vec<ResolutionCandidate*>& candidates, FnSymbol* fn, CallInfo& info); static BlockStmt* getParentBlock(Expr* expr); static bool isMoreVisibleInternal(BlockStmt* block, FnSymbol* fn1, FnSymbol* fn2, Vec<BlockStmt*>& visited); static bool isMoreVisible(Expr* expr, FnSymbol* fn1, FnSymbol* fn2); static bool explainCallMatch(CallExpr* call); static CallExpr* userCall(CallExpr* call); static void printResolutionErrorAmbiguous( Vec<FnSymbol*>& candidateFns, CallInfo* info); static void printResolutionErrorUnresolved( Vec<FnSymbol*>& visibleFns, CallInfo* info); static void issueCompilerError(CallExpr* call); static void reissueCompilerWarning(const char* str, int offset); BlockStmt* getVisibilityBlock(Expr* expr); static void buildVisibleFunctionMap(); static BlockStmt* getVisibleFunctions(BlockStmt* block, const char* name, Vec<FnSymbol*>& visibleFns, Vec<BlockStmt*>& visited); static Expr* resolve_type_expr(Expr* expr); static void makeNoop(CallExpr* call); static void resolveDefaultGenericType(CallExpr* call); static void gatherCandidates(Vec<ResolutionCandidate*>& candidates, Vec<FnSymbol*>& visibleFns, CallInfo& info); static void resolveCall(CallExpr* call); static void resolveNormalCall(CallExpr* call); static void lvalueCheck(CallExpr* call); static void resolveTupleAndExpand(CallExpr* call); static void resolveTupleExpand(CallExpr* call); static void resolveSetMember(CallExpr* call); static void resolveMove(CallExpr* call); static void resolveNew(CallExpr* call); static bool formalRequiresTemp(ArgSymbol* formal); static void insertFormalTemps(FnSymbol* fn); static void addLocalCopiesAndWritebacks(FnSymbol* fn, SymbolMap& formals2vars); static Type* param_for_index_type(CallExpr* loop); static void fold_param_for(CallExpr* loop); static Expr* dropUnnecessaryCast(CallExpr* call); static AggregateType* createAndInsertFunParentClass(CallExpr *call, const char *name); static FnSymbol* createAndInsertFunParentMethod(CallExpr *call, AggregateType *parent, AList &arg_list, bool isFormal, Type *retType); static std::string buildParentName(AList &arg_list, bool isFormal, Type *retType); static AggregateType* createOrFindFunTypeFromAnnotation(AList &arg_list, CallExpr *call); static Expr* createFunctionAsValue(CallExpr *call); static bool isOuterVar(Symbol* sym, FnSymbol* fn, Symbol* parent = NULL); static bool usesOuterVars(FnSymbol* fn, Vec<FnSymbol*> &seen); static Expr* preFold(Expr* expr); static void foldEnumOp(int op, EnumSymbol *e1, EnumSymbol *e2, Immediate *imm); static bool isSubType(Type* sub, Type* super); static void insertValueTemp(Expr* insertPoint, Expr* actual); FnSymbol* requiresImplicitDestroy(CallExpr* call); static Expr* postFold(Expr* expr); static void computeReturnTypeParamVectors(BaseAST* ast, Symbol* retSymbol, Vec<Type*>& retTypes, Vec<Symbol*>& retParams); static void replaceSetterArgWithTrue(BaseAST* ast, FnSymbol* fn); static void replaceSetterArgWithFalse(BaseAST* ast, FnSymbol* fn, Symbol* ret); static void insertCasts(BaseAST* ast, FnSymbol* fn, Vec<CallExpr*>& casts); static void buildValueFunction(FnSymbol* fn); static void resolveFns(FnSymbol* fn); static bool possible_signature_match(FnSymbol* fn, FnSymbol* gn); static bool signature_match(FnSymbol* fn, FnSymbol* gn); static void collectInstantiatedAggregateTypes(Vec<Type*>& icts, Type* ct); static bool isVirtualChild(FnSymbol* child, FnSymbol* parent); static void addToVirtualMaps(FnSymbol* pfn, AggregateType* ct); static void addAllToVirtualMaps(FnSymbol* fn, AggregateType* ct); static void buildVirtualMaps(); static void addVirtualMethodTableEntry(Type* type, FnSymbol* fn, bool exclusive = false); static void computeStandardModuleSet(); static void unmarkDefaultedGenerics(); static void resolveUses(ModuleSymbol* mod); static void resolveExports(); static void resolveEnumTypes(); static void resolveDynamicDispatches(); static void insertRuntimeTypeTemps(); static void resolveAutoCopies(); static void resolveRecordInitializers(); static void insertDynamicDispatchCalls(); static Type* buildRuntimeTypeInfo(FnSymbol* fn); static void insertReturnTemps(); static void initializeClass(Expr* stmt, Symbol* sym); static void handleRuntimeTypes(); static void pruneResolvedTree(); static void removeUnusedFunctions(); static void removeUnusedTypes(); static void buildRuntimeTypeInitFns(); static void buildRuntimeTypeInitFn(FnSymbol* fn, Type* runtimeType); static void removeUnusedGlobals(); static void removeParamArgs(); static void removeRandomPrimitives(); static void removeActualNames(); static void removeTypeBlocks(); static void removeFormalTypeAndInitBlocks(); static void replaceTypeArgsWithFormalTypeTemps(); static void replaceValuesWithRuntimeTypes(); static void removeWhereClauses(); static void replaceReturnedValuesWithRuntimeTypes(); static void insertRuntimeInitTemps(); static void removeInitFields(); static void removeMootFields(); static void expandInitFieldPrims(); static void fixTypeNames(AggregateType* ct); static void setScalarPromotionType(AggregateType* ct); bool ResolutionCandidate::computeAlignment(CallInfo& info) { if (alignedActuals.n != 0) alignedActuals.clear(); if (alignedFormals.n != 0) alignedFormals.clear(); return computeActualFormalAlignment(fn, alignedActuals, alignedFormals, info); } void ResolutionCandidate::computeSubstitutions() { if (substitutions.n != 0) substitutions.clear(); computeGenericSubs(substitutions, fn, alignedActuals); } static bool hasRefField(Type *type) { if (isPrimitiveType(type)) return false; if (type->symbol->hasFlag(FLAG_OBJECT_CLASS)) return false; if (!isClass(type)) { // record or union if (AggregateType *ct = toAggregateType(type)) { for_fields(field, ct) { if (hasRefField(field->type)) return true; } } return false; } return true; } static bool typeHasRefField(Type *type) { if (AggregateType *ct = toAggregateType(type)) { for_fields(field, ct) { if (hasRefField(field->typeInfo())) return true; } } return false; } // // build reference type // static FnSymbol* resolveUninsertedCall(Type* type, CallExpr* call) { if (type->defaultInitializer) { if (type->defaultInitializer->instantiationPoint) type->defaultInitializer->instantiationPoint->insertAtHead(call); else type->symbol->defPoint->insertBefore(call); } else { chpl_gen_main->insertAtHead(call); } resolveCall(call); call->remove(); return call->isResolved(); } // Fills in the refType field of a type // with the type's corresponding reference type. static void makeRefType(Type* type) { if (!type) // Should this be an assert? return; if (type->refType) { // Already done. return; } if (type == dtMethodToken || type == dtUnknown || type->symbol->hasFlag(FLAG_REF) || type->symbol->hasFlag(FLAG_GENERIC)) { return; } CallExpr* call = new CallExpr("_type_construct__ref", type->symbol); FnSymbol* fn = resolveUninsertedCall(type, call); type->refType = toAggregateType(fn->retType); type->refType->getField(1)->type = type; if (type->symbol->hasFlag(FLAG_ATOMIC_TYPE)) type->refType->symbol->addFlag(FLAG_ATOMIC_TYPE); } static void resolveAutoCopy(Type* type) { SET_LINENO(type->symbol); Symbol* tmp = newTemp(type); chpl_gen_main->insertAtHead(new DefExpr(tmp)); CallExpr* call = new CallExpr("chpl__autoCopy", tmp); FnSymbol* fn = resolveUninsertedCall(type, call); resolveFns(fn); autoCopyMap.put(type, fn); tmp->defPoint->remove(); } static void resolveAutoDestroy(Type* type) { SET_LINENO(type->symbol); Symbol* tmp = newTemp(type); chpl_gen_main->insertAtHead(new DefExpr(tmp)); CallExpr* call = new CallExpr("chpl__autoDestroy", tmp); FnSymbol* fn = resolveUninsertedCall(type, call); resolveFns(fn); autoDestroyMap.put(type, fn); tmp->defPoint->remove(); } FnSymbol* getAutoCopy(Type *t) { return autoCopyMap.get(t); } FnSymbol* getAutoDestroy(Type* t) { return autoDestroyMap.get(t); } const char* toString(Type* type) { return type->getValType()->symbol->name; } const char* toString(CallInfo* info) { bool method = false; bool _this = false; const char *str = ""; if (info->actuals.n > 1) if (info->actuals.head()->type == dtMethodToken) method = true; if (!strcmp("this", info->name)) { _this = true; method = false; } if (method) { if (info->actuals.v[1] && info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE)) str = astr(str, "type ", toString(info->actuals.v[1]->type), "."); else str = astr(str, toString(info->actuals.v[1]->type), "."); } if (!developer && !strncmp("_type_construct_", info->name, 16)) { str = astr(str, info->name+16); } else if (!developer && !strncmp("_construct_", info->name, 11)) { str = astr(str, info->name+11); } else if (!_this) { str = astr(str, info->name); } if (!info->call->methodTag) { if (info->call->square) str = astr(str, "["); else str = astr(str, "("); } bool first = false; int start = 0; if (method) start = 2; if (_this) start = 2; for (int i = start; i < info->actuals.n; i++) { if (!first) first = true; else str = astr(str, ", "); if (info->actualNames.v[i]) str = astr(str, info->actualNames.v[i], "="); VarSymbol* var = toVarSymbol(info->actuals.v[i]); if (info->actuals.v[i]->type->symbol->hasFlag(FLAG_ITERATOR_RECORD) && info->actuals.v[i]->type->defaultInitializer->hasFlag(FLAG_PROMOTION_WRAPPER)) str = astr(str, "promoted expression"); else if (info->actuals.v[i] && info->actuals.v[i]->hasFlag(FLAG_TYPE_VARIABLE)) str = astr(str, "type ", toString(info->actuals.v[i]->type)); else if (var && var->immediate) { if (var->immediate->const_kind == CONST_KIND_STRING) { str = astr(str, "\"", var->immediate->v_string, "\""); } else { const size_t bufSize = 512; char buff[bufSize]; snprint_imm(buff, bufSize, *var->immediate); str = astr(str, buff); } } else str = astr(str, toString(info->actuals.v[i]->type)); } if (!info->call->methodTag) { if (info->call->square) str = astr(str, "]"); else str = astr(str, ")"); } return str; } const char* toString(FnSymbol* fn) { if (fn->userString) { if (developer) return astr(fn->userString, " [", istr(fn->id), "]"); else return fn->userString; } const char* str; int start = 0; if (developer) { // report the name as-is and include all args str = fn->name; } else { if (fn->instantiatedFrom) fn = fn->instantiatedFrom; if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) { // if not, make sure 'str' is built as desired INT_ASSERT(!strncmp("_type_construct_", fn->name, 16)); str = astr(fn->name+16); } else if (fn->hasFlag(FLAG_CONSTRUCTOR)) { INT_ASSERT(!strncmp("_construct_", fn->name, 11)); str = astr(fn->name+11); } else if (fn->hasFlag(FLAG_METHOD)) { if (!strcmp(fn->name, "this")) { INT_ASSERT(fn->hasFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION)); str = astr(toString(fn->getFormal(2)->type)); start = 1; } else { INT_ASSERT(! fn->hasFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION)); str = astr(toString(fn->getFormal(2)->type), ".", fn->name); start = 2; } } else if (fn->hasFlag(FLAG_MODULE_INIT)) { INT_ASSERT(!strncmp("chpl__init_", fn->name, 11)); //if not, fix next line str = astr("top-level module statements for ", fn->name+11); } else str = astr(fn->name); } // if !developer bool skipParens = fn->hasFlag(FLAG_NO_PARENS) || (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR) && fn->numFormals() == 0) || (fn->hasFlag(FLAG_MODULE_INIT) && !developer); if (!skipParens) str = astr(str, "("); bool first = false; for (int i = start; i < fn->numFormals(); i++) { ArgSymbol* arg = fn->getFormal(i+1); if (arg->hasFlag(FLAG_IS_MEME)) continue; if (!first) { first = true; if (skipParens) str = astr(str, " "); } else str = astr(str, ", "); if (arg->intent == INTENT_PARAM || arg->hasFlag(FLAG_INSTANTIATED_PARAM)) str = astr(str, "param "); if (arg->hasFlag(FLAG_TYPE_VARIABLE)) str = astr(str, "type ", arg->name); else if (arg->type == dtUnknown) { SymExpr* sym = NULL; if (arg->typeExpr) sym = toSymExpr(arg->typeExpr->body.tail); if (sym) str = astr(str, arg->name, ": ", sym->var->name); else str = astr(str, arg->name); } else if (arg->type == dtAny) { str = astr(str, arg->name); } else str = astr(str, arg->name, ": ", toString(arg->type)); if (arg->variableExpr) str = astr(str, " ..."); } if (!skipParens) str = astr(str, ")"); if (developer) str = astr(str, " [", istr(fn->id), "]"); return str; } static FnSymbol* protoIteratorMethod(IteratorInfo* ii, const char* name, Type* retType) { FnSymbol* fn = new FnSymbol(name); fn->addFlag(FLAG_AUTO_II); if (strcmp(name, "advance")) fn->addFlag(FLAG_INLINE); fn->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken)); fn->_this = new ArgSymbol(INTENT_BLANK, "this", ii->iclass); fn->_this->addFlag(FLAG_ARG_THIS); fn->retType = retType; fn->insertFormalAtTail(fn->_this); ii->iterator->defPoint->insertBefore(new DefExpr(fn)); normalize(fn); return fn; } static void protoIteratorClass(FnSymbol* fn) { INT_ASSERT(!fn->iteratorInfo); SET_LINENO(fn); IteratorInfo* ii = new IteratorInfo(); fn->iteratorInfo = ii; fn->iteratorInfo->iterator = fn; const char* className = astr(fn->name); if (fn->_this) className = astr(className, "_", fn->_this->type->symbol->cname); ii->iclass = new AggregateType(AGGREGATE_CLASS); TypeSymbol* cts = new TypeSymbol(astr("_ic_", className), ii->iclass); cts->addFlag(FLAG_ITERATOR_CLASS); add_root_type(ii->iclass); // Add super : dtObject. fn->defPoint->insertBefore(new DefExpr(cts)); ii->irecord = new AggregateType(AGGREGATE_RECORD); TypeSymbol* rts = new TypeSymbol(astr("_ir_", className), ii->irecord); rts->addFlag(FLAG_ITERATOR_RECORD); if (fn->retTag == RET_VAR) rts->addFlag(FLAG_REF_ITERATOR_CLASS); fn->defPoint->insertBefore(new DefExpr(rts)); ii->tag = it_iterator; ii->advance = protoIteratorMethod(ii, "advance", dtVoid); ii->zip1 = protoIteratorMethod(ii, "zip1", dtVoid); ii->zip2 = protoIteratorMethod(ii, "zip2", dtVoid); ii->zip3 = protoIteratorMethod(ii, "zip3", dtVoid); ii->zip4 = protoIteratorMethod(ii, "zip4", dtVoid); ii->hasMore = protoIteratorMethod(ii, "hasMore", dtInt[INT_SIZE_DEFAULT]); ii->getValue = protoIteratorMethod(ii, "getValue", fn->retType); ii->irecord->defaultInitializer = fn; ii->irecord->scalarPromotionType = fn->retType; fn->retType = ii->irecord; fn->retTag = RET_VALUE; makeRefType(fn->retType); fn->iteratorInfo->zip1->addFlag(FLAG_RESOLVED); fn->iteratorInfo->zip2->addFlag(FLAG_RESOLVED); fn->iteratorInfo->zip3->addFlag(FLAG_RESOLVED); fn->iteratorInfo->zip4->addFlag(FLAG_RESOLVED); fn->iteratorInfo->advance->addFlag(FLAG_RESOLVED); fn->iteratorInfo->hasMore->addFlag(FLAG_RESOLVED); fn->iteratorInfo->getValue->addFlag(FLAG_RESOLVED); ii->getIterator = new FnSymbol("_getIterator"); ii->getIterator->addFlag(FLAG_AUTO_II); ii->getIterator->addFlag(FLAG_INLINE); ii->getIterator->retType = ii->iclass; ii->getIterator->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "ir", ii->irecord)); VarSymbol* ret = newTemp("_ic_", ii->iclass); ii->getIterator->insertAtTail(new DefExpr(ret)); CallExpr* icAllocCall = callChplHereAlloc(ret->typeInfo()->symbol); ii->getIterator->insertAtTail(new CallExpr(PRIM_MOVE, ret, icAllocCall)); ii->getIterator->insertAtTail(new CallExpr(PRIM_SETCID, ret)); ii->getIterator->insertAtTail(new CallExpr(PRIM_RETURN, ret)); fn->defPoint->insertBefore(new DefExpr(ii->getIterator)); ii->iclass->defaultInitializer = ii->getIterator; normalize(ii->getIterator); resolveFns(ii->getIterator); // No shortcuts. } // // returns true if the field was instantiated // static bool isInstantiatedField(Symbol* field) { TypeSymbol* ts = toTypeSymbol(field->defPoint->parentSymbol); INT_ASSERT(ts); AggregateType* ct = toAggregateType(ts->type); INT_ASSERT(ct); for_formals(formal, ct->defaultTypeConstructor) { if (!strcmp(field->name, formal->name)) if (formal->hasFlag(FLAG_TYPE_VARIABLE)) return true; } return false; } // // determine field associated with query expression // static Symbol* determineQueriedField(CallExpr* call) { AggregateType* ct = toAggregateType(call->get(1)->getValType()); INT_ASSERT(ct); SymExpr* last = toSymExpr(call->get(call->numActuals())); INT_ASSERT(last); VarSymbol* var = toVarSymbol(last->var); INT_ASSERT(var && var->immediate); if (var->immediate->const_kind == CONST_KIND_STRING) { // field queried by name return ct->getField(var->immediate->v_string, false); } else { // field queried by position int position = var->immediate->int_value(); Vec<ArgSymbol*> args; for_formals(arg, ct->defaultTypeConstructor) { args.add(arg); } for (int i = 2; i < call->numActuals(); i++) { SymExpr* actual = toSymExpr(call->get(i)); INT_ASSERT(actual); VarSymbol* var = toVarSymbol(actual->var); INT_ASSERT(var && var->immediate && var->immediate->const_kind == CONST_KIND_STRING); for (int j = 0; j < args.n; j++) { if (args.v[j] && !strcmp(args.v[j]->name, var->immediate->v_string)) args.v[j] = NULL; } } forv_Vec(ArgSymbol, arg, args) { if (arg) { if (position == 1) return ct->getField(arg->name, false); position--; } } } return NULL; } // // For some types, e.g. _domain/_array records, implementing // Chapel's ref/out/... intents can be done simply by passing the // value itself, rather than address-of. This function flags such cases // by returning false, meaning "not OK to convert". // static bool okToConvertFormalToRefType(Type* type) { if (isRecordWrappedType(type)) // no, don't return false; // otherwise, proceed with the original plan return true; } static void resolveSpecifiedReturnType(FnSymbol* fn) { resolveBlock(fn->retExprType); fn->retType = fn->retExprType->body.tail->typeInfo(); if (fn->retType != dtUnknown) { if (fn->retTag == RET_VAR) { makeRefType(fn->retType); fn->retType = fn->retType->refType; } fn->retExprType->remove(); if (fn->hasFlag(FLAG_ITERATOR_FN) && !fn->iteratorInfo) { protoIteratorClass(fn); } } } // // Generally, atomics must also be passed by reference when // passed by blank intent. The following expression checks for // these cases by looking for atomics passed by blank intent and // changing their type to a ref type. Interestingly, this // conversion does not seem to be required for single-locale // compilation, but it is for multi-locale. Otherwise, updates // to atomics are lost (as demonstrated by // test/functions/bradc/intents/test_pass_atomic.chpl). // // I say "generally" because there are a few cases where passing // atomics by reference breaks things -- primarily in // constructors, assignment operators, and tuple construction. // So we have some unfortunate special checks that dance around // these cases. // // While I can't explain precisely why these special cases are // required yet, here are the tests that tend to have problems // without these special conditions: // // test/release/examples/benchmarks/hpcc/ra-atomics.chpl // test/types/atomic/sungeun/no_atomic_assign.chpl // test/functions/bradc/intents/test_construct_atomic_intent.chpl // test/users/vass/barrierWF.test-1.chpl // test/studies/shootout/spectral-norm/spectralnorm.chpl // test/release/examples/benchmarks/ssca2/SSCA2_main.chpl // test/parallel/taskPar/sungeun/barrier/*.chpl // static bool convertAtomicFormalTypeToRef(ArgSymbol* formal, FnSymbol* fn) { return (formal->intent == INTENT_BLANK && !formal->hasFlag(FLAG_TYPE_VARIABLE) && isAtomicType(formal->type)) && !fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR) && !fn->hasFlag(FLAG_CONSTRUCTOR) && strcmp(fn->name,"=") != 0 && !fn->hasFlag(FLAG_BUILD_TUPLE); } void resolveFormals(FnSymbol* fn) { static Vec<FnSymbol*> done; if (!fn->hasFlag(FLAG_GENERIC)) { if (done.set_in(fn)) return; done.set_add(fn); for_formals(formal, fn) { if (formal->type == dtUnknown) { if (!formal->typeExpr) { formal->type = dtObject; } else { resolveBlock(formal->typeExpr); formal->type = formal->typeExpr->body.tail->getValType(); } } // // Fix up value types that need to be ref types. // if (formal->type->symbol->hasFlag(FLAG_REF)) // Already a ref type, so done. continue; if (formal->intent == INTENT_INOUT || formal->intent == INTENT_OUT || formal->intent == INTENT_REF || formal->intent == INTENT_CONST_REF || convertAtomicFormalTypeToRef(formal, fn) || formal->hasFlag(FLAG_WRAP_WRITTEN_FORMAL) || (formal == fn->_this && (isUnion(formal->type) || isRecord(formal->type)))) { if (okToConvertFormalToRefType(formal->type)) { makeRefType(formal->type); formal->type = formal->type->refType; // The type of the formal is its own ref type! } } } if (fn->retExprType) resolveSpecifiedReturnType(fn); resolvedFormals.set_add(fn); } } static bool fits_in_int_helper(int width, int64_t val) { switch (width) { default: INT_FATAL("bad width in fits_in_int_helper"); case 1: return (val == 0 || val == 1); case 8: return (val >= INT8_MIN && val <= INT8_MAX); case 16: return (val >= INT16_MIN && val <= INT16_MAX); case 32: return (val >= INT32_MIN && val <= INT32_MAX); case 64: return (val >= INT64_MIN && val <= INT64_MAX); } } static bool fits_in_int(int width, Immediate* imm) { if (imm->const_kind == NUM_KIND_INT && imm->num_index == INT_SIZE_DEFAULT) { int64_t i = imm->int_value(); return fits_in_int_helper(width, i); } /* BLC: There is some question in my mind about whether this function should include the following code as well -- that is, whether default-sized uint params should get the same special treatment in cases like this. I didn't enable it for now because nothing seemed to rely on it and I didn't come up with a case that would. But it's worth keeping around for future consideration. Similarly, we may want to consider enabling such param casts for int sizes other then default-width. else if (imm->const_kind == NUM_KIND_UINT && imm->num_index == INT_SIZE_DEFAULT) { uint64_t u = imm->uint_value(); int64_t i = (int64_t)u; if (i < 0) return false; return fits_in_int_helper(width, i); }*/ return false; } static bool fits_in_uint_helper(int width, uint64_t val) { switch (width) { default: INT_FATAL("bad width in fits_in_uint_helper"); case 1: return (val <= 1); case 8: return (val <= UINT8_MAX); case 16: return (val <= UINT16_MAX); case 32: return (val <= UINT32_MAX); case 64: return (val <= UINT64_MAX); } } static bool fits_in_uint(int width, Immediate* imm) { if (imm->const_kind == NUM_KIND_INT && imm->num_index == INT_SIZE_DEFAULT) { int64_t i = imm->int_value(); if (i < 0) return false; return fits_in_uint_helper(width, (uint64_t)i); } /* BLC: See comment just above in fits_in_int()... else if (imm->const_kind == NUM_KIND_UINT && imm->num_index == INT_SIZE_64) { uint64_t u = imm->uint_value(); return fits_in_uint_helper(width, u); }*/ return false; } static void ensureEnumTypeResolved(EnumType* etype) { INT_ASSERT( etype != NULL ); if( ! etype->integerType ) { // Make sure to resolve all enum types. for_enums(def, etype) { if (def->init) { // Type* enumtype = Expr* enumTypeExpr = resolve_type_expr(def->init); Type* enumtype = enumTypeExpr->typeInfo(); if (enumtype == dtUnknown) INT_FATAL(def->init, "Unable to resolve enumerator type expression"); // printf("Type of %s.%s is %s\n", etype->symbol->name, def->sym->name, // enumtype->symbol->name); } } // Now try computing the enum size... etype->sizeAndNormalize(); } INT_ASSERT(etype->integerType != NULL); } // Is this a legal actual argument where an l-value is required? // I.e. for an out/inout/ref formal. static bool isLegalLvalueActualArg(ArgSymbol* formal, Expr* actual) { if (SymExpr* se = toSymExpr(actual)) if (se->var->hasFlag(FLAG_EXPR_TEMP) || se->var->hasFlag(FLAG_REF_TO_CONST) || (se->var->isConstant() && !formal->hasFlag(FLAG_ARG_THIS)) || se->var->isParameter()) if (okToConvertFormalToRefType(formal->type)) return false; // Perhaps more checks are needed. return true; } // Is this a legal actual argument for a 'const ref' formal? // At present, params cannot be passed to 'const ref'. static bool isLegalConstRefActualArg(ArgSymbol* formal, Expr* actual) { if (SymExpr* se = toSymExpr(actual)) if (se->var->isParameter()) if (okToConvertFormalToRefType(formal->type)) return false; // Perhaps more checks are needed. return true; } // Returns true iff dispatching the actualType to the formalType // results in an instantiation. static bool canInstantiate(Type* actualType, Type* formalType) { if (actualType == dtMethodToken) return false; if (formalType == dtAny) return true; if (formalType == dtIntegral && (is_int_type(actualType) || is_uint_type(actualType))) return true; if (formalType == dtAnyEnumerated && (is_enum_type(actualType))) return true; if (formalType == dtNumeric && (is_int_type(actualType) || is_uint_type(actualType) || is_imag_type(actualType) || is_real_type(actualType) || is_complex_type(actualType))) return true; if (formalType == dtString && actualType==dtStringC) return true; if (formalType == dtIteratorRecord && actualType->symbol->hasFlag(FLAG_ITERATOR_RECORD)) return true; if (formalType == dtIteratorClass && actualType->symbol->hasFlag(FLAG_ITERATOR_CLASS)) return true; if (actualType == formalType) return true; if (actualType->instantiatedFrom && canInstantiate(actualType->instantiatedFrom, formalType)) return true; return false; } // // returns true if dispatching from actualType to formalType results // in a compile-time coercion; this is a subset of canCoerce below as, // for example, real(32) cannot be coerced to real(64) at compile-time // static bool canParamCoerce(Type* actualType, Symbol* actualSym, Type* formalType) { if (is_bool_type(formalType) && is_bool_type(actualType)) return true; if (is_int_type(formalType)) { if (is_bool_type(actualType)) return true; if (is_int_type(actualType) && get_width(actualType) < get_width(formalType)) return true; if (is_uint_type(actualType) && get_width(actualType) < get_width(formalType)) return true; // // If the actual is an enum, check to see if *all* its values // are small enough that they fit into this integer width // if (EnumType* etype = toEnumType(actualType)) { ensureEnumTypeResolved(etype); if (get_width(etype->getIntegerType()) <= get_width(formalType)) return true; } // // For smaller integer types, if the argument is a param, does it // store a value that's small enough that it could dispatch to // this argument? // if (get_width(formalType) < 64) { if (VarSymbol* var = toVarSymbol(actualSym)) if (var->immediate) if (fits_in_int(get_width(formalType), var->immediate)) return true; if (EnumType* etype = toEnumType(actualType)) { ensureEnumTypeResolved(etype); if (EnumSymbol* enumsym = toEnumSymbol(actualSym)) { if (Immediate* enumval = enumsym->getImmediate()) { if (fits_in_int(get_width(formalType), enumval)) { return true; } } } } } } if (is_uint_type(formalType)) { if (is_bool_type(actualType)) return true; if (is_uint_type(actualType) && get_width(actualType) < get_width(formalType)) return true; if (VarSymbol* var = toVarSymbol(actualSym)) if (var->immediate) if (fits_in_uint(get_width(formalType), var->immediate)) return true; } return false; } // // returns true iff dispatching the actualType to the formalType // results in a coercion. // bool canCoerce(Type* actualType, Symbol* actualSym, Type* formalType, FnSymbol* fn, bool* promotes) { if (canParamCoerce(actualType, actualSym, formalType)) return true; if (is_real_type(formalType)) { if ((is_int_type(actualType) || is_uint_type(actualType)) && get_width(formalType) >= 64) return true; if (is_real_type(actualType) && get_width(actualType) < get_width(formalType)) return true; } if (is_complex_type(formalType)) { if ((is_int_type(actualType) || is_uint_type(actualType)) && get_width(formalType) >= 128) return true; if (is_real_type(actualType) && (get_width(actualType) <= get_width(formalType)/2)) return true; if (is_imag_type(actualType) && (get_width(actualType) <= get_width(formalType)/2)) return true; if (is_complex_type(actualType) && (get_width(actualType) < get_width(formalType))) return true; } if (isSyncType(actualType)) { Type* baseType = actualType->getField("base_type")->type; return canDispatch(baseType, NULL, formalType, fn, promotes); } if (actualType->symbol->hasFlag(FLAG_REF)) return canDispatch(actualType->getValType(), NULL, formalType, fn, promotes); if ((((toVarSymbol(actualSym) || toArgSymbol(actualSym))) && (actualType==dtStringC)) && (formalType == dtString)) return true; return false; } // Returns true iff the actualType can dispatch to the formalType. // The function symbol is used to avoid scalar promotion on =. // param is set if the actual is a parameter (compile-time constant). bool canDispatch(Type* actualType, Symbol* actualSym, Type* formalType, FnSymbol* fn, bool* promotes, bool paramCoerce) { if (promotes) *promotes = false; if (actualType == formalType) return true; // // The following check against FLAG_REF ensures that 'nil' can't be // passed to a by-ref argument (for example, an atomic type). I // found that without this, calls like autocopy(nil) became // ambiguous when given the choice between the completely generic // autocopy(x) and the autocopy(x: atomic int) (represented as // autocopy(x: ref(atomic int)) internally). // if (actualType == dtNil && isClass(formalType) && !formalType->symbol->hasFlag(FLAG_REF)) return true; if (actualType->refType == formalType) return true; if (!paramCoerce && canCoerce(actualType, actualSym, formalType, fn, promotes)) return true; if (paramCoerce && canParamCoerce(actualType, actualSym, formalType)) return true; forv_Vec(Type, parent, actualType->dispatchParents) { if (parent == formalType || canDispatch(parent, NULL, formalType, fn, promotes)) { return true; } } if (fn && strcmp(fn->name, "=") && actualType->scalarPromotionType && (canDispatch(actualType->scalarPromotionType, NULL, formalType, fn))) { if (promotes) *promotes = true; return true; } return false; } bool isDispatchParent(Type* t, Type* pt) { forv_Vec(Type, p, t->dispatchParents) if (p == pt || isDispatchParent(p, pt)) return true; return false; } static bool moreSpecific(FnSymbol* fn, Type* actualType, Type* formalType) { if (canDispatch(actualType, NULL, formalType, fn)) return true; if (canInstantiate(actualType, formalType)) { return true; } return false; } static bool computeActualFormalAlignment(FnSymbol* fn, Vec<Symbol*>& alignedActuals, Vec<ArgSymbol*>& alignedFormals, CallInfo& info) { alignedActuals.fill(fn->numFormals()); alignedFormals.fill(info.actuals.n); // Match named actuals against formal names in the function signature. // Record successful matches. for (int i = 0; i < alignedFormals.n; i++) { if (info.actualNames.v[i]) { bool match = false; int j = 0; for_formals(formal, fn) { if (!strcmp(info.actualNames.v[i], formal->name)) { match = true; alignedFormals.v[i] = formal; alignedActuals.v[j] = info.actuals.v[i]; break; } j++; } // Fail if no matching formal is found. if (!match) return false; } } // Fill in unmatched formals in sequence with the remaining actuals. // Record successful substitutions. int j = 0; ArgSymbol* formal = (fn->numFormals()) ? fn->getFormal(1) : NULL; for (int i = 0; i < alignedFormals.n; i++) { if (!info.actualNames.v[i]) { bool match = false; while (formal) { if (formal->variableExpr) return (fn->hasFlag(FLAG_GENERIC)) ? true : false; if (!alignedActuals.v[j]) { match = true; alignedFormals.v[i] = formal; alignedActuals.v[j] = info.actuals.v[i]; break; } formal = next_formal(formal); j++; } // Fail if there are too many unnamed actuals. if (!match && !(fn->hasFlag(FLAG_GENERIC) && fn->hasFlag(FLAG_TUPLE))) return false; } } // Make sure that any remaining formals are matched by name // or have a default value. while (formal) { if (!alignedActuals.v[j] && !formal->defaultExpr) // Fail if not. return false; formal = next_formal(formal); j++; } return true; } // // returns the type that a formal type should be instantiated to when // instantiated by a given actual type // static Type* getInstantiationType(Type* actualType, Type* formalType) { if (canInstantiate(actualType, formalType)) { return actualType; } if (Type* st = actualType->scalarPromotionType) { if (canInstantiate(st, formalType)) return st; } if (Type* vt = actualType->getValType()) { if (canInstantiate(vt, formalType)) return vt; else if (Type* st = vt->scalarPromotionType) if (canInstantiate(st, formalType)) return st; } return NULL; } static void computeGenericSubs(SymbolMap &subs, FnSymbol* fn, Vec<Symbol*>& alignedActuals) { int i = 0; for_formals(formal, fn) { if (formal->intent == INTENT_PARAM) { if (alignedActuals.v[i] && alignedActuals.v[i]->isParameter()) { if (!formal->type->symbol->hasFlag(FLAG_GENERIC) || canInstantiate(alignedActuals.v[i]->type, formal->type)) subs.put(formal, alignedActuals.v[i]); } else if (!alignedActuals.v[i] && formal->defaultExpr) { // break because default expression may reference generic // arguments earlier in formal list; make those substitutions // first (test/classes/bradc/paramInClass/weirdParamInit4) if (subs.n) break; resolveBlock(formal->defaultExpr); SymExpr* se = toSymExpr(formal->defaultExpr->body.tail); if (se && se->var->isParameter() && (!formal->type->symbol->hasFlag(FLAG_GENERIC) || canInstantiate(se->var->type, formal->type))) subs.put(formal, se->var); else INT_FATAL(fn, "unable to handle default parameter"); } } else if (formal->type->symbol->hasFlag(FLAG_GENERIC)) { // // check for field with specified generic type // if (!formal->hasFlag(FLAG_TYPE_VARIABLE) && formal->type != dtAny && strcmp(formal->name, "outer") && strcmp(formal->name, "meme") && (fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR) || fn->hasFlag(FLAG_TYPE_CONSTRUCTOR))) USR_FATAL(formal, "invalid generic type specification on class field"); if (alignedActuals.v[i]) { if (Type* type = getInstantiationType(alignedActuals.v[i]->type, formal->type)) { // String literal actuals aligned with non-param generic // formals of type dtAny will result in an instantiation of // a dtString formal. This is in line with variable // declarations with non-typed initializing expressions and // non-param formals with string literal default expressions // (see fix_def_expr() and hack_resolve_types() in // normalize.cpp). if ((formal->type == dtAny) && (!formal->hasFlag(FLAG_PARAM)) && (type == dtStringC) && (alignedActuals.v[i]->type == dtStringC) && (alignedActuals.v[i]->isImmediate())) subs.put(formal, dtString->symbol); else subs.put(formal, type->symbol); } } else if (formal->defaultExpr) { // break because default expression may reference generic // arguments earlier in formal list; make those substitutions // first (test/classes/bradc/genericTypes) if (subs.n) break; resolveBlock(formal->defaultExpr); Type* defaultType = formal->defaultExpr->body.tail->typeInfo(); if (defaultType == dtTypeDefaultToken) subs.put(formal, dtTypeDefaultToken->symbol); else if (Type* type = getInstantiationType(defaultType, formal->type)) subs.put(formal, type->symbol); } } i++; } } /** Common code for multiple paths through expandVarArgs. * * This code handles the case where the number of varargs are known at compile * time. It inserts the necessary code to copy the values into and out of the * varargs tuple. */ static void handleSymExprInExpandVarArgs(FnSymbol* workingFn, ArgSymbol* formal, SymExpr* sym) { workingFn->addFlag(FLAG_EXPANDED_VARARGS); // Handle specified number of variable arguments. if (VarSymbol* n_var = toVarSymbol(sym->var)) { if (n_var->type == dtInt[INT_SIZE_DEFAULT] && n_var->immediate) { int n = n_var->immediate->int_value(); CallExpr* tupleCall = new CallExpr((formal->hasFlag(FLAG_TYPE_VARIABLE)) ? "_type_construct__tuple" : "_construct__tuple"); for (int i = 0; i < n; i++) { DefExpr* new_arg_def = formal->defPoint->copy(); ArgSymbol* new_formal = toArgSymbol(new_arg_def->sym); new_formal->variableExpr = NULL; tupleCall->insertAtTail(new SymExpr(new_formal)); new_formal->name = astr("_e", istr(i), "_", formal->name); new_formal->cname = astr("_e", istr(i), "_", formal->cname); formal->defPoint->insertBefore(new_arg_def); } VarSymbol* var = new VarSymbol(formal->name); // Replace mappings to the old formal with mappings to the new variable. if (workingFn->hasFlag(FLAG_PARTIAL_COPY)) { for (int index = workingFn->partialCopyMap.n; --index >= 0;) { SymbolMapElem& mapElem = workingFn->partialCopyMap.v[index]; if (mapElem.value == formal) { mapElem.value = var; break; } } } if (formal->hasFlag(FLAG_TYPE_VARIABLE)) { var->addFlag(FLAG_TYPE_VARIABLE); } if (formal->intent == INTENT_OUT || formal->intent == INTENT_INOUT) { int i = 1; for_actuals(actual, tupleCall) { VarSymbol* tmp = newTemp("_varargs_tmp_"); workingFn->insertBeforeReturnAfterLabel(new DefExpr(tmp)); workingFn->insertBeforeReturnAfterLabel(new CallExpr(PRIM_MOVE, tmp, new CallExpr(var, new_IntSymbol(i)))); workingFn->insertBeforeReturnAfterLabel(new CallExpr("=", actual->copy(), tmp)); i++; } } tupleCall->insertAtHead(new_IntSymbol(n)); workingFn->insertAtHead(new CallExpr(PRIM_MOVE, var, tupleCall)); workingFn->insertAtHead(new DefExpr(var)); formal->defPoint->remove(); if (workingFn->hasFlag(FLAG_PARTIAL_COPY)) { // If this is a partial copy, store the mapping for substitution later. workingFn->partialCopyMap.put(formal, var); } else { // Otherwise, do the substitution now. subSymbol(workingFn->body, formal, var); } if (workingFn->where) { VarSymbol* var = new VarSymbol(formal->name); if (formal->hasFlag(FLAG_TYPE_VARIABLE)) { var->addFlag(FLAG_TYPE_VARIABLE); } workingFn->where->insertAtHead(new CallExpr(PRIM_MOVE, var, tupleCall->copy())); workingFn->where->insertAtHead(new DefExpr(var)); subSymbol(workingFn->where, formal, var); } } } } static FnSymbol* expandVarArgs(FnSymbol* origFn, int numActuals) { bool genericArgSeen = false; FnSymbol* workingFn = origFn; SymbolMap substitutions; static Map<FnSymbol*,Vec<FnSymbol*>*> cache; // check for cached stamped out function if (Vec<FnSymbol*>* cfns = cache.get(origFn)) { forv_Vec(FnSymbol, cfn, *cfns) { if (cfn->numFormals() == numActuals) return cfn; } } for_formals(formal, origFn) { if (workingFn != origFn) { formal = toArgSymbol(substitutions.get(formal)); } if (!genericArgSeen && formal->variableExpr && !isDefExpr(formal->variableExpr->body.tail)) { resolveBlock(formal->variableExpr); } /* * Set genericArgSeen to true if a generic argument appears before the * argument with the variable expression. */ // INT_ASSERT(arg->type); // Adding 'ref' intent to the "ret" arg of // inline proc =(ref ret:syserr, x:syserr) { __primitive("=", ret, x); } // in SysBasic.chpl:150 causes a segfault. // The addition of the arg->type test in the folloiwng conditional is a // workaround. // A better approach would be to add a check that each formal of a function // has a type (if that can be expected) and then fix the fault where it occurs. if (formal->type && formal->type->symbol->hasFlag(FLAG_GENERIC)) { genericArgSeen = true; } if (!formal->variableExpr) { continue; } // Handle unspecified variable number of arguments. if (DefExpr* def = toDefExpr(formal->variableExpr->body.tail)) { int numCopies = numActuals - workingFn->numFormals() + 1; if (numCopies <= 0) { if (workingFn != origFn) delete workingFn; return NULL; } if (workingFn == origFn) { workingFn = origFn->copy(&substitutions); INT_ASSERT(! workingFn->hasFlag(FLAG_RESOLVED)); workingFn->addFlag(FLAG_INVISIBLE_FN); origFn->defPoint->insertBefore(new DefExpr(workingFn)); formal = static_cast<ArgSymbol*>(substitutions.get(formal)); } Symbol* newSym = substitutions.get(def->sym); SymExpr* newSymExpr = new SymExpr(new_IntSymbol(numCopies)); newSym->defPoint->replace(newSymExpr); subSymbol(workingFn, newSym, new_IntSymbol(numCopies)); handleSymExprInExpandVarArgs(workingFn, formal, newSymExpr); genericArgSeen = false; } else if (SymExpr* sym = toSymExpr(formal->variableExpr->body.tail)) { handleSymExprInExpandVarArgs(workingFn, formal, sym); } else if (!workingFn->hasFlag(FLAG_GENERIC)) { INT_FATAL("bad variableExpr"); } } Vec<FnSymbol*>* cfns = cache.get(origFn); if (cfns == NULL) { cfns = new Vec<FnSymbol*>(); } cfns->add(workingFn); cache.put(origFn, cfns); return workingFn; } static void resolve_type_constructor(FnSymbol* fn, CallInfo& info) { SET_LINENO(fn); CallExpr* typeConstructorCall = new CallExpr(astr("_type", fn->name)); for_formals(formal, fn) { if (strcmp(formal->name, "meme")) { if (fn->_this->type->symbol->hasFlag(FLAG_TUPLE)) { if (formal->instantiatedFrom) { typeConstructorCall->insertAtTail(formal->type->symbol); } else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) { typeConstructorCall->insertAtTail(paramMap.get(formal)); } } else { if (!strcmp(formal->name, "outer") || formal->type == dtMethodToken) { typeConstructorCall->insertAtTail(formal); } else if (formal->instantiatedFrom) { typeConstructorCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal->type->symbol))); } else if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) { typeConstructorCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(paramMap.get(formal)))); } } } } info.call->insertBefore(typeConstructorCall); resolveCall(typeConstructorCall); INT_ASSERT(typeConstructorCall->isResolved()); resolveFns(typeConstructorCall->isResolved()); fn->_this->type = typeConstructorCall->isResolved()->retType; typeConstructorCall->remove(); } /** Candidate filtering logic specific to concrete functions. * * \param candidates The list to add possible candidates to. * \param currCandidate The current candidate to consider. * \param info The CallInfo object for the call site. */ static void filterConcreteCandidate(Vec<ResolutionCandidate*>& candidates, ResolutionCandidate* currCandidate, CallInfo& info) { currCandidate->fn = expandVarArgs(currCandidate->fn, info.actuals.n); if (!currCandidate->fn) return; if (!currCandidate->computeAlignment(info)) { return; } /* * Make sure that type constructor is resolved before other constructors. */ if (currCandidate->fn->hasFlag(FLAG_DEFAULT_CONSTRUCTOR)) { resolve_type_constructor(currCandidate->fn, info); } /* * A derived generic type will use the type of its parent, and expects this to * be instantiated before it is. */ resolveFormals(currCandidate->fn); int coindex = -1; for_formals(formal, currCandidate->fn) { if (Symbol* actual = currCandidate->alignedActuals.v[++coindex]) { if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) { return; } if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formal->hasFlag(FLAG_INSTANTIATED_PARAM))) { return; } } } candidates.add(currCandidate); } /** Candidate filtering logic specific to generic functions. * * \param candidates The list to add possible candidates to. * \param currCandidate The current candidate to consider. * \param info The CallInfo object for the call site. */ static void filterGenericCandidate(Vec<ResolutionCandidate*>& candidates, ResolutionCandidate* currCandidate, CallInfo& info) { currCandidate->fn = expandVarArgs(currCandidate->fn, info.actuals.n); if (!currCandidate->fn) return; if (!currCandidate->computeAlignment(info)) { return; } /* * Early rejection of generic functions. */ int coindex = 0; for_formals(formal, currCandidate->fn) { if (formal->type != dtUnknown) { if (Symbol* actual = currCandidate->alignedActuals.v[coindex]) { if (actual->hasFlag(FLAG_TYPE_VARIABLE) != formal->hasFlag(FLAG_TYPE_VARIABLE)) { return; } if (formal->type->symbol->hasFlag(FLAG_GENERIC)) { Type* vt = actual->getValType(); Type* st = actual->type->scalarPromotionType; Type* svt = (vt) ? vt->scalarPromotionType : NULL; if (!canInstantiate(actual->type, formal->type) && (!vt || !canInstantiate(vt, formal->type)) && (!st || !canInstantiate(st, formal->type)) && (!svt || !canInstantiate(svt, formal->type))) { return; } } else { if (!canDispatch(actual->type, actual, formal->type, currCandidate->fn, NULL, formal->hasFlag(FLAG_INSTANTIATED_PARAM))) { return; } } } } ++coindex; } // Compute the param/type substitutions for generic arguments. currCandidate->computeSubstitutions(); /* * If no substitutions were made we can't instantiate this generic, and must * reject it. */ if (currCandidate->substitutions.n > 0) { /* * Instantiate just enough of the generic to get through the rest of the * filtering and disambiguation processes. */ currCandidate->fn = instantiateSignature(currCandidate->fn, currCandidate->substitutions, info.call); if (currCandidate->fn != NULL) { filterCandidate(candidates, currCandidate, info); } } } /** Tests to see if a function is a candidate for resolving a specific call. If * it is a candidate, we add it to the candidate lists. * * This version of filterCandidate is called by other versions of * filterCandidate, and shouldn't be called outside this family of functions. * * \param candidates The list to add possible candidates to. * \param currCandidate The current candidate to consider. * \param info The CallInfo object for the call site. */ static void filterCandidate(Vec<ResolutionCandidate*>& candidates, ResolutionCandidate* currCandidate, CallInfo& info) { if (currCandidate->fn->hasFlag(FLAG_GENERIC)) { filterGenericCandidate(candidates, currCandidate, info); } else { filterConcreteCandidate(candidates, currCandidate, info); } } /** Tests to see if a function is a candidate for resolving a specific call. If * it is a candidate, we add it to the candidate lists. * * This version of filterCandidate is called by code outside the filterCandidate * family of functions. * * \param candidates The list to add possible candidates to. * \param currCandidate The current candidate to consider. * \param info The CallInfo object for the call site. */ static void filterCandidate(Vec<ResolutionCandidate*>& candidates, FnSymbol* fn, CallInfo& info) { ResolutionCandidate* currCandidate = new ResolutionCandidate(fn); filterCandidate(candidates, currCandidate, info); if (candidates.tail() != currCandidate) { // The candidate was not accepted. Time to clean it up. delete currCandidate; } } static BlockStmt* getParentBlock(Expr* expr) { for (Expr* tmp = expr->parentExpr; tmp; tmp = tmp->parentExpr) { if (BlockStmt* block = toBlockStmt(tmp)) return block; } if (expr->parentSymbol) { FnSymbol* parentFn = toFnSymbol(expr->parentSymbol); if (parentFn && parentFn->instantiationPoint) return parentFn->instantiationPoint; else if (expr->parentSymbol->defPoint) return getParentBlock(expr->parentSymbol->defPoint); } return NULL; } // // helper routine for isMoreVisible (below); // static bool isMoreVisibleInternal(BlockStmt* block, FnSymbol* fn1, FnSymbol* fn2, Vec<BlockStmt*>& visited) { // // fn1 is more visible // if (fn1->defPoint->parentExpr == block) return true; // // fn2 is more visible // if (fn2->defPoint->parentExpr == block) return false; visited.set_add(block); // // default to true if neither are visible // bool moreVisible = true; // // ensure f2 is not more visible via parent block, and recurse // if (BlockStmt* parentBlock = getParentBlock(block)) if (!visited.set_in(parentBlock)) moreVisible &= isMoreVisibleInternal(parentBlock, fn1, fn2, visited); // // ensure f2 is not more visible via module uses, and recurse // if (block && block->modUses) { for_actuals(expr, block->modUses) { SymExpr* se = toSymExpr(expr); INT_ASSERT(se); ModuleSymbol* mod = toModuleSymbol(se->var); INT_ASSERT(mod); if (!visited.set_in(mod->block)) moreVisible &= isMoreVisibleInternal(mod->block, fn1, fn2, visited); } } return moreVisible; } // // return true if fn1 is more visible than fn2 from expr // // assumption: fn1 and fn2 are visible from expr; if this assumption // is violated, this function will return true // static bool isMoreVisible(Expr* expr, FnSymbol* fn1, FnSymbol* fn2) { // // common-case check to see if functions have equal visibility // if (fn1->defPoint->parentExpr == fn2->defPoint->parentExpr) { // Special check which makes cg-initializers inferior to user-defined constructors // with the same args. if (fn2->hasFlag(FLAG_DEFAULT_CONSTRUCTOR)) return true; return false; } // // call helper function with visited set to avoid infinite recursion // Vec<BlockStmt*> visited; BlockStmt* block = toBlockStmt(expr); if (!block) block = getParentBlock(expr); return isMoreVisibleInternal(block, fn1, fn2, visited); } static bool paramWorks(Symbol* actual, Type* formalType) { Immediate* imm = NULL; if (VarSymbol* var = toVarSymbol(actual)) { imm = var->immediate; } if (EnumSymbol* enumsym = toEnumSymbol(actual)) { ensureEnumTypeResolved(toEnumType(enumsym->type)); imm = enumsym->getImmediate(); } if (imm) { if (is_int_type(formalType)) { return fits_in_int(get_width(formalType), imm); } if (is_uint_type(formalType)) { return fits_in_uint(get_width(formalType), imm); } } return false; } // // This is a utility function that essentially tracks which function, // if any, the param arguments prefer. // static inline void registerParamPreference(int& paramPrefers, int preference, const char* argstr, DisambiguationContext DC) { if (paramPrefers == 0 || paramPrefers == preference) { /* if the param currently has no preference or it matches the new preference, preserve the current preference */ paramPrefers = preference; TRACE_DISAMBIGUATE_BY_MATCH("param prefers %s\n", argstr); } else { /* otherwise its preference contradicts the previous arguments, so mark it as not preferring either */ paramPrefers = -1; TRACE_DISAMBIGUATE_BY_MATCH("param prefers differing things\n"); } } static bool considerParamMatches(Type* actualtype, Type* arg1type, Type* arg2type) { /* BLC: Seems weird to have to add this; could just add it in the enum case if enums have to be special-cased here. Otherwise, how are the int cases handled later...? */ if (actualtype->symbol->hasFlag(FLAG_REF)) { actualtype = actualtype->getValType(); } if (actualtype == arg1type && actualtype != arg2type) { return true; } // If we don't have an exact match in the previous line, let's see if // we have a bool(w1) passed to bool(w2) or non-bool case; This is // based on the enum case developed in r20208 if (is_bool_type(actualtype) && is_bool_type(arg1type) && !is_bool_type(arg2type)) { return true; } // Otherwise, have bool cast to default-sized integer over a smaller size if (is_bool_type(actualtype) && actualtype != arg1type && actualtype != arg2type) { return considerParamMatches(dtInt[INT_SIZE_DEFAULT], arg1type, arg2type); } if (is_enum_type(actualtype) && actualtype != arg1type && actualtype != arg2type) { return considerParamMatches(dtInt[INT_SIZE_DEFAULT], arg1type, arg2type); } if (isSyncType(actualtype) && actualtype != arg1type && actualtype != arg2type) { return considerParamMatches(actualtype->getField("base_type")->type, arg1type, arg2type); } return false; } /** Compare two argument mappings, given a set of actual arguments, and set the * disambiguation state appropriately. * * This function implements the argument mapping comparison component of the * disambiguation procedure as detailed in section 13.14.3 of the Chapel * language specification (page 107). * * \param fn1 The first function to be compared. * \param formal1 The formal argument that correspond to the actual argument * for the first function. * \param fn2 The second function to be compared. * \param formal2 The formal argument that correspond to the actual argument * for the second function. * \param actual The actual argument from the call site. * \param DC The disambiguation context. * \param DS The disambiguation state. */ static void testArgMapping(FnSymbol* fn1, ArgSymbol* formal1, FnSymbol* fn2, ArgSymbol* formal2, Symbol* actual, const DisambiguationContext& DC, DisambiguationState& DS) { TRACE_DISAMBIGUATE_BY_MATCH("Actual's type: %s\n", toString(actual->type)); bool formal1Promotes = false; canDispatch(actual->type, actual, formal1->type, fn1, &formal1Promotes); DS.fn1Promotes |= formal1Promotes; TRACE_DISAMBIGUATE_BY_MATCH("Formal 1's type: %s\n", toString(formal1->type)); if (formal1Promotes) { TRACE_DISAMBIGUATE_BY_MATCH("Actual requires promotion to match formal 1\n"); } else { TRACE_DISAMBIGUATE_BY_MATCH("Actual DOES NOT require promotion to match formal 1\n"); } if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) { TRACE_DISAMBIGUATE_BY_MATCH("Formal 1 is an instantiated param.\n"); } else { TRACE_DISAMBIGUATE_BY_MATCH("Formal 1 is NOT an instantiated param.\n"); } bool formal2Promotes = false; canDispatch(actual->type, actual, formal2->type, fn1, &formal2Promotes); DS.fn2Promotes |= formal2Promotes; TRACE_DISAMBIGUATE_BY_MATCH("Formal 2's type: %s\n", toString(formal2->type)); if (formal1Promotes) { TRACE_DISAMBIGUATE_BY_MATCH("Actual requires promotion to match formal 2\n"); } else { TRACE_DISAMBIGUATE_BY_MATCH("Actual DOES NOT require promotion to match formal 2\n"); } if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) { TRACE_DISAMBIGUATE_BY_MATCH("Formal 2 is an instantiated param.\n"); } else { TRACE_DISAMBIGUATE_BY_MATCH("Formal 2 is NOT an instantiated param.\n"); } if (formal1->type == formal2->type && formal1->hasFlag(FLAG_INSTANTIATED_PARAM) && !formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) { TRACE_DISAMBIGUATE_BY_MATCH("A: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (formal1->type == formal2->type && !formal1->hasFlag(FLAG_INSTANTIATED_PARAM) && formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) { TRACE_DISAMBIGUATE_BY_MATCH("B: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else if (!formal1Promotes && formal2Promotes) { TRACE_DISAMBIGUATE_BY_MATCH("C: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (formal1Promotes && !formal2Promotes) { TRACE_DISAMBIGUATE_BY_MATCH("D: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else if (formal1->type == formal2->type && !formal1->instantiatedFrom && formal2->instantiatedFrom) { TRACE_DISAMBIGUATE_BY_MATCH("E: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (formal1->type == formal2->type && formal1->instantiatedFrom && !formal2->instantiatedFrom) { TRACE_DISAMBIGUATE_BY_MATCH("F: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else if (formal1->instantiatedFrom != dtAny && formal2->instantiatedFrom == dtAny) { TRACE_DISAMBIGUATE_BY_MATCH("G: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (formal1->instantiatedFrom == dtAny && formal2->instantiatedFrom != dtAny) { TRACE_DISAMBIGUATE_BY_MATCH("H: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else if (considerParamMatches(actual->type, formal1->type, formal2->type)) { TRACE_DISAMBIGUATE_BY_MATCH("In first param case\n"); // The actual matches formal1's type, but not formal2's if (paramWorks(actual, formal2->type)) { // but the actual is a param and works for formal2 if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) { // the param works equally well for both, but // matches the first slightly better if we had to // decide registerParamPreference(DS.paramPrefers, 1, "formal1", DC); } else if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) { registerParamPreference(DS.paramPrefers, 2, "formal2", DC); } else { // neither is a param, but formal1 is an exact type // match, so prefer that one registerParamPreference(DS.paramPrefers, 1, "formal1", DC); } } else { TRACE_DISAMBIGUATE_BY_MATCH("I: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } } else if (considerParamMatches(actual->type, formal2->type, formal1->type)) { TRACE_DISAMBIGUATE_BY_MATCH("In second param case\n"); // The actual matches formal2's type, but not formal1's if (paramWorks(actual, formal1->type)) { // but the actual is a param and works for formal1 if (formal2->hasFlag(FLAG_INSTANTIATED_PARAM)) { // the param works equally well for both, but // matches the second slightly better if we had to // decide registerParamPreference(DS.paramPrefers, 2, "formal2", DC); } else if (formal1->hasFlag(FLAG_INSTANTIATED_PARAM)) { registerParamPreference(DS.paramPrefers, 1, "formal1", DC); } else { // neither is a param, but formal1 is an exact type // match, so prefer that one registerParamPreference(DS.paramPrefers, 2, "formal2", DC); } } else { TRACE_DISAMBIGUATE_BY_MATCH("J: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } } else if (moreSpecific(fn1, formal1->type, formal2->type) && formal2->type != formal1->type) { TRACE_DISAMBIGUATE_BY_MATCH("K: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (moreSpecific(fn1, formal2->type, formal1->type) && formal2->type != formal1->type) { TRACE_DISAMBIGUATE_BY_MATCH("L: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else if (is_int_type(formal1->type) && is_uint_type(formal2->type)) { TRACE_DISAMBIGUATE_BY_MATCH("M: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (is_int_type(formal2->type) && is_uint_type(formal1->type)) { TRACE_DISAMBIGUATE_BY_MATCH("N: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else { TRACE_DISAMBIGUATE_BY_MATCH("O: no information gained from argument\n"); } } /** Determines if fn1 is a better match than fn2. * * This function implements the function comparison component of the * disambiguation procedure as detailed in section 13.14.3 of the Chapel * language specification (page 106). * * \param candidate1 The function on the left-hand side of the comparison. * \param candidate2 The function on the right-hand side of the comparison. * \param DC The disambiguation context. * * \return True if fn1 is a more specific function than f2, false otherwise. */ static bool isBetterMatch(ResolutionCandidate* candidate1, ResolutionCandidate* candidate2, const DisambiguationContext& DC) { DisambiguationState DS; for (int k = 0; k < candidate1->alignedFormals.n; ++k) { Symbol* actual = DC.actuals->v[k]; ArgSymbol* formal1 = candidate1->alignedFormals.v[k]; ArgSymbol* formal2 = candidate2->alignedFormals.v[k]; TRACE_DISAMBIGUATE_BY_MATCH("\nLooking at argument %d\n", k); testArgMapping(candidate1->fn, formal1, candidate2->fn, formal2, actual, DC, DS); } if (!DS.fn1Promotes && DS.fn2Promotes) { TRACE_DISAMBIGUATE_BY_MATCH("\nP: Fn %d does not require argument promotion; Fn %d does\n", DC.i, DC.j); DS.printSummary("P", DC); return true; } if (!(DS.fn1MoreSpecific || DS.fn2MoreSpecific)) { // If the decision hasn't been made based on the argument mappings... if (isMoreVisible(DC.scope, candidate1->fn, candidate2->fn)) { TRACE_DISAMBIGUATE_BY_MATCH("\nQ: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (isMoreVisible(DC.scope, candidate2->fn, candidate1->fn)) { TRACE_DISAMBIGUATE_BY_MATCH("\nR: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else if (DS.paramPrefers == 1) { TRACE_DISAMBIGUATE_BY_MATCH("\nS: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (DS.paramPrefers == 2) { TRACE_DISAMBIGUATE_BY_MATCH("\nT: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } else if (candidate1->fn->where && !candidate2->fn->where) { TRACE_DISAMBIGUATE_BY_MATCH("\nU: Fn %d is more specific\n", DC.i); DS.fn1MoreSpecific = true; } else if (!candidate1->fn->where && candidate2->fn->where) { TRACE_DISAMBIGUATE_BY_MATCH("\nV: Fn %d is more specific\n", DC.j); DS.fn2MoreSpecific = true; } } DS.printSummary("W", DC); return DS.fn1MoreSpecific && !DS.fn2MoreSpecific; } /** Find the best candidate from a list of candidates. * * This function finds the best Chapel function from a set of candidates, given * a call site. This is an implementation of 13.14.3 of the Chapel language * specification (page 106). * * \param candidates A list of the candidate functions, from which the best * match is selected. * \param DC The disambiguation context. * * \return The result of the disambiguation process. */ static ResolutionCandidate* disambiguateByMatch(Vec<ResolutionCandidate*>& candidates, DisambiguationContext DC) { // If index i is set then we can skip testing function F_i because we already // know it can not be the best match. std::vector<bool> notBest(candidates.n, false); for (int i = 0; i < candidates.n; ++i) { TRACE_DISAMBIGUATE_BY_MATCH("##########################\n"); TRACE_DISAMBIGUATE_BY_MATCH("# Considering function %d #\n", i); TRACE_DISAMBIGUATE_BY_MATCH("##########################\n\n"); ResolutionCandidate* candidate1 = candidates.v[i]; bool best = true; // is fn1 the best candidate? TRACE_DISAMBIGUATE_BY_MATCH("%s\n\n", toString(candidate1->fn)); if (notBest[i]) { TRACE_DISAMBIGUATE_BY_MATCH("Already known to not be best match. Skipping.\n\n"); continue; } for (int j = 0; j < candidates.n; ++j) { if (i == j) continue; TRACE_DISAMBIGUATE_BY_MATCH("Comparing to function %d\n", j); TRACE_DISAMBIGUATE_BY_MATCH("-----------------------\n"); ResolutionCandidate* candidate2 = candidates.v[j]; TRACE_DISAMBIGUATE_BY_MATCH("%s\n", toString(candidate2->fn)); if (isBetterMatch(candidate1, candidate2, DC.forPair(i, j))) { TRACE_DISAMBIGUATE_BY_MATCH("X: Fn %d is a better match than Fn %d\n\n\n", i, j); notBest[j] = true; } else { TRACE_DISAMBIGUATE_BY_MATCH("X: Fn %d is NOT a better match than Fn %d\n\n\n", i, j); best = false; break; } } if (best) { TRACE_DISAMBIGUATE_BY_MATCH("Y: Fn %d is the best match.\n\n\n", i); return candidate1; } else { TRACE_DISAMBIGUATE_BY_MATCH("Y: Fn %d is NOT the best match.\n\n\n", i); } } TRACE_DISAMBIGUATE_BY_MATCH("Z: No non-ambiguous best match.\n\n"); return NULL; } static bool explainCallMatch(CallExpr* call) { if (!call->isNamed(fExplainCall)) return false; if (explainCallModule && explainCallModule != call->getModule()) return false; if (explainCallLine != -1 && explainCallLine != call->linenum()) return false; return true; } static CallExpr* userCall(CallExpr* call) { if (developer) return call; // If the called function is compiler-generated or is in one of the internal // modules, back up the stack until a call is encountered whose target // function is neither. // TODO: This function should be rewritten so each test appears only once. if (call->getFunction()->hasFlag(FLAG_COMPILER_GENERATED) || call->getModule()->modTag == MOD_INTERNAL) { for (int i = callStack.n-1; i >= 0; i--) { if (!callStack.v[i]->getFunction()->hasFlag(FLAG_COMPILER_GENERATED) && callStack.v[i]->getModule()->modTag != MOD_INTERNAL) return callStack.v[i]; } } return call; } static void printResolutionErrorAmbiguous( Vec<FnSymbol*>& candidates, CallInfo* info) { CallExpr* call = userCall(info->call); if (!strcmp("this", info->name)) { USR_FATAL(call, "ambiguous access of '%s' by '%s'", toString(info->actuals.v[1]->type), toString(info)); } else { const char* entity = "call"; if (!strncmp("_type_construct_", info->name, 16)) entity = "type specifier"; const char* str = toString(info); if (info->scope) { ModuleSymbol* mod = toModuleSymbol(info->scope->parentSymbol); INT_ASSERT(mod); str = astr(mod->name, ".", str); } USR_FATAL_CONT(call, "ambiguous %s '%s'", entity, str); if (developer) { for (int i = callStack.n-1; i>=0; i--) { CallExpr* cs = callStack.v[i]; FnSymbol* f = cs->getFunction(); if (f->instantiatedFrom) USR_PRINT(callStack.v[i], " instantiated from %s", f->name); else break; } } bool printed_one = false; forv_Vec(FnSymbol, fn, candidates) { USR_PRINT(fn, "%s %s", printed_one ? " " : "candidates are:", toString(fn)); printed_one = true; } USR_STOP(); } } static void printResolutionErrorUnresolved( Vec<FnSymbol*>& visibleFns, CallInfo* info) { CallExpr* call = userCall(info->call); if (!strcmp("_cast", info->name)) { if (!info->actuals.head()->hasFlag(FLAG_TYPE_VARIABLE)) { USR_FATAL(call, "illegal cast to non-type", toString(info->actuals.v[1]->type), toString(info->actuals.v[0]->type)); } else { USR_FATAL(call, "illegal cast from %s to %s", toString(info->actuals.v[1]->type), toString(info->actuals.v[0]->type)); } } else if (!strcmp("free", info->name)) { if (info->actuals.n > 0 && isRecord(info->actuals.v[2]->type)) USR_FATAL(call, "delete not allowed on records"); } else if (!strcmp("these", info->name)) { if (info->actuals.n == 2 && info->actuals.v[0]->type == dtMethodToken) USR_FATAL(call, "cannot iterate over values of type %s", toString(info->actuals.v[1]->type)); } else if (!strcmp("_type_construct__tuple", info->name)) { if (info->call->argList.length == 0) USR_FATAL(call, "tuple size must be specified"); SymExpr* sym = toSymExpr(info->call->get(1)); if (!sym || !sym->var->isParameter()) { USR_FATAL(call, "tuple size must be static"); } else { USR_FATAL(call, "invalid tuple"); } } else if (!strcmp("=", info->name)) { if (info->actuals.v[0] && !info->actuals.v[0]->hasFlag(FLAG_TYPE_VARIABLE) && info->actuals.v[1] && info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE)) { USR_FATAL(call, "illegal assignment of type to value"); } else if (info->actuals.v[0] && info->actuals.v[0]->hasFlag(FLAG_TYPE_VARIABLE) && info->actuals.v[1] && !info->actuals.v[1]->hasFlag(FLAG_TYPE_VARIABLE)) { USR_FATAL(call, "illegal assignment of value to type"); } else if (info->actuals.v[1]->type == dtNil) { USR_FATAL(call, "type mismatch in assignment from nil to %s", toString(info->actuals.v[0]->type)); } else { USR_FATAL(call, "type mismatch in assignment from %s to %s", toString(info->actuals.v[1]->type), toString(info->actuals.v[0]->type)); } } else if (!strcmp("this", info->name)) { Type* type = info->actuals.v[1]->getValType(); if (type->symbol->hasFlag(FLAG_ITERATOR_RECORD)) { USR_FATAL(call, "illegal access of iterator or promoted expression"); } else if (type->symbol->hasFlag(FLAG_FUNCTION_CLASS)) { USR_FATAL(call, "illegal access of first class function"); } else { USR_FATAL(call, "unresolved access of '%s' by '%s'", toString(info->actuals.v[1]->type), toString(info)); } } else { const char* entity = "call"; if (!strncmp("_type_construct_", info->name, 16)) entity = "type specifier"; const char* str = toString(info); if (info->scope) { ModuleSymbol* mod = toModuleSymbol(info->scope->parentSymbol); INT_ASSERT(mod); str = astr(mod->name, ".", str); } USR_FATAL_CONT(call, "unresolved %s '%s'", entity, str); if (visibleFns.n > 0) { if (developer) { for (int i = callStack.n-1; i>=0; i--) { CallExpr* cs = callStack.v[i]; FnSymbol* f = cs->getFunction(); if (f->instantiatedFrom) USR_PRINT(callStack.v[i], " instantiated from %s", f->name); else break; } } bool printed_one = false; forv_Vec(FnSymbol, fn, visibleFns) { // Consider "visible functions are" USR_PRINT(fn, "%s %s", printed_one ? " " : "candidates are:", toString(fn)); printed_one = true; } } if (visibleFns.n == 1 && visibleFns.v[0]->numFormals() == 0 && !strncmp("_type_construct_", info->name, 16)) USR_PRINT(call, "did you forget the 'new' keyword?"); USR_STOP(); } } static void issueCompilerError(CallExpr* call) { // // Disable compiler warnings in internal modules that are triggered // within a dynamic dispatch context because of potential user // confusion. Removed the following code and See the following // tests: // // test/arrays/bradc/workarounds/arrayOfSpsArray.chpl // test/arrays/deitz/part4/test_array_of_associative_arrays.chpl // test/classes/bradc/arrayInClass/genericArrayInClass-otharrs.chpl // if (call->isPrimitive(PRIM_WARNING)) if (inDynamicDispatchResolution) if (call->getModule()->modTag == MOD_INTERNAL && callStack.head()->getModule()->modTag == MOD_INTERNAL) return; // // If an errorDepth was specified, report a diagnostic about the call // that deep into the callStack. The default depth is 1. // FnSymbol* fn = toFnSymbol(call->parentSymbol); VarSymbol* depthParam = toVarSymbol(paramMap.get(toDefExpr(fn->formals.tail)->sym)); int64_t depth; bool foundDepthVal; if (depthParam && depthParam->immediate && depthParam->immediate->const_kind == NUM_KIND_INT) { depth = depthParam->immediate->int_value(); foundDepthVal = true; } else { depth = 1; foundDepthVal = false; } if (depth > callStack.n - 1) { if (foundDepthVal) USR_WARN(call, "compiler diagnostic depth value exceeds call stack depth"); depth = callStack.n - 1; } if (depth < 0) { USR_WARN(call, "compiler diagnostic depth value can not be negative"); depth = 0; } CallExpr* from = NULL; for (int i = callStack.n-1 - depth; i >= 0; i--) { from = callStack.v[i]; // We report calls whose target function is not compiler-generated and is // not defined in one of the internal modules. if (from->linenum() > 0 && from->getModule()->modTag != MOD_INTERNAL && !from->getFunction()->hasFlag(FLAG_COMPILER_GENERATED)) break; } const char* str = ""; for_formals(arg, fn) { if (foundDepthVal && arg->defPoint == fn->formals.tail) continue; VarSymbol* var = toVarSymbol(paramMap.get(arg)); INT_ASSERT(var && var->immediate && var->immediate->const_kind == CONST_KIND_STRING); str = astr(str, var->immediate->v_string); } if (call->isPrimitive(PRIM_ERROR)) { USR_FATAL(from, "%s", str); } else { USR_WARN(from, "%s", str); } if (FnSymbol* fn = toFnSymbol(callStack.tail()->isResolved())) innerCompilerWarningMap.put(fn, str); if (FnSymbol* fn = toFnSymbol(callStack.v[callStack.n-1 - depth]->isResolved())) outerCompilerWarningMap.put(fn, str); } static void reissueCompilerWarning(const char* str, int offset) { // // Disable compiler warnings in internal modules that are triggered // within a dynamic dispatch context because of potential user // confusion. See note in 'issueCompileError' above. // if (inDynamicDispatchResolution) if (callStack.tail()->getModule()->modTag == MOD_INTERNAL && callStack.head()->getModule()->modTag == MOD_INTERNAL) return; CallExpr* from = NULL; for (int i = callStack.n-offset; i >= 0; i--) { from = callStack.v[i]; // We report calls whose target function is not compiler-generated and is // not defined in one of the internal modules. if (from->linenum() > 0 && from->getModule()->modTag != MOD_INTERNAL && !from->getFunction()->hasFlag(FLAG_COMPILER_GENERATED)) break; } USR_WARN(from, "%s", str); } class VisibleFunctionBlock { public: Map<const char*,Vec<FnSymbol*>*> visibleFunctions; VisibleFunctionBlock() { } }; static Map<BlockStmt*,VisibleFunctionBlock*> visibleFunctionMap; static int nVisibleFunctions = 0; // for incremental build static Map<BlockStmt*,BlockStmt*> visibilityBlockCache; static Vec<BlockStmt*> standardModuleSet; // // return the innermost block for searching for visible functions // BlockStmt* getVisibilityBlock(Expr* expr) { if (BlockStmt* block = toBlockStmt(expr->parentExpr)) { if (block->blockTag == BLOCK_SCOPELESS) return getVisibilityBlock(block); else return block; } else if (expr->parentExpr) { return getVisibilityBlock(expr->parentExpr); } else if (Symbol* s = expr->parentSymbol) { FnSymbol* fn = toFnSymbol(s); if (fn && fn->instantiationPoint) return fn->instantiationPoint; else return getVisibilityBlock(s->defPoint); } else { INT_FATAL(expr, "Expresion has no visibility block."); return NULL; } } static void buildVisibleFunctionMap() { for (int i = nVisibleFunctions; i < gFnSymbols.n; i++) { FnSymbol* fn = gFnSymbols.v[i]; if (!fn->hasFlag(FLAG_INVISIBLE_FN) && fn->defPoint->parentSymbol && !isArgSymbol(fn->defPoint->parentSymbol)) { BlockStmt* block = NULL; if (fn->hasFlag(FLAG_AUTO_II)) { block = theProgram->block; } else { block = getVisibilityBlock(fn->defPoint); // // add all functions in standard modules to theProgram // if (standardModuleSet.set_in(block)) block = theProgram->block; } VisibleFunctionBlock* vfb = visibleFunctionMap.get(block); if (!vfb) { vfb = new VisibleFunctionBlock(); visibleFunctionMap.put(block, vfb); } Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(fn->name); if (!fns) { fns = new Vec<FnSymbol*>(); vfb->visibleFunctions.put(fn->name, fns); } fns->add(fn); } } nVisibleFunctions = gFnSymbols.n; } static BlockStmt* getVisibleFunctions(BlockStmt* block, const char* name, Vec<FnSymbol*>& visibleFns, Vec<BlockStmt*>& visited) { // // all functions in standard modules are stored in a single block // if (standardModuleSet.set_in(block)) block = theProgram->block; // // avoid infinite recursion due to modules with mutual uses // if (visited.set_in(block)) return NULL; else if (isModuleSymbol(block->parentSymbol)) visited.set_add(block); bool canSkipThisBlock = true; VisibleFunctionBlock* vfb = visibleFunctionMap.get(block); if (vfb) { canSkipThisBlock = false; // cannot skip if this block defines functions Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(name); if (fns) { visibleFns.append(*fns); } } if (block->modUses) { for_actuals(expr, block->modUses) { SymExpr* se = toSymExpr(expr); INT_ASSERT(se); ModuleSymbol* mod = toModuleSymbol(se->var); INT_ASSERT(mod); canSkipThisBlock = false; // cannot skip if this block uses modules getVisibleFunctions(mod->block, name, visibleFns, visited); } } // // visibilityBlockCache contains blocks that can be skipped // if (BlockStmt* next = visibilityBlockCache.get(block)) { getVisibleFunctions(next, name, visibleFns, visited); return (canSkipThisBlock) ? next : block; } if (block != rootModule->block) { BlockStmt* next = getVisibilityBlock(block); BlockStmt* cache = getVisibleFunctions(next, name, visibleFns, visited); if (cache) visibilityBlockCache.put(block, cache); return (canSkipThisBlock) ? cache : block; } return NULL; } static void replaceActualWithDeref(CallExpr* call, Type* derefType, SymExpr* actualExpr, Symbol* actualSym, CallInfo* info, int argNum) { SET_LINENO(call); Expr* stmt = call->getStmtExpr(); VarSymbol* derefTmp = newTemp("derefTmp", derefType); stmt->insertBefore(new DefExpr(derefTmp)); stmt->insertBefore(new_Expr("'move'(%S, 'deref'(%S))", derefTmp, actualSym)); actualExpr->var = derefTmp; INT_ASSERT(info->actuals.v[argNum] == actualSym); info->actuals.v[argNum] = derefTmp; } static void handleCaptureArgs(CallExpr* call, FnSymbol* taskFn, CallInfo* info) { INT_ASSERT(taskFn); if (!needsCapture(taskFn)) { // A task function should have args only if it needsCapture. if (taskFn->hasFlag(FLAG_ON)) { // Documenting the current state: fn_on gets a chpl_localeID_t arg. INT_ASSERT(call->numActuals() == 1); } else { INT_ASSERT(!isTaskFun(taskFn) || call->numActuals() == 0); } return; } int argNum = -1; for_formals_actuals(formal, actual, call) { argNum++; SymExpr* symexpActual = toSymExpr(actual); INT_ASSERT(symexpActual); // because of how we invoke a task function Symbol* varActual = symexpActual->var; // If 'call' is in a generic function, it is supposed to have been // instantiated by now. Otherwise our begin_fn has to remain generic. INT_ASSERT(!varActual->type->symbol->hasFlag(FLAG_GENERIC)); // need to copy varActual->type even for type variables formal->type = varActual->type; // If the actual is a ref, still need to capture it => remove ref. if (isReferenceType(varActual->type)) { Type* deref = varActual->type->getValType(); if (needsCapture(deref)) { formal->type = deref; replaceActualWithDeref(call, deref, symexpActual, varActual, info, argNum); } else { // Probably OK to leave as-is. } } if (varActual->hasFlag(FLAG_TYPE_VARIABLE)) formal->addFlag(FLAG_TYPE_VARIABLE); else if (varActual->type->symbol->hasFlag(FLAG_SYNC) || varActual->type->symbol->hasFlag(FLAG_SINGLE)) // this will do nothing e.g. for temps or sync formals varActual->removeFlag(FLAG_INSERT_AUTO_DESTROY); } // Even if some formals are (now) types, if 'taskFn' remained generic, // gatherCandidates() would not instantiate it, for some reason. taskFn->removeFlag(FLAG_GENERIC); } static Expr* resolve_type_expr(Expr* expr) { Expr* result = NULL; for_exprs_postorder(e, expr) { result = preFold(e); if (CallExpr* call = toCallExpr(result)) { if (call->parentSymbol) { callStack.add(call); resolveCall(call); FnSymbol* fn = call->isResolved(); if (fn && call->parentSymbol) { resolveFormals(fn); if (fn->retTag == RET_PARAM || fn->retTag == RET_TYPE || fn->retType == dtUnknown) resolveFns(fn); } callStack.pop(); } } result = postFold(result); } return result; } static void makeNoop(CallExpr* call) { if (call->baseExpr) call->baseExpr->remove(); while (call->numActuals()) call->get(1)->remove(); call->primitive = primitives[PRIM_NOOP]; } static bool isInConstructorLikeFunction(CallExpr* call) { return call->parentSymbol->hasFlag(FLAG_CONSTRUCTOR) || !strcmp(call->parentSymbol->name, "initialize"); } // The function call->parentSymbol is invoked from a constructor // or initialize(), with the constructor's or intialize's 'this' // as the receiver actual. static bool isInvokedFromConstructorLikeFunction(CallExpr* call1) { // We assume that 'call' is at the top of the call stack. INT_ASSERT(callStack.n >= 1 && call1 == callStack.v[callStack.n-1]); if (callStack.n >= 2) { CallExpr* call2 = callStack.v[callStack.n-2]; INT_ASSERT(call2->isResolved() == call1->parentSymbol); // sanity if (isInConstructorLikeFunction(call2)) if (call2->numActuals() >= 2) if (SymExpr* thisArg2 = toSymExpr(call2->get(2))) if (thisArg2->var->hasFlag(FLAG_ARG_THIS)) return true; } return false; } // Check whether the actual comes from accessing a const field of 'this' // and the call is in a function invoked directly from this's constructor. // In such case, fields of 'this' are not considered 'const', // so we remove the const-ness flag. static bool checkAndUpdateIfLegalFieldOfThis(CallExpr* call, Expr* actual) { if (SymExpr* se = toSymExpr(actual)) if (se->var->hasFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS)) if (isInvokedFromConstructorLikeFunction(call)) { // Yes, this is the case we are looking for. se->var->removeFlag(FLAG_REF_TO_CONST); return true; } return false; } // If 'fn' is the default assignment for a record type, return // the name of that record type; otherwise return NULL. static const char* defaultRecordAssignmentTo(FnSymbol* fn) { if (!strcmp("=", fn->name)) { if (fn->hasFlag(FLAG_COMPILER_GENERATED)) { Type* desttype = fn->getFormal(1)->type->getValType(); INT_ASSERT(desttype != dtUnknown); // otherwise this test is unreliable if (isRecord(desttype) || isUnion(desttype)) return desttype->symbol->name; } } return NULL; } // // special case cast of class w/ type variables that is not generic // i.e. type variables are type definitions (have default types) // static void resolveDefaultGenericType(CallExpr* call) { SET_LINENO(call); for_actuals(actual, call) { if (NamedExpr* ne = toNamedExpr(actual)) actual = ne->actual; if (SymExpr* te = toSymExpr(actual)) { if (TypeSymbol* ts = toTypeSymbol(te->var)) { if (AggregateType* ct = toAggregateType(ts->type)) { if (ct->symbol->hasFlag(FLAG_GENERIC)) { CallExpr* cc = new CallExpr(ct->defaultTypeConstructor->name); te->replace(cc); resolveCall(cc); cc->replace(new SymExpr(cc->typeInfo()->symbol)); } } } } } } static void gatherCandidates(Vec<ResolutionCandidate*>& candidates, Vec<FnSymbol*>& visibleFns, CallInfo& info) { // Search user-defined (i.e. non-compiler-generated) functions first. forv_Vec(FnSymbol, visibleFn, visibleFns) { if (visibleFn->hasFlag(FLAG_COMPILER_GENERATED)) { continue; } if (info.call->methodTag && ! (visibleFn->hasFlag(FLAG_NO_PARENS) || visibleFn->hasFlag(FLAG_TYPE_CONSTRUCTOR))) { continue; } if (fExplainVerbose && ((explainCallLine && explainCallMatch(info.call)) || info.call->id == explainCallID)) { USR_PRINT(visibleFn, "Considering function: %s", toString(visibleFn)); } filterCandidate(candidates, visibleFn, info); } // Return if we got a successful match with user-defined functions. if (candidates.n) { return; } // No. So search compiler-defined functions. forv_Vec(FnSymbol, visibleFn, visibleFns) { if (!visibleFn->hasFlag(FLAG_COMPILER_GENERATED)) { continue; } if (info.call->methodTag && ! (visibleFn->hasFlag(FLAG_NO_PARENS) || visibleFn->hasFlag(FLAG_TYPE_CONSTRUCTOR))) { continue; } if (fExplainVerbose && ((explainCallLine && explainCallMatch(info.call)) || info.call->id == explainCallID)) { USR_PRINT(visibleFn, "Considering function: %s", toString(visibleFn)); } filterCandidate(candidates, visibleFn, info); } } static void resolveCall(CallExpr* call) { if (call->primitive) { switch (call->primitive->tag) { default: /* do nothing */ break; case PRIM_TUPLE_AND_EXPAND: resolveTupleAndExpand(call); break; case PRIM_TUPLE_EXPAND: resolveTupleExpand(call); break; case PRIM_SET_MEMBER: resolveSetMember(call); break; case PRIM_MOVE: resolveMove(call); break; case PRIM_TYPE_INIT: case PRIM_INIT: resolveDefaultGenericType(call); break; case PRIM_NO_INIT: resolveDefaultGenericType(call); break; case PRIM_NEW: resolveNew(call); break; } } else { resolveNormalCall(call); } } static void resolveNormalCall(CallExpr* call) { resolveDefaultGenericType(call); CallInfo info(call); Vec<FnSymbol*> visibleFns; // visible functions // // update visible function map as necessary // if (gFnSymbols.n != nVisibleFunctions) { buildVisibleFunctionMap(); } if (!call->isResolved()) { if (!info.scope) { Vec<BlockStmt*> visited; getVisibleFunctions(getVisibilityBlock(call), info.name, visibleFns, visited); } else { if (VisibleFunctionBlock* vfb = visibleFunctionMap.get(info.scope)) { if (Vec<FnSymbol*>* fns = vfb->visibleFunctions.get(info.name)) { visibleFns.append(*fns); } } } } else { visibleFns.add(call->isResolved()); handleCaptureArgs(call, call->isResolved(), &info); } if ((explainCallLine && explainCallMatch(call)) || call->id == explainCallID) { USR_PRINT(call, "call: %s", toString(&info)); if (visibleFns.n == 0) USR_PRINT(call, "no visible functions found"); bool first = true; forv_Vec(FnSymbol, visibleFn, visibleFns) { USR_PRINT(visibleFn, "%s %s", first ? "visible functions are:" : " ", toString(visibleFn)); first = false; } } Vec<ResolutionCandidate*> candidates; gatherCandidates(candidates, visibleFns, info); if ((explainCallLine && explainCallMatch(info.call)) || call->id == explainCallID) { if (candidates.n == 0) { USR_PRINT(info.call, "no candidates found"); } else { bool first = true; forv_Vec(ResolutionCandidate*, candidate, candidates) { USR_PRINT(candidate->fn, "%s %s", first ? "candidates are:" : " ", toString(candidate->fn)); first = false; } } } Expr* scope = (info.scope) ? info.scope : getVisibilityBlock(call); bool explain = fExplainVerbose && ((explainCallLine && explainCallMatch(call)) || info.call->id == explainCallID); DisambiguationContext DC(&info.actuals, scope, explain); ResolutionCandidate* best = disambiguateByMatch(candidates, DC); if (best && best->fn) { /* * Finish instantiating the body. This is a noop if the function wasn't * partially instantiated. */ instantiateBody(best->fn); if (explainCallLine && explainCallMatch(call)) { USR_PRINT(best->fn, "best candidate is: %s", toString(best->fn)); } } if (call->partialTag && (!best || !best->fn->hasFlag(FLAG_NO_PARENS))) { if (best != NULL) { delete best; best = NULL; } } else if (!best) { if (tryStack.n) { tryFailure = true; return; } else { if (candidates.n > 0) { Vec<FnSymbol*> candidateFns; forv_Vec(ResolutionCandidate*, candidate, candidates) { candidateFns.add(candidate->fn); } printResolutionErrorAmbiguous(candidateFns, &info); } else { printResolutionErrorUnresolved(visibleFns, &info); } } } else { best->fn = defaultWrap(best->fn, &best->alignedFormals, &info); reorderActuals(best->fn, &best->alignedFormals, &info); best->fn = coercionWrap(best->fn, &info); best->fn = promotionWrap(best->fn, &info); } FnSymbol* resolvedFn = best != NULL ? best->fn : NULL; forv_Vec(ResolutionCandidate*, candidate, candidates) { delete candidate; } if (call->partialTag) { if (!resolvedFn) { return; } call->partialTag = false; } if (resolvedFn && !strcmp("=", resolvedFn->name) && isRecord(resolvedFn->getFormal(1)->type) && resolvedFn->getFormal(2)->type == dtNil) { USR_FATAL(userCall(call), "type mismatch in assignment from nil to %s", toString(resolvedFn->getFormal(1)->type)); } if (!resolvedFn) { INT_FATAL(call, "unable to resolve call"); } if (call->parentSymbol) { SET_LINENO(call); call->baseExpr->replace(new SymExpr(resolvedFn)); } if (resolvedFn->hasFlag(FLAG_FIELD_ACCESSOR)) { SymExpr* baseExpr = toSymExpr(call->get(2)); INT_ASSERT(baseExpr); // otherwise, cannot do the checking Symbol* baseSym = baseExpr->var; // Is the outcome of 'call' a reference to a const? bool refConst = false; if (resolvedFn->hasFlag(FLAG_REF_TO_CONST)) { // 'call' accesses a const field. refConst = true; // Do not consider it const if it is an access to 'this' // in a constructor. Todo: will need to reconcile with UMM. if (baseSym->hasFlag(FLAG_ARG_THIS) && isInConstructorLikeFunction(call)) refConst = false; } else { // See if the variable being accessed is const. if (baseSym->hasFlag(FLAG_CONST) || baseSym->hasFlag(FLAG_REF_TO_CONST) ) { // Todo: fine-tuning may be desired, e.g. // if FLAG_CONST then baseType = baseSym->type. Type* baseType = baseSym->type->getValType(); // Exclude classes: even if a class variable is const, // its non-const fields are OK to modify. if (isRecord(baseType) || isUnion(baseType)) refConst = true; } } if (refConst) { if (CallExpr* parent = toCallExpr(call->parentExpr)) { if (parent->isPrimitive(PRIM_MOVE)) { SymExpr* dest = toSymExpr(parent->get(1)); INT_ASSERT(dest); // what else can it be? dest->var->addFlag(FLAG_REF_TO_CONST); if (baseSym->hasFlag(FLAG_ARG_THIS)) dest->var->addFlag(FLAG_REF_FOR_CONST_FIELD_OF_THIS); } } } } if (resolvedFn->hasFlag(FLAG_MODIFIES_CONST_FIELDS)) // Not allowed if it is not called directly from a constructor. if (!isInConstructorLikeFunction(call)) USR_FATAL_CONT(call, "illegal call to %s() - it modifies 'const' fields of 'this', therefore it can be invoked only directly from a constructor", resolvedFn->name); lvalueCheck(call); if (const char* str = innerCompilerWarningMap.get(resolvedFn)) { reissueCompilerWarning(str, 2); if (FnSymbol* fn = toFnSymbol(callStack.v[callStack.n-2]->isResolved())) outerCompilerWarningMap.put(fn, str); } if (const char* str = outerCompilerWarningMap.get(resolvedFn)) { reissueCompilerWarning(str, 1); } } static void lvalueCheck(CallExpr* call) { // Check to ensure the actual supplied to an OUT, INOUT or REF argument // is an lvalue. for_formals_actuals(formal, actual, call) { bool errorMsg = false; switch (formal->intent) { case INTENT_BLANK: case INTENT_IN: case INTENT_CONST: case INTENT_CONST_IN: case INTENT_PARAM: case INTENT_TYPE: // not checking them here break; case INTENT_INOUT: case INTENT_OUT: case INTENT_REF: if (!isLegalLvalueActualArg(formal, actual)) errorMsg = true; break; case INTENT_CONST_REF: if (!isLegalConstRefActualArg(formal, actual)) errorMsg = true; break; default: // all intents should be covered above INT_ASSERT(false); break; } if (errorMsg && checkAndUpdateIfLegalFieldOfThis(call, actual)) { errorMsg = false; call->parentSymbol->addFlag(FLAG_MODIFIES_CONST_FIELDS); } if (errorMsg) { FnSymbol* calleeFn = call->isResolved(); INT_ASSERT(calleeFn == formal->defPoint->parentSymbol); // sanity if (calleeFn->hasFlag(FLAG_ASSIGNOP)) { // This assert is FYI. Perhaps can remove it if it fails. INT_ASSERT(callStack.n > 0 && callStack.v[callStack.n-1] == call); const char* recordName = defaultRecordAssignmentTo(toFnSymbol(call->parentSymbol)); if (recordName && callStack.n >= 2) // blame on the caller of the caller, if available USR_FATAL_CONT(callStack.v[callStack.n-2], "cannot assign to a record of the type %s" " using the default assignment operator" " because it has 'const' field(s)", recordName); else USR_FATAL_CONT(actual, "illegal lvalue in assignment"); } else { ModuleSymbol* mod = calleeFn->getModule(); char cn1 = calleeFn->name[0]; const char* calleeParens = (isalpha(cn1) || cn1 == '_') ? "()" : ""; // Should this be the same condition as in insertLineNumber() ? if (developer || mod->modTag == MOD_USER || mod->modTag == MOD_MAIN) { USR_FATAL_CONT(actual, "non-lvalue actual is passed to %s formal '%s'" " of %s%s", formal->intentDescrString(), formal->name, calleeFn->name, calleeParens); } else { USR_FATAL_CONT(actual, "non-lvalue actual is passed to a %s formal of" " %s%s", formal->intentDescrString(), calleeFn->name, calleeParens); } } } } } static void resolveTupleAndExpand(CallExpr* call) { SymExpr* se = toSymExpr(call->get(1)); int size = 0; for (int i = 0; i < se->var->type->substitutions.n; i++) { if (se->var->type->substitutions.v[i].key) { if (!strcmp("size", se->var->type->substitutions.v[i].key->name)) { size = toVarSymbol(se->var->type->substitutions.v[i].value)->immediate->int_value(); break; } } } INT_ASSERT(size); CallExpr* noop = new CallExpr(PRIM_NOOP); call->getStmtExpr()->insertBefore(noop); VarSymbol* tmp = gTrue; for (int i = 1; i <= size; i++) { VarSymbol* tmp1 = newTemp("_tuple_and_expand_tmp_"); tmp1->addFlag(FLAG_MAYBE_PARAM); tmp1->addFlag(FLAG_MAYBE_TYPE); VarSymbol* tmp2 = newTemp("_tuple_and_expand_tmp_"); tmp2->addFlag(FLAG_MAYBE_PARAM); tmp2->addFlag(FLAG_MAYBE_TYPE); VarSymbol* tmp3 = newTemp("_tuple_and_expand_tmp_"); tmp3->addFlag(FLAG_MAYBE_PARAM); tmp3->addFlag(FLAG_MAYBE_TYPE); VarSymbol* tmp4 = newTemp("_tuple_and_expand_tmp_"); tmp4->addFlag(FLAG_MAYBE_PARAM); tmp4->addFlag(FLAG_MAYBE_TYPE); call->getStmtExpr()->insertBefore(new DefExpr(tmp1)); call->getStmtExpr()->insertBefore(new DefExpr(tmp2)); call->getStmtExpr()->insertBefore(new DefExpr(tmp3)); call->getStmtExpr()->insertBefore(new DefExpr(tmp4)); call->getStmtExpr()->insertBefore( new CallExpr(PRIM_MOVE, tmp1, new CallExpr(se->copy(), new_IntSymbol(i)))); CallExpr* query = new CallExpr(PRIM_QUERY, tmp1); for (int i = 2; i < call->numActuals(); i++) query->insertAtTail(call->get(i)->copy()); call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp2, query)); call->getStmtExpr()->insertBefore( new CallExpr(PRIM_MOVE, tmp3, new CallExpr("==", tmp2, call->get(3)->copy()))); call->getStmtExpr()->insertBefore( new CallExpr(PRIM_MOVE, tmp4, new CallExpr("&", tmp3, tmp))); tmp = tmp4; } call->replace(new SymExpr(tmp)); noop->replace(call); // put call back in ast for function resolution makeNoop(call); } static void resolveTupleExpand(CallExpr* call) { SymExpr* sym = toSymExpr(call->get(1)); Type* type = sym->var->getValType(); if (!type->symbol->hasFlag(FLAG_TUPLE)) USR_FATAL(call, "invalid tuple expand primitive"); int size = 0; for (int i = 0; i < type->substitutions.n; i++) { if (type->substitutions.v[i].key) { if (!strcmp("size", type->substitutions.v[i].key->name)) { size = toVarSymbol(type->substitutions.v[i].value)->immediate->int_value(); break; } } } if (size == 0) INT_FATAL(call, "Invalid tuple expand primitive"); CallExpr* parent = toCallExpr(call->parentExpr); CallExpr* noop = new CallExpr(PRIM_NOOP); call->getStmtExpr()->insertBefore(noop); for (int i = 1; i <= size; i++) { VarSymbol* tmp = newTemp("_tuple_expand_tmp_"); tmp->addFlag(FLAG_MAYBE_TYPE); DefExpr* def = new DefExpr(tmp); call->getStmtExpr()->insertBefore(def); CallExpr* e = NULL; if (!call->parentSymbol->hasFlag(FLAG_EXPAND_TUPLES_WITH_VALUES)) { e = new CallExpr(sym->copy(), new_IntSymbol(i)); } else { e = new CallExpr(PRIM_GET_MEMBER_VALUE, sym->copy(), new_StringSymbol(astr("x", istr(i)))); } CallExpr* move = new CallExpr(PRIM_MOVE, tmp, e); call->getStmtExpr()->insertBefore(move); call->insertBefore(new SymExpr(tmp)); } call->remove(); noop->replace(call); // put call back in ast for function resolution makeNoop(call); // increase tuple rank if (parent && parent->isNamed("_type_construct__tuple")) { parent->get(1)->replace(new SymExpr(new_IntSymbol(parent->numActuals()-1))); } } static void resolveSetMember(CallExpr* call) { // Get the field name. SymExpr* sym = toSymExpr(call->get(2)); if (!sym) INT_FATAL(call, "bad set member primitive"); VarSymbol* var = toVarSymbol(sym->var); if (!var || !var->immediate) INT_FATAL(call, "bad set member primitive"); const char* name = var->immediate->v_string; // Special case: An integer field name is actually a tuple member index. { int64_t i; if (get_int(sym, &i)) { name = astr("x", istr(i)); call->get(2)->replace(new SymExpr(new_StringSymbol(name))); } } AggregateType* ct = toAggregateType(call->get(1)->typeInfo()); if (!ct) INT_FATAL(call, "bad set member primitive"); Symbol* fs = NULL; for_fields(field, ct) { if (!strcmp(field->name, name)) { fs = field; break; } } if (!fs) INT_FATAL(call, "bad set member primitive"); Type* t = call->get(3)->typeInfo(); // I think this never happens, so can be turned into an assert. <hilde> if (t == dtUnknown) INT_FATAL(call, "Unable to resolve field type"); if (t == dtNil && fs->type == dtUnknown) USR_FATAL(call->parentSymbol, "unable to determine type of field from nil"); if (fs->type == dtUnknown) fs->type = t; if (t != fs->type && t != dtNil && t != dtObject) { USR_FATAL(userCall(call), "cannot assign expression of type %s to field of type %s", toString(t), toString(fs->type)); } } static void resolveMove(CallExpr* call) { Expr* rhs = call->get(2); Symbol* lhs = NULL; if (SymExpr* se = toSymExpr(call->get(1))) lhs = se->var; INT_ASSERT(lhs); FnSymbol* fn = toFnSymbol(call->parentSymbol); if (lhs->hasFlag(FLAG_TYPE_VARIABLE) && !isTypeExpr(rhs)) { if (lhs == fn->getReturnSymbol()) { if (!fn->hasFlag(FLAG_RUNTIME_TYPE_INIT_FN)) USR_FATAL(call, "illegal return of value where type is expected"); } else { USR_FATAL(call, "illegal assignment of value to type"); } } if (!lhs->hasFlag(FLAG_TYPE_VARIABLE) && !lhs->hasFlag(FLAG_MAYBE_TYPE) && isTypeExpr(rhs)) { if (lhs == fn->getReturnSymbol()) { USR_FATAL(call, "illegal return of type where value is expected"); } else { USR_FATAL(call, "illegal assignment of type to value"); } } // do not resolve function return type yet // except for constructors if (fn && call->parentExpr != fn->where && call->parentExpr != fn->retExprType && fn->getReturnSymbol() == lhs && fn->_this != lhs) { if (fn->retType == dtUnknown) { return; } } Type* rhsType = rhs->typeInfo(); if (rhsType == dtVoid) { if (lhs == fn->getReturnSymbol() && (lhs->type == dtVoid || lhs->type == dtUnknown)) { // It is OK to assign void to the return value variable as long as its // type is void or is not yet established. } else { if (CallExpr* rhsFn = toCallExpr(rhs)) { if (FnSymbol* rhsFnSym = rhsFn->isResolved()) { USR_FATAL(userCall(call), "illegal use of function that does not return a value: '%s'", rhsFnSym->name); } } USR_FATAL(userCall(call), "illegal use of function that does not return a value"); } } if (lhs->type == dtUnknown || lhs->type == dtNil) lhs->type = rhsType; Type* lhsType = lhs->type; if (CallExpr* call = toCallExpr(rhs)) { if (FnSymbol* fn = call->isResolved()) { if (rhsType == dtUnknown) { USR_FATAL_CONT(fn, "unable to resolve return type of function '%s'", fn->name); USR_FATAL(rhs, "called recursively at this point"); } } } if (rhsType == dtUnknown) USR_FATAL(call, "unable to resolve type"); if (rhsType == dtNil && lhsType != dtNil && !isClass(lhsType)) USR_FATAL(userCall(call), "type mismatch in assignment from nil to %s", toString(lhsType)); Type* lhsBaseType = lhsType->getValType(); Type* rhsBaseType = rhsType->getValType(); bool isChplHereAlloc = false; // Fix up calls inserted by callChplHereAlloc() if (CallExpr* rhsCall = toCallExpr(rhs)) { // Here we are going to fix up calls inserted by // callChplHereAlloc() and callChplHereFree() // // Currently this code assumes that such primitives are only // inserted by the compiler. TODO: Add a check to make sure // these are the ones added by the above functions. // if (rhsCall->isPrimitive(PRIM_SIZEOF)) { // Fix up arg to sizeof(), as we may not have known the // type earlier SymExpr* sizeSym = toSymExpr(rhsCall->get(1)); INT_ASSERT(sizeSym); rhs->replace(new CallExpr(PRIM_SIZEOF, sizeSym->var->typeInfo()->symbol)); return; } else if (rhsCall->isPrimitive(PRIM_CAST_TO_VOID_STAR)) { if (isReferenceType(rhsCall->get(1)->typeInfo())) { // Add a dereference as needed, as we did not have complete // type information earlier SymExpr* castVar = toSymExpr(rhsCall->get(1)); INT_ASSERT(castVar); VarSymbol* derefTmp = newTemp("castDeref", castVar->typeInfo()->getValType()); call->insertBefore(new DefExpr(derefTmp)); call->insertBefore(new CallExpr(PRIM_MOVE, derefTmp, new CallExpr(PRIM_DEREF, new SymExpr(castVar->var)))); rhsCall->replace(new CallExpr(PRIM_CAST_TO_VOID_STAR, new SymExpr(derefTmp))); } } else if (rhsCall->isResolved() == gChplHereAlloc) { // Insert cast below for calls to chpl_here_*alloc() isChplHereAlloc = true; } } if (!isChplHereAlloc && rhsType != dtNil && rhsBaseType != lhsBaseType && !isDispatchParent(rhsBaseType, lhsBaseType)) USR_FATAL(userCall(call), "type mismatch in assignment from %s to %s", toString(rhsType), toString(lhsType)); if (isChplHereAlloc || (rhsType != lhsType && isDispatchParent(rhsBaseType, lhsBaseType))) { Symbol* tmp = newTemp("cast_tmp", rhsType); call->insertBefore(new DefExpr(tmp)); call->insertBefore(new CallExpr(PRIM_MOVE, tmp, rhs->remove())); call->insertAtTail(new CallExpr(PRIM_CAST, isChplHereAlloc ? lhs->type->symbol : lhsBaseType->symbol, tmp)); } } // Some new expressions are converted in normalize(). For example, a call to a // type function is resolved at this point. // The syntax supports calling the result of a type function as a constructor, // but this is not fully implemented. static void resolveNew(CallExpr* call) { // This is a 'new' primitive, so we expect the argument to be a constructor // call. CallExpr* ctor = toCallExpr(call->get(1)); // May need to resolve ctor here. if (FnSymbol* fn = ctor->isResolved()) { // If the function is a constructor, just bridge out the 'new' primitive // and call the constructor. Done. if (fn->hasFlag(FLAG_CONSTRUCTOR)) { call->replace(ctor); return; } // Not a constructor, so issue an error. USR_FATAL(call, "invalid use of 'new' on %s", fn->name); return; } if (UnresolvedSymExpr* urse = toUnresolvedSymExpr(ctor->baseExpr)) { USR_FATAL(call, "invalid use of 'new' on %s", urse->unresolved); return; } USR_FATAL(call, "invalid use of 'new'"); } // // This tells us whether we can rely on the compiler's back end (e.g., // C) to provide the copy for us for 'in' or 'const in' intents when // passing an argument of type 't'. // static bool backendRequiresCopyForIn(Type* t) { return (isRecord(t) || t->symbol->hasFlag(FLAG_ARRAY) || t->symbol->hasFlag(FLAG_DOMAIN)); } // Returns true if the formal needs an internal temporary, false otherwise. static bool formalRequiresTemp(ArgSymbol* formal) { // // get the formal's function // FnSymbol* fn = toFnSymbol(formal->defPoint->parentSymbol); INT_ASSERT(fn); return // // 'out' and 'inout' intents are passed by ref at the C level, so we // need to make an explicit copy in the codegen'd function */ // (formal->intent == INTENT_OUT || formal->intent == INTENT_INOUT || // // 'in' and 'const in' also require a copy, but for simple types // (like ints or class references), we can rely on C's copy when // passing the argument, as long as the routine is not // inlined. // ((formal->intent == INTENT_IN || formal->intent == INTENT_CONST_IN) && (backendRequiresCopyForIn(formal->type) || !fn->hasFlag(FLAG_INLINE))) // // The following case reduces memory leaks for zippered forall // leader/follower pairs where the communicated intermediate // result is a tuple of ranges, but I can't explain why it'd be // needed. Tom has said that iterators haven't really been // bolted down in terms of memory leaks, so future work would be // to remove this hack and close the leak properly. // || strcmp(formal->name, "followThis") == 0 ); } static void insertFormalTemps(FnSymbol* fn) { SymbolMap formals2vars; for_formals(formal, fn) { if (formalRequiresTemp(formal)) { SET_LINENO(formal); VarSymbol* tmp = newTemp(astr("_formal_tmp_", formal->name)); formals2vars.put(formal, tmp); } } if (formals2vars.n > 0) { // The names of formals in the body of this function are replaced with the // names of their corresponding local temporaries. update_symbols(fn->body, &formals2vars); // Add calls to chpl__initCopy to create local copies as necessary. // Add writeback code for out and inout intents. addLocalCopiesAndWritebacks(fn, formals2vars); } } // Given the map from formals to local "_formal_tmp_" variables, this function // adds code as necessary // - to copy the formal into the temporary at the start of the function // - and copy it back when done. // The copy in is needed for "inout", "in" and "const in" intents. // The copy out is needed for "inout" and "out" intents. // Blank intent is treated like "const", and normally copies the formal through // chpl__autoCopy. // Note that autoCopy is called in this case, but not for "inout", "in" and "const in". // Either record-wrapped types are always passed by ref, or some unexpected // behavior will result by applying "in" intents to them. static void addLocalCopiesAndWritebacks(FnSymbol* fn, SymbolMap& formals2vars) { // Enumerate the formals that have local temps. form_Map(SymbolMapElem, e, formals2vars) { ArgSymbol* formal = toArgSymbol(e->key); // Get the formal. Symbol* tmp = e->value; // Get the temp. SET_LINENO(formal); // TODO: Move this closer to the location (in code) where we determine // whether tmp owns its value or not. That is, push setting these flags // (or not) into the cases below, as appropriate. Type* formalType = formal->type->getValType(); if ((formal->intent == INTENT_BLANK || formal->intent == INTENT_CONST || formal->intent == INTENT_CONST_IN) && !isSyncType(formalType) && !isRefCountedType(formalType)) { tmp->addFlag(FLAG_CONST); tmp->addFlag(FLAG_INSERT_AUTO_DESTROY); } // This switch adds the extra code inside the current function necessary // to implement the ref-to-value semantics, where needed. switch (formal->intent) { // Make sure we handle every case. default: INT_FATAL("Unhandled INTENT case."); break; // These cases are weeded out by formalRequiresTemp() above. case INTENT_PARAM: case INTENT_TYPE: case INTENT_REF: case INTENT_CONST_REF: INT_FATAL("Unexpected INTENT case."); break; case INTENT_OUT: if (formal->defaultExpr && formal->defaultExpr->body.tail->typeInfo() != dtTypeDefaultToken) { BlockStmt* defaultExpr = formal->defaultExpr->copy(); fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, defaultExpr->body.tail->remove())); fn->insertAtHead(defaultExpr); } else { VarSymbol* refTmp = newTemp("_formal_ref_tmp_"); VarSymbol* typeTmp = newTemp("_formal_type_tmp_"); typeTmp->addFlag(FLAG_MAYBE_TYPE); fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_INIT, typeTmp))); fn->insertAtHead(new CallExpr(PRIM_MOVE, typeTmp, new CallExpr(PRIM_TYPEOF, refTmp))); fn->insertAtHead(new CallExpr(PRIM_MOVE, refTmp, new CallExpr(PRIM_DEREF, formal))); fn->insertAtHead(new DefExpr(refTmp)); fn->insertAtHead(new DefExpr(typeTmp)); } break; case INTENT_INOUT: case INTENT_IN: case INTENT_CONST_IN: // TODO: Adding a formal temp for INTENT_CONST_IN is conservative. // If the compiler verifies in a separate pass that it is never written, // we don't have to copy it. fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr("chpl__initCopy", formal))); tmp->addFlag(FLAG_INSERT_AUTO_DESTROY); break; case INTENT_BLANK: case INTENT_CONST: { TypeSymbol* ts = formal->type->symbol; if (!getRecordWrappedFlags(ts).any() && !ts->hasFlag(FLAG_ITERATOR_CLASS) && !ts->hasFlag(FLAG_ITERATOR_RECORD) && !getSyncFlags(ts).any()) { if (fn->hasFlag(FLAG_BEGIN)) { // autoCopy/autoDestroy will be added later, in parallel pass // by insertAutoCopyDestroyForTaskArg() fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, formal)); tmp->removeFlag(FLAG_INSERT_AUTO_DESTROY); } else { // Note that because we reject the case of record-wrapped types above, // the only way we can get a formal whose call to chpl__autoCopy does // anything different from calling chpl__initCopy is if the formal is a // tuple containing a record-wrapped type. This is probably not // intentional: It gives tuple-wrapped record-wrapped types different // behavior from bare record-wrapped types. fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, new CallExpr("chpl__autoCopy", formal))); // WORKAROUND: // This is a temporary bug fix that results in leaked memory. // // Here we avoid calling the destructor for any formals that // are records or have records because the call may result // in repeatedly freeing memory if the user defined // destructor calls delete on any fields. I think we // probably need a similar change in the INOUT/IN case // above. See test/types/records/sungeun/destructor3.chpl // and test/users/recordbug3.chpl. // // For records, this problem should go away if/when we // implement 'const ref' intents and make them the default // for records. // // Another solution (and the one that would fix records in // classes) is to call the user record's default // constructor if it takes no arguments. This is not the // currently described behavior in the spec. This would // require the user to implement a default constructor if // explicit memory allocation is required. // if (!isAggregateType(formal->type) || (isRecord(formal->type) && ((formal->type->getModule()->modTag==MOD_INTERNAL) || (formal->type->getModule()->modTag==MOD_STANDARD))) || !typeHasRefField(formal->type)) tmp->addFlag(FLAG_INSERT_AUTO_DESTROY); } } else { fn->insertAtHead(new CallExpr(PRIM_MOVE, tmp, formal)); // If this is a simple move, then we did not call chpl__autoCopy to // create tmp, so then it is a bad idea to insert a call to // chpl__autodestroy later. tmp->removeFlag(FLAG_INSERT_AUTO_DESTROY); } break; } } fn->insertAtHead(new DefExpr(tmp)); // For inout or out intent, this assigns the modified value back to the // formal at the end of the function body. if (formal->intent == INTENT_INOUT || formal->intent == INTENT_OUT) { fn->insertBeforeReturnAfterLabel(new CallExpr("=", formal, tmp)); } } } // // Calculate the index type for a param for loop by checking the type of // the range that would be built using the same low and high values. // static Type* param_for_index_type(CallExpr* loop) { BlockStmt* block = toBlockStmt(loop->parentExpr); SymExpr* lse = toSymExpr(loop->get(2)); SymExpr* hse = toSymExpr(loop->get(3)); CallExpr* range = new CallExpr("_build_range", lse->copy(), hse->copy()); block->insertBefore(range); resolveCall(range); if (!range->isResolved()) { INT_FATAL("unresolved range"); } resolveFormals(range->isResolved()); DefExpr* formal = toDefExpr(range->isResolved()->formals.get(1)); Type* formalType; if (toArgSymbol(formal->sym)->typeExpr) { // range->isResolved() is the coercion wrapper for _build_range formalType = toArgSymbol(formal->sym)->typeExpr->body.tail->typeInfo(); } else { formalType = formal->sym->type; } range->remove(); return formalType; } static void fold_param_for(CallExpr* loop) { BlockStmt* block = toBlockStmt(loop->parentExpr); SymExpr* lse = toSymExpr(loop->get(2)); SymExpr* hse = toSymExpr(loop->get(3)); SymExpr* sse = toSymExpr(loop->get(4)); if (!block || !lse || !hse || !sse) USR_FATAL(loop, "param for loop must be defined over a param range"); VarSymbol* lvar = toVarSymbol(lse->var); VarSymbol* hvar = toVarSymbol(hse->var); VarSymbol* svar = toVarSymbol(sse->var); if (!lvar || !hvar || !svar) USR_FATAL(loop, "param for loop must be defined over a param range"); if (!lvar->immediate || !hvar->immediate || !svar->immediate) USR_FATAL(loop, "param for loop must be defined over a param range"); Expr* index_expr = loop->get(1); Type* formalType = param_for_index_type(loop); IF1_int_type idx_size; if (get_width(formalType) == 32) { idx_size = INT_SIZE_32; } else { idx_size = INT_SIZE_64; } if (block->blockTag != BLOCK_NORMAL) INT_FATAL("ha"); loop->remove(); CallExpr* noop = new CallExpr(PRIM_NOOP); block->insertAfter(noop); Symbol* index = toSymExpr(index_expr)->var; if (is_int_type(formalType)) { int64_t low = lvar->immediate->int_value(); int64_t high = hvar->immediate->int_value(); int64_t stride = svar->immediate->int_value(); if (stride <= 0) { for (int64_t i = high; i >= low; i += stride) { SymbolMap map; map.put(index, new_IntSymbol(i, idx_size)); noop->insertBefore(block->copy(&map)); } } else { for (int64_t i = low; i <= high; i += stride) { SymbolMap map; map.put(index, new_IntSymbol(i, idx_size)); noop->insertBefore(block->copy(&map)); } } } else { INT_ASSERT(is_uint_type(formalType) || is_bool_type(formalType)); uint64_t low = lvar->immediate->uint_value(); uint64_t high = hvar->immediate->uint_value(); int64_t stride = svar->immediate->int_value(); if (stride <= 0) { for (uint64_t i = high; i >= low; i += stride) { SymbolMap map; map.put(index, new_UIntSymbol(i, idx_size)); noop->insertBefore(block->copy(&map)); } } else { for (uint64_t i = low; i <= high; i += stride) { SymbolMap map; map.put(index, new_UIntSymbol(i, idx_size)); noop->insertBefore(block->copy(&map)); } } } block->replace(loop); makeNoop(loop); } static Expr* dropUnnecessaryCast(CallExpr* call) { // Check for and remove casts to the original type and size Expr* result = call; if (!call->isNamed("_cast")) INT_FATAL("dropUnnecessaryCasts called on non _cast call"); if (SymExpr* sym = toSymExpr(call->get(2))) { if (VarSymbol* var = toVarSymbol(sym->var)) { if (SymExpr* sym = toSymExpr(call->get(1))) { Type* oldType = var->type; Type* newType = sym->var->type; if (newType == oldType) { result = new SymExpr(var); call->replace(result); } } } else if (EnumSymbol* e = toEnumSymbol(sym->var)) { if (SymExpr* sym = toSymExpr(call->get(1))) { EnumType* oldType = toEnumType(e->type); EnumType* newType = toEnumType(sym->var->type); if (newType && oldType == newType) { result = new SymExpr(e); call->replace(result); } } } } return result; } /* Creates the parent class which will represent the function's type. Children of the parent class will capture different functions which happen to share the same function type. By using the parent class we can assign new values onto variable that match the function type but may currently be pointing at a different function. */ static AggregateType* createAndInsertFunParentClass(CallExpr *call, const char *name) { AggregateType *parent = new AggregateType(AGGREGATE_CLASS); TypeSymbol *parent_ts = new TypeSymbol(name, parent); parent_ts->addFlag(FLAG_FUNCTION_CLASS); // Because this function type needs to be globally visible (because we don't know the modules it will be passed to), we put // it at the highest scope theProgram->block->body.insertAtTail(new DefExpr(parent_ts)); parent->dispatchParents.add(dtObject); dtObject->dispatchChildren.add(parent); VarSymbol* parent_super = new VarSymbol("super", dtObject); parent_super->addFlag(FLAG_SUPER_CLASS); parent->fields.insertAtHead(new DefExpr(parent_super)); build_constructors(parent); return parent; } /* To mimic a function call, we create a .this method for the parent class. This will allow the object to look and feel like a first-class function, by both being an object and being invoked using parentheses syntax. Children of the parent class will override this method and wrap the function that is being used as a first-class value. To focus on just the types of the arguments and not their names or default values, we use the parent method's names and types as the basis for all children which override it. The function is put at the highest scope so that all functions of a given type will share the same parent class. */ static FnSymbol* createAndInsertFunParentMethod(CallExpr *call, AggregateType *parent, AList &arg_list, bool isFormal, Type *retType) { FnSymbol* parent_method = new FnSymbol("this"); parent_method->addFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION); parent_method->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken)); ArgSymbol* thisParentSymbol = new ArgSymbol(INTENT_BLANK, "this", parent); thisParentSymbol->addFlag(FLAG_ARG_THIS); parent_method->insertFormalAtTail(thisParentSymbol); parent_method->_this = thisParentSymbol; int i = 0, alength = arg_list.length; //We handle the arg list differently depending on if it's a list of formal args or actual args if (isFormal) { for_alist(formalExpr, arg_list) { DefExpr* dExp = toDefExpr(formalExpr); ArgSymbol* fArg = toArgSymbol(dExp->sym); if (fArg->type != dtVoid) { ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, fArg->name, fArg->type); if (fArg->typeExpr) newFormal->typeExpr = fArg->typeExpr->copy(); parent_method->insertFormalAtTail(newFormal); } } } else { char name_buffer[100]; int name_index = 0; for_alist(actualExpr, arg_list) { sprintf(name_buffer, "name%i", name_index++); if (i != (alength-1)) { SymExpr* sExpr = toSymExpr(actualExpr); if (sExpr->var->type != dtVoid) { ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, name_buffer, sExpr->var->type); parent_method->insertFormalAtTail(newFormal); } } ++i; } } if (retType != dtVoid) { VarSymbol *tmp = newTemp("_return_tmp_", retType); parent_method->insertAtTail(new DefExpr(tmp)); parent_method->insertAtTail(new CallExpr(PRIM_RETURN, tmp)); } // Because this function type needs to be globally visible (because we don't know the modules it will be passed to), we put // it at the highest scope theProgram->block->body.insertAtTail(new DefExpr(parent_method)); normalize(parent_method); parent->methods.add(parent_method); return parent_method; } /* Builds up the name of the parent for lookup by looking through the types of the arguments, either formal or actual */ static std::string buildParentName(AList &arg_list, bool isFormal, Type *retType) { std::ostringstream oss; oss << "chpl__fcf_type_"; bool isFirst = true; if (isFormal) { if (arg_list.length == 0) { oss << "void"; } else { for_alist(formalExpr, arg_list) { DefExpr* dExp = toDefExpr(formalExpr); ArgSymbol* fArg = toArgSymbol(dExp->sym); if (!isFirst) oss << "_"; oss << fArg->type->symbol->cname; isFirst = false; } } oss << "_"; oss << retType->symbol->cname; } else { int i = 0, alength = arg_list.length; if (alength == 1) { oss << "void_"; } for_alist(actualExpr, arg_list) { if (!isFirst) oss << "_"; SymExpr* sExpr = toSymExpr(actualExpr); ++i; oss << sExpr->var->type->symbol->cname; isFirst = false; } } return oss.str(); } /* Helper function for creating or finding the parent class for a given function type specified by the type signature. The last type given in the signature is the return type, the remainder represent arguments to the function. */ static AggregateType* createOrFindFunTypeFromAnnotation(AList &arg_list, CallExpr *call) { AggregateType *parent; SymExpr *retTail = toSymExpr(arg_list.tail); Type *retType = retTail->var->type; std::string parent_name = buildParentName(arg_list, false, retType); if (functionTypeMap.find(parent_name) != functionTypeMap.end()) { parent = functionTypeMap[parent_name].first; } else { parent = createAndInsertFunParentClass(call, parent_name.c_str()); FnSymbol* parent_method = createAndInsertFunParentMethod(call, parent, arg_list, false, retType); functionTypeMap[parent_name] = std::pair<AggregateType*, FnSymbol*>(parent, parent_method); } return parent; } /* Captures a function as a first-class value by creating an object that will represent the function. The class is created at the same scope as the function being referenced. Each class is unique and shared among all uses of that function as a value. Once built, the class will override the .this method of the parent and wrap the call to the function being captured as a value. Then, an instance of the class is instantiated and returned. */ static Expr* createFunctionAsValue(CallExpr *call) { static int unique_fcf_id = 0; UnresolvedSymExpr* use = toUnresolvedSymExpr(call->get(1)); INT_ASSERT(use); const char *flname = use->unresolved; Vec<FnSymbol*> visibleFns; Vec<BlockStmt*> visited; getVisibleFunctions(getVisibilityBlock(call), flname, visibleFns, visited); if (visibleFns.n > 1) { USR_FATAL(call, "%s: can not capture overloaded functions as values", visibleFns.v[0]->name); } INT_ASSERT(visibleFns.n == 1); FnSymbol* captured_fn = visibleFns.head(); //Check to see if we've already cached the capture somewhere if (functionCaptureMap.find(captured_fn) != functionCaptureMap.end()) { return new CallExpr(functionCaptureMap[captured_fn]); } resolveFormals(captured_fn); resolveFns(captured_fn); AggregateType *parent; FnSymbol *thisParentMethod; std::string parent_name = buildParentName(captured_fn->formals, true, captured_fn->retType); if (functionTypeMap.find(parent_name) != functionTypeMap.end()) { std::pair<AggregateType*, FnSymbol*> ctfs = functionTypeMap[parent_name]; parent = ctfs.first; thisParentMethod = ctfs.second; } else { parent = createAndInsertFunParentClass(call, parent_name.c_str()); thisParentMethod = createAndInsertFunParentMethod(call, parent, captured_fn->formals, true, captured_fn->retType); functionTypeMap[parent_name] = std::pair<AggregateType*, FnSymbol*>(parent, thisParentMethod); } AggregateType *ct = new AggregateType(AGGREGATE_CLASS); std::ostringstream fcf_name; fcf_name << "_chpl_fcf_" << unique_fcf_id++ << "_" << flname; TypeSymbol *ts = new TypeSymbol(astr(fcf_name.str().c_str()), ct); call->parentExpr->insertBefore(new DefExpr(ts)); ct->dispatchParents.add(parent); bool inserted = parent->dispatchChildren.add_exclusive(ct); INT_ASSERT(inserted); VarSymbol* super = new VarSymbol("super", parent); super->addFlag(FLAG_SUPER_CLASS); ct->fields.insertAtHead(new DefExpr(super)); build_constructors(ct); FnSymbol *thisMethod = new FnSymbol("this"); thisMethod->addFlag(FLAG_FIRST_CLASS_FUNCTION_INVOCATION); thisMethod->insertFormalAtTail(new ArgSymbol(INTENT_BLANK, "_mt", dtMethodToken)); ArgSymbol *thisSymbol = new ArgSymbol(INTENT_BLANK, "this", ct); thisSymbol->addFlag(FLAG_ARG_THIS); thisMethod->insertFormalAtTail(thisSymbol); thisMethod->_this = thisSymbol; CallExpr *innerCall = new CallExpr(captured_fn); int skip = 2; for_alist(formalExpr, thisParentMethod->formals) { //Skip the first two arguments from the parent, which are _mt and this if (skip) { --skip; continue; } DefExpr* dExp = toDefExpr(formalExpr); ArgSymbol* fArg = toArgSymbol(dExp->sym); ArgSymbol* newFormal = new ArgSymbol(INTENT_BLANK, fArg->name, fArg->type); if (fArg->typeExpr) newFormal->typeExpr = fArg->typeExpr->copy(); SymExpr* argSym = new SymExpr(newFormal); innerCall->insertAtTail(argSym); thisMethod->insertFormalAtTail(newFormal); } Vec<CallExpr*> calls; collectCallExprs(captured_fn, calls); forv_Vec(CallExpr, cl, calls) { if (cl->isPrimitive(PRIM_YIELD)) { USR_FATAL_CONT(cl, "Iterators not allowed in first class functions"); } } if (captured_fn->retType == dtVoid) { thisMethod->insertAtTail(innerCall); } else { VarSymbol *tmp = newTemp("_return_tmp_"); thisMethod->insertAtTail(new DefExpr(tmp)); thisMethod->insertAtTail(new CallExpr(PRIM_MOVE, tmp, innerCall)); thisMethod->insertAtTail(new CallExpr(PRIM_RETURN, tmp)); } call->parentExpr->insertBefore(new DefExpr(thisMethod)); normalize(thisMethod); ct->methods.add(thisMethod); FnSymbol *wrapper = new FnSymbol("wrapper"); wrapper->addFlag(FLAG_INLINE); wrapper->insertAtTail(new CallExpr(PRIM_RETURN, new CallExpr(PRIM_CAST, parent->symbol, new CallExpr(ct->defaultInitializer)))); call->getStmtExpr()->insertBefore(new DefExpr(wrapper)); normalize(wrapper); CallExpr *call_wrapper = new CallExpr(wrapper); functionCaptureMap[captured_fn] = wrapper; return call_wrapper; } // // returns true if the symbol is defined in an outer function to fn // third argument not used at call site // static bool isOuterVar(Symbol* sym, FnSymbol* fn, Symbol* parent /* = NULL*/) { if (!parent) parent = fn->defPoint->parentSymbol; if (!isFnSymbol(parent)) return false; else if (sym->defPoint->parentSymbol == parent) return true; else return isOuterVar(sym, fn, parent->defPoint->parentSymbol); } // // finds outer vars directly used in a function // static bool usesOuterVars(FnSymbol* fn, Vec<FnSymbol*> &seen) { Vec<BaseAST*> asts; collect_asts(fn, asts); forv_Vec(BaseAST, ast, asts) { if (toCallExpr(ast)) { CallExpr *call = toCallExpr(ast); //dive into calls Vec<FnSymbol*> visibleFns; Vec<BlockStmt*> visited; getVisibleFunctions(getVisibilityBlock(call), call->parentSymbol->name, visibleFns, visited); forv_Vec(FnSymbol, called_fn, visibleFns) { bool seen_this_fn = false; forv_Vec(FnSymbol, seen_fn, seen) { if (called_fn == seen_fn) { seen_this_fn = true; break; } } if (!seen_this_fn) { seen.add(called_fn); if (usesOuterVars(called_fn, seen)) { return true; } } } } if (SymExpr* symExpr = toSymExpr(ast)) { Symbol* sym = symExpr->var; if (toVarSymbol(sym) || toArgSymbol(sym)) if (isOuterVar(sym, fn)) return true; } } return false; } static bool isNormalField(Symbol* field) { if( field->hasFlag(FLAG_IMPLICIT_ALIAS_FIELD) ) return false; if( field->hasFlag(FLAG_TYPE_VARIABLE) ) return false; if( field->hasFlag(FLAG_SUPER_CLASS) ) return false; // TODO -- this will break user fields named outer! if( 0 == strcmp("outer", field->name)) return false; return true; } static Expr* preFold(Expr* expr) { Expr* result = expr; if (CallExpr* call = toCallExpr(expr)) { // Match calls that look like: (<type-symbol> <immediate-integer>) // and replace them with: <new-type-symbol> // <type-symbol> is in {dtBools, dtInt, dtUint, dtReal, dtImag, dtComplex}. // This replaces, e.g. ( dtInt[INT_SIZE_DEFAULT] 32) with dtInt[INT_SIZE_32]. if (SymExpr* sym = toSymExpr(call->baseExpr)) { if (TypeSymbol* type = toTypeSymbol(sym->var)) { if (call->numActuals() == 1) { if (SymExpr* arg = toSymExpr(call->get(1))) { if (VarSymbol* var = toVarSymbol(arg->var)) { if (var->immediate) { if (NUM_KIND_INT == var->immediate->const_kind || NUM_KIND_UINT == var->immediate->const_kind) { int size; if (NUM_KIND_INT == var->immediate->const_kind) { size = var->immediate->int_value(); } else { size = (int)var->immediate->uint_value(); } TypeSymbol* tsize = NULL; if (type == dtBools[BOOL_SIZE_SYS]->symbol) { switch (size) { case 8: tsize = dtBools[BOOL_SIZE_8]->symbol; break; case 16: tsize = dtBools[BOOL_SIZE_16]->symbol; break; case 32: tsize = dtBools[BOOL_SIZE_32]->symbol; break; case 64: tsize = dtBools[BOOL_SIZE_64]->symbol; break; default: USR_FATAL( call, "illegal size %d for bool", size); } result = new SymExpr(tsize); call->replace(result); } else if (type == dtInt[INT_SIZE_DEFAULT]->symbol) { switch (size) { case 8: tsize = dtInt[INT_SIZE_8]->symbol; break; case 16: tsize = dtInt[INT_SIZE_16]->symbol; break; case 32: tsize = dtInt[INT_SIZE_32]->symbol; break; case 64: tsize = dtInt[INT_SIZE_64]->symbol; break; default: USR_FATAL( call, "illegal size %d for int", size); } result = new SymExpr(tsize); call->replace(result); } else if (type == dtUInt[INT_SIZE_DEFAULT]->symbol) { switch (size) { case 8: tsize = dtUInt[INT_SIZE_8]->symbol; break; case 16: tsize = dtUInt[INT_SIZE_16]->symbol; break; case 32: tsize = dtUInt[INT_SIZE_32]->symbol; break; case 64: tsize = dtUInt[INT_SIZE_64]->symbol; break; default: USR_FATAL( call, "illegal size %d for uint", size); } result = new SymExpr(tsize); call->replace(result); } else if (type == dtReal[FLOAT_SIZE_64]->symbol) { switch (size) { case 32: tsize = dtReal[FLOAT_SIZE_32]->symbol; break; case 64: tsize = dtReal[FLOAT_SIZE_64]->symbol; break; default: USR_FATAL( call, "illegal size %d for real", size); } result = new SymExpr(tsize); call->replace(result); } else if (type == dtImag[FLOAT_SIZE_64]->symbol) { switch (size) { case 32: tsize = dtImag[FLOAT_SIZE_32]->symbol; break; case 64: tsize = dtImag[FLOAT_SIZE_64]->symbol; break; default: USR_FATAL( call, "illegal size %d for imag", size); } result = new SymExpr(tsize); call->replace(result); } else if (type == dtComplex[COMPLEX_SIZE_128]->symbol) { switch (size) { case 64: tsize = dtComplex[COMPLEX_SIZE_64]->symbol; break; case 128: tsize = dtComplex[COMPLEX_SIZE_128]->symbol; break; default: USR_FATAL( call, "illegal size %d for complex", size); } result = new SymExpr(tsize); call->replace(result); } } } } } } } } if (SymExpr* sym = toSymExpr(call->baseExpr)) { if (toVarSymbol(sym->var) || toArgSymbol(sym->var)) { Expr* base = call->baseExpr; base->replace(new UnresolvedSymExpr("this")); call->insertAtHead(base); call->insertAtHead(gMethodToken); } } if (CallExpr* base = toCallExpr(call->baseExpr)) { if (base->partialTag) { for_actuals_backward(actual, base) { actual->remove(); call->insertAtHead(actual); } base->replace(base->baseExpr->remove()); } else { VarSymbol* this_temp = newTemp("_this_tmp_"); this_temp->addFlag(FLAG_EXPR_TEMP); base->replace(new UnresolvedSymExpr("this")); CallExpr* move = new CallExpr(PRIM_MOVE, this_temp, base); call->insertAtHead(new SymExpr(this_temp)); call->insertAtHead(gMethodToken); call->getStmtExpr()->insertBefore(new DefExpr(this_temp)); call->getStmtExpr()->insertBefore(move); result = move; return result; } } if (call->isNamed("this")) { SymExpr* base = toSymExpr(call->get(2)); INT_ASSERT(base); if (isVarSymbol(base->var) && base->var->hasFlag(FLAG_TYPE_VARIABLE)) { if (call->numActuals() == 2) USR_FATAL(call, "illegal call of type"); int64_t index; if (!get_int(call->get(3), &index)) USR_FATAL(call, "illegal type index expression"); char field[8]; sprintf(field, "x%" PRId64, index); result = new SymExpr(base->var->type->getField(field)->type->symbol); call->replace(result); } else if (base && (isVarSymbol(base->var) || isArgSymbol(base->var))) { // // resolve tuple indexing by an integral parameter // Type* t = base->var->getValType(); if (t->symbol->hasFlag(FLAG_TUPLE)) { if (call->numActuals() != 3) USR_FATAL(call, "illegal tuple indexing expression"); Type* indexType = call->get(3)->getValType(); if (!is_int_type(indexType) && !is_uint_type(indexType)) USR_FATAL(call, "tuple indexing expression is not of integral type"); int64_t index; uint64_t uindex; if (get_int(call->get(3), &index)) { char field[8]; sprintf(field, "x%" PRId64, index); if (index <= 0 || index >= toAggregateType(t)->fields.length) USR_FATAL(call, "tuple index out-of-bounds error (%ld)", index); if (toAggregateType(t)->getField(field)->type->symbol->hasFlag(FLAG_REF)) result = new CallExpr(PRIM_GET_MEMBER_VALUE, base->var, new_StringSymbol(field)); else result = new CallExpr(PRIM_GET_MEMBER, base->var, new_StringSymbol(field)); call->replace(result); } else if (get_uint(call->get(3), &uindex)) { char field[8]; sprintf(field, "x%" PRIu64, uindex); if (uindex <= 0 || uindex >= (unsigned long)toAggregateType(t)->fields.length) USR_FATAL(call, "tuple index out-of-bounds error (%lu)", uindex); if (toAggregateType(t)->getField(field)->type->symbol->hasFlag(FLAG_REF)) result = new CallExpr(PRIM_GET_MEMBER_VALUE, base->var, new_StringSymbol(field)); else result = new CallExpr(PRIM_GET_MEMBER, base->var, new_StringSymbol(field)); call->replace(result); } } } } else if (call->isPrimitive(PRIM_NO_INIT)) { SymExpr* se = toSymExpr(call->get(1)); INT_ASSERT(se); if (!se->var->hasFlag(FLAG_TYPE_VARIABLE)) USR_FATAL(call, "invalid type specification"); Type* type = call->get(1)->getValType(); if (isAggregateType(type)) { if (type->symbol->hasFlag(FLAG_IGNORE_NOINIT)) { // These types deal with their uninitialized fields differently than // normal records/classes. They may require special case // implementations, but were capable of being isolated from the new // cases that do work. bool nowarn = false; // In the case of temporary variables that use noinit (at this point // only return variables), it is not useful to warn the user we are // still default initializing the values as they weren't the ones to // tell us to use noinit in the first place. So squash the warning // in this case. if (call->parentExpr) { CallExpr* parent = toCallExpr(call->parentExpr); if (parent && parent->isPrimitive(PRIM_MOVE)) { // Should always be true, but just in case... if (SymExpr* holdsDest = toSymExpr(parent->get(1))) { Symbol* dest = holdsDest->var; if (dest->hasFlag(FLAG_TEMP) && !strcmp(dest->name, "ret")) { nowarn = true; } } } } if (!nowarn) USR_WARN("type %s does not currently support noinit, using default initialization", type->symbol->name); result = new CallExpr(PRIM_INIT, call->get(1)->remove()); call->replace(result); inits.add((CallExpr *)result); } else { result = call; inits.add(call); } } } else if (call->isPrimitive(PRIM_INIT)) { SymExpr* se = toSymExpr(call->get(1)); INT_ASSERT(se); if (!se->var->hasFlag(FLAG_TYPE_VARIABLE)) USR_FATAL(call, "invalid type specification"); Type* type = call->get(1)->getValType(); if (type->defaultValue || type->symbol->hasFlag(FLAG_ITERATOR_CLASS)) { // In these cases, the _defaultOf method for that type can be resolved // now. Otherwise, it needs to wait until resolveRecordInitializers result = new CallExpr("_defaultOf", type->symbol); call->replace(result); } else { inits.add(call); } } else if (call->isPrimitive(PRIM_TYPEOF)) { Type* type = call->get(1)->getValType(); if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) { result = new CallExpr("chpl__convertValueToRuntimeType", call->get(1)->remove()); call->replace(result); } } else if (call->isPrimitive(PRIM_QUERY)) { Symbol* field = determineQueriedField(call); if (field && (field->hasFlag(FLAG_PARAM) || field->hasFlag(FLAG_TYPE_VARIABLE))) { result = new CallExpr(field->name, gMethodToken, call->get(1)->remove()); call->replace(result); } else if (isInstantiatedField(field)) { VarSymbol* tmp = newTemp("_instantiated_field_tmp_"); call->getStmtExpr()->insertBefore(new DefExpr(tmp)); if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_TUPLE) && field->name[0] == 'x') result = new CallExpr(PRIM_GET_MEMBER_VALUE, call->get(1)->remove(), new_StringSymbol(field->name)); else result = new CallExpr(field->name, gMethodToken, call->get(1)->remove()); call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, result)); call->replace(new CallExpr(PRIM_TYPEOF, tmp)); } else USR_FATAL(call, "invalid query -- queried field must be a type or parameter"); } else if (call->isPrimitive(PRIM_CAPTURE_FN)) { result = createFunctionAsValue(call); call->replace(result); } else if (call->isPrimitive(PRIM_CREATE_FN_TYPE)) { AggregateType *parent = createOrFindFunTypeFromAnnotation(call->argList, call); result = new SymExpr(parent->symbol); call->replace(result); } else if (call->isNamed("chpl__initCopy") || call->isNamed("chpl__autoCopy")) { if (call->numActuals() == 1) { if (SymExpr* symExpr = toSymExpr(call->get(1))) { if (VarSymbol* var = toVarSymbol(symExpr->var)) { if (var->immediate) { result = new SymExpr(var); call->replace(result); } } else { if (EnumSymbol* var = toEnumSymbol(symExpr->var)) { // Treat enum values as immediates result = new SymExpr(var); call->replace(result); } } } } } else if (call->isNamed("_cast")) { result = dropUnnecessaryCast(call); if (result == call) { // The cast was not dropped. Remove integer casts on immediate values. if (SymExpr* sym = toSymExpr(call->get(2))) { if (VarSymbol* var = toVarSymbol(sym->var)) { if (var->immediate) { if (SymExpr* sym = toSymExpr(call->get(1))) { Type* oldType = var->type; Type* newType = sym->var->type; if ((is_int_type(oldType) || is_uint_type(oldType) || is_bool_type(oldType)) && (is_int_type(newType) || is_uint_type(newType) || is_bool_type(newType) || is_enum_type(newType) || (newType == dtStringC))) { VarSymbol* typevar = toVarSymbol(newType->defaultValue); EnumType* typeenum = toEnumType(newType); if (typevar) { if (!typevar->immediate) INT_FATAL("unexpected case in cast_fold"); Immediate coerce = *typevar->immediate; coerce_immediate(var->immediate, &coerce); result = new SymExpr(new_ImmediateSymbol(&coerce)); call->replace(result); } else if (typeenum) { int64_t value, count = 0; bool replaced = false; if (!get_int(call->get(2), &value)) { INT_FATAL("unexpected case in cast_fold"); } for_enums(constant, typeenum) { if (!get_int(constant->init, &count)) { count++; } if (count == value) { result = new SymExpr(constant->sym); call->replace(result); replaced = true; break; } } if (!replaced) { USR_FATAL(call->get(2), "enum cast out of bounds"); } } else { INT_FATAL("unexpected case in cast_fold"); } } } } } else if (EnumSymbol* enumSym = toEnumSymbol(sym->var)) { if (SymExpr* sym = toSymExpr(call->get(1))) { Type* newType = sym->var->type; if (newType == dtStringC) { result = new SymExpr(new_StringSymbol(enumSym->name)); call->replace(result); } } } } } } else if (call->isNamed("==")) { if (isTypeExpr(call->get(1)) && isTypeExpr(call->get(2))) { Type* lt = call->get(1)->getValType(); Type* rt = call->get(2)->getValType(); if (lt != dtUnknown && rt != dtUnknown && !lt->symbol->hasFlag(FLAG_GENERIC) && !rt->symbol->hasFlag(FLAG_GENERIC)) { result = (lt == rt) ? new SymExpr(gTrue) : new SymExpr(gFalse); call->replace(result); } } } else if (call->isNamed("!=")) { if (isTypeExpr(call->get(1)) && isTypeExpr(call->get(2))) { Type* lt = call->get(1)->getValType(); Type* rt = call->get(2)->getValType(); if (lt != dtUnknown && rt != dtUnknown && !lt->symbol->hasFlag(FLAG_GENERIC) && !rt->symbol->hasFlag(FLAG_GENERIC)) { result = (lt != rt) ? new SymExpr(gTrue) : new SymExpr(gFalse); call->replace(result); } } } else if (call->isNamed("_type_construct__tuple") && !call->isResolved()) { if (SymExpr* sym = toSymExpr(call->get(1))) { if (VarSymbol* var = toVarSymbol(sym->var)) { if (var->immediate) { int rank = var->immediate->int_value(); if (rank != call->numActuals() - 1) { if (call->numActuals() != 2) INT_FATAL(call, "bad homogeneous tuple"); Expr* actual = call->get(2); for (int i = 1; i < rank; i++) { call->insertAtTail(actual->copy()); } } } } } } else if (call->isPrimitive(PRIM_BLOCK_PARAM_LOOP)) { fold_param_for(call); // } else if (call->isPrimitive(PRIM_BLOCK_FOR_LOOP) && // call->numActuals() == 2) { // result = expand_for_loop(call); } else if (call->isPrimitive(PRIM_LOGICAL_FOLDER)) { bool removed = false; SymExpr* sym1 = toSymExpr(call->get(1)); if (VarSymbol* sym = toVarSymbol(sym1->var)) { if (sym->immediate || paramMap.get(sym)) { CallExpr* mvCall = toCallExpr(call->parentExpr); SymExpr* sym = toSymExpr(mvCall->get(1)); VarSymbol* var = toVarSymbol(sym->var); removed = true; var->addFlag(FLAG_MAYBE_PARAM); result = call->get(2)->remove(); call->replace(result); } } if (!removed) { result = call->get(2)->remove(); call->replace(result); } } else if (call->isPrimitive(PRIM_ADDR_OF)) { // remove set ref if already a reference if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) { result = call->get(1)->remove(); call->replace(result); } else { // This test is turned off if we are in a wrapper function. FnSymbol* fn = call->getFunction(); if (!fn->hasFlag(FLAG_WRAPPER)) { SymExpr* lhs = NULL; // check legal var function return if (CallExpr* move = toCallExpr(call->parentExpr)) { if (move->isPrimitive(PRIM_MOVE)) { lhs = toSymExpr(move->get(1)); if (lhs && lhs->var == fn->getReturnSymbol()) { SymExpr* ret = toSymExpr(call->get(1)); INT_ASSERT(ret); if (ret->var->defPoint->getFunction() == move->getFunction() && !ret->var->type->symbol->hasFlag(FLAG_ITERATOR_RECORD) && !ret->var->type->symbol->hasFlag(FLAG_ARRAY)) // Should this conditional include domains, distributions, sync and/or single? USR_FATAL(ret, "illegal return expression in var function"); if (ret->var->isConstant() || ret->var->isParameter()) USR_FATAL(ret, "var function returns constant value"); } } } // // check that the operand of 'addr of' is a legal lvalue. if (SymExpr* rhs = toSymExpr(call->get(1))) { if (!(lhs && lhs->var->hasFlag(FLAG_REF_VAR) && lhs->var->hasFlag(FLAG_CONST))) { if (rhs->var->hasFlag(FLAG_EXPR_TEMP) || rhs->var->isConstant() || rhs->var->isParameter()) { if (lhs && lhs->var->hasFlag(FLAG_REF_VAR)) { if (rhs->var->isImmediate()) { USR_FATAL_CONT(call, "Can not set a non-const reference to a literal value."); } else { USR_FATAL_CONT(call, "Can not set a non-const reference to a const variable."); } } else { // This probably indicates that an invalid 'addr of' primitive // was inserted, which would be the compiler's fault, not the // user's. // At least, we might perform the check at or before the 'addr // of' primitive is inserted. INT_FATAL(call, "A non-lvalue appears where an lvalue is expected."); } } } } } } } else if (call->isPrimitive(PRIM_DEREF)) { // remove deref if arg is already a value if (!call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) { result = call->get(1)->remove(); call->replace(result); } } else if (call->isPrimitive(PRIM_TYPE_TO_STRING)) { SymExpr* se = toSymExpr(call->get(1)); INT_ASSERT(se && se->var->hasFlag(FLAG_TYPE_VARIABLE)); result = new SymExpr(new_StringSymbol(se->var->type->symbol->name)); call->replace(result); } else if (call->isPrimitive(PRIM_WIDE_GET_LOCALE) || call->isPrimitive(PRIM_WIDE_GET_NODE)) { Type* type = call->get(1)->getValType(); // // ensure .locale (and on) are applied to lvalues or classes // (locale type is a class) // SymExpr* se = toSymExpr(call->get(1)); if (se->var->hasFlag(FLAG_EXPR_TEMP) && !isClass(type)) USR_WARN(se, "accessing the locale of a local expression"); // // if .locale is applied to an expression of array, domain, or distribution // wrapper type, apply .locale to the _value field of the // wrapper // if (isRecordWrappedType(type)) { VarSymbol* tmp = newTemp("_locale_tmp_"); call->getStmtExpr()->insertBefore(new DefExpr(tmp)); result = new CallExpr("_value", gMethodToken, call->get(1)->remove()); call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, result)); call->insertAtTail(tmp); } } else if (call->isPrimitive(PRIM_TO_LEADER)) { FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer; CallExpr* leaderCall; if (FnSymbol* leader = iteratorLeaderMap.get(iterator)) leaderCall = new CallExpr(leader); else leaderCall = new CallExpr(iterator->name); for_formals(formal, iterator) { leaderCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal))); } // "tag" should be placed at the end of the formals in the source code as // well, to avoid insertion of an order wrapper. leaderCall->insertAtTail(new NamedExpr("tag", new SymExpr(gLeaderTag))); call->replace(leaderCall); result = leaderCall; } else if (call->isPrimitive(PRIM_TO_FOLLOWER)) { FnSymbol* iterator = call->get(1)->typeInfo()->defaultInitializer->getFormal(1)->type->defaultInitializer; CallExpr* followerCall; if (FnSymbol* follower = iteratorFollowerMap.get(iterator)) followerCall = new CallExpr(follower); else followerCall = new CallExpr(iterator->name); for_formals(formal, iterator) { followerCall->insertAtTail(new NamedExpr(formal->name, new SymExpr(formal))); } // "tag", "followThis" and optionally "fast" should be placed at the end // of the formals in the source code as well, to avoid insertion of an // order wrapper. followerCall->insertAtTail(new NamedExpr("tag", new SymExpr(gFollowerTag))); followerCall->insertAtTail(new NamedExpr(iterFollowthisArgname, call->get(2)->remove())); if (call->numActuals() > 1) { followerCall->insertAtTail(new NamedExpr("fast", call->get(2)->remove())); } call->replace(followerCall); result = followerCall; } else if (call->isPrimitive(PRIM_NUM_FIELDS)) { AggregateType* classtype = toAggregateType(toSymExpr(call->get(1))->var->type); INT_ASSERT( classtype != NULL ); classtype = toAggregateType(classtype->getValType()); INT_ASSERT( classtype != NULL ); int fieldcount = 0; for_fields(field, classtype) { if( ! isNormalField(field) ) continue; fieldcount++; } result = new SymExpr(new_IntSymbol(fieldcount)); call->replace(result); } else if (call->isPrimitive(PRIM_FIELD_NUM_TO_NAME)) { AggregateType* classtype = toAggregateType(toSymExpr(call->get(1))->var->type); INT_ASSERT( classtype != NULL ); classtype = toAggregateType(classtype->getValType()); INT_ASSERT( classtype != NULL ); VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var); INT_ASSERT( var != NULL ); int fieldnum = var->immediate->int_value(); int fieldcount = 0; const char* name = NULL; for_fields(field, classtype) { if( ! isNormalField(field) ) continue; fieldcount++; if (fieldcount == fieldnum) { name = field->name; } } result = new SymExpr(new_StringSymbol(name)); call->replace(result); } else if (call->isPrimitive(PRIM_FIELD_VALUE_BY_NUM)) { AggregateType* classtype = toAggregateType(call->get(1)->typeInfo()); INT_ASSERT( classtype != NULL ); classtype = toAggregateType(classtype->getValType()); INT_ASSERT( classtype != NULL ); VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var); INT_ASSERT( var != NULL ); int fieldnum = var->immediate->int_value(); int fieldcount = 0; for_fields(field, classtype) { if( ! isNormalField(field) ) continue; fieldcount++; if (fieldcount == fieldnum) { result = new CallExpr(PRIM_GET_MEMBER, call->get(1)->copy(), new_StringSymbol(field->name)); break; } } call->replace(result); } else if (call->isPrimitive(PRIM_FIELD_ID_BY_NUM)) { AggregateType* classtype = toAggregateType(call->get(1)->typeInfo()); INT_ASSERT( classtype != NULL ); classtype = toAggregateType(classtype->getValType()); INT_ASSERT( classtype != NULL ); VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var); INT_ASSERT( var != NULL ); int fieldnum = var->immediate->int_value(); int fieldcount = 0; for_fields(field, classtype) { if( ! isNormalField(field) ) continue; fieldcount++; if (fieldcount == fieldnum) { result = new SymExpr(new_IntSymbol(field->id)); break; } } call->replace(result); } else if (call->isPrimitive(PRIM_FIELD_VALUE_BY_NAME)) { AggregateType* classtype = toAggregateType(call->get(1)->typeInfo()); INT_ASSERT( classtype != NULL ); classtype = toAggregateType(classtype->getValType()); INT_ASSERT( classtype != NULL ); VarSymbol* var = toVarSymbol(toSymExpr(call->get(2))->var); INT_ASSERT( var != NULL ); Immediate* imm = var->immediate; INT_ASSERT( classtype != NULL ); // fail horribly if immediate is not a string . INT_ASSERT(imm->const_kind == CONST_KIND_STRING); const char* fieldname = imm->v_string; int fieldcount = 0; for_fields(field, classtype) { if( ! isNormalField(field) ) continue; fieldcount++; if ( 0 == strcmp(field->name, fieldname) ) { result = new CallExpr(PRIM_GET_MEMBER, call->get(1)->copy(), new_StringSymbol(field->name)); break; } } call->replace(result); } else if (call->isPrimitive(PRIM_ENUM_MIN_BITS) || call->isPrimitive(PRIM_ENUM_IS_SIGNED)) { EnumType* et = toEnumType(toSymExpr(call->get(1))->var->type); ensureEnumTypeResolved(et); result = NULL; if( call->isPrimitive(PRIM_ENUM_MIN_BITS) ) { result = new SymExpr(new_IntSymbol(get_width(et->integerType))); } else if( call->isPrimitive(PRIM_ENUM_IS_SIGNED) ) { if( is_int_type(et->integerType) ) result = new SymExpr(gTrue); else result = new SymExpr(gFalse); } call->replace(result); } else if (call->isPrimitive(PRIM_IS_UNION_TYPE)) { AggregateType* classtype = toAggregateType(call->get(1)->typeInfo()); if( isUnion(classtype) ) result = new SymExpr(gTrue); else result = new SymExpr(gFalse); call->replace(result); } else if (call->isPrimitive(PRIM_IS_ATOMIC_TYPE)) { if (isAtomicType(call->get(1)->typeInfo())) result = new SymExpr(gTrue); else result = new SymExpr(gFalse); call->replace(result); } else if (call->isPrimitive(PRIM_IS_SYNC_TYPE)) { Type* syncType = call->get(1)->typeInfo(); if (syncType->symbol->hasFlag(FLAG_SYNC)) result = new SymExpr(gTrue); else result = new SymExpr(gFalse); call->replace(result); } else if (call->isPrimitive(PRIM_IS_SINGLE_TYPE)) { Type* singleType = call->get(1)->typeInfo(); if (singleType->symbol->hasFlag(FLAG_SINGLE)) result = new SymExpr(gTrue); else result = new SymExpr(gFalse); call->replace(result); } else if (call->isPrimitive(PRIM_IS_TUPLE_TYPE)) { Type* tupleType = call->get(1)->typeInfo(); if (tupleType->symbol->hasFlag(FLAG_TUPLE)) result = new SymExpr(gTrue); else result = new SymExpr(gFalse); call->replace(result); } else if (call->isPrimitive(PRIM_IS_STAR_TUPLE_TYPE)) { Type* tupleType = call->get(1)->typeInfo(); INT_ASSERT(tupleType->symbol->hasFlag(FLAG_TUPLE)); if (tupleType->symbol->hasFlag(FLAG_STAR_TUPLE)) result = new SymExpr(gTrue); else result = new SymExpr(gFalse); call->replace(result); } } // // ensure result of pre-folding is in the AST // INT_ASSERT(result->parentSymbol); return result; } static void foldEnumOp(int op, EnumSymbol *e1, EnumSymbol *e2, Immediate *imm) { int64_t val1 = -1, val2 = -1, count = 0; // ^^^ This is an assumption that "long" on the compiler host is at // least as big as "int" on the target. This is not guaranteed to be true. EnumType *type1, *type2; type1 = toEnumType(e1->type); type2 = toEnumType(e2->type); INT_ASSERT(type1 && type2); // Loop over the enum values to find the int value of e1 for_enums(constant, type1) { if (!get_int(constant->init, &count)) { count++; } if (constant->sym == e1) { val1 = count; break; } } // Loop over the enum values to find the int value of e2 count = 0; for_enums(constant, type2) { if (!get_int(constant->init, &count)) { count++; } if (constant->sym == e2) { val2 = count; break; } } // All operators on enum types result in a bool imm->const_kind = NUM_KIND_BOOL; imm->num_index = BOOL_SIZE_SYS; switch (op) { default: INT_FATAL("fold constant op not supported"); break; case P_prim_equal: imm->v_bool = val1 == val2; break; case P_prim_notequal: imm->v_bool = val1 != val2; break; case P_prim_less: imm->v_bool = val1 < val2; break; case P_prim_lessorequal: imm->v_bool = val1 <= val2; break; case P_prim_greater: imm->v_bool = val1 > val2; break; case P_prim_greaterorequal: imm->v_bool = val1 >= val2; break; } } #define FOLD_CALL1(prim) \ if (SymExpr* sym = toSymExpr(call->get(1))) { \ if (VarSymbol* lhs = toVarSymbol(sym->var)) { \ if (lhs->immediate) { \ Immediate i3; \ fold_constant(prim, lhs->immediate, NULL, &i3); \ result = new SymExpr(new_ImmediateSymbol(&i3)); \ call->replace(result); \ } \ } \ } #define FOLD_CALL2(prim) \ if (SymExpr* sym = toSymExpr(call->get(1))) { \ if (VarSymbol* lhs = toVarSymbol(sym->var)) { \ if (lhs->immediate) { \ if (SymExpr* sym = toSymExpr(call->get(2))) { \ if (VarSymbol* rhs = toVarSymbol(sym->var)) { \ if (rhs->immediate) { \ Immediate i3; \ fold_constant(prim, lhs->immediate, rhs->immediate, &i3); \ result = new SymExpr(new_ImmediateSymbol(&i3)); \ call->replace(result); \ } \ } \ } \ } \ } else if (EnumSymbol* lhs = toEnumSymbol(sym->var)) { \ if (SymExpr* sym = toSymExpr(call->get(2))) { \ if (EnumSymbol* rhs = toEnumSymbol(sym->var)) { \ Immediate imm; \ foldEnumOp(prim, lhs, rhs, &imm); \ result = new SymExpr(new_ImmediateSymbol(&imm)); \ call->replace(result); \ } \ } \ } \ } static bool isSubType(Type* sub, Type* super) { if (sub == super) return true; forv_Vec(Type, parent, sub->dispatchParents) { if (isSubType(parent, super)) return true; } return false; } static void insertValueTemp(Expr* insertPoint, Expr* actual) { if (SymExpr* se = toSymExpr(actual)) { if (!se->var->type->refType) { VarSymbol* tmp = newTemp("_value_tmp_", se->var->getValType()); insertPoint->insertBefore(new DefExpr(tmp)); insertPoint->insertBefore(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_DEREF, se->var))); se->var = tmp; } } } // // returns resolved function if the function requires an implicit // destroy of its returned value (i.e. reference count) // // Currently, FLAG_DONOR_FN is only relevant when placed on // chpl__autoCopy(). // FnSymbol* requiresImplicitDestroy(CallExpr* call) { if (FnSymbol* fn = call->isResolved()) { FnSymbol* parent = call->getFunction(); INT_ASSERT(parent); if (!parent->hasFlag(FLAG_DONOR_FN) && // No autocopy/destroy calls in a donor function (this might // need to change when this flag is used more generally)). // Currently, this assumes we have thoughtfully written // chpl__autoCopy functions. // Return type is a record (which includes array, record, and // dist) or a ref counted type that is passed by reference (isRecord(fn->retType) || (fn->retType->symbol->hasFlag(FLAG_REF) && isRefCountedType(fn->retType->getValType()))) && // These are special functions where we don't want to destroy // the result !fn->hasFlag(FLAG_NO_IMPLICIT_COPY) && !fn->hasFlag(FLAG_ITERATOR_FN) && !fn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE) && !fn->hasFlag(FLAG_DONOR_FN) && !fn->hasFlag(FLAG_INIT_COPY_FN) && strcmp(fn->name, "=") && !fn->hasFlag(FLAG_AUTO_II) && !fn->hasFlag(FLAG_CONSTRUCTOR) && !fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) { return fn; } } return NULL; } static Expr* postFold(Expr* expr) { Expr* result = expr; if (!expr->parentSymbol) return result; SET_LINENO(expr); if (CallExpr* call = toCallExpr(expr)) { if (FnSymbol* fn = call->isResolved()) { if (fn->retTag == RET_PARAM || fn->hasFlag(FLAG_MAYBE_PARAM)) { VarSymbol* ret = toVarSymbol(fn->getReturnSymbol()); if (ret && ret->immediate) { result = new SymExpr(ret); expr->replace(result); } else if (EnumSymbol* es = toEnumSymbol(fn->getReturnSymbol())) { result = new SymExpr(es); expr->replace(result); } else if (fn->retTag == RET_PARAM) { USR_FATAL(call, "param function does not resolve to a param symbol"); } } if (fn->hasFlag(FLAG_MAYBE_TYPE) && fn->getReturnSymbol()->hasFlag(FLAG_TYPE_VARIABLE)) fn->retTag = RET_TYPE; if (fn->retTag == RET_TYPE) { Symbol* ret = fn->getReturnSymbol(); if (!ret->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) { result = new SymExpr(ret->type->symbol); expr->replace(result); } } } else if (call->isPrimitive(PRIM_QUERY_TYPE_FIELD) || call->isPrimitive(PRIM_QUERY_PARAM_FIELD)) { SymExpr* classWrap = toSymExpr(call->get(1)); // Really should be a symExpr INT_ASSERT(classWrap); AggregateType* ct = toAggregateType(classWrap->var->type); if (!ct) { USR_FATAL(call, "Attempted to obtain field of a type that was not a record or class"); } const char* memberName = get_string(call->get(2)); // Finds the field matching the specified name. Vec<Symbol *> keys; ct->substitutions.get_keys(keys); forv_Vec(Symbol, key, keys) { if (!strcmp(memberName, key->name)) { // If there is a substitution for it, replace this call with that // substitution if (Symbol* value = ct->substitutions.get(key)) { result = new SymExpr(value); expr->replace(result); } } } } // param initialization should not involve PRIM_ASSIGN or "=". else if (call->isPrimitive(PRIM_MOVE)) { bool set = false; if (SymExpr* lhs = toSymExpr(call->get(1))) { if (lhs->var->hasFlag(FLAG_MAYBE_PARAM) || lhs->var->isParameter()) { if (paramMap.get(lhs->var)) INT_FATAL(call, "parameter set multiple times"); VarSymbol* lhsVar = toVarSymbol(lhs->var); // We are expecting the LHS to be a var (what else could it be? if (lhsVar->immediate) { // The value of the LHS of this move has already been // established, most likely through a construct like // if (cond) return x; // return y; // In this case, the first 'true' conditional that hits a return // can fast-forward to the end of the routine, and some // resolution time can be saved. // Re-enable the fatal error to catch this case; the correct // solution is to ensure that the containing expression is never // resolved, using the abbreviated resolution suggested above. // INT_ASSERT(!lhsVar->immediate); set = true; // That is, set previously. } else { if (SymExpr* rhs = toSymExpr(call->get(2))) { if (VarSymbol* rhsVar = toVarSymbol(rhs->var)) { if (rhsVar->immediate) { paramMap.put(lhs->var, rhsVar); lhs->var->defPoint->remove(); makeNoop(call); set = true; } } if (EnumSymbol* rhsv = toEnumSymbol(rhs->var)) { paramMap.put(lhs->var, rhsv); lhs->var->defPoint->remove(); makeNoop(call); set = true; } } } if (!set && lhs->var->isParameter()) USR_FATAL(call, "Initializing parameter '%s' to value not known at compile time", lhs->var->name); } if (!set) { if (lhs->var->hasFlag(FLAG_MAYBE_TYPE)) { // Add FLAG_TYPE_VARIABLE when relevant if (SymExpr* rhs = toSymExpr(call->get(2))) { if (rhs->var->hasFlag(FLAG_TYPE_VARIABLE)) lhs->var->addFlag(FLAG_TYPE_VARIABLE); } else if (CallExpr* rhs = toCallExpr(call->get(2))) { if (FnSymbol* fn = rhs->isResolved()) { if (fn->retTag == RET_TYPE) lhs->var->addFlag(FLAG_TYPE_VARIABLE); } else if (rhs->isPrimitive(PRIM_DEREF)) { if (isTypeExpr(rhs->get(1))) lhs->var->addFlag(FLAG_TYPE_VARIABLE); } } } if (CallExpr* rhs = toCallExpr(call->get(2))) { if (rhs->isPrimitive(PRIM_TYPEOF)) { lhs->var->addFlag(FLAG_TYPE_VARIABLE); } if (FnSymbol* fn = rhs->isResolved()) { if (!strcmp(fn->name, "=") && fn->retType == dtVoid) { call->replace(rhs->remove()); result = rhs; set = true; } } } } if (!set) { if (lhs->var->hasFlag(FLAG_EXPR_TEMP) && !lhs->var->hasFlag(FLAG_TYPE_VARIABLE)) { if (CallExpr* rhsCall = toCallExpr(call->get(2))) { if (requiresImplicitDestroy(rhsCall)) { lhs->var->addFlag(FLAG_INSERT_AUTO_COPY); lhs->var->addFlag(FLAG_INSERT_AUTO_DESTROY); } } } if (isReferenceType(lhs->var->type) || lhs->var->type->symbol->hasFlag(FLAG_REF_ITERATOR_CLASS) || lhs->var->type->symbol->hasFlag(FLAG_ARRAY)) // Should this conditional include domains, distributions, sync and/or single? lhs->var->removeFlag(FLAG_EXPR_TEMP); } if (!set) { if (CallExpr* rhs = toCallExpr(call->get(2))) { if (rhs->isPrimitive(PRIM_NO_INIT)) { // If the lhs is a primitive, then we can safely just remove this // value. Otherwise the type needs to be resolved a little // further and so this statement can't be removed until // resolveRecordInitializers if (!isAggregateType(rhs->get(1)->getValType())) { makeNoop(call); } } } } } } else if (call->isPrimitive(PRIM_GET_MEMBER)) { Type* baseType = call->get(1)->getValType(); const char* memberName = get_string(call->get(2)); Symbol* sym = baseType->getField(memberName); SymExpr* left = toSymExpr(call->get(1)); if (left && left->var->hasFlag(FLAG_TYPE_VARIABLE)) { result = new SymExpr(sym->type->symbol); call->replace(result); } else if (sym->isParameter()) { Vec<Symbol*> keys; baseType->substitutions.get_keys(keys); forv_Vec(Symbol, key, keys) { if (!strcmp(sym->name, key->name)) { if (Symbol* value = baseType->substitutions.get(key)) { result = new SymExpr(value); call->replace(result); } } } } } else if (call->isPrimitive(PRIM_IS_SUBTYPE)) { if (isTypeExpr(call->get(1)) || isTypeExpr(call->get(2))) { Type* lt = call->get(2)->getValType(); // a:t cast is cast(t,a) Type* rt = call->get(1)->getValType(); if (lt != dtUnknown && rt != dtUnknown && lt != dtAny && rt != dtAny && !lt->symbol->hasFlag(FLAG_GENERIC)) { bool is_true = false; if (lt->instantiatedFrom == rt) is_true = true; if (isSubType(lt, rt)) is_true = true; result = (is_true) ? new SymExpr(gTrue) : new SymExpr(gFalse); call->replace(result); } } } else if (call->isPrimitive(PRIM_CAST)) { Type* t= call->get(1)->typeInfo(); if (t == dtUnknown) INT_FATAL(call, "Unable to resolve type"); call->get(1)->replace(new SymExpr(t->symbol)); } else if (call->isPrimitive("string_compare")) { SymExpr* lhs = toSymExpr(call->get(1)); SymExpr* rhs = toSymExpr(call->get(2)); INT_ASSERT(lhs && rhs); if (lhs->var->isParameter() && rhs->var->isParameter()) { const char* lstr = get_string(lhs); const char* rstr = get_string(rhs); int comparison = strcmp(lstr, rstr); result = new SymExpr(new_IntSymbol(comparison)); call->replace(result); } } else if (call->isPrimitive("string_concat")) { SymExpr* lhs = toSymExpr(call->get(1)); SymExpr* rhs = toSymExpr(call->get(2)); INT_ASSERT(lhs && rhs); if (lhs->var->isParameter() && rhs->var->isParameter()) { const char* lstr = get_string(lhs); const char* rstr = get_string(rhs); result = new SymExpr(new_StringSymbol(astr(lstr, rstr))); call->replace(result); } } else if (call->isPrimitive("string_length")) { SymExpr* se = toSymExpr(call->get(1)); INT_ASSERT(se); if (se->var->isParameter()) { const char* str = get_string(se); result = new SymExpr(new_IntSymbol(strlen(str), INT_SIZE_DEFAULT)); call->replace(result); } } else if (call->isPrimitive("ascii")) { SymExpr* se = toSymExpr(call->get(1)); INT_ASSERT(se); if (se->var->isParameter()) { const char* str = get_string(se); result = new SymExpr(new_IntSymbol((int)str[0], INT_SIZE_DEFAULT)); call->replace(result); } } else if (call->isPrimitive("string_contains")) { SymExpr* lhs = toSymExpr(call->get(1)); SymExpr* rhs = toSymExpr(call->get(2)); INT_ASSERT(lhs && rhs); if (lhs->var->isParameter() && rhs->var->isParameter()) { const char* lstr = get_string(lhs); const char* rstr = get_string(rhs); result = new SymExpr(strstr(lstr, rstr) ? gTrue : gFalse); call->replace(result); } } else if (call->isPrimitive(PRIM_UNARY_MINUS)) { FOLD_CALL1(P_prim_minus); } else if (call->isPrimitive(PRIM_UNARY_PLUS)) { FOLD_CALL1(P_prim_plus); } else if (call->isPrimitive(PRIM_UNARY_NOT)) { FOLD_CALL1(P_prim_not); } else if (call->isPrimitive(PRIM_UNARY_LNOT)) { FOLD_CALL1(P_prim_lnot); } else if (call->isPrimitive(PRIM_ADD)) { FOLD_CALL2(P_prim_add); } else if (call->isPrimitive(PRIM_SUBTRACT)) { FOLD_CALL2(P_prim_subtract); } else if (call->isPrimitive(PRIM_MULT)) { FOLD_CALL2(P_prim_mult); } else if (call->isPrimitive(PRIM_DIV)) { FOLD_CALL2(P_prim_div); } else if (call->isPrimitive(PRIM_MOD)) { FOLD_CALL2(P_prim_mod); } else if (call->isPrimitive(PRIM_EQUAL)) { FOLD_CALL2(P_prim_equal); } else if (call->isPrimitive(PRIM_NOTEQUAL)) { FOLD_CALL2(P_prim_notequal); } else if (call->isPrimitive(PRIM_LESSOREQUAL)) { FOLD_CALL2(P_prim_lessorequal); } else if (call->isPrimitive(PRIM_GREATEROREQUAL)) { FOLD_CALL2(P_prim_greaterorequal); } else if (call->isPrimitive(PRIM_LESS)) { FOLD_CALL2(P_prim_less); } else if (call->isPrimitive(PRIM_GREATER)) { FOLD_CALL2(P_prim_greater); } else if (call->isPrimitive(PRIM_AND)) { FOLD_CALL2(P_prim_and); } else if (call->isPrimitive(PRIM_OR)) { FOLD_CALL2(P_prim_or); } else if (call->isPrimitive(PRIM_XOR)) { FOLD_CALL2(P_prim_xor); } else if (call->isPrimitive(PRIM_POW)) { FOLD_CALL2(P_prim_pow); } else if (call->isPrimitive(PRIM_LSH)) { FOLD_CALL2(P_prim_lsh); } else if (call->isPrimitive(PRIM_RSH)) { FOLD_CALL2(P_prim_rsh); } else if (call->isPrimitive(PRIM_ARRAY_ALLOC) || call->isPrimitive(PRIM_SYNC_INIT) || call->isPrimitive(PRIM_SYNC_LOCK) || call->isPrimitive(PRIM_SYNC_UNLOCK) || call->isPrimitive(PRIM_SYNC_WAIT_FULL) || call->isPrimitive(PRIM_SYNC_WAIT_EMPTY) || call->isPrimitive(PRIM_SYNC_SIGNAL_FULL) || call->isPrimitive(PRIM_SYNC_SIGNAL_EMPTY) || call->isPrimitive(PRIM_SINGLE_INIT) || call->isPrimitive(PRIM_SINGLE_LOCK) || call->isPrimitive(PRIM_SINGLE_UNLOCK) || call->isPrimitive(PRIM_SINGLE_WAIT_FULL) || call->isPrimitive(PRIM_SINGLE_SIGNAL_FULL) || call->isPrimitive(PRIM_WRITEEF) || call->isPrimitive(PRIM_WRITEFF) || call->isPrimitive(PRIM_WRITEXF) || call->isPrimitive(PRIM_READFF) || call->isPrimitive(PRIM_READFE) || call->isPrimitive(PRIM_READXX) || call->isPrimitive(PRIM_SYNC_IS_FULL) || call->isPrimitive(PRIM_SINGLE_WRITEEF) || call->isPrimitive(PRIM_SINGLE_READFF) || call->isPrimitive(PRIM_SINGLE_READXX) || call->isPrimitive(PRIM_SINGLE_IS_FULL) || call->isPrimitive(PRIM_EXECUTE_TASKS_IN_LIST) || call->isPrimitive(PRIM_FREE_TASK_LIST) || (call->primitive && (!strncmp("_fscan", call->primitive->name, 6) || !strcmp("_readToEndOfLine", call->primitive->name) || !strcmp("_now_timer", call->primitive->name)))) { // // these primitives require temps to dereference actuals // why not do this to all primitives? // for_actuals(actual, call) { insertValueTemp(call->getStmtExpr(), actual); } } } else if (SymExpr* sym = toSymExpr(expr)) { if (Symbol* val = paramMap.get(sym->var)) { CallExpr* call = toCallExpr(sym->parentExpr); if (call && call->get(1) == sym) { // This is a place where param substitution has already determined the // value of a move or assignment, so we can just ignore the update. if (call->isPrimitive(PRIM_MOVE)) { makeNoop(call); return result; } // The substitution usually happens before resolution, so for // assignment, we key off of the name :-( if (call->isNamed("=")) { makeNoop(call); return result; } } if (sym->var->type != dtUnknown && sym->var->type != val->type) { CallExpr* cast = new CallExpr("_cast", sym->var, val); sym->replace(cast); result = preFold(cast); } else { sym->var = val; } } } if (CondStmt* cond = toCondStmt(result->parentExpr)) { if (cond->condExpr == result) { if (Expr* expr = cond->fold_cond_stmt()) { result = expr; } else { // // push try block // if (SymExpr* se = toSymExpr(result)) if (se->var == gTryToken) tryStack.add(cond); } } } // // pop try block and delete else // if (tryStack.n) { if (BlockStmt* block = toBlockStmt(result)) { if (tryStack.tail()->thenStmt == block) { tryStack.tail()->replace(block->remove()); tryStack.pop(); } } } return result; } static bool is_param_resolved(FnSymbol* fn, Expr* expr) { if (BlockStmt* block = toBlockStmt(expr)) { if (block->blockInfo) { USR_FATAL(expr, "param function cannot contain a non-param loop"); } } if (BlockStmt* block = toBlockStmt(expr->parentExpr)) { if (isCondStmt(block->parentExpr)) { USR_FATAL(block->parentExpr, "param function cannot contain a non-param conditional"); } } if (paramMap.get(fn->getReturnSymbol())) { CallExpr* call = toCallExpr(fn->body->body.tail); INT_ASSERT(call); INT_ASSERT(call->isPrimitive(PRIM_RETURN)); call->get(1)->replace(new SymExpr(paramMap.get(fn->getReturnSymbol()))); return true; // param function is resolved } return false; } // Resolves an expression and manages the callStack and tryStack. // On success, returns the call that was passed in. // On a try failure, returns either the expression preceding the elseStmt, // substituted for the body of the param condition (if that substitution could // be made), or NULL. // If null, then resolution of the current block should be aborted. tryFailure // is true in this case, so the search for a matching elseStmt continue in the // surrounding block or call. static Expr* resolveExpr(Expr* expr) { FnSymbol* fn = toFnSymbol(expr->parentSymbol); SET_LINENO(expr); if (SymExpr* se = toSymExpr(expr)) { if (se->var) { makeRefType(se->var->type); } } expr = preFold(expr); if (fn && fn->retTag == RET_PARAM) { if (is_param_resolved(fn, expr)) { return expr; } } if (DefExpr* def = toDefExpr(expr)) { if (def->init) { Expr* init = preFold(def->init); init = resolveExpr(init); // expr is unchanged, so is treated as "resolved". } } if (CallExpr* call = toCallExpr(expr)) { if (call->isPrimitive(PRIM_ERROR) || call->isPrimitive(PRIM_WARNING)) { issueCompilerError(call); } // Resolve expressions of the form: <type> ( args ) // These will be constructor calls (or type constructor calls) that slipped // past normalization due to the use of typedefs. if (SymExpr* se = toSymExpr(call->baseExpr)) { if (TypeSymbol* ts = toTypeSymbol(se->var)) { if (call->numActuals() == 0 || (call->numActuals() == 2 && isSymExpr(call->get(1)) && toSymExpr(call->get(1))->var == gMethodToken)) { // This looks like a typedef, so ignore it. } else { // More needed here ... . INT_FATAL(ts, "not yet implemented."); } } } callStack.add(call); resolveCall(call); if (!tryFailure && call->isResolved()) { resolveFns(call->isResolved()); } if (tryFailure) { if (tryStack.tail()->parentSymbol == fn) { while (callStack.tail()->isResolved() != tryStack.tail()->elseStmt->parentSymbol) { if (callStack.n == 0) INT_FATAL(call, "unable to roll back stack due to try block failure"); callStack.pop(); } BlockStmt* block = tryStack.tail()->elseStmt; tryStack.tail()->replace(block->remove()); tryStack.pop(); if (!block->prev) block->insertBefore(new CallExpr(PRIM_NOOP)); expr = block->prev; return expr; } else { return NULL; } } callStack.pop(); } if (SymExpr* sym = toSymExpr(expr)) { // Avoid record constructors via cast // should be fixed by out-of-order resolution CallExpr* parent = toCallExpr(sym->parentExpr); if (!parent || !parent->isPrimitive(PRIM_IS_SUBTYPE) || !sym->var->hasFlag(FLAG_TYPE_VARIABLE)) { if (AggregateType* ct = toAggregateType(sym->typeInfo())) { if (!ct->symbol->hasFlag(FLAG_GENERIC) && !ct->symbol->hasFlag(FLAG_ITERATOR_CLASS) && !ct->symbol->hasFlag(FLAG_ITERATOR_RECORD)) { resolveFormals(ct->defaultTypeConstructor); if (resolvedFormals.set_in(ct->defaultTypeConstructor)) { if (ct->defaultTypeConstructor->hasFlag(FLAG_PARTIAL_COPY)) instantiateBody(ct->defaultTypeConstructor); resolveFns(ct->defaultTypeConstructor); } } } } } expr = postFold(expr); return expr; } void resolveBlock(Expr* body) { for_exprs_postorder(expr, body) { expr = resolveExpr(expr); if (tryFailure) { if (expr == NULL) return; tryFailure = false; } } } static void computeReturnTypeParamVectors(BaseAST* ast, Symbol* retSymbol, Vec<Type*>& retTypes, Vec<Symbol*>& retParams) { if (CallExpr* call = toCallExpr(ast)) { if (call->isPrimitive(PRIM_MOVE)) { if (SymExpr* sym = toSymExpr(call->get(1))) { if (sym->var == retSymbol) { if (SymExpr* sym = toSymExpr(call->get(2))) retParams.add(sym->var); else retParams.add(NULL); retTypes.add(call->get(2)->typeInfo()); } } } } AST_CHILDREN_CALL(ast, computeReturnTypeParamVectors, retSymbol, retTypes, retParams); } static void replaceSetterArgWithTrue(BaseAST* ast, FnSymbol* fn) { if (SymExpr* se = toSymExpr(ast)) { if (se->var == fn->setter->sym) { se->var = gTrue; if (fn->hasFlag(FLAG_ITERATOR_FN)) USR_WARN(fn, "setter argument is not supported in iterators"); } } AST_CHILDREN_CALL(ast, replaceSetterArgWithTrue, fn); } static void replaceSetterArgWithFalse(BaseAST* ast, FnSymbol* fn, Symbol* ret) { if (SymExpr* se = toSymExpr(ast)) { if (se->var == fn->setter->sym) se->var = gFalse; else if (se->var == ret) { if (CallExpr* move = toCallExpr(se->parentExpr)) if (move->isPrimitive(PRIM_MOVE)) if (CallExpr* call = toCallExpr(move->get(2))) if (call->isPrimitive(PRIM_ADDR_OF)) call->primitive = primitives[PRIM_DEREF]; } } AST_CHILDREN_CALL(ast, replaceSetterArgWithFalse, fn, ret); } static void insertCasts(BaseAST* ast, FnSymbol* fn, Vec<CallExpr*>& casts) { if (CallExpr* call = toCallExpr(ast)) { if (call->parentSymbol == fn) { if (call->isPrimitive(PRIM_MOVE)) { if (SymExpr* lhs = toSymExpr(call->get(1))) { Expr* rhs = call->get(2); Type* rhsType = rhs->typeInfo(); if (rhsType != lhs->var->type && rhsType->refType != lhs->var->type && rhsType != lhs->var->type->refType) { SET_LINENO(rhs); rhs->remove(); Symbol* tmp = NULL; if (SymExpr* se = toSymExpr(rhs)) { tmp = se->var; } else { tmp = newTemp("_cast_tmp_", rhs->typeInfo()); call->insertBefore(new DefExpr(tmp)); call->insertBefore(new CallExpr(PRIM_MOVE, tmp, rhs)); } CallExpr* cast = new CallExpr("_cast", lhs->var->type->symbol, tmp); call->insertAtTail(cast); casts.add(cast); } } } } } AST_CHILDREN_CALL(ast, insertCasts, fn, casts); } static void instantiate_default_constructor(FnSymbol* fn) { // // instantiate initializer // if (fn->instantiatedFrom) { INT_ASSERT(!fn->retType->defaultInitializer); FnSymbol* instantiatedFrom = fn->instantiatedFrom; while (instantiatedFrom->instantiatedFrom) instantiatedFrom = instantiatedFrom->instantiatedFrom; CallExpr* call = new CallExpr(instantiatedFrom->retType->defaultInitializer); for_formals(formal, fn) { if (formal->type == dtMethodToken || formal == fn->_this) { call->insertAtTail(formal); } else if (paramMap.get(formal)) { call->insertAtTail(new NamedExpr(formal->name, new SymExpr(paramMap.get(formal)))); } else { Symbol* field = fn->retType->getField(formal->name); if (instantiatedFrom->hasFlag(FLAG_TUPLE)) { call->insertAtTail(field); } else { call->insertAtTail(new NamedExpr(formal->name, new SymExpr(field))); } } } fn->insertBeforeReturn(call); resolveCall(call); fn->retType->defaultInitializer = call->isResolved(); INT_ASSERT(fn->retType->defaultInitializer); // resolveFns(fn->retType->defaultInitializer); call->remove(); } } static void buildValueFunction(FnSymbol* fn) { if (!fn->hasFlag(FLAG_ITERATOR_FN)) { FnSymbol* copy; bool valueFunctionExists = fn->valueFunction; if (!valueFunctionExists) { // Build the value function when it does not already exist. copy = fn->copy(); copy->removeFlag(FLAG_RESOLVED); copy->addFlag(FLAG_INVISIBLE_FN); if (fn->hasFlag(FLAG_NO_IMPLICIT_COPY)) copy->addFlag(FLAG_NO_IMPLICIT_COPY); copy->retTag = RET_VALUE; // Change ret flag to value (not ref). fn->defPoint->insertBefore(new DefExpr(copy)); fn->valueFunction = copy; Symbol* ret = copy->getReturnSymbol(); replaceSetterArgWithFalse(copy, copy, ret); replaceSetterArgWithTrue(fn, fn); } else { copy = fn->valueFunction; } resolveFns(copy); } else { replaceSetterArgWithTrue(fn, fn); } } static void resolveReturnType(FnSymbol* fn) { // Resolve return type. Symbol* ret = fn->getReturnSymbol(); Type* retType = ret->type; if (retType == dtUnknown) { Vec<Type*> retTypes; Vec<Symbol*> retParams; computeReturnTypeParamVectors(fn, ret, retTypes, retParams); if (retTypes.n == 1) retType = retTypes.head(); else if (retTypes.n > 1) { for (int i = 0; i < retTypes.n; i++) { bool best = true; for (int j = 0; j < retTypes.n; j++) { if (retTypes.v[i] != retTypes.v[j]) { bool requireScalarPromotion = false; if (!canDispatch(retTypes.v[j], retParams.v[j], retTypes.v[i], fn, &requireScalarPromotion)) best = false; if (requireScalarPromotion) best = false; } } if (best) { retType = retTypes.v[i]; break; } } } if (!fn->iteratorInfo) { if (retTypes.n == 0) retType = dtVoid; } } ret->type = retType; if (!fn->iteratorInfo) { if (retType == dtUnknown) USR_FATAL(fn, "unable to resolve return type"); fn->retType = retType; } } static void resolveFns(FnSymbol* fn) { if (fn->isResolved()) return; fn->addFlag(FLAG_RESOLVED); if (fn->hasFlag(FLAG_EXTERN)) { resolveBlock(fn->body); resolveReturnType(fn); return; } if (fn->hasFlag(FLAG_FUNCTION_PROTOTYPE)) return; if (fn->retTag == RET_VAR) { buildValueFunction(fn); } insertFormalTemps(fn); resolveBlock(fn->body); if (tryFailure) { fn->removeFlag(FLAG_RESOLVED); return; } if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) { AggregateType* ct = toAggregateType(fn->retType); if (!ct) INT_FATAL(fn, "Constructor has no class type"); setScalarPromotionType(ct); fixTypeNames(ct); } resolveReturnType(fn); // // insert casts as necessary // if (fn->retTag != RET_PARAM) { Vec<CallExpr*> casts; insertCasts(fn->body, fn, casts); forv_Vec(CallExpr, cast, casts) { resolveCall(cast); if (cast->isResolved()) { resolveFns(cast->isResolved()); } } } // // mark leaders for inlining // if (fn->hasFlag(FLAG_ITERATOR_FN)) { for_formals(formal, fn) { if (formal->type == gLeaderTag->type && paramMap.get(formal) == gLeaderTag) { fn->addFlag(FLAG_INLINE_ITERATOR); } } } if (fn->hasFlag(FLAG_ITERATOR_FN) && !fn->iteratorInfo) { protoIteratorClass(fn); } // Resolve base class type constructors as well. if (fn->hasFlag(FLAG_TYPE_CONSTRUCTOR)) { forv_Vec(Type, parent, fn->retType->dispatchParents) { if (toAggregateType(parent) && parent != dtValue && parent != dtObject && parent->defaultTypeConstructor) { resolveFormals(parent->defaultTypeConstructor); if (resolvedFormals.set_in(parent->defaultTypeConstructor)) { resolveFns(parent->defaultTypeConstructor); } } } if (AggregateType* ct = toAggregateType(fn->retType)) { for_fields(field, ct) { if (AggregateType* fct = toAggregateType(field->type)) { if (fct->defaultTypeConstructor) { resolveFormals(fct->defaultTypeConstructor); if (resolvedFormals.set_in(fct->defaultTypeConstructor)) { resolveFns(fct->defaultTypeConstructor); } } } } } // This instantiates the default constructor for the corresponding type constructor. instantiate_default_constructor(fn); // // resolve destructor // if (AggregateType* ct = toAggregateType(fn->retType)) { if (!ct->destructor && !ct->symbol->hasFlag(FLAG_REF)) { VarSymbol* tmp = newTemp(ct); CallExpr* call = new CallExpr("~chpl_destroy", gMethodToken, tmp); fn->insertAtHead(new CallExpr(call)); fn->insertAtHead(new DefExpr(tmp)); resolveCall(call); resolveFns(call->isResolved()); ct->destructor = call->isResolved(); call->remove(); tmp->defPoint->remove(); } } } // // mark privatized classes // if (fn->hasFlag(FLAG_PRIVATIZED_CLASS)) { if (fn->getReturnSymbol() == gTrue) { fn->getFormal(1)->type->symbol->addFlag(FLAG_PRIVATIZED_CLASS); } } } static bool possible_signature_match(FnSymbol* fn, FnSymbol* gn) { if (fn->name != gn->name) return false; if (fn->numFormals() != gn->numFormals()) return false; for (int i = 3; i <= fn->numFormals(); i++) { ArgSymbol* fa = fn->getFormal(i); ArgSymbol* ga = gn->getFormal(i); if (strcmp(fa->name, ga->name)) return false; } return true; } static bool signature_match(FnSymbol* fn, FnSymbol* gn) { if (fn->name != gn->name) return false; if (fn->numFormals() != gn->numFormals()) return false; for (int i = 3; i <= fn->numFormals(); i++) { ArgSymbol* fa = fn->getFormal(i); ArgSymbol* ga = gn->getFormal(i); if (strcmp(fa->name, ga->name)) return false; if (fa->type != ga->type) return false; } return true; } // // add to vector icts all types instantiated from ct // static void collectInstantiatedAggregateTypes(Vec<Type*>& icts, Type* ct) { forv_Vec(TypeSymbol, ts, gTypeSymbols) { if (ts->type->defaultTypeConstructor) if (!ts->hasFlag(FLAG_GENERIC) && ts->type->defaultTypeConstructor->instantiatedFrom == ct->defaultTypeConstructor) icts.add(ts->type); } } // // return true if child overrides parent in dispatch table // static bool isVirtualChild(FnSymbol* child, FnSymbol* parent) { if (Vec<FnSymbol*>* children = virtualChildrenMap.get(parent)) { forv_Vec(FnSymbol*, candidateChild, *children) { if (candidateChild == child) return true; } } return false; } static void addToVirtualMaps(FnSymbol* pfn, AggregateType* ct) { forv_Vec(FnSymbol, cfn, ct->methods) { if (cfn && !cfn->instantiatedFrom && possible_signature_match(pfn, cfn)) { Vec<Type*> types; if (ct->symbol->hasFlag(FLAG_GENERIC)) collectInstantiatedAggregateTypes(types, ct); else types.add(ct); forv_Vec(Type, type, types) { SymbolMap subs; if (ct->symbol->hasFlag(FLAG_GENERIC)) subs.put(cfn->getFormal(2), type->symbol); for (int i = 3; i <= cfn->numFormals(); i++) { ArgSymbol* arg = cfn->getFormal(i); if (arg->intent == INTENT_PARAM) { subs.put(arg, paramMap.get(pfn->getFormal(i))); } else if (arg->type->symbol->hasFlag(FLAG_GENERIC)) { subs.put(arg, pfn->getFormal(i)->type->symbol); } } FnSymbol* fn = cfn; if (subs.n) { fn = instantiate(fn, subs, NULL); if (fn) { if (type->defaultTypeConstructor->instantiationPoint) fn->instantiationPoint = type->defaultTypeConstructor->instantiationPoint; else fn->instantiationPoint = toBlockStmt(type->defaultTypeConstructor->defPoint->parentExpr); INT_ASSERT(fn->instantiationPoint); } } if (fn) { resolveFormals(fn); if (signature_match(pfn, fn)) { resolveFns(fn); if (fn->retType->symbol->hasFlag(FLAG_ITERATOR_RECORD) && pfn->retType->symbol->hasFlag(FLAG_ITERATOR_RECORD)) { if (!isSubType(fn->retType->defaultInitializer->iteratorInfo->getValue->retType, pfn->retType->defaultInitializer->iteratorInfo->getValue->retType)) { USR_FATAL_CONT(pfn, "conflicting return type specified for '%s: %s'", toString(pfn), pfn->retType->defaultInitializer->iteratorInfo->getValue->retType->symbol->name); USR_FATAL_CONT(fn, " overridden by '%s: %s'", toString(fn), fn->retType->defaultInitializer->iteratorInfo->getValue->retType->symbol->name); USR_STOP(); } else { pfn->retType->dispatchChildren.add_exclusive(fn->retType); fn->retType->dispatchParents.add_exclusive(pfn->retType); Type* pic = pfn->retType->defaultInitializer->iteratorInfo->iclass; Type* ic = fn->retType->defaultInitializer->iteratorInfo->iclass; INT_ASSERT(ic->symbol->hasFlag(FLAG_ITERATOR_CLASS)); // Iterator classes are created as normal top-level classes (inheriting // from dtObject). Here, we want to re-parent ic with pic, so // we need to remove and replace the object base class. INT_ASSERT(ic->dispatchParents.n == 1); Type* parent = ic->dispatchParents.only(); if (parent == dtObject) { int item = parent->dispatchChildren.index(ic); parent->dispatchChildren.remove(item); ic->dispatchParents.remove(0); } pic->dispatchChildren.add_exclusive(ic); ic->dispatchParents.add_exclusive(pic); continue; // do not add to virtualChildrenMap; handle in _getIterator } } else if (!isSubType(fn->retType, pfn->retType)) { USR_FATAL_CONT(pfn, "conflicting return type specified for '%s: %s'", toString(pfn), pfn->retType->symbol->name); USR_FATAL_CONT(fn, " overridden by '%s: %s'", toString(fn), fn->retType->symbol->name); USR_STOP(); } { Vec<FnSymbol*>* fns = virtualChildrenMap.get(pfn); if (!fns) fns = new Vec<FnSymbol*>(); fns->add(fn); virtualChildrenMap.put(pfn, fns); fn->addFlag(FLAG_VIRTUAL); pfn->addFlag(FLAG_VIRTUAL); } { Vec<FnSymbol*>* fns = virtualRootsMap.get(fn); if (!fns) fns = new Vec<FnSymbol*>(); bool added = false; // // check if parent or child already exists in vector // for (int i = 0; i < fns->n; i++) { // // if parent already exists, do not add child to vector // if (isVirtualChild(pfn, fns->v[i])) { added = true; break; } // // if child already exists, replace with parent // if (isVirtualChild(fns->v[i], pfn)) { fns->v[i] = pfn; added = true; break; } } if (!added) fns->add(pfn); virtualRootsMap.put(fn, fns); } } } } } } } static void addAllToVirtualMaps(FnSymbol* fn, AggregateType* ct) { forv_Vec(Type, t, ct->dispatchChildren) { AggregateType* ct = toAggregateType(t); if (ct->defaultTypeConstructor && (ct->defaultTypeConstructor->hasFlag(FLAG_GENERIC) || ct->defaultTypeConstructor->isResolved())) addToVirtualMaps(fn, ct); if (!ct->instantiatedFrom) addAllToVirtualMaps(fn, ct); } } static void buildVirtualMaps() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->hasFlag(FLAG_WRAPPER)) // Only "true" functions are used to populate virtual maps. continue; if (! fn->isResolved()) // Only functions that are actually used go into the virtual map. continue; if (fn->hasFlag(FLAG_NO_PARENS)) // Parenthesesless functions are statically bound; that is, they are not // dispatched through the virtual table. continue; if (fn->retTag == RET_PARAM || fn->retTag == RET_TYPE) // Only run-time functions populate the virtual map. continue; if (fn->numFormals() > 1 && fn->getFormal(1)->type == dtMethodToken) { // Only methods go in the virtual function table. if (AggregateType* pt = toAggregateType(fn->getFormal(2)->type)) { if (isClass(pt) && !pt->symbol->hasFlag(FLAG_GENERIC)) { addAllToVirtualMaps(fn, pt); } } } } } static void addVirtualMethodTableEntry(Type* type, FnSymbol* fn, bool exclusive /*= false*/) { Vec<FnSymbol*>* fns = virtualMethodTable.get(type); if (!fns) fns = new Vec<FnSymbol*>(); if (exclusive) { forv_Vec(FnSymbol, f, *fns) { if (f == fn) return; } } fns->add(fn); virtualMethodTable.put(type, fns); } void parseExplainFlag(char* flag, int* line, ModuleSymbol** module) { *line = 0; if (strcmp(flag, "")) { char *token, *str1 = NULL, *str2 = NULL; token = strstr(flag, ":"); if (token) { *token = '\0'; str1 = token+1; token = strstr(str1, ":"); if (token) { *token = '\0'; str2 = token + 1; } } if (str1) { if (str2 || !atoi(str1)) { forv_Vec(ModuleSymbol, mod, allModules) { if (!strcmp(mod->name, str1)) { *module = mod; break; } } if (!*module) USR_FATAL("invalid module name '%s' passed to --explain-call flag", str1); } else *line = atoi(str1); if (str2) *line = atoi(str2); } if (*line == 0) *line = -1; } } static void computeStandardModuleSet() { standardModuleSet.set_add(rootModule->block); standardModuleSet.set_add(theProgram->block); Vec<ModuleSymbol*> stack; stack.add(standardModule); while (ModuleSymbol* mod = stack.pop()) { if (mod->block->modUses) { for_actuals(expr, mod->block->modUses) { SymExpr* se = toSymExpr(expr); INT_ASSERT(se); ModuleSymbol* use = toModuleSymbol(se->var); INT_ASSERT(use); if (!standardModuleSet.set_in(use->block)) { stack.add(use); standardModuleSet.set_add(use->block); } } } } } void resolve() { parseExplainFlag(fExplainCall, &explainCallLine, &explainCallModule); computeStandardModuleSet(); // call _nilType nil so as to not confuse the user dtNil->symbol->name = gNil->name; bool changed = true; while (changed) { changed = false; forv_Vec(FnSymbol, fn, gFnSymbols) { changed = fn->tag_generic() || changed; } } unmarkDefaultedGenerics(); resolveUses(mainModule); resolveUses(printModuleInitModule); resolveFns(chpl_gen_main); USR_STOP(); resolveExports(); resolveEnumTypes(); resolveDynamicDispatches(); insertRuntimeTypeTemps(); resolveAutoCopies(); resolveRecordInitializers(); resolveOther(); insertDynamicDispatchCalls(); insertReturnTemps(); handleRuntimeTypes(); pruneResolvedTree(); freeCache(ordersCache); freeCache(defaultsCache); freeCache(genericsCache); freeCache(coercionsCache); freeCache(promotionsCache); Vec<VisibleFunctionBlock*> vfbs; visibleFunctionMap.get_values(vfbs); forv_Vec(VisibleFunctionBlock, vfb, vfbs) { Vec<Vec<FnSymbol*>*> vfns; vfb->visibleFunctions.get_values(vfns); forv_Vec(Vec<FnSymbol*>, vfn, vfns) { delete vfn; } delete vfb; } visibleFunctionMap.clear(); visibilityBlockCache.clear(); forv_Vec(BlockStmt, stmt, gBlockStmts) { stmt->moduleUseClear(); } resolved = true; } static void unmarkDefaultedGenerics() { // // make it so that arguments with types that have default values for // all generic arguments used those defaults // // FLAG_MARKED_GENERIC is used to identify places where the user inserted // '?' (queries) to mark such a type as generic. // forv_Vec(FnSymbol, fn, gFnSymbols) { if (!fn->inTree()) continue; bool unmark = fn->hasFlag(FLAG_GENERIC); for_formals(formal, fn) { if (formal->type->hasGenericDefaults) { if (!formal->hasFlag(FLAG_MARKED_GENERIC) && formal != fn->_this && !formal->hasFlag(FLAG_IS_MEME)) { SET_LINENO(formal); formal->typeExpr = new BlockStmt(new CallExpr(formal->type->defaultTypeConstructor)); insert_help(formal->typeExpr, NULL, formal); formal->type = dtUnknown; } else { unmark = false; } } else if (formal->type->symbol->hasFlag(FLAG_GENERIC) || formal->intent == INTENT_PARAM) { unmark = false; } } if (unmark) { fn->removeFlag(FLAG_GENERIC); INT_ASSERT(false); } } } // Resolve uses in postorder (removing back-links). // We have to resolve modules in dependency order, // so that the types of globals are ready when we need them. static void resolveUses(ModuleSymbol* mod) { static Vec<ModuleSymbol*> initMods; static int module_resolution_depth = 0; // Test and set to break loops and prevent infinite recursion. if (initMods.set_in(mod)) return; initMods.set_add(mod); ++module_resolution_depth; // I use my parent implicitly. if (ModuleSymbol* parent = mod->defPoint->getModule()) if (parent != theProgram && parent != rootModule) resolveUses(parent); // Now, traverse my use statements, and call the initializer for each // module I use. forv_Vec(ModuleSymbol, usedMod, mod->modUseList) resolveUses(usedMod); // Finally, myself. if (fPrintModuleResolution) fprintf(stderr, "%2d Resolving module %s ...", module_resolution_depth, mod->name); FnSymbol* fn = mod->initFn; resolveFormals(fn); resolveFns(fn); if (fPrintModuleResolution) putc('\n', stderr); --module_resolution_depth; } static void resolveExports() { // We need to resolve any additional functions that will be exported. forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->hasFlag(FLAG_EXPORT)) { SET_LINENO(fn); resolveFormals(fn); resolveFns(fn); } } } static void resolveEnumTypes() { // need to handle enumerated types better forv_Vec(TypeSymbol, type, gTypeSymbols) { if (EnumType* et = toEnumType(type->type)) { ensureEnumTypeResolved(et); } } } static void resolveDynamicDispatches() { inDynamicDispatchResolution = true; int num_types; do { num_types = gTypeSymbols.n; { Vec<Vec<FnSymbol*>*> values; virtualChildrenMap.get_values(values); forv_Vec(Vec<FnSymbol*>, value, values) { delete value; } } virtualChildrenMap.clear(); { Vec<Vec<FnSymbol*>*> values; virtualRootsMap.get_values(values); forv_Vec(Vec<FnSymbol*>, value, values) { delete value; } } virtualRootsMap.clear(); buildVirtualMaps(); } while (num_types != gTypeSymbols.n); for (int i = 0; i < virtualRootsMap.n; i++) { if (virtualRootsMap.v[i].key) { for (int j = 0; j < virtualRootsMap.v[i].value->n; j++) { FnSymbol* root = virtualRootsMap.v[i].value->v[j]; addVirtualMethodTableEntry(root->_this->type, root, true); } } } Vec<Type*> ctq; ctq.add(dtObject); forv_Vec(Type, ct, ctq) { if (Vec<FnSymbol*>* parentFns = virtualMethodTable.get(ct)) { forv_Vec(FnSymbol, pfn, *parentFns) { Vec<Type*> childSet; if (Vec<FnSymbol*>* childFns = virtualChildrenMap.get(pfn)) { forv_Vec(FnSymbol, cfn, *childFns) { forv_Vec(Type, pt, cfn->_this->type->dispatchParents) { if (pt == ct) { if (!childSet.set_in(cfn->_this->type)) { addVirtualMethodTableEntry(cfn->_this->type, cfn); childSet.set_add(cfn->_this->type); } break; } } } } forv_Vec(Type, childType, ct->dispatchChildren) { if (!childSet.set_in(childType)) { addVirtualMethodTableEntry(childType, pfn); } } } } forv_Vec(Type, child, ct->dispatchChildren) { ctq.add(child); } } for (int i = 0; i < virtualMethodTable.n; i++) { if (virtualMethodTable.v[i].key) { virtualMethodTable.v[i].value->reverse(); for (int j = 0; j < virtualMethodTable.v[i].value->n; j++) { virtualMethodMap.put(virtualMethodTable.v[i].value->v[j], j); } } } inDynamicDispatchResolution = false; if (fPrintDispatch) { printf("Dynamic dispatch table:\n"); for (int i = 0; i < virtualMethodTable.n; i++) { if (Type* t = virtualMethodTable.v[i].key) { printf(" %s\n", toString(t)); for (int j = 0; j < virtualMethodTable.v[i].value->n; j++) { printf(" %s\n", toString(virtualMethodTable.v[i].value->v[j])); } } } } } static void insertRuntimeTypeTemps() { forv_Vec(TypeSymbol, ts, gTypeSymbols) { if (ts->defPoint && ts->defPoint->parentSymbol && ts->hasFlag(FLAG_HAS_RUNTIME_TYPE) && !ts->hasFlag(FLAG_GENERIC)) { SET_LINENO(ts); VarSymbol* tmp = newTemp("_runtime_type_tmp_", ts->type); ts->type->defaultInitializer->insertBeforeReturn(new DefExpr(tmp)); CallExpr* call = new CallExpr("chpl__convertValueToRuntimeType", tmp); ts->type->defaultInitializer->insertBeforeReturn(call); resolveCall(call); resolveFns(call->isResolved()); valueToRuntimeTypeMap.put(ts->type, call->isResolved()); call->remove(); tmp->defPoint->remove(); } } } static void resolveAutoCopies() { forv_Vec(TypeSymbol, ts, gTypeSymbols) { if ((isRecord(ts->type) || getSyncFlags(ts).any()) && !ts->hasFlag(FLAG_GENERIC) && !ts->hasFlag(FLAG_SYNTACTIC_DISTRIBUTION)) { resolveAutoCopy(ts->type); resolveAutoDestroy(ts->type); } } } static void resolveRecordInitializers() { // // resolve PRIM_INITs for records // forv_Vec(CallExpr, init, inits) { // Ignore if dead. if (!init->parentSymbol) continue; Type* type = init->get(1)->typeInfo(); // Don't resolve initializers for runtime types. // I think this should be dead code because runtime type expressions // are all resolved during resolution (and this function is called // after that). if (type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) continue; // Extract the value type. if (type->symbol->hasFlag(FLAG_REF)) type = type->getValType(); // Resolve the AggregateType that has noinit used on it. if (init->isPrimitive(PRIM_NO_INIT)) { // Replaces noinit with a call to the defaultTypeConstructor, // providing the param and type arguments necessary to allocate // space for the instantiation of this (potentially) generic type. // defaultTypeConstructor calls are already cleaned up at the end of // function resolution, so the noinit cleanup would be redundant. SET_LINENO(init); CallExpr* res = new CallExpr(type->defaultTypeConstructor); for_formals(formal, type->defaultTypeConstructor) { Vec<Symbol *> keys; // Finds each named argument in the type constructor and inserts // the substitution provided. type->substitutions.get_keys(keys); // I don't think we can guarantee that the substitutions will be // in the same order as the arguments for the defaultTypeConstructor. // That would make this O(n) instead of potentially O(n*n) forv_Vec(Symbol, key, keys) { if (!strcmp(formal->name, key->name)) { Symbol* formalVal = type->substitutions.get(key); res->insertAtTail(new NamedExpr(formal->name, new SymExpr(formalVal))); } } } init->get(1)->replace(res); resolveCall(res); makeNoop((CallExpr *)init->parentExpr); // Now that we've resolved the type constructor and thus resolved the // generic type of the variable we were assigning to, the outer move // is no longer needed, so remove it and continue to the next init. continue; } // This could be an assert... if (type->defaultValue) INT_FATAL(init, "PRIM_INIT should have been replaced already"); SET_LINENO(init); if (type->symbol->hasFlag(FLAG_DISTRIBUTION)) { // This initialization cannot be replaced by a _defaultOf function // earlier in the compiler, there is not enough information to build a // default function for it. When we have the ability to call a // constructor from a type alias, it can be moved directly into module // code Symbol* tmp = newTemp("_distribution_tmp_"); init->getStmtExpr()->insertBefore(new DefExpr(tmp)); CallExpr* classCall = new CallExpr(type->getField("_valueType")->type->defaultInitializer); CallExpr* move = new CallExpr(PRIM_MOVE, tmp, classCall); init->getStmtExpr()->insertBefore(move); resolveCall(classCall); resolveFns(classCall->isResolved()); resolveCall(move); CallExpr* distCall = new CallExpr("chpl__buildDistValue", tmp); init->replace(distCall); resolveCall(distCall); resolveFns(distCall->isResolved()); } else { CallExpr* call = new CallExpr("_defaultOf", type->symbol); init->replace(call); resolveNormalCall(call); // At this point in the compiler, we can resolve the _defaultOf function // for the type, so do so. if (call->isResolved()) resolveFns(call->isResolved()); } } } // // Resolve other things we might want later // static void resolveOther() { // // When compiling with --minimal-modules, gPrintModuleInitFn is not // defined. // if (gPrintModuleInitFn) { // Resolve the function that will print module init order resolveFns(gPrintModuleInitFn); } } static void insertDynamicDispatchCalls() { // Select resolved calls whose function appears in the virtualChildrenMap. // These are the dynamically-dispatched calls. forv_Vec(CallExpr, call, gCallExprs) { if (!call->parentSymbol) continue; if (!call->getStmtExpr()) continue; FnSymbol* key = call->isResolved(); if (!key) continue; Vec<FnSymbol*>* fns = virtualChildrenMap.get(key); if (!fns) continue; SET_LINENO(call); //Check to see if any of the overridden methods reference outer variables. If they do, then when we later change the //signature in flattenFunctions, the vtable style will break (function signatures will no longer match). To avoid this //we switch to the if-block style in the case where outer variables are discovered. //Note: This is conservative, as we haven't finished resolving functions and calls yet, we check all possibilities. bool referencesOuterVars = false; Vec<FnSymbol*> seen; referencesOuterVars = usesOuterVars(key, seen); if (!referencesOuterVars) { for (int i = 0; i < fns->n; ++i) { seen.clear(); if ( (referencesOuterVars = usesOuterVars(key, seen)) ) { break; } } } if ((fns->n + 1 > fConditionalDynamicDispatchLimit) && (!referencesOuterVars)) { // // change call of root method into virtual method call; // Insert function SymExpr and virtual method temp at head of argument // list. // // N.B.: The following variable must have the same size as the type of // chpl__class_id / chpl_cid_* -- otherwise communication will cause // problems when it tries to read the cid of a remote class. See // test/classes/sungeun/remoteDynamicDispatch.chpl (on certain // machines and configurations). VarSymbol* cid = newTemp("_virtual_method_tmp_", dtInt[INT_SIZE_32]); call->getStmtExpr()->insertBefore(new DefExpr(cid)); call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, cid, new CallExpr(PRIM_GETCID, call->get(2)->copy()))); call->get(1)->insertBefore(new SymExpr(cid)); // "remove" here means VMT calls are not really "resolved". // That is, calls to isResolved() return NULL. call->get(1)->insertBefore(call->baseExpr->remove()); call->primitive = primitives[PRIM_VIRTUAL_METHOD_CALL]; // This clause leads to necessary reference temporaries not being inserted, // while the clause below works correctly. <hilde> // Increase --conditional-dynamic-dispatch-limit to see this. } else { forv_Vec(FnSymbol, fn, *fns) { Type* type = fn->getFormal(2)->type; CallExpr* subcall = call->copy(); SymExpr* tmp = new SymExpr(gNil); // Build the IF block. BlockStmt* ifBlock = new BlockStmt(); VarSymbol* cid = newTemp("_dynamic_dispatch_tmp_", dtBool); ifBlock->insertAtTail(new DefExpr(cid)); ifBlock->insertAtTail(new CallExpr(PRIM_MOVE, cid, new CallExpr(PRIM_TESTCID, call->get(2)->copy(), type->symbol))); VarSymbol* _ret = NULL; if (key->retType != dtVoid) { _ret = newTemp("_return_tmp_", key->retType); ifBlock->insertAtTail(new DefExpr(_ret)); } // Build the TRUE block. BlockStmt* trueBlock = new BlockStmt(); if (fn->retType == key->retType) { if (_ret) trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, _ret, subcall)); else trueBlock->insertAtTail(subcall); } else if (isSubType(fn->retType, key->retType)) { // Insert a cast to the overridden method's return type VarSymbol* castTemp = newTemp("_cast_tmp_", fn->retType); trueBlock->insertAtTail(new DefExpr(castTemp)); trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, castTemp, subcall)); INT_ASSERT(_ret); trueBlock->insertAtTail(new CallExpr(PRIM_MOVE, _ret, new CallExpr(PRIM_CAST, key->retType->symbol, castTemp))); } else INT_FATAL(key, "unexpected case"); // Build the FALSE block. BlockStmt* falseBlock = NULL; if (_ret) falseBlock = new BlockStmt(new CallExpr(PRIM_MOVE, _ret, tmp)); else falseBlock = new BlockStmt(tmp); ifBlock->insertAtTail(new CondStmt( new SymExpr(cid), trueBlock, falseBlock)); if (key->retType == dtUnknown) INT_FATAL(call, "bad parent virtual function return type"); call->getStmtExpr()->insertBefore(ifBlock); if (_ret) call->replace(new SymExpr(_ret)); else call->remove(); tmp->replace(call); subcall->baseExpr->replace(new SymExpr(fn)); if (SymExpr* se = toSymExpr(subcall->get(2))) { VarSymbol* tmp = newTemp("_cast_tmp_", type); se->getStmtExpr()->insertBefore(new DefExpr(tmp)); se->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_CAST, type->symbol, se->var))); se->replace(new SymExpr(tmp)); } else if (CallExpr* ce = toCallExpr(subcall->get(2))) if (ce->isPrimitive(PRIM_CAST)) ce->get(1)->replace(new SymExpr(type->symbol)); else INT_FATAL(subcall, "unexpected"); else INT_FATAL(subcall, "unexpected"); } } } } static Type* buildRuntimeTypeInfo(FnSymbol* fn) { SET_LINENO(fn); AggregateType* ct = new AggregateType(AGGREGATE_RECORD); TypeSymbol* ts = new TypeSymbol(astr("_RuntimeTypeInfo"), ct); for_formals(formal, fn) { if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) continue; VarSymbol* field = new VarSymbol(formal->name, formal->type); ct->fields.insertAtTail(new DefExpr(field)); if (formal->hasFlag(FLAG_TYPE_VARIABLE)) field->addFlag(FLAG_TYPE_VARIABLE); } theProgram->block->insertAtTail(new DefExpr(ts)); ct->symbol->addFlag(FLAG_RUNTIME_TYPE_VALUE); makeRefType(ts->type); // make sure the new type has a ref type. return ct; } static void insertReturnTemps() { // // Insert return temps for functions that return values if no // variable captures the result. If the value is a sync/single var or a // reference to a sync/single var, pass it through the _statementLevelSymbol // function to get the semantics of reading a sync/single var. If the value // is an iterator pass it through another overload of // _statementLevelSymbol to iterate through it for side effects. // Note that we do not do this for --minimal-modules compilation // because we do not support sync/singles for minimal modules. // forv_Vec(CallExpr, call, gCallExprs) { if (call->parentSymbol) { if (FnSymbol* fn = call->isResolved()) { if (fn->retType != dtVoid) { CallExpr* parent = toCallExpr(call->parentExpr); if (!parent && !isDefExpr(call->parentExpr)) { // no use SET_LINENO(call); // TODO: reset_ast_loc() below? VarSymbol* tmp = newTemp("_return_tmp_", fn->retType); DefExpr* def = new DefExpr(tmp); call->insertBefore(def); if (!fMinimalModules && ((fn->retType->getValType() && isSyncType(fn->retType->getValType())) || isSyncType(fn->retType) || fn->hasFlag(FLAG_ITERATOR_FN))) { CallExpr* sls = new CallExpr("_statementLevelSymbol", tmp); call->insertBefore(sls); reset_ast_loc(sls, call); resolveCall(sls); INT_ASSERT(sls->isResolved()); resolveFns(sls->isResolved()); } def->insertAfter(new CallExpr(PRIM_MOVE, tmp, call->remove())); } } } } } } // // insert code to initialize a class or record // static void initializeClass(Expr* stmt, Symbol* sym) { AggregateType* ct = toAggregateType(sym->type); INT_ASSERT(ct); for_fields(field, ct) { if (!field->hasFlag(FLAG_SUPER_CLASS)) { SET_LINENO(field); if (field->type->defaultValue) { stmt->insertBefore(new CallExpr(PRIM_SET_MEMBER, sym, field, field->type->defaultValue)); } else if (isRecord(field->type)) { VarSymbol* tmp = newTemp("_init_class_tmp_", field->type); stmt->insertBefore(new DefExpr(tmp)); initializeClass(stmt, tmp); stmt->insertBefore(new CallExpr(PRIM_SET_MEMBER, sym, field, tmp)); } } } } static void handleRuntimeTypes() { // insertRuntimeTypeTemps is also called earlier in resolve(). That call // can insert variables that need autoCopies and inserting autoCopies can // insert things that need runtime type temps. These need to be fixed up // by insertRuntimeTypeTemps before buildRuntimeTypeInitFns is called to // update the type -> runtimeType mapping. Without this, there is an // actual/formal type mismatch (with --verify) for the code: // record R { var A: [1..1][1..1] real; } insertRuntimeTypeTemps(); buildRuntimeTypeInitFns(); replaceValuesWithRuntimeTypes(); replaceReturnedValuesWithRuntimeTypes(); insertRuntimeInitTemps(); } // // pruneResolvedTree -- prunes and cleans the AST after all of the // function calls and types have been resolved // static void pruneResolvedTree() { removeUnusedFunctions(); removeRandomPrimitives(); replaceTypeArgsWithFormalTypeTemps(); removeParamArgs(); removeUnusedGlobals(); removeUnusedTypes(); removeActualNames(); removeFormalTypeAndInitBlocks(); removeTypeBlocks(); removeInitFields(); removeWhereClauses(); removeMootFields(); expandInitFieldPrims(); } static void removeUnusedFunctions() { // Remove unused functions forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->hasFlag(FLAG_PRINT_MODULE_INIT_FN)) continue; if (fn->defPoint && fn->defPoint->parentSymbol) { if (! fn->isResolved() || fn->retTag == RET_PARAM) fn->defPoint->remove(); } } } static bool isUnusedClass(AggregateType *ct) { // Special case for global types. if (ct->symbol->hasFlag(FLAG_GLOBAL_TYPE_SYMBOL)) return false; // Runtime types are assumed to be always used. if (ct->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) return false; // FALSE if initializers are used if (ct->defaultInitializer && ct->defaultInitializer->isResolved()) return false; // FALSE if the type constructor is used. if (ct->defaultTypeConstructor && ct->defaultTypeConstructor->isResolved()) return false; bool allChildrenUnused = true; forv_Vec(Type, child, ct->dispatchChildren) { AggregateType* childClass = toAggregateType(child); INT_ASSERT(childClass); if (!isUnusedClass(childClass)) { allChildrenUnused = false; break; } } return allChildrenUnused; } // Remove unused types static void removeUnusedTypes() { // Remove unused aggregate types. forv_Vec(TypeSymbol, type, gTypeSymbols) { if (type->defPoint && type->defPoint->parentSymbol) { // Skip ref and runtime value types: // ref types are handled below; // runtime value types are assumed to be always used. if (type->hasFlag(FLAG_REF)) continue; if (type->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) continue; if (AggregateType* ct = toAggregateType(type->type)) if (isUnusedClass(ct)) ct->symbol->defPoint->remove(); } } // Remove unused ref types. forv_Vec(TypeSymbol, type, gTypeSymbols) { if (type->defPoint && type->defPoint->parentSymbol) { if (type->hasFlag(FLAG_REF)) { // Get the value type of the ref type. if (AggregateType* ct = toAggregateType(type->getValType())) { if (isUnusedClass(ct)) { // If the value type is unused, its ref type can also be removed. type->defPoint->remove(); } } // If the default type constructor for this ref type is in the tree, it // can be removed. if (type->type->defaultTypeConstructor->defPoint->parentSymbol) type->type->defaultTypeConstructor->defPoint->remove(); } } } } static void removeUnusedGlobals() { forv_Vec(DefExpr, def, gDefExprs) { // Remove unused global variables if (toVarSymbol(def->sym)) if (toModuleSymbol(def->parentSymbol)) if (def->sym->type == dtUnknown) def->remove(); } } static void removeRandomPrimitive(CallExpr* call) { if (! call->primitive) // TODO: This is weird. // Calls which trigger this case appear as the init clause of a type // variable. // The parent module or function may be resolved, but apparently the type // variable is resolved only if it is used. // Generally speaking, we resolve a declaration only if it is used. // But right now, we only apply this test to functions. // The test should be extended to variable declarations as well. That is, // variables need only be resolved if they are actually used. return; // A primitive. switch (call->primitive->tag) { default: /* do nothing */ break; case PRIM_NOOP: call->remove(); break; case PRIM_TYPEOF: { // Remove move(x, PRIM_TYPEOF(y)) calls -- useless after this CallExpr* parentCall = toCallExpr(call->parentExpr); if (parentCall && parentCall->isPrimitive(PRIM_MOVE) && parentCall->get(2) == call) { parentCall->remove(); } else { // Replace PRIM_TYPEOF with argument call->replace(call->get(1)->remove()); } } break; case PRIM_CAST: // Remove trivial casts. if (call->get(1)->typeInfo() == call->get(2)->typeInfo()) call->replace(call->get(2)->remove()); break; case PRIM_SET_MEMBER: case PRIM_GET_MEMBER: case PRIM_GET_MEMBER_VALUE: { // Remove member accesses of types // Replace string literals with field symbols in member primitives Type* baseType = call->get(1)->typeInfo(); if (baseType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) break; if (!call->parentSymbol->hasFlag(FLAG_REF) && baseType->symbol->hasFlag(FLAG_REF)) baseType = baseType->getValType(); const char* memberName = get_string(call->get(2)); Symbol* sym = baseType->getField(memberName); if (sym->hasFlag(FLAG_TYPE_VARIABLE) || !strcmp(sym->name, "_promotionType") || sym->isParameter()) call->getStmtExpr()->remove(); else { SET_LINENO(call->get(2)); call->get(2)->replace(new SymExpr(sym)); } } break; // Maybe this can be pushed into the following case, where a PRIM_MOVE gets // removed if its rhs is a type symbol. That is, resolution of a // PRIM_TYPE_INIT replaces the primitive with symexpr that contains a type symbol. case PRIM_TYPE_INIT: { // A "type init" call that is in the tree should always have a callExpr // parent, as guaranteed by CallExpr::verify(). CallExpr* parent = toCallExpr(call->parentExpr); // We expect all PRIM_TYPE_INIT primitives to have a PRIM_MOVE // parent, following the insertion of call temps. if (parent->isPrimitive(PRIM_MOVE)) parent->remove(); else INT_FATAL(parent, "expected parent of PRIM_TYPE_EXPR to be a PRIM_MOVE"); } break; case PRIM_MOVE: { // Remove types to enable --baseline SymExpr* sym = toSymExpr(call->get(2)); if (sym && isTypeSymbol(sym->var)) call->remove(); } break; } } // Remove the method token, parameter and type arguments from // function signatures and corresponding calls. static void removeParamArgs() { compute_call_sites(); forv_Vec(FnSymbol, fn, gFnSymbols) { if (! fn->isResolved()) // Don't bother with unresolved functions. // They will be removed from the tree. continue; for_formals(formal, fn) { if (formal->hasFlag(FLAG_INSTANTIATED_PARAM) || formal->type == dtMethodToken) { // Remove the argument from the call site. forv_Vec(CallExpr, call, *fn->calledBy) { // Performance note: AList::get(int) also performs a linear search. for_formals_actuals(cf, ca, call) { if (cf == formal) { ca->remove(); break; } } } formal->defPoint->remove(); } } } } static void removeRandomPrimitives() { forv_Vec(CallExpr, call, gCallExprs) { // Don't bother with calls that are not in the tree. if (! call->parentSymbol) continue; // Ignore calls to actual functions. if (call->isResolved()) continue; // Only primitives remain. removeRandomPrimitive(call); } } static void removeActualNames() { forv_Vec(NamedExpr, named, gNamedExprs) { if (! named->parentSymbol) continue; // Remove names of named actuals Expr* actual = named->actual; actual->remove(); named->replace(actual); } } static void removeTypeBlocks() { forv_Vec(BlockStmt, block, gBlockStmts) { if (! block->parentSymbol) continue; // Remove type blocks--code that exists only to determine types if (block->blockTag == BLOCK_TYPE) block->remove(); } } // // buildRuntimeTypeInitFns: Build a 'chpl__convertRuntimeTypeToValue' // (value) function for all functions tagged as runtime type // initialization functions. Also, build a function to return the // runtime type for all runtime type initialization functions. // // Functions flagged with the "runtime type init fn" pragma // (FLAG_RUNTIME_TYPE_INIT_FN during compilation) are designed to // specify to the compiler how to create a new value of a given type // from the arguments to the function. These arguments effectively // supply whatever static and/or runtime information is required to // build such a value (and therefore effectively represent the // "type"). Any non-static arguments are bundled into a runtime type // (record) by the compiler and passed around to represent the type at // execution time. // // The actual type specified is fully-resolved during function resolution. So // the "runtime type" mechanism is a way to create a parameterized type, but up // to a point handle it uniformly in the compiler. // Perhaps a more complete implementation of generic types with inheritance // would get rid of the need for this specialized machinery. // // In practice, we currently use these to create // runtime types for domains and arrays (via procedures named // 'chpl__buildDomainRuntimeType' and 'chpl__buildArrayRuntimeType', // respectively). // // For each such flagged function: // // - Clone the function, naming it 'chpl__convertRuntimeTypeToValue' // and change it to a value function // // - Replace the body of the original function with a new function // that returns the dynamic runtime type info // // Subsequently, the functions as written in the modules are now // called 'chpl__convertRuntimeTypeToValue' and used to initialize // variables with runtime types later in insertRuntimeInitTemps(). // // Notice also that the original functions had been marked as type // functions during parsing even though they were not written as such // (see addPragmaFlags() in build.cpp for more info). Now they are // actually type functions. // static void buildRuntimeTypeInitFns() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->defPoint && fn->defPoint->parentSymbol) { // Look only at functions flagged as "runtime type init fn". if (fn->hasFlag(FLAG_RUNTIME_TYPE_INIT_FN)) { // Look only at resolved instances. if (! fn->isResolved()) continue; INT_ASSERT(fn->retType->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)); SET_LINENO(fn); // Build a new runtime type for this function Type* runtimeType = buildRuntimeTypeInfo(fn); runtimeTypeMap.put(fn->retType, runtimeType); // Build chpl__convertRuntimeTypeToValue() instance. buildRuntimeTypeInitFn(fn, runtimeType); } } } } // Build a function to return the runtime type by modifying // the original function. static void buildRuntimeTypeInitFn(FnSymbol* fn, Type* runtimeType) { // Clone the original function and call the clone chpl__convertRuntimeTypeToValue. FnSymbol* runtimeTypeToValueFn = fn->copy(); INT_ASSERT(runtimeTypeToValueFn->hasFlag(FLAG_RESOLVED)); runtimeTypeToValueFn->name = astr("chpl__convertRuntimeTypeToValue"); runtimeTypeToValueFn->cname = runtimeTypeToValueFn->name; // Remove this flag from the clone. runtimeTypeToValueFn->removeFlag(FLAG_RUNTIME_TYPE_INIT_FN); // Make the clone a value function. runtimeTypeToValueFn->getReturnSymbol()->removeFlag(FLAG_TYPE_VARIABLE); runtimeTypeToValueFn->retTag = RET_VALUE; fn->defPoint->insertBefore(new DefExpr(runtimeTypeToValueFn)); // Remove static arguments from the RTTV function. for_formals(formal, runtimeTypeToValueFn) { if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) formal->defPoint->remove(); if (formal->hasFlag(FLAG_TYPE_VARIABLE)) { Symbol* field = runtimeType->getField(formal->name); if (! field->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) formal->defPoint->remove(); } } // Insert the clone (convertRuntimeTypeToValue) into the runtimeTypeToValueMap. runtimeTypeToValueMap.put(runtimeType, runtimeTypeToValueFn); // Change the return type of the original function. fn->retType = runtimeType; fn->getReturnSymbol()->type = runtimeType; // Build a new body for the original function. BlockStmt* block = new BlockStmt(); VarSymbol* var = newTemp("_return_tmp_", fn->retType); block->insertAtTail(new DefExpr(var)); // Bundle all non-static arguments into the runtime type record. // Remove static arguments from this specialized buildRuntimeType function. for_formals(formal, fn) { if (formal->hasFlag(FLAG_INSTANTIATED_PARAM)) continue; Symbol* field = runtimeType->getField(formal->name); if (formal->hasFlag(FLAG_TYPE_VARIABLE) && ! field->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) continue; block->insertAtTail(new CallExpr(PRIM_SET_MEMBER, var, field, formal)); } block->insertAtTail(new CallExpr(PRIM_RETURN, var)); // Replace the body of the orignal chpl__buildRuntime...Type() function. fn->body->replace(block); } static void removeFormalTypeAndInitBlocks() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->defPoint && fn->defPoint->parentSymbol) { for_formals(formal, fn) { // Remove formal default values if (formal->defaultExpr) formal->defaultExpr->remove(); // Remove formal type expressions if (formal->typeExpr) formal->typeExpr->remove(); } } } } static void replaceTypeArgsWithFormalTypeTemps() { compute_call_sites(); forv_Vec(FnSymbol, fn, gFnSymbols) { if (! fn->isResolved()) // Don't bother with unresolved functions. // They will be removed from the tree. continue; // Skip this function if it is not in the tree. if (! fn->defPoint) continue; if (! fn->defPoint->parentSymbol) continue; // We do not remove type args from extern functions // TODO: Find out if we really support type args in extern functions. if (fn->hasFlag(FLAG_EXTERN)) continue; for_formals(formal, fn) { // We are only interested in type formals if (! formal->hasFlag(FLAG_TYPE_VARIABLE)) continue; // Replace the formal with a _formal_type_tmp_. SET_LINENO(formal); VarSymbol* tmp = newTemp("_formal_type_tmp_", formal->type); fn->insertAtHead(new DefExpr(tmp)); subSymbol(fn, formal, tmp); // Remove the corresponding actual from all call sites. forv_Vec(CallExpr, call, *fn->calledBy) { for_formals_actuals(cf, ca, call) { if (cf == formal) { ca->remove(); break; } } } formal->defPoint->remove(); } } } static void replaceValuesWithRuntimeTypes() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->defPoint && fn->defPoint->parentSymbol) { for_formals(formal, fn) { if (formal->hasFlag(FLAG_TYPE_VARIABLE) && formal->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) { if (FnSymbol* fn = valueToRuntimeTypeMap.get(formal->type)) { Type* rt = (fn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) ? fn->retType : runtimeTypeMap.get(fn->retType); INT_ASSERT(rt); formal->type = rt; formal->removeFlag(FLAG_TYPE_VARIABLE); } } } } } } static void removeWhereClauses() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->defPoint && fn->defPoint->parentSymbol) { if (fn->where) fn->where->remove(); } } } static void replaceReturnedValuesWithRuntimeTypes() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->defPoint && fn->defPoint->parentSymbol) { if (fn->retTag == RET_TYPE) { VarSymbol* ret = toVarSymbol(fn->getReturnSymbol()); if (ret && ret->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) { if (FnSymbol* rtfn = valueToRuntimeTypeMap.get(ret->type)) { Type* rt = (rtfn->retType->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) ? rtfn->retType : runtimeTypeMap.get(rtfn->retType); INT_ASSERT(rt); ret->type = rt; fn->retType = ret->type; fn->retTag = RET_VALUE; } } } } } } static void replaceInitPrims(Vec<BaseAST*>& asts) { forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = toCallExpr(ast)) { // We are only interested in INIT primitives. if (call->isPrimitive(PRIM_INIT)) { FnSymbol* parent = toFnSymbol(call->parentSymbol); // Call must be in the tree and lie in a resolved function. if (! parent || ! parent->isResolved()) continue; SymExpr* se = toSymExpr(call->get(1)); Type* rt = se->var->type; if (rt->symbol->hasFlag(FLAG_RUNTIME_TYPE_VALUE)) { // ('init' foo), where typeof(foo) has flag "runtime type value" // // ==> // // (var _runtime_type_tmp_1) // ('move' _runtime_type_tmp_1 ('.v' foo "field1")) // (var _runtime_type_tmp_2) // ('move' _runtime_type_tmp_2 ('.v' foo "field2")) // (chpl__convertRuntimeTypeToValue _runtime_type_tmp_1 _rtt_2 ... ) SET_LINENO(call); FnSymbol* runtimeTypeToValueFn = runtimeTypeToValueMap.get(rt); INT_ASSERT(runtimeTypeToValueFn); CallExpr* runtimeTypeToValueCall = new CallExpr(runtimeTypeToValueFn); for_formals(formal, runtimeTypeToValueFn) { Symbol* field = rt->getField(formal->name); INT_ASSERT(field); VarSymbol* tmp = newTemp("_runtime_type_tmp_", field->type); call->getStmtExpr()->insertBefore(new DefExpr(tmp)); call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_GET_MEMBER_VALUE, se->var, field))); if (formal->hasFlag(FLAG_TYPE_VARIABLE)) tmp->addFlag(FLAG_TYPE_VARIABLE); runtimeTypeToValueCall->insertAtTail(tmp); } VarSymbol* tmp = newTemp("_runtime_type_tmp_", runtimeTypeToValueFn->retType); call->getStmtExpr()->insertBefore(new DefExpr(tmp)); call->getStmtExpr()->insertBefore(new CallExpr(PRIM_MOVE, tmp, runtimeTypeToValueCall)); INT_ASSERT(autoCopyMap.get(tmp->type)); call->replace(new CallExpr(autoCopyMap.get(tmp->type), tmp)); } else if (rt->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) { // // This is probably related to a comment that used to handle // this case elsewhere: // // special handling of tuple constructor to avoid // initialization of array based on an array type symbol // rather than a runtime array type // // this code added during the introduction of the new // keyword; it should be removed when possible // call->getStmtExpr()->remove(); } else { INT_FATAL(call, "PRIM_INIT should have already been handled"); } } } } } static void insertRuntimeInitTemps() { Vec<BaseAST*> asts; collect_asts_postorder(rootModule, asts); // Collect asts which are definitions of VarSymbols that are type variables // and are flagged as runtime types. forv_Vec(BaseAST, ast, asts) { if (DefExpr* def = toDefExpr(ast)) { if (isVarSymbol(def->sym) && def->sym->hasFlag(FLAG_TYPE_VARIABLE) && def->sym->type->symbol->hasFlag(FLAG_HAS_RUNTIME_TYPE)) { // Collapse these through the runtimeTypeMap ... Type* rt = runtimeTypeMap.get(def->sym->type); INT_ASSERT(rt); def->sym->type = rt; // ... and remove the type variable flag // (Make these declarations look like normal vars.) def->sym->removeFlag(FLAG_TYPE_VARIABLE); } } } replaceInitPrims(asts); forv_Vec(BaseAST, ast, asts) { if (SymExpr* se = toSymExpr(ast)) { // remove dead type expressions if (se->getStmtExpr() == se) if (se->var->hasFlag(FLAG_TYPE_VARIABLE)) se->remove(); } } } // Remove typedef definitions static void removeInitFields() { forv_Vec(DefExpr, def, gDefExprs) { if (! def->inTree()) continue; if (! def->init) continue; if (! def->sym->hasFlag(FLAG_TYPE_VARIABLE)) continue; def->init->remove(); def->init = NULL; } } static void removeMootFields() { // Remove type fields, parameter fields, and _promotionType field forv_Vec(TypeSymbol, type, gTypeSymbols) { if (type->defPoint && type->defPoint->parentSymbol) { if (AggregateType* ct = toAggregateType(type->type)) { for_fields(field, ct) { if (field->hasFlag(FLAG_TYPE_VARIABLE) || field->isParameter() || !strcmp(field->name, "_promotionType")) field->defPoint->remove(); } } } } } static void expandInitFieldPrims() { forv_Vec(CallExpr, call, gCallExprs) { if (call->isPrimitive(PRIM_INIT_FIELDS)) { initializeClass(call, toSymExpr(call->get(1))->var); call->remove(); } } } static void fixTypeNames(AggregateType* ct) { const char default_domain_name[] = "DefaultRectangularDom"; if (!ct->symbol->hasFlag(FLAG_BASE_ARRAY) && isArrayClass(ct)) { const char* domain_type = ct->getField("dom")->type->symbol->name; const char* elt_type = ct->getField("eltType")->type->symbol->name; ct->symbol->name = astr("[", domain_type, "] ", elt_type); } if (ct->instantiatedFrom && !strcmp(ct->instantiatedFrom->symbol->name, default_domain_name)) { ct->symbol->name = astr("domain", ct->symbol->name+strlen(default_domain_name)); } if (isRecordWrappedType(ct)) { ct->symbol->name = ct->getField("_valueType")->type->symbol->name; } } static void setScalarPromotionType(AggregateType* ct) { for_fields(field, ct) { if (!strcmp(field->name, "_promotionType")) ct->scalarPromotionType = field->type; } }
{ "content_hash": "61ff396cb0ee8e9a9b7df2c9143846fa", "timestamp": "", "source": "github", "line_count": 7666, "max_line_length": 170, "avg_line_length": 34.47665014349074, "alnum_prop": 0.6096149043882284, "repo_name": "sungeunchoi/chapel", "id": "c9d9c008ca1c9117ab8190b246a9f75c15a4854d", "size": "264298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "compiler/resolution/functionResolution.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "40291" }, { "name": "C", "bytes": "14254118" }, { "name": "C++", "bytes": "7117921" }, { "name": "CSS", "bytes": "13497" }, { "name": "Cuda", "bytes": "4304" }, { "name": "Emacs Lisp", "bytes": "28558" }, { "name": "Fortran", "bytes": "18153" }, { "name": "Gnuplot", "bytes": "4678" }, { "name": "Io", "bytes": "7451" }, { "name": "JavaScript", "bytes": "29328" }, { "name": "Objective-C", "bytes": "498310" }, { "name": "Perl", "bytes": "654589" }, { "name": "Python", "bytes": "242307" }, { "name": "R", "bytes": "170" }, { "name": "Ruby", "bytes": "440" }, { "name": "Shell", "bytes": "2222295" }, { "name": "TeX", "bytes": "1025330" }, { "name": "VimL", "bytes": "14443" }, { "name": "Zimpl", "bytes": "1115" } ], "symlink_target": "" }
#include "../SDL_internal.h" #ifndef SDL_sysaudio_h_ #define SDL_sysaudio_h_ #include "SDL_mutex.h" #include "SDL_thread.h" #include "../SDL_dataqueue.h" #include "./SDL_audio_c.h" /* !!! FIXME: These are wordy and unlocalized... */ #define DEFAULT_OUTPUT_DEVNAME "System audio output device" #define DEFAULT_INPUT_DEVNAME "System audio capture device" /* The SDL audio driver */ typedef struct SDL_AudioDevice SDL_AudioDevice; #define _THIS SDL_AudioDevice *_this /* Audio targets should call this as devices are added to the system (such as a USB headset being plugged in), and should also be called for for every device found during DetectDevices(). */ extern void SDL_AddAudioDevice(const int iscapture, const char *name, void *handle); /* Audio targets should call this as devices are removed, so SDL can update its list of available devices. */ extern void SDL_RemoveAudioDevice(const int iscapture, void *handle); /* Audio targets should call this if an opened audio device is lost while being used. This can happen due to i/o errors, or a device being unplugged, etc. If the device is totally gone, please also call SDL_RemoveAudioDevice() as appropriate so SDL's list of devices is accurate. */ extern void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device); /* This is the size of a packet when using SDL_QueueAudio(). We allocate these as necessary and pool them, under the assumption that we'll eventually end up with a handful that keep recycling, meeting whatever the app needs. We keep packing data tightly as more arrives to avoid wasting space, and if we get a giant block of data, we'll split them into multiple packets behind the scenes. My expectation is that most apps will have 2-3 of these in the pool. 8k should cover most needs, but if this is crippling for some embedded system, we can #ifdef this. The system preallocates enough packets for 2 callbacks' worth of data. */ #define SDL_AUDIOBUFFERQUEUE_PACKETLEN (8 * 1024) typedef struct SDL_AudioDriverImpl { void (*DetectDevices) (void); int (*OpenDevice) (_THIS, void *handle, const char *devname, int iscapture); void (*ThreadInit) (_THIS); /* Called by audio thread at start */ void (*ThreadDeinit) (_THIS); /* Called by audio thread at end */ void (*BeginLoopIteration)(_THIS); /* Called by audio thread at top of loop */ void (*WaitDevice) (_THIS); void (*PlayDevice) (_THIS); Uint8 *(*GetDeviceBuf) (_THIS); int (*CaptureFromDevice) (_THIS, void *buffer, int buflen); void (*FlushCapture) (_THIS); void (*PrepareToClose) (_THIS); /**< Called between run and draining wait for playback devices */ void (*CloseDevice) (_THIS); void (*LockDevice) (_THIS); void (*UnlockDevice) (_THIS); void (*FreeDeviceHandle) (void *handle); /**< SDL is done with handle from SDL_AddAudioDevice() */ void (*Deinitialize) (void); /* !!! FIXME: add pause(), so we can optimize instead of mixing silence. */ /* Some flags to push duplicate code into the core and reduce #ifdefs. */ /* !!! FIXME: these should be SDL_bool */ int ProvidesOwnCallbackThread; int SkipMixerLock; int HasCaptureSupport; int OnlyHasDefaultOutputDevice; int OnlyHasDefaultCaptureDevice; int AllowsArbitraryDeviceNames; } SDL_AudioDriverImpl; typedef struct SDL_AudioDeviceItem { void *handle; char *name; char *original_name; int dupenum; struct SDL_AudioDeviceItem *next; } SDL_AudioDeviceItem; typedef struct SDL_AudioDriver { /* * * */ /* The name of this audio driver */ const char *name; /* * * */ /* The description of this audio driver */ const char *desc; SDL_AudioDriverImpl impl; /* A mutex for device detection */ SDL_mutex *detectionLock; SDL_bool captureDevicesRemoved; SDL_bool outputDevicesRemoved; int outputDeviceCount; int inputDeviceCount; SDL_AudioDeviceItem *outputDevices; SDL_AudioDeviceItem *inputDevices; } SDL_AudioDriver; /* Define the SDL audio driver structure */ struct SDL_AudioDevice { /* * * */ /* Data common to all devices */ SDL_AudioDeviceID id; /* The device's current audio specification */ SDL_AudioSpec spec; /* The callback's expected audio specification (converted vs device's spec). */ SDL_AudioSpec callbackspec; /* Stream that converts and resamples. NULL if not needed. */ SDL_AudioStream *stream; /* Current state flags */ SDL_atomic_t shutdown; /* true if we are signaling the play thread to end. */ SDL_atomic_t enabled; /* true if device is functioning and connected. */ SDL_atomic_t paused; SDL_bool iscapture; /* Scratch buffer used in the bridge between SDL and the user callback. */ Uint8 *work_buffer; /* Size, in bytes, of work_buffer. */ Uint32 work_buffer_len; /* A mutex for locking the mixing buffers */ SDL_mutex *mixer_lock; /* A thread to feed the audio device */ SDL_Thread *thread; SDL_threadID threadid; /* Queued buffers (if app not using callback). */ SDL_DataQueue *buffer_queue; /* * * */ /* Data private to this driver */ struct SDL_PrivateAudioData *hidden; void *handle; }; #undef _THIS typedef struct AudioBootStrap { const char *name; const char *desc; int (*init) (SDL_AudioDriverImpl * impl); int demand_only; /* 1==request explicitly, or it won't be available. */ } AudioBootStrap; /* Not all of these are available in a given build. Use #ifdefs, etc. */ extern AudioBootStrap PULSEAUDIO_bootstrap; extern AudioBootStrap ALSA_bootstrap; extern AudioBootStrap JACK_bootstrap; extern AudioBootStrap SNDIO_bootstrap; extern AudioBootStrap NETBSDAUDIO_bootstrap; extern AudioBootStrap DSP_bootstrap; extern AudioBootStrap QSAAUDIO_bootstrap; extern AudioBootStrap SUNAUDIO_bootstrap; extern AudioBootStrap ARTS_bootstrap; extern AudioBootStrap ESD_bootstrap; extern AudioBootStrap NACLAUDIO_bootstrap; extern AudioBootStrap NAS_bootstrap; extern AudioBootStrap WASAPI_bootstrap; extern AudioBootStrap DSOUND_bootstrap; extern AudioBootStrap WINMM_bootstrap; extern AudioBootStrap PAUDIO_bootstrap; extern AudioBootStrap HAIKUAUDIO_bootstrap; extern AudioBootStrap COREAUDIO_bootstrap; extern AudioBootStrap DISKAUDIO_bootstrap; extern AudioBootStrap DUMMYAUDIO_bootstrap; extern AudioBootStrap FUSIONSOUND_bootstrap; extern AudioBootStrap openslES_bootstrap; extern AudioBootStrap ANDROIDAUDIO_bootstrap; extern AudioBootStrap PSPAUDIO_bootstrap; extern AudioBootStrap EMSCRIPTENAUDIO_bootstrap; #endif /* SDL_sysaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
{ "content_hash": "0809b612a3c65f0345c692c965a67884", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 103, "avg_line_length": 34.422680412371136, "alnum_prop": 0.7207247678945792, "repo_name": "SuperWangKai/Urho3D", "id": "5a87a3b60eac606b533618b3d86264ec21121580", "size": "7616", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "Source/ThirdParty/SDL/src/audio/SDL_sysaudio.h", "mode": "33188", "license": "mit", "language": [ { "name": "AngelScript", "bytes": "1480081" }, { "name": "Batchfile", "bytes": "16611" }, { "name": "C++", "bytes": "8453831" }, { "name": "CMake", "bytes": "413641" }, { "name": "GLSL", "bytes": "154112" }, { "name": "HLSL", "bytes": "178063" }, { "name": "HTML", "bytes": "1375" }, { "name": "Kotlin", "bytes": "37791" }, { "name": "Lua", "bytes": "589912" }, { "name": "MAXScript", "bytes": "94704" }, { "name": "Objective-C", "bytes": "6539" }, { "name": "Ruby", "bytes": "56062" }, { "name": "Shell", "bytes": "28209" } ], "symlink_target": "" }
package org.elasticsearch.analysis.common; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.pattern.SimplePatternSplitTokenizer; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.analysis.AbstractTokenizerFactory; public class SimplePatternSplitTokenizerFactory extends AbstractTokenizerFactory { private final String pattern; public SimplePatternSplitTokenizerFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) { super(indexSettings, settings, name); pattern = settings.get("pattern", ""); } @Override public Tokenizer create() { return new SimplePatternSplitTokenizer(pattern); } }
{ "content_hash": "96411e9fa2cf1c94b574e2b994bd539c", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 133, "avg_line_length": 32.03846153846154, "alnum_prop": 0.7911164465786314, "repo_name": "robin13/elasticsearch", "id": "ab508fcbfe34daa178dad8829af61d89a71c4cf9", "size": "1186", "binary": false, "copies": "36", "ref": "refs/heads/master", "path": "modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SimplePatternSplitTokenizerFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "14049" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "315863" }, { "name": "HTML", "bytes": "3399" }, { "name": "Java", "bytes": "40107206" }, { "name": "Perl", "bytes": "7271" }, { "name": "Python", "bytes": "54437" }, { "name": "Shell", "bytes": "108937" } ], "symlink_target": "" }
package net.lecousin.framework.core.tests.text; import java.util.Arrays; import java.util.Collection; import net.lecousin.framework.core.test.runners.LCConcurrentRunner; import net.lecousin.framework.core.test.text.TestArrayString; import net.lecousin.framework.text.ArrayString; import net.lecousin.framework.text.ByteArrayStringIso8859; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; @RunWith(LCConcurrentRunner.Parameterized.class) @org.junit.runners.Parameterized.UseParametersRunnerFactory(LCConcurrentRunner.ConcurrentParameterizedRunnedFactory.class) public class TestByteArrayStringIso8859 extends TestArrayString { @SuppressWarnings("boxing") @Parameters(name = "start = {0}, end = {1}") public static Collection<Object[]> parameters() { return Arrays.asList( new Object[] { 0, 0 }, new Object[] { 1, 0 }, new Object[] { 0, 1 }, new Object[] { 1, 1 }, new Object[] { 10, 0 }, new Object[] { 0, 10 }, new Object[] { 10, 10 } ); } public TestByteArrayStringIso8859(int start, int end) { this.start = start; this.end = end; } protected int start; protected int end; @Override protected ArrayString createString(String s) { byte[] chars = new byte[s.length() + start + end]; char[] c = s.toCharArray(); for (int i = 0; i < c.length; ++i) chars[i + start] = (byte)c[i]; return new ByteArrayStringIso8859(chars, start, c.length, c.length + end); } @Test public void testConstructor() { ByteArrayStringIso8859 s1 = new ByteArrayStringIso8859(5); s1.append("Hello").append(' ').append("World").append('!'); ByteArrayStringIso8859 s2 = new ByteArrayStringIso8859(s1); s1.append("!!!"); Assert.assertEquals("Hello World!", s2.asString()); } }
{ "content_hash": "d9bc663edd3fe78b4c276391bf7119ab", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 171, "avg_line_length": 30.610169491525422, "alnum_prop": 0.7181616832779624, "repo_name": "lecousin/java-framework-core", "id": "5aab54faa9f5d48af67c9f701e61d1bce308a81f", "size": "1806", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "net.lecousin.core/src/test/java/net/lecousin/framework/core/tests/text/TestByteArrayStringIso8859.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2710621" }, { "name": "Perl", "bytes": "5" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Bivi.Domaine { public class RechercheArticleResult { public IEnumerable<ArticleListeResult> Articles { get; set; } public IEnumerable<AxeResult> Axes { get; set; } } }
{ "content_hash": "8ada37eef42ef37725a330f0d6382c0c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 69, "avg_line_length": 23.615384615384617, "alnum_prop": 0.6775244299674267, "repo_name": "apo-j/Projects_Working", "id": "3c0e6702504a1cd5ee8817a5ba948c601dd7f284", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Bivi/src/Bivi.Common/Bivi.Domaine/Results/RechercheArticleResult.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "16118" }, { "name": "Batchfile", "bytes": "1096" }, { "name": "C#", "bytes": "27262375" }, { "name": "CSS", "bytes": "8474090" }, { "name": "Groff", "bytes": "2101703" }, { "name": "HTML", "bytes": "4910101" }, { "name": "JavaScript", "bytes": "20716565" }, { "name": "PHP", "bytes": "9283" }, { "name": "XSLT", "bytes": "930531" } ], "symlink_target": "" }
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI spec version: 1.5.1-pre.0 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator * https://github.com/OpenAPITools/openapi-generator * Do not edit the class manually. */ #include "OpenAPIFreeStyleBuild.h" #include "OpenAPIModule.h" #include "OpenAPIHelpers.h" #include "Templates/SharedPointer.h" namespace OpenAPI { void OpenAPIFreeStyleBuild::WriteJson(JsonWriter& Writer) const { Writer->WriteObjectStart(); if (_Class.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("_class")); WriteJsonValue(Writer, _Class.GetValue()); } if (Number.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("number")); WriteJsonValue(Writer, Number.GetValue()); } if (Url.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("url")); WriteJsonValue(Writer, Url.GetValue()); } if (Actions.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("actions")); WriteJsonValue(Writer, Actions.GetValue()); } if (Building.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("building")); WriteJsonValue(Writer, Building.GetValue()); } if (Description.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("description")); WriteJsonValue(Writer, Description.GetValue()); } if (DisplayName.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("displayName")); WriteJsonValue(Writer, DisplayName.GetValue()); } if (Duration.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("duration")); WriteJsonValue(Writer, Duration.GetValue()); } if (EstimatedDuration.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("estimatedDuration")); WriteJsonValue(Writer, EstimatedDuration.GetValue()); } if (Executor.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("executor")); WriteJsonValue(Writer, Executor.GetValue()); } if (FullDisplayName.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("fullDisplayName")); WriteJsonValue(Writer, FullDisplayName.GetValue()); } if (Id.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("id")); WriteJsonValue(Writer, Id.GetValue()); } if (KeepLog.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("keepLog")); WriteJsonValue(Writer, KeepLog.GetValue()); } if (QueueId.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("queueId")); WriteJsonValue(Writer, QueueId.GetValue()); } if (Result.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("result")); WriteJsonValue(Writer, Result.GetValue()); } if (Timestamp.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("timestamp")); WriteJsonValue(Writer, Timestamp.GetValue()); } if (BuiltOn.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("builtOn")); WriteJsonValue(Writer, BuiltOn.GetValue()); } if (ChangeSet.IsSet()) { Writer->WriteIdentifierPrefix(TEXT("changeSet")); WriteJsonValue(Writer, ChangeSet.GetValue()); } Writer->WriteObjectEnd(); } bool OpenAPIFreeStyleBuild::FromJson(const TSharedPtr<FJsonValue>& JsonValue) { const TSharedPtr<FJsonObject>* Object; if (!JsonValue->TryGetObject(Object)) return false; bool ParseSuccess = true; ParseSuccess &= TryGetJsonValue(*Object, TEXT("_class"), _Class); ParseSuccess &= TryGetJsonValue(*Object, TEXT("number"), Number); ParseSuccess &= TryGetJsonValue(*Object, TEXT("url"), Url); ParseSuccess &= TryGetJsonValue(*Object, TEXT("actions"), Actions); ParseSuccess &= TryGetJsonValue(*Object, TEXT("building"), Building); ParseSuccess &= TryGetJsonValue(*Object, TEXT("description"), Description); ParseSuccess &= TryGetJsonValue(*Object, TEXT("displayName"), DisplayName); ParseSuccess &= TryGetJsonValue(*Object, TEXT("duration"), Duration); ParseSuccess &= TryGetJsonValue(*Object, TEXT("estimatedDuration"), EstimatedDuration); ParseSuccess &= TryGetJsonValue(*Object, TEXT("executor"), Executor); ParseSuccess &= TryGetJsonValue(*Object, TEXT("fullDisplayName"), FullDisplayName); ParseSuccess &= TryGetJsonValue(*Object, TEXT("id"), Id); ParseSuccess &= TryGetJsonValue(*Object, TEXT("keepLog"), KeepLog); ParseSuccess &= TryGetJsonValue(*Object, TEXT("queueId"), QueueId); ParseSuccess &= TryGetJsonValue(*Object, TEXT("result"), Result); ParseSuccess &= TryGetJsonValue(*Object, TEXT("timestamp"), Timestamp); ParseSuccess &= TryGetJsonValue(*Object, TEXT("builtOn"), BuiltOn); ParseSuccess &= TryGetJsonValue(*Object, TEXT("changeSet"), ChangeSet); return ParseSuccess; } }
{ "content_hash": "27e7cb637e9cb06e6cd467c7b29ba91e", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 113, "avg_line_length": 33.35114503816794, "alnum_prop": 0.7338063630121309, "repo_name": "cliffano/swaggy-jenkins", "id": "bd30a5450973c3de032c9547e9a7b3ce1e7dad18", "size": "4369", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "clients/cpp-ue4/generated/Private/OpenAPIFreeStyleBuild.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "569823" }, { "name": "Apex", "bytes": "741346" }, { "name": "Batchfile", "bytes": "14792" }, { "name": "C", "bytes": "971274" }, { "name": "C#", "bytes": "5131336" }, { "name": "C++", "bytes": "7799032" }, { "name": "CMake", "bytes": "20609" }, { "name": "CSS", "bytes": "4873" }, { "name": "Clojure", "bytes": "129018" }, { "name": "Crystal", "bytes": "864941" }, { "name": "Dart", "bytes": "876777" }, { "name": "Dockerfile", "bytes": "7385" }, { "name": "Eiffel", "bytes": "424642" }, { "name": "Elixir", "bytes": "139252" }, { "name": "Elm", "bytes": "187067" }, { "name": "Emacs Lisp", "bytes": "191" }, { "name": "Erlang", "bytes": "373074" }, { "name": "F#", "bytes": "556012" }, { "name": "Gherkin", "bytes": "951" }, { "name": "Go", "bytes": "345227" }, { "name": "Groovy", "bytes": "89524" }, { "name": "HTML", "bytes": "2367424" }, { "name": "Haskell", "bytes": "680841" }, { "name": "Java", "bytes": "12164874" }, { "name": "JavaScript", "bytes": "1959006" }, { "name": "Kotlin", "bytes": "1280953" }, { "name": "Lua", "bytes": "322316" }, { "name": "Makefile", "bytes": "11882" }, { "name": "Nim", "bytes": "65818" }, { "name": "OCaml", "bytes": "94665" }, { "name": "Objective-C", "bytes": "464903" }, { "name": "PHP", "bytes": "4383673" }, { "name": "Perl", "bytes": "743304" }, { "name": "PowerShell", "bytes": "678274" }, { "name": "Python", "bytes": "5529523" }, { "name": "QMake", "bytes": "6915" }, { "name": "R", "bytes": "840841" }, { "name": "Raku", "bytes": "10945" }, { "name": "Ruby", "bytes": "328360" }, { "name": "Rust", "bytes": "1735375" }, { "name": "Scala", "bytes": "1387368" }, { "name": "Shell", "bytes": "407167" }, { "name": "Swift", "bytes": "342562" }, { "name": "TypeScript", "bytes": "3060093" } ], "symlink_target": "" }
<?php namespace App\Listeners; use App\Jobs\PostGitDeployedJob; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Orphans\GitDeploy\Events\GitDeployed; class GitDeployedListener implements ShouldQueue { use InteractsWithQueue; /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param GitDeployed $event * * @return void */ public function handle(GitDeployed $event) { PostGitDeployedJob::dispatch(); } }
{ "content_hash": "3a4c3c53977b40aac1f75e419a570270", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 48, "avg_line_length": 17.685714285714287, "alnum_prop": 0.630048465266559, "repo_name": "NottingHack/hms2", "id": "1efb4181fb081722890dfd9cdc416c39db5c7875", "size": "619", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "app/Listeners/GitDeployedListener.php", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "324994" }, { "name": "PHP", "bytes": "1634851" }, { "name": "Shell", "bytes": "6621" }, { "name": "Vue", "bytes": "204358" } ], "symlink_target": "" }
balancing/balancing.cpp balancing/display.cpp balancing/main.cpp balancing/stimulus.cpp
{ "content_hash": "85893f6b0f4ca1369dbee1a1fc523d09", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 23, "avg_line_length": 22, "alnum_prop": 0.8636363636363636, "repo_name": "gem5/gem5", "id": "0a6488983f3bc7b61032b00975890eb366da6e5a", "size": "88", "binary": false, "copies": "6", "ref": "refs/heads/stable", "path": "src/systemc/tests/systemc/misc/cae_test/general/control/case/balancing/balancing.f", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "145626" }, { "name": "Awk", "bytes": "3386" }, { "name": "BASIC", "bytes": "2884" }, { "name": "C", "bytes": "3927153" }, { "name": "C++", "bytes": "42960484" }, { "name": "CMake", "bytes": "133888" }, { "name": "Dockerfile", "bytes": "34102" }, { "name": "Emacs Lisp", "bytes": "1914" }, { "name": "Forth", "bytes": "354" }, { "name": "Fortran", "bytes": "15436" }, { "name": "HTML", "bytes": "146414" }, { "name": "Hack", "bytes": "139769" }, { "name": "Java", "bytes": "6966" }, { "name": "M4", "bytes": "42624" }, { "name": "Makefile", "bytes": "39573" }, { "name": "Perl", "bytes": "23784" }, { "name": "Python", "bytes": "8079781" }, { "name": "Roff", "bytes": "8754" }, { "name": "SCSS", "bytes": "2971" }, { "name": "SWIG", "bytes": "173" }, { "name": "Scala", "bytes": "5328" }, { "name": "Shell", "bytes": "95638" }, { "name": "Starlark", "bytes": "25668" }, { "name": "SuperCollider", "bytes": "8869" }, { "name": "Vim Script", "bytes": "4343" }, { "name": "sed", "bytes": "3897" } ], "symlink_target": "" }