repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
koji-m/airbyte
airbyte-integrations/connectors/destination-oracle/src/test-integration/java/io/airbyte/integrations/destination/oracle/OracleIntegrationTest.java
/* * Copyright (c) 2021 Airbyte, Inc., all rights reserved. */ package io.airbyte.integrations.destination.oracle; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.airbyte.commons.io.IOs; import io.airbyte.commons.json.Jsons; import io.airbyte.db.Database; import io.airbyte.db.Databases; import io.airbyte.integrations.destination.ExtendedNameTransformer; import io.airbyte.integrations.standardtest.destination.DestinationAcceptanceTest; import java.nio.file.Path; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.jooq.JSONFormat; import org.jooq.JSONFormat.RecordFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OracleIntegrationTest extends DestinationAcceptanceTest { private static final Logger LOGGER = LoggerFactory.getLogger(OracleIntegrationTest.class); private static final JSONFormat JSON_FORMAT = new JSONFormat().recordFormat(RecordFormat.OBJECT); private static JsonNode baseConfig; private ExtendedNameTransformer namingResolver = new OracleNameTransformer(); private static JsonNode config; public JsonNode getStaticConfig() { return Jsons.deserialize(IOs.readFile(Path.of("secrets/config.json"))); } @Override protected String getImageName() { return "airbyte/destination-oracle:dev"; } @Override protected JsonNode getConfig() { return config; } @Override protected List<JsonNode> retrieveRecords(TestDestinationEnv env, String streamName, String namespace, JsonNode streamSchema) throws Exception { return retrieveRecordsFromTable(namingResolver.getRawTableName(streamName), namespace) .stream() .map(r -> Jsons.deserialize(r.get(OracleDestination.COLUMN_NAME_DATA.replace("\"", "")).asText())) .collect(Collectors.toList()); } @Override protected boolean implementsNamespaces() { return true; } @Override protected boolean supportsDBT() { return true; } @Override protected List<JsonNode> retrieveNormalizedRecords(TestDestinationEnv env, String streamName, String namespace) throws Exception { String tableName = namingResolver.getIdentifier(streamName); return retrieveRecordsFromTable(tableName, namespace); } @Override protected JsonNode getFailCheckConfig() { final JsonNode invalidConfig = Jsons.clone(config); ((ObjectNode) invalidConfig).put("password", "<PASSWORD>"); return invalidConfig; } @Override protected List<String> resolveIdentifier(String identifier) { final List<String> result = new ArrayList<>(); final String resolved = namingResolver.getIdentifier(identifier); result.add(identifier); result.add(resolved); if (!resolved.startsWith("\"")) { result.add(resolved.toLowerCase()); result.add(resolved.toUpperCase()); } return result; } private List<JsonNode> retrieveRecordsFromTable(String tableName, String schemaName) throws SQLException { List<org.jooq.Record> result = getDatabase() .query(ctx -> ctx.fetch(String.format("SELECT * FROM %s.%s ORDER BY %s ASC", schemaName, tableName, OracleDestination.COLUMN_NAME_EMITTED_AT)) .stream() .collect(Collectors.toList())); return result .stream() .map(r -> r.formatJSON(JSON_FORMAT)) .map(Jsons::deserialize) .collect(Collectors.toList()); } private static Database getDatabase() { // todo (cgardens) - rework this abstraction so that we do not have to pass a null into the // constructor. at least explicitly handle it, even if the impl doesn't change. return Databases.createDatabase( baseConfig.get("username").asText(), baseConfig.get("password").asText(), String.format("jdbc:oracle:thin:@//%s:%s/%s", baseConfig.get("host").asText(), baseConfig.get("port").asText(), baseConfig.get("sid").asText()), "oracle.jdbc.driver.OracleDriver", null); } private List<String> allTables; private List<String> getAllTables(Database db) { try { return db.query(ctx -> ctx.fetch("select OWNER, TABLE_NAME from ALL_TABLES where upper(TABLESPACE_NAME) = 'USERS'") .stream() .map(r -> String.format("%s.%s", r.get("OWNER"), r.get("TABLE_NAME"))) .collect(Collectors.toList())); } catch (SQLException e) { LOGGER.error("Error while cleaning up test.", e); return null; } } @Override protected void setup(TestDestinationEnv testEnv) throws SQLException { // config = getConfig(db); baseConfig = getStaticConfig(); config = Jsons.clone(baseConfig); final Database database = getDatabase(); allTables = getAllTables(database); } @Override protected void tearDown(TestDestinationEnv testEnv) { config = getStaticConfig(); final Database database = getDatabase(); var tables = getAllTables(database); try { for (String table : tables) { database.query(ctx -> { ctx.execute("drop table " + table); return null; }); } } catch (SQLException e) { LOGGER.error("Error while cleaning up test.", e); } } }
SamB/cerberus
tests/csmith/small_int_arith/csmith_957.c
<filename>tests/csmith/small_int_arith/csmith_957.c // Options: --no-arrays --no-pointers --no-structs --no-unions --argc --no-bitfields --checksum --comma-operators --compound-assignment --concise --consts --divs --embedded-assigns --pre-incr-operator --pre-decr-operator --post-incr-operator --post-decr-operator --unary-plus-operator --jumps --longlong --int8 --uint8 --no-float --main --math64 --muls --safe-math --no-packed-struct --no-paranoid --no-volatiles --no-volatile-pointers --const-pointers --no-builtins --max-array-dim 1 --max-array-len-per-dim 4 --max-block-depth 1 --max-block-size 4 --max-expr-complexity 2 --max-funcs 2 --max-pointer-depth 2 --max-struct-fields 2 --max-union-fields 2 -o csmith_957.c #include "csmith.h" static long __undefined; static uint32_t g_4 = 1UL; static int32_t g_6 = 0xBE187950L; static uint16_t func_1(void); static uint16_t func_1(void) { int8_t l_5 = 0x20L; int32_t l_10 = 1L; g_6 = (safe_lshift_func_uint8_t_u_s((g_4 ^ l_5), g_4)); for (g_4 = (-15); (g_4 == 42); ++g_4) { int32_t l_9 = 0x0BC5021CL; return l_9; } l_10 |= l_5; return l_5; } int main (int argc, char* argv[]) { int print_hash_value = 0; if (argc == 2 && strcmp(argv[1], "1") == 0) print_hash_value = 1; platform_main_begin(); crc32_gentab(); func_1(); transparent_crc(g_4, "g_4", print_hash_value); transparent_crc(g_6, "g_6", print_hash_value); platform_main_end(crc32_context ^ 0xFFFFFFFFUL, print_hash_value); return 0; }
fioresoft/NO5
SimpleInputDlg.h
// SimpleInputDlg.h: interface for the CSimpleInputDlg class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_SIMPLEINPUTDLG_H__85DF3529_CF6E_4523_A991_D26E351E6D8F__INCLUDED_) #define AFX_SIMPLEINPUTDLG_H__85DF3529_CF6E_4523_A991_D26E351E6D8F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <atlddx.h> class CSimpleInputDlg : \ public CDialogImpl<CSimpleInputDlg>, public CWinDataExchange<CSimpleInputDlg> { public: enum { IDD = IDD_INPUT }; BEGIN_MSG_MAP(CSimpleInputDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOK) COMMAND_ID_HANDLER(IDCANCEL, OnCancel) END_MSG_MAP() BEGIN_DDX_MAP(CSimpleInputDlg) DDX_TEXT_LEN(IDC_EDIT1,m_text,m_max) END_DDX_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); CSimpleInputDlg(void) { m_max = 0; m_bInit = false; } void Init(LPCTSTR title,LPCTSTR label,int maxchars,LPCTSTR txt = NULL) { m_text = txt; m_label = label; m_title = title; m_max = maxchars; m_bInit = true; } CString m_text; CString m_label; CString m_title; int m_max; // max input chars bool m_bInit; }; #endif // !defined(AFX_SIMPLEINPUTDLG_H__85DF3529_CF6E_4523_A991_D26E351E6D8F__INCLUDED_)
UXPin/mineral-ui
src/website/app/demos/Dropdown/examples/scrolling.js
/* @flow */ import Button from '../../../../../library/Button'; import Dropdown from '../../../../../library/Dropdown'; import ScrollParent from '../../Popover/components/ScrollBox'; import data from '../../Menu/components/menuData'; export default { id: 'scrolling-container', title: 'Scrolling container', description: `Dropdown will attempt to keep its menu visible in an \`overflow: scroll\` container.`, scope: { Button, data, Dropdown, ScrollParent }, source: ` <ScrollParent height={430}> <Dropdown data={data} isOpen placement="bottom-start"> <Button>Menu</Button> </Dropdown> </ScrollParent> ` };
qwersm/ruoyi
ruoyi-knowledge/src/main/java/com/ruoyi/knowledge/service/impl/CmsCategoryServiceImpl.java
package com.ruoyi.knowledge.service.impl; import java.util.ArrayList; import java.util.List; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.Ztree; import com.ruoyi.common.core.domain.ZtreeExt; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.knowledge.mapper.CmsCategoryMapper; import com.ruoyi.knowledge.domain.CmsCategory; import com.ruoyi.knowledge.service.ICmsCategoryService; import com.ruoyi.common.core.text.Convert; /** * 栏目 服务层实现 * * @author ruoyi * @date 2019-05-05 */ @Service public class CmsCategoryServiceImpl implements ICmsCategoryService { @Autowired private CmsCategoryMapper cmsCategoryMapper; /** * 查询栏目信息 * * @param id 栏目ID * @return 栏目信息 */ @Override public CmsCategory selectCmsCategoryById(String id) { return cmsCategoryMapper.selectCmsCategoryById(id); } /** * 查询栏目列表 * * @param cmsCategory 栏目信息 * @return 栏目集合 */ @Override public List<CmsCategory> selectCmsCategoryList(CmsCategory cmsCategory) { return cmsCategoryMapper.selectCmsCategoryList(cmsCategory); } /** * 新增栏目 * * @param cmsCategory 栏目信息 * @return 结果 */ @Override public int insertCmsCategory(CmsCategory cmsCategory) { CmsCategory info = cmsCategoryMapper.selectCmsCategoryById(cmsCategory.getParentId()); if(info!=null){ cmsCategory.setParentIds(info.getParentIds() + "," + cmsCategory.getParentId()); }else{ cmsCategory.setParentIds("0," + cmsCategory.getParentId()); } return cmsCategoryMapper.insertCmsCategory(cmsCategory); } /** * 修改栏目 * * @param cmsCategory 栏目信息 * @return 结果 */ @Override public int updateCmsCategory(CmsCategory cmsCategory) { return cmsCategoryMapper.updateCmsCategory(cmsCategory); } /** * 删除栏目对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deleteCmsCategoryByIds(String ids) { return cmsCategoryMapper.deleteCmsCategoryByIds(Convert.toStrArray(ids)); } @Override public int selectCountCategoryByParentId(String id) { return cmsCategoryMapper.selectCountCategoryByParentId(id); } @Override public List<ZtreeExt> selectCategoryTree(CmsCategory cmsCategory) { List<CmsCategory> deptList = cmsCategoryMapper.selectCmsCategoryList(cmsCategory); List<ZtreeExt> ztrees = initZtree(deptList); return ztrees; } @Override public CmsCategory selectCategoryByName(CmsCategory cmsCategory) { return cmsCategoryMapper.selectCategoryByName(cmsCategory); } /** * 对象转部门树 * * @param cmsCategoryList 部门列表 * @return 树结构列表 */ public List<ZtreeExt> initZtree(List<CmsCategory> cmsCategoryList) { return initZtree(cmsCategoryList, null); } public List<ZtreeExt> initZtree(List<CmsCategory> cmsCategoryList, List<String> roleDeptList) { List<ZtreeExt> ztrees = new ArrayList<ZtreeExt>(); boolean isCheck = StringUtils.isNotNull(roleDeptList); for (CmsCategory cmsCategory : cmsCategoryList) { if (UserConstants.DEPT_NORMAL.equals(cmsCategory.getDelFlag())) { ZtreeExt ztree = new ZtreeExt(); ztree.setId(cmsCategory.getId()); ztree.setpId(cmsCategory.getParentId()); ztree.setName(cmsCategory.getName()); ztree.setTitle(cmsCategory.getName()); if (isCheck) { ztree.setChecked(roleDeptList.contains(cmsCategory.getId() + cmsCategory.getName())); } ztrees.add(ztree); } } return ztrees; } }
penehyba/arquillian-cube
kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/api/AnnotationProvider.java
<reponame>penehyba/arquillian-cube<filename>kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/api/AnnotationProvider.java package org.arquillian.cube.kubernetes.api; import java.util.Map; public interface AnnotationProvider extends WithToImmutable<AnnotationProvider> { String SESSION_ID = "arquillian.org/test-session-id"; String TEST_SESSION_STATUS = "arquillian.org/test-session-status"; String TEST_CASE_STATUS_FORMAT = "fabric8.io/test-status-%s"; int MAX_ANNOTATION_KEY_LENGTH = 63; Map<String, String> create(String sessionId, String status); }
Kapersyx/sync-endpoint
src/main/java/org/opendatakit/aggregate/odktables/rest/entity/PropertyEntryXmlList.java
/* * Copyright (C) 2014 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.opendatakit.aggregate.odktables.rest.entity; import java.util.ArrayList; import java.util.Collections; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; /** * This holds a list of {@link PropertyEntryXml}. * Proper XML documents can contain only one root node. * This wrapping class provides that root node. * * This is used when getting the properties.csv as an * XML properties array, and when putting an update to that * file as an XML properties array. * * See {@link PropertyEntryJson} for the JSON variant. * * @author <EMAIL> * */ @JacksonXmlRootElement(localName="propertyList") public class PropertyEntryXmlList { /** * The KeyValueStore entries. */ @JsonProperty(required = true) @JsonTypeInfo(use=JsonTypeInfo.Id.NONE, defaultImpl=PropertyEntryXml.class) @JacksonXmlElementWrapper(useWrapping=false,localName="properties") @JacksonXmlProperty(localName="property") private ArrayList<PropertyEntryXml> properties; /** * Constructor used by Jackson */ public PropertyEntryXmlList() { this.properties = new ArrayList<PropertyEntryXml>(); } /** * Constructor used by our Java code. * * The list cannot contain any nulls. * * Sorts the passed-in array and * takes ownership of it. * * @param entries */ public PropertyEntryXmlList(ArrayList<PropertyEntryXml> properties) { if ( properties == null ) { this.properties = new ArrayList<PropertyEntryXml>(); } else { this.properties = properties; // throws an exception if there are any nulls in the list... Collections.sort(this.properties); } } /** * Get the sorted list of properties. * * @return */ public ArrayList<PropertyEntryXml> getProperties() { return properties; } /** * The list cannot contain any nulls. * * Sorts the passed-in array and * takes ownership of it. * * @param properties */ public void setProperties(ArrayList<PropertyEntryXml> properties) { this.properties = properties; // throws an exception if there are any nulls in the list... Collections.sort(this.properties); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((properties == null) ? 0 : properties.hashCode()); return result; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!(obj instanceof PropertyEntryXmlList)) { return false; } PropertyEntryXmlList other = (PropertyEntryXmlList) obj; boolean simpleResult = (properties == null ? other.properties == null : (other.properties != null && properties.size() == other.properties.size())); if ( !simpleResult ) { return false; } if ( properties == null ) { return true; } // the properties are an ordered list. // Do an O(n) compare of the lists. for ( int i = 0 ; i < properties.size() ; ++i ) { PropertyEntryXml left = this.properties.get(i); PropertyEntryXml right = other.properties.get(i); if ( ! left.equals(right) ) { return false; } } return true; } }
vicpopov/omim
routing/geometry.cpp
<reponame>vicpopov/omim #include "routing/geometry.hpp" #include "routing/city_roads.hpp" #include "routing/maxspeeds.hpp" #include "routing/routing_exceptions.hpp" #include "routing/routing_options.hpp" #include "indexer/altitude_loader.hpp" #include "indexer/data_source.hpp" #include "indexer/ftypes_matcher.hpp" #include "geometry/distance_on_sphere.hpp" #include "geometry/mercator.hpp" #include "base/assert.hpp" #include "base/string_utils.hpp" #include <algorithm> #include <string> using namespace routing; using namespace std; namespace { // @TODO(bykoianko) Consider setting cache size based on available memory. // Maximum road geometry cache size in items. size_t constexpr kRoadsCacheSize = 5000; double CalcFerryDurationHours(string const & durationHours, double roadLenKm) { // Look for more info: https://confluence.mail.ru/display/MAPSME/Ferries // Shortly: the coefs were received from statistic about ferries with durations in OSM. double constexpr kIntercept = 0.2490726747447476; double constexpr kSlope = 0.02078913; if (durationHours.empty()) return kIntercept + kSlope * roadLenKm; double durationH = 0.0; CHECK(strings::to_double(durationHours.c_str(), durationH), (durationHours)); // See: https://confluence.mail.ru/download/attachments/249123157/image2019-8-22_16-15-53.png // Shortly: we drop some points: (x: lengthKm, y: durationH), that are upper or lower these two lines. double constexpr kUpperBoundIntercept = 4.0; double constexpr kUpperBoundSlope = 0.037; if (kUpperBoundIntercept + kUpperBoundSlope * roadLenKm - durationH < 0) return kIntercept + kSlope * roadLenKm; double constexpr kLowerBoundIntercept = -2.0; double constexpr kLowerBoundSlope = 0.015; if (kLowerBoundIntercept + kLowerBoundSlope * roadLenKm - durationH > 0) return kIntercept + kSlope * roadLenKm; return durationH; } // GeometryLoaderImpl ------------------------------------------------------------------------------ class GeometryLoaderImpl final : public GeometryLoader { public: GeometryLoaderImpl(DataSource const & dataSource, MwmSet::MwmHandle const & handle, shared_ptr<VehicleModelInterface> vehicleModel, AttrLoader attrLoader, bool loadAltitudes); // GeometryLoader overrides: void Load(uint32_t featureId, RoadGeometry & road) override; private: shared_ptr<VehicleModelInterface> m_vehicleModel; AttrLoader m_attrLoader; FeaturesLoaderGuard m_guard; string const m_country; feature::AltitudeLoader m_altitudeLoader; bool const m_loadAltitudes; }; GeometryLoaderImpl::GeometryLoaderImpl(DataSource const & dataSource, MwmSet::MwmHandle const & handle, shared_ptr<VehicleModelInterface> vehicleModel, AttrLoader attrLoader, bool loadAltitudes) : m_vehicleModel(move(vehicleModel)) , m_attrLoader(move(attrLoader)) , m_guard(dataSource, handle.GetId()) , m_country(handle.GetInfo()->GetCountryName()) , m_altitudeLoader(dataSource, handle.GetId()) , m_loadAltitudes(loadAltitudes) { CHECK(handle.IsAlive(), ()); CHECK(m_vehicleModel, ()); CHECK(m_attrLoader.m_cityRoads, ()); CHECK(m_attrLoader.m_maxspeeds, ()); } void GeometryLoaderImpl::Load(uint32_t featureId, RoadGeometry & road) { auto feature = m_guard.GetFeatureByIndex(featureId); if (!feature) MYTHROW(RoutingException, ("Feature", featureId, "not found in ", m_country)); feature->ParseGeometry(FeatureType::BEST_GEOMETRY); geometry::Altitudes const * altitudes = nullptr; if (m_loadAltitudes) altitudes = &(m_altitudeLoader.GetAltitudes(featureId, feature->GetPointsCount())); road.Load(*m_vehicleModel, *feature, altitudes, m_attrLoader.m_cityRoads->IsCityRoad(featureId), m_attrLoader.m_maxspeeds->GetMaxspeed(featureId)); m_altitudeLoader.ClearCache(); } // FileGeometryLoader ------------------------------------------------------------------------------ class FileGeometryLoader final : public GeometryLoader { public: FileGeometryLoader(string const & fileName, shared_ptr<VehicleModelInterface> vehicleModel); // GeometryLoader overrides: void Load(uint32_t featureId, RoadGeometry & road) override; private: FeaturesVectorTest m_featuresVector; CityRoads m_cityRoads; Maxspeeds m_maxspeeds; shared_ptr<VehicleModelInterface> m_vehicleModel; }; FileGeometryLoader::FileGeometryLoader(string const & fileName, shared_ptr<VehicleModelInterface> vehicleModel) : m_featuresVector(FilesContainerR(make_unique<FileReader>(fileName))) , m_vehicleModel(vehicleModel) { auto const cont = FilesContainerR(make_unique<FileReader>(fileName)); try { if (cont.IsExist(CITY_ROADS_FILE_TAG)) LoadCityRoads(fileName, cont.GetReader(CITY_ROADS_FILE_TAG), m_cityRoads); if (cont.IsExist(MAXSPEEDS_FILE_TAG)) LoadMaxspeeds(cont.GetReader(MAXSPEEDS_FILE_TAG), m_maxspeeds); } catch (Reader::OpenException const & e) { LOG(LERROR, ("File", cont.GetFileName(), "Error while reading", CITY_ROADS_FILE_TAG, "or", MAXSPEEDS_FILE_TAG, "section.", e.Msg())); } CHECK(m_vehicleModel, ()); } void FileGeometryLoader::Load(uint32_t featureId, RoadGeometry & road) { auto feature = m_featuresVector.GetVector().GetByIndex(featureId); CHECK(feature, ()); feature->ParseGeometry(FeatureType::BEST_GEOMETRY); // Note. If FileGeometryLoader is used for generation cross mwm section for bicycle or // pedestrian routing |altitudes| should be used here. road.Load(*m_vehicleModel, *feature, nullptr /* altitudes */, m_cityRoads.IsCityRoad(featureId), m_maxspeeds.GetMaxspeed(featureId)); } } // namespace namespace routing { // RoadGeometry ------------------------------------------------------------------------------------ RoadGeometry::RoadGeometry(bool oneWay, double weightSpeedKMpH, double etaSpeedKMpH, Points const & points) : m_forwardSpeed{weightSpeedKMpH, etaSpeedKMpH} , m_backwardSpeed(m_forwardSpeed) , m_isOneWay(oneWay) , m_valid(true) { ASSERT_GREATER(weightSpeedKMpH, 0.0, ()); ASSERT_GREATER(etaSpeedKMpH, 0.0, ()); m_junctions.reserve(points.size()); for (auto const & point : points) m_junctions.emplace_back(mercator::ToLatLon(point), geometry::kDefaultAltitudeMeters); } void RoadGeometry::Load(VehicleModelInterface const & vehicleModel, FeatureType & feature, geometry::Altitudes const * altitudes, bool inCity, Maxspeed const & maxspeed) { CHECK(altitudes == nullptr || altitudes->size() == feature.GetPointsCount(), ()); m_valid = vehicleModel.IsRoad(feature); m_isOneWay = vehicleModel.IsOneWay(feature); m_forwardSpeed = vehicleModel.GetSpeed(feature, {true /* forward */, inCity, maxspeed}); m_backwardSpeed = vehicleModel.GetSpeed(feature, {false /* forward */, inCity, maxspeed}); m_highwayType = vehicleModel.GetHighwayType(feature); m_isPassThroughAllowed = vehicleModel.IsPassThroughAllowed(feature); feature::TypesHolder types(feature); auto const & optionsClassfier = RoutingOptionsClassifier::Instance(); for (uint32_t type : types) { if (auto const it = optionsClassfier.Get(type)) m_routingOptions.Add(*it); } m_junctions.clear(); m_junctions.reserve(feature.GetPointsCount()); for (size_t i = 0; i < feature.GetPointsCount(); ++i) { m_junctions.emplace_back(mercator::ToLatLon(feature.GetPoint(i)), altitudes ? (*altitudes)[i] : geometry::kDefaultAltitudeMeters); } if (m_routingOptions.Has(RoutingOptions::Road::Ferry)) { auto const durationHours = feature.GetMetadata(feature::Metadata::FMD_DURATION); auto const roadLenKm = GetRoadLengthM() / 1000.0; double const durationH = CalcFerryDurationHours(durationHours, roadLenKm); CHECK(!base::AlmostEqualAbs(durationH, 0.0, 1e-5), (durationH)); if (roadLenKm != 0.0) { m_forwardSpeed = m_backwardSpeed = SpeedKMpH(std::min(vehicleModel.GetMaxWeightSpeed(), roadLenKm / durationH)); } } if (m_valid && (!m_forwardSpeed.IsValid() || !m_backwardSpeed.IsValid())) { auto const & id = feature.GetID(); CHECK(!m_junctions.empty(), ("mwm:", id.GetMwmName(), ", featureId:", id.m_index)); auto const & begin = m_junctions.front().GetLatLon(); auto const & end = m_junctions.back().GetLatLon(); LOG(LERROR, ("Invalid speed m_forwardSpeed:", m_forwardSpeed, "m_backwardSpeed:", m_backwardSpeed, "mwm:", id.GetMwmName(), ", featureId:", id.m_index, ", begin:", begin, "end:", end)); m_valid = false; } } SpeedKMpH const & RoadGeometry::GetSpeed(bool forward) const { return forward ? m_forwardSpeed : m_backwardSpeed; } double RoadGeometry::GetRoadLengthM() const { double lenM = 0.0; for (size_t i = 1; i < GetPointsCount(); ++i) { lenM += ms::DistanceOnEarth(m_junctions[i - 1].GetLatLon(), m_junctions[i].GetLatLon()); } return lenM; } // Geometry ---------------------------------------------------------------------------------------- Geometry::Geometry(unique_ptr<GeometryLoader> loader) : m_loader(move(loader)) , m_featureIdToRoad(make_unique<RoutingFifoCache>( kRoadsCacheSize, [this](uint32_t featureId, RoadGeometry & road) { m_loader->Load(featureId, road); })) { CHECK(m_loader, ()); } RoadGeometry const & Geometry::GetRoad(uint32_t featureId) { ASSERT(m_featureIdToRoad, ()); ASSERT(m_loader, ()); return m_featureIdToRoad->GetValue(featureId); } // static unique_ptr<GeometryLoader> GeometryLoader::Create(DataSource const & dataSource, MwmSet::MwmHandle const & handle, shared_ptr<VehicleModelInterface> vehicleModel, AttrLoader && attrLoader, bool loadAltitudes) { CHECK(handle.IsAlive(), ()); return make_unique<GeometryLoaderImpl>(dataSource, handle, vehicleModel, move(attrLoader), loadAltitudes); } // static unique_ptr<GeometryLoader> GeometryLoader::CreateFromFile(string const & fileName, shared_ptr<VehicleModelInterface> vehicleModel) { return make_unique<FileGeometryLoader>(fileName, vehicleModel); } } // namespace routing
liziGaoLi/MobileOfficePad
app/src/main/java/com/mobilepolice/office/webservice/ItemAdapter.java
<filename>app/src/main/java/com/mobilepolice/office/webservice/ItemAdapter.java package com.mobilepolice.office.webservice; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.mobilepolice.office.R; import java.util.List; public class ItemAdapter extends ArrayAdapter<Item> { private int resourceId; public ItemAdapter(Context context, int textViewResourceId, List<Item> objects){ super(context, textViewResourceId, objects); resourceId = textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent){ Item item = getItem(position);// 获取当前项的School实例 View view; ViewHolder viewHolder; if(convertView == null){ view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false); viewHolder = new ViewHolder(); // viewHolder.showId = (TextView) view.findViewById(R.id.id); viewHolder.showYear = (TextView)view.findViewById(R.id.Year); viewHolder.showMon = (TextView)view.findViewById(R.id.Month); viewHolder.showDay = (TextView)view.findViewById(R.id.Day); viewHolder.showHour = (TextView)view.findViewById(R.id.Hour); viewHolder.showMin = (TextView)view.findViewById(R.id.Min); viewHolder.showSec= (TextView)view.findViewById(R.id.Sec); viewHolder.showItem = (TextView)view.findViewById(R.id.specific_item); /*viewHolder.showImage = (ImageView)view.findViewById(R.id.small_image);*/ view.setTag(viewHolder); // 将viewHolder存储在View中 } else{ view = convertView; viewHolder = (ViewHolder)view.getTag(); // 重新获取ViewHolder } // viewHolder.showId.setText(String.valueOf(item.getId())); int is = item.getId(); viewHolder.showYear.setText(String.valueOf(item.getIt_year())); viewHolder.showMon.setText(String.valueOf(item.getIt_month())); viewHolder.showDay.setText(String.valueOf(item.getIt_day())); viewHolder.showHour.setText(String.valueOf(item.getAlarm_hour())); viewHolder.showMin.setText(String.valueOf(item.getAlarm_min())); viewHolder.showSec.setText(String.valueOf(item.getAlarm_sec())); viewHolder.showItem.setText(item.getMy_item()); /*byte[]images = item.getNew_image(); if(images != null){ Bitmap bitmap = BitmapFactory.decodeByteArray(images,0,images.length); viewHolder.showImage.setImageBitmap(bitmap); }*/ return view; } class ViewHolder{ // TextView showId; TextView showYear; TextView showMon; TextView showDay; TextView showHour; TextView showMin; TextView showSec; TextView showItem; /*ImageView showImage;*/ } }
cj-chung/alcor
services/data_plane_manager/src/test/java/com/futurewei/alcor/dataplane/entity/UTPortWithSubnetAndIPMapping.java
/* MIT License Copyright(c) 2020 Futurewei Cloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.futurewei.alcor.dataplane.entity; import com.futurewei.alcor.web.entity.port.PortEntity; import java.util.List; /** * Ports created info per Host, not include the ports exist in host already, host and port mapping */ public class UTPortWithSubnetAndIPMapping { private String portId; private String portName; private String portMacAddress; private String vethName; private String bindingHostId; private List<PortEntity.FixedIp> fixedIps; public UTPortWithSubnetAndIPMapping() { } public UTPortWithSubnetAndIPMapping(String portId, List<PortEntity.FixedIp> fixedIps) { this.portId = portId; this.fixedIps = fixedIps; } public String getPortId() { return portId; } public void setPortId(String portId) { this.portId = portId; } public List<PortEntity.FixedIp> getFixedIps() { return fixedIps; } public void setFixedIps(List<PortEntity.FixedIp> fixedIps) { this.fixedIps = fixedIps; } public String getPortName() { return portName; } public void setPortName(String portName) { this.portName = portName; } public String getPortMacAddress() { return portMacAddress; } public void setPortMacAddress(String portMacAddress) { this.portMacAddress = portMacAddress; } public String getVethName() { return vethName; } public void setVethName(String vethName) { this.vethName = vethName; } public String getBindingHostId() { return bindingHostId; } public void setBindingHostId(String bindingHostId) { this.bindingHostId = bindingHostId; } }
jahanzebbaber/hazelcast-jet
hazelcast-jet-core/src/main/java/com/hazelcast/jet/datamodel/Tag.java
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.datamodel; import java.io.Serializable; /** * A tag object useful as a key in heterogeneous maps. Carries static type * information in its type parameter, which is expected to correspond to * the type of the item retrieved from the map. * <p> * Tags are also used by hash-join and co-group builder objects. The same * tag supplied to the builder is used to retrieve the data from the * heterogeneous maps ({@link ItemsByTag}) that appear in the output. * * @param <T> the type of the data associated with the tag * * @since 3.0 */ public final class Tag<T> implements Comparable<Tag<?>>, Serializable { private static final Tag TAG_0 = new Tag(0); private static final Tag TAG_1 = new Tag(1); private static final Tag TAG_2 = new Tag(2); private final int index; private Tag(int index) { this.index = index; } /** * Returns a tag object associated with the specified index. The * tag's type parameter is inferred from the call site. The method * will not necessarily create a new tag object. */ public static <T> Tag<T> tag(int index) { return index == 0 ? TAG_0 : index == 1 ? TAG_1 : index == 2 ? TAG_2 : new Tag<>(index); } /** * Returns the index associated with this tag. It can refer to the * index of a contributing stream in a hash-join or co-group operation, * or to the index used internally to store the data associated with * the tag. */ public int index() { return index; } /** * Returns the tag constant {@link #TAG_0}. */ @SuppressWarnings("unchecked") public static <T> Tag<T> tag0() { return TAG_0; } /** * Returns the tag constant {@link #TAG_1}. */ @SuppressWarnings("unchecked") public static <T> Tag<T> tag1() { return TAG_1; } /** * Returns the tag constant {@link #TAG_2}. */ @SuppressWarnings("unchecked") public static <T> Tag<T> tag2() { return TAG_2; } @Override public boolean equals(Object obj) { return this == obj || obj instanceof Tag && this.index == ((Tag) obj).index; } @Override public int hashCode() { return index; } @Override public int compareTo(Tag<?> that) { return Integer.compare(this.index, that.index); } @Override public String toString() { return "Tag" + index; } }
bieganski/gitlab-runner
vendor/github.com/saracen/fastzip/extractor_unix.go
// +build !windows package fastzip import ( "os" "runtime" "time" "golang.org/x/sys/unix" ) func lchmod(name string, mode os.FileMode) error { var flags int if runtime.GOOS == "linux" { if mode&os.ModeSymlink != 0 { return nil } } else { flags = unix.AT_SYMLINK_NOFOLLOW } err := unix.Fchmodat(unix.AT_FDCWD, name, uint32(mode), flags) if err != nil { return &os.PathError{Op: "lchmod", Path: name, Err: err} } return nil } func lchtimes(name string, mode os.FileMode, atime, mtime time.Time) error { at := unix.NsecToTimeval(atime.UnixNano()) mt := unix.NsecToTimeval(mtime.UnixNano()) tv := [2]unix.Timeval{at, mt} err := unix.Lutimes(name, tv[:]) if err != nil { return &os.PathError{Op: "lchtimes", Path: name, Err: err} } return nil } func lchown(name string, uid, gid int) error { return os.Lchown(name, uid, gid) }
Kardzhaliyski/Java-OOP
2.InheritanceExercise/src/animals/Animal.java
<filename>2.InheritanceExercise/src/animals/Animal.java<gh_stars>0 package animals; public class Animal { private String name; private int age; private String gender; public Animal(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public static boolean isAgeValid(int age) { return age >= 0; } public String getName() { return name; } public int getAge() { return age; } public String getGender() { return gender; } public String produceSound() { return ""; } @Override public String toString() { return this.getClass().getSimpleName() + System.lineSeparator() + this.name + " " + this.age + " " + this.gender + System.lineSeparator() + produceSound(); } }
amarzavery/cool_sdk
lib/services/resourceManagement/lib/resource/models/basicDependency.js
<filename>lib/services/resourceManagement/lib/resource/models/basicDependency.js 'use strict'; var util = require('util'); var models = require('./index'); /** * @class * Initializes a new instance of the BasicDependency class. * @constructor */ function BasicDependency() { } /** * Validate the payload against the BasicDependency schema * * @param {JSON} payload * */ BasicDependency.prototype.validate = function (payload) { if (!payload) { throw new Error('BasicDependency cannot be null.'); } if (payload['id'] !== null && payload['id'] !== undefined && typeof payload['id'].valueOf() !== 'string') { throw new Error('payload[\'id\'] must be of type string.'); } if (payload['resourceType'] !== null && payload['resourceType'] !== undefined && typeof payload['resourceType'].valueOf() !== 'string') { throw new Error('payload[\'resourceType\'] must be of type string.'); } if (payload['resourceName'] !== null && payload['resourceName'] !== undefined && typeof payload['resourceName'].valueOf() !== 'string') { throw new Error('payload[\'resourceName\'] must be of type string.'); } }; /** * Deserialize the instance to BasicDependency schema * * @param {JSON} instance * */ BasicDependency.prototype.deserialize = function (instance) { return instance; }; module.exports = new BasicDependency();
bounoable/cqrs-es
eventbus/channel/eventbus.go
<gh_stars>0 package channel import ( "context" "sync" "github.com/bounoable/cqrs-es" ) // Option ... type Option func(*config) type eventBus struct { cfg config events chan cqrs.Event mux sync.RWMutex subscribers map[cqrs.EventType][]chan cqrs.Event } type config struct { BufferSize int } // BufferSize ... func BufferSize(size int) Option { return func(cfg *config) { cfg.BufferSize = size } } // EventBus ... func EventBus(ctx context.Context, options ...Option) cqrs.EventBus { var cfg config for _, opt := range options { opt(&cfg) } bus := &eventBus{ events: make(chan cqrs.Event, cfg.BufferSize), subscribers: make(map[cqrs.EventType][]chan cqrs.Event), } go bus.start(ctx) return bus } func (b *eventBus) Publish(ctx context.Context, events ...cqrs.Event) error { for _, event := range events { select { case <-ctx.Done(): return ctx.Err() case b.events <- event: } } return nil } func (b *eventBus) Subscribe(ctx context.Context, types ...cqrs.EventType) (<-chan cqrs.Event, error) { b.mux.Lock() defer b.mux.Unlock() var allsubs []chan cqrs.Event for _, typ := range types { typsubs, ok := b.subscribers[typ] if !ok { typsubs = make([]chan cqrs.Event, 0) } sub := make(chan cqrs.Event, b.cfg.BufferSize) typsubs = append(typsubs, sub) b.subscribers[typ] = typsubs allsubs = append(allsubs, typsubs...) } events := make(chan cqrs.Event, b.cfg.BufferSize*len(allsubs)) var wg sync.WaitGroup for _, sub := range allsubs { wg.Add(1) go func(sub chan cqrs.Event) { defer wg.Done() for { select { case <-ctx.Done(): return case event, ok := <-sub: if !ok { return } events <- event } } }(sub) } go func() { wg.Wait() close(events) }() return events, nil } func (b *eventBus) start(ctx context.Context) { for { select { case <-ctx.Done(): return case event := <-b.events: b.publish(ctx, event) } } } func (b *eventBus) publish(ctx context.Context, event cqrs.Event) { b.mux.RLock() subs, ok := b.subscribers[event.Type()] b.mux.RUnlock() if !ok { return } for _, sub := range subs { sub <- event } }
odrevet/SimpleGameLayer
src/image.c
<filename>src/image.c #include "image.h" void image_load(image *p_image, const char *full_path, SDL_Renderer *renderer) { p_image->p_texture = IMG_LoadTexture(renderer, full_path); SDL_QueryTexture(p_image->p_texture, NULL, NULL, &p_image->width, &p_image->height); p_image->flip = false; } bool image_draw(image *p_image, SDL_Renderer *renderer, int x, int y) { SDL_Rect rect_dest = {.x = x, .y = y, .h = p_image->height, .w = p_image->width}; int retcode = SDL_RenderCopy(renderer, p_image->p_texture, NULL, &rect_dest); return (retcode > 0); } bool image_draw_resize(image *p_image, SDL_Renderer *renderer, int x, int y, int w, int h) { SDL_Rect rect_dest = {.x = x, .y = y, .h = h, .w = w}; int retcode = SDL_RenderCopy(renderer, p_image->p_texture, NULL, &rect_dest); return (retcode > 0); } bool image_draw_part(image *p_image, SDL_Renderer *renderer, int x, int y, SDL_Rect *src) { SDL_Rect dest = {.x = x, .y = y, .w = src->w, .h = src->h}; int retcode; if (p_image->flip) { retcode = SDL_RenderCopyEx(renderer, p_image->p_texture, src, &dest, 0, NULL, true); } else { retcode = SDL_RenderCopy(renderer, p_image->p_texture, src, &dest); } return (retcode > 0); } void image_set_tint(image *p_image, int r, int g, int b) { SDL_SetTextureColorMod(p_image->p_texture, r, g, b); } void image_free(image *p_image) { if (p_image->p_texture) { SDL_DestroyTexture(p_image->p_texture); } }
KDr2/v8
test/mjsunit/regress/regress-crbug-980529.js
<reponame>KDr2/v8<gh_stars>0 // Copyright 2019 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax --turbofan --no-always-turbofan const a = {toString: () => { console.log("print arguments", print.arguments); }}; function g(x) { print(x); } %PrepareFunctionForOptimization(g); g(a); g(a); %OptimizeFunctionOnNextCall(g); g(a);
onezens/QQTweak
qqtw/qqheaders7.2/QQStoryShareToGroupCell.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "UITableViewCell.h" @class QQAvatarView, QQStoryShareToGroupCellModel, UIButton, UILabel, UIView; @interface QQStoryShareToGroupCell : UITableViewCell { QQStoryShareToGroupCellModel *_model; QQAvatarView *_groupAvatar; UILabel *_groupName; UIButton *_checkBox; UIView *_separatorView; id <QQStoryShareToGroupCellDelegate> _delegate; } - (void)checkBoxClicked:(id)arg1; - (void)dealloc; @property(nonatomic) id <QQStoryShareToGroupCellDelegate> delegate; // @synthesize delegate=_delegate; - (void)didSelectCell; - (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2; - (void)p_initUI; - (void)setModel:(id)arg1; @end
wvanheemstra/core
public/app/service/asset/mock/Service.js
/** * The mock asset service object. */ Ext.define("Core.service.asset.mock.Service", { extend: "FlowMVC.mvc.service.mock.AbstractServiceMock", inject: [ "logger" ], /** * The mock service call. */ createAsset: function(asset) { this.logger.debug("createAsset"); var response = { success: true, asset: { kp_AssetID: this.getRandomInt(1000, 99999), AssetName: asset.AssetName } }; response = Ext.create("Core.model.asset.Model", response.asset); return this.delayedSuccess(response); }, /** * The mock service call. */ updateAsset: function(asset) { this.logger.debug("updateAsset: kp_AssetID = " + asset.kp_AssetID); var response = { success: true, asset: { kp_AssetID: asset.kp_AssetID, AssetName: asset.AssetName } }; response = Ext.create("Core.model.asset.Model", response.asset); return this.delayedSuccess(response); }, /** * The mock service call. */ deleteAsset: function(asset) { this.logger.debug("deleteAsset: kp_AssetID = " + asset.kp_AssetID); var response = { success: true, asset: { kp_AssetID: asset.kp_AssetID, AssetName: asset.AssetName } }; response = Ext.create("Core.model.asset.Model", response.asset); return this.delayedSuccess(response); }, /** * The mock service call. */ readAssets: function() { this.logger.debug("readAssets"); var response = { success: true, assets: [ { kp_AssetID: 1, AssetName: "Adam" }, { kp_AssetID: 2, AssetName: "Bob" }, { kp_AssetID: 3, AssetName: "Carol" }, { kp_AssetID: 4, AssetName: "David" }, { kp_AssetID: 5, AssetName: "Eddie" }, { kp_AssetID: 6, AssetName: "Frank" }, { kp_AssetID: 7, AssetName: "George" }, { kp_AssetID: 8, AssetName: "Harry" }, { kp_AssetID: 9, AssetName: "Ike" }, { kp_AssetID: 10, AssetName: "Jim" }, { kp_AssetID: 11, AssetName: "Kenny" }, { kp_AssetID: 12, AssetName: "Larry" }, { kp_AssetID: 13, AssetName: "Mary" }, { kp_AssetID: 14, AssetName: "Nancy" }, { kp_AssetID: 15, AssetName: "Olivier" }, { kp_AssetID: 16, AssetName: "Peter" }, { kp_AssetID: 17, AssetName: "Quincy" }, { kp_AssetID: 18, AssetName: "Roger" }, { kp_AssetID: 19, AssetName: "Sam" }, { kp_AssetID: 20, AssetName: "Thomas" }, { kp_AssetID: 21, AssetName: "Uncle" }, { kp_AssetID: 22, AssetName: "Vincent" }, { kp_AssetID: 23, AssetName: "William" }, { kp_AssetID: 24, AssetName: "Xavier" }, { kp_AssetID: 25, AssetName: "Yogi" }, { kp_AssetID: 26, AssetName: "Zachary" } ] }; return this.delayedSuccess(response); } });
mkesmetzis/starter-kit-spring-maven
src/main/java/com/client/core/base/tools/propertyeditors/MyCustomNumberEditor.java
package com.client.core.base.tools.propertyeditors; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.util.StringUtils; public class MyCustomNumberEditor extends CustomNumberEditor { private static Log log = LogFactory.getLog(MyCustomNumberEditor.class); public MyCustomNumberEditor(Class<? extends Number> numberClass) throws IllegalArgumentException { super(numberClass, true); } /** * Parse the Number from the given text, using the specified NumberFormat. */ @Override public void setAsText(String text) throws IllegalArgumentException { if (NumberUtils.isNumber(text) || !StringUtils.hasText(text)) { super.setAsText(text); } else { log.error("Attempting to set a number field using the non-numeric value:" + text); } } }
gesslar/shadowgate
d/avatars/myrkul/zombieshirt.c
<reponame>gesslar/shadowgate<filename>d/avatars/myrkul/zombieshirt.c<gh_stars>10-100 #include <std.h> inherit "/d/common/obj/clothing/shirt"; void create(){ ::create(); set_name("%^RESET%^%^CYAN%^z%^GREEN%^o%^CYAN%^m%^GREEN%^b%^CYAN%^i%^GREEN%^e %^YELLOW%^s%^RESET%^%^ORANGE%^h%^YELLOW%^r%^RESET%^%^ORANGE%^e%^YELLOW%^d%^RESET%^%^ORANGE%^d%^YELLOW%^e%^RESET%^%^ORANGE%^d %^CYAN%^s%^GREEN%^h%^CYAN%^i%^GREEN%^r%^CYAN%^t%^RESET%^"); set_id(({ "shirt" })); set_short("%^RESET%^%^CYAN%^z%^GREEN%^o%^CYAN%^m%^GREEN%^b%^CYAN%^i%^GREEN%^e %^YELLOW%^s%^RESET%^%^ORANGE%^h%^YELLOW%^r%^RESET%^%^ORANGE%^e%^YELLOW%^d%^RESET%^%^ORANGE%^d%^YELLOW%^e%^RESET%^%^ORANGE%^d %^CYAN%^s%^GREEN%^h%^CYAN%^i%^GREEN%^r%^CYAN%^t%^RESET%^"); set_obvious_short("%^RESET%^%^CYAN%^z%^GREEN%^o%^CYAN%^m%^GREEN%^b%^CYAN%^i%^GREEN%^e %^YELLOW%^s%^RESET%^%^ORANGE%^h%^YELLOW%^r%^RESET%^%^ORANGE%^e%^YELLOW%^d%^RESET%^%^ORANGE%^d%^YELLOW%^e%^RESET%^%^ORANGE%^d %^CYAN%^s%^GREEN%^h%^CYAN%^i%^GREEN%^r%^CYAN%^t%^RESET%^"); set_long("%^RESET%^%^CYAN%^This once %^RED%^fine%^CYAN%^ shirt has been %^MAGENTA%^torn%^CYAN%^ asunder by %^RESET%^claws.%^CYAN%^ It still has a collar, but one sleeve is missing. Deep rents criss-cross the ta" "ttered remains. It appears to be coated in some kind of %^GREEN%^slimy ichor.%^RESET%^ " ); set_value(0); set_lore("Ethius was once a devout follower of Cyric, but he decided to leave when Cyrics dogma changed. Alzar the high priest hunted Ethius down and trapped his soul in a bottle. Cyric leveled a curse on Ethiu" "s that his corpse should remain a zombie and forever try to reclaim his soul. This is the shirt that Ethius wore on that fateful day. " ); set_property("lore difficulty",10); set("strbonus",2); set("chabonus",-4); set_heart_beat(1); set_size(2); set_property("enchantment",2); set_wear((:TO,"wear_func":)); set_remove((:TO,"remove_func":)); set_struck((:TO,"strike_func":)); } int wear_func(){ tell_room(environment(ETO),"",ETO); tell_object(ETO,""); ETO->add_attack_bonus(1); ETO->add_damage_bonus(1); return 1; } int remove_func(){ tell_room(environment(ETO),"",ETO); tell_object(ETO,""); ETO->add_attack_bonus(-1); ETO->add_damage_bonus(-1); return 1; } int strike_func(int damage, object what, object who){ if(random(1000) < 1000){ tell_room(environment(query_worn()),"%^YELLOW%^"+who->QCN+"%^YELLOW%^ chokes on a %^GREEN%^cloud of gas%^YELLOW%^ emanating from "+query_short()+"%^YELLOW%^ worn by "+ETOQCN+".%^RESET%^",({ETO,who})); tell_object(ETO,"%^YELLOW%^"+who->QCN+"%^YELLOW%^ chokes on a %^GREEN%^cloud of gas%^YELLOW%^ emanating from "+query_short()+".%^RESET%^"); tell_object(who,"%^YELLOW%^You choke on a %^GREEN%^cloud of gas%^YELLOW%^ emanating from "+query_short()+"%^YELLOW%^ worn by "+ETOQCN+".%^RESET%^"); who->do_damage("torso",roll_dice(20,2)); return damage; } } void heart_beat() { if(!objectp(TO)) { return; } if(!objectp(ETO)) { return; } if(TO->is_weapon()) { if(!TO->query_wielded()) { return; } } if(TO->is_armor()) { if(!TO->query_worn()) { return; } } if(!interactive(ETO)) { return; } if(random(1000) > 998) { switch(random(4)) { case 0: tell_object(ETO, "%^BOLD%^%^GREEN%^A %^YELLOW%^miasma%^GREEN%^ of horrible stench fills the %^WHITE%^air%^RESET%^."); tell_room(EETO, "%^BOLD%^%^GREEN%^A %^YELLOW%^miasma%^GREEN%^ of horrible stench fills the %^WHITE%^air%^RESET%^.", ({ETO})); break; case 1: tell_object(ETO, "%^RESET%^%^MAGENTA%^A hideous cloud of %^BOLD%^%^BLACK%^flies%^RESET%^%^MAGENTA%^ gathers nearby, searching for %^RED%^dead flesh%^MAGENTA%^ to infest.%^RESET%^"); tell_room(EETO, "%^RESET%^%^MAGENTA%^A hideous cloud of %^BOLD%^%^BLACK%^flies%^RESET%^%^MAGENTA%^ gathers nearby, searching for %^RED%^dead flesh%^MAGENTA%^ to infest.%^RESET%^", ({ETO})); break; case 2: tell_object(ETO, "%^BOLD%^%^CYAN%^A %^RED%^pervasive%^CYAN%^ sense of %^BLACK%^dread%^CYAN%^ passes through you as if some %^BLUE%^supernatural %^RED%^evil%^CYAN%^ lurks near you.%^RESET%^"); tell_room(EETO, "%^BOLD%^%^CYAN%^A %^RED%^pervasive%^CYAN%^ sense of %^BLACK%^dread%^CYAN%^ passes through you as if some %^BLUE%^supernatural %^RED%^evil%^CYAN%^ lurks near you.%^RESET%^", ({ETO})); break; case 3: tell_object(ETO, "%^YELLOW%^Hmm, that %^MAGENTA%^perfume%^YELLOW%^, you smell a distinct %^GREEN%^fragrance%^YELLOW%^ - %^RESET%^%^ORANGE%^eau%^YELLOW%^ de %^RED%^Z%^RESET%^%^RED%^o%^BOLD%^m%^RESET%^%^RED%^b%^BOLD%^i%^RESET%^%^RED%^e%^BOLD%^.%^RESET%^"); tell_room(EETO, "%^YELLOW%^Hmm, that %^MAGENTA%^perfume%^YELLOW%^, you smell a distinct %^GREEN%^fragrance%^YELLOW%^ - %^RESET%^%^ORANGE%^eau%^YELLOW%^ de %^RED%^Z%^RESET%^%^RED%^o%^BOLD%^m%^RESET%^%^RED%^b%^BOLD%^i%^RESET%^%^RED%^e%^BOLD%^.%^RESET%^", ({ETO})); break; } } }
EchoDao-BSC/badger-system
assistant/rewards/RewardsLogger.py
<filename>assistant/rewards/RewardsLogger.py from tabulate import tabulate from rich.console import Console import json console = Console() class RewardsLogger: def __init__(self): self._distributionInfo = {} self._unlockSchedules = {} self._userData = {} self._epochData = {} def _check_user_vault(self,address,vault): if vault not in self._userData: self._userData[vault] = {} if address not in self._userData[vault]: self._userData[vault][address] = {} def add_epoch_data(self,users,vault,token,unit,epoch): if vault not in self._epochData: self._epochData[vault] = {} if epoch not in self._epochData[vault]: self._epochData[vault][epoch] = {} for user in users: totals = {} totals[token] = unit * user.shareSeconds self._epochData[vault][epoch][user.address] = { "shareSeconds":user.shareSeconds, "totals":totals } def add_user_share_seconds(self,address,vault,shareSeconds): self._check_user_vault(address,vault) if "shareSeconds" not in self._userData[vault][address]: self._userData[vault][address]["shareSeconds"] = shareSeconds else: self._userData[vault][address]["shareSeconds"] += shareSeconds def add_user_token(self,address,vault,token,tokenAmount): self._check_user_vault(address,vault) if "totals" not in self._userData[vault][address]: self._userData[vault][address]["totals"] = {} if token not in self._userData[vault][address]["totals"]: self._userData[vault][address]["totals"][token] = tokenAmount else: self._userData[vault][address]["totals"][token] += tokenAmount def add_multiplier(self,address,vault,multiplier): self._check_user_vault(address,vault) self._userData[vault][address]["multiplier"] = multiplier def add_unlock_schedule(self,token,schedule): self._unlockSchedules[token] = schedule def add_distribution_info(self,geyserName,distribution): self._distributionInfo[geyserName] = distribution def save(self,fileName): data = { "userData":self._userData, "distributionInfo":self._distributionInfo, "unlockSchedules":self._unlockSchedules, "retroactiveData":self._epochData } with open("logs/{}.json".format(fileName),"w") as f: json.dump(data,f,indent=4) rewardsLogger = RewardsLogger()
kngeno/Arbiter-Android
Arbiter-Android/assets/www/js/Arbiter/DatabaseHelpers/ProjectDbHelper.js
Arbiter.ProjectDbHelper = (function(){ var PROJECT_DATABASE_NAME = "projectdb"; var projectDb = null; var manager = null; return { getProjectDatabase: function(){ if(projectDb === null){ projectDb = sqlitePlugin.openDatabase(PROJECT_DATABASE_NAME); Arbiter.SQLiteTransactionManager.push(projectDb); } return projectDb; } }; })();
mladencekic/Social_Backend_RubyonRails
facet/spec/support/test_classes/bottle.rb
# frozen_string_literal: true class Bottle < ActiveRecord::Base self.per_page = 2 scope :broken, -> { where(broken: true) } scope :unbroken, -> { where(broken: false) } scope :newest_first, -> { order(updated_at: :desc) } end
grame-cncm/inscoredoc
docs/BNF/13-mapping/scoreMap.js
ComplexDiagram( Sequence ('map', Choice (0, 'page', 'system', 'systemflat', 'staffn', 'voicen')) ).addTo()
crsiebler/my-site
assets/components/PageLayout/Sections/AvatarSection.js
<gh_stars>0 import React from "react"; import Avatar from "@material-ui/core/Avatar"; import Typography from "@material-ui/core/Typography"; import Grid from "@material-ui/core/Grid"; import IconButton from "@material-ui/core/IconButton"; import avatar from "images/avatar.webp"; import { menuItems } from "constants/navigationConstants"; const AvatarSection = () => ( <Grid container spacing={3} direction="column" justify="flex-start" alignItems="center" className="m-page__avatar" > <Grid item xs> <Typography variant="h6" align="center" className="m-page__avatar__title"> <NAME> </Typography> </Grid> <Grid item xs> <Avatar alt="<NAME>" src={avatar} className="m-page__avatar__img" /> </Grid> <Grid item xs> <Typography variant="body2" className="m-page__avatar__caption"> Hi! My name is <NAME>. Welcome to my personal website! </Typography> </Grid> <Grid container item xs direction="row" alignItems="center" justify="space-evenly" className="m-page__avatar__socials" > {menuItems.map((item, index) => ( <Grid item xs={4} key={index}> <IconButton aria-label={item.ariaLabel} aria-controls="menu-appbar" aria-haspopup="true" href={item.href} target={item.target ? item.target : "_self"} > {item.icon} </IconButton> </Grid> ))} </Grid> </Grid> ); export default AvatarSection;
dianziguan1234/CustomCategory
PageViewController/PagerView.h
<filename>PageViewController/PagerView.h<gh_stars>1-10 // // PagerView.h // PagerViewController // // Created by 曾涛 on 2017/6/12. // Copyright © 2017年 曾涛. All rights reserved. // #import <UIKit/UIKit.h> @interface PagerView : UIView @property (strong, nonatomic) UIViewController *viewController; /** 滑块按钮 @param frame selfFrame @param segmentViewHeight 按钮高度 @param titleArray 按钮名 @param controller 主控住器 @param lineW 选中条宽度 @param lineH 选中条高度 @return self */ - (instancetype)initWithFrame:(CGRect)frame SegmentViewHeight:(CGFloat)segmentViewHeight titleArray:(NSArray *)titleArray Controller:(UIViewController *)controller lineWidth:(float)lineW lineHeight:(float)lineH; @end
ragupta-git/ucscentralsdk
ucscentralsdk/mometa/nfs/NfsMountDef.py
<filename>ucscentralsdk/mometa/nfs/NfsMountDef.py<gh_stars>0 """This module contains the general information for NfsMountDef ManagedObject.""" from ...ucscentralmo import ManagedObject from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta from ...ucscentralmeta import VersionMeta class NfsMountDefConsts(): ADMIN_STATE_DISABLED = "disabled" ADMIN_STATE_ENABLED = "enabled" ADMIN_STATE_SUSPENDED = "suspended" INT_ID_NONE = "none" POLICY_OWNER_LOCAL = "local" POLICY_OWNER_PENDING_POLICY = "pending-policy" POLICY_OWNER_POLICY = "policy" POLICY_OWNER_UNSPECIFIED = "unspecified" PURPOSE_BACKUP = "backup" PURPOSE_IMAGE = "image" class NfsMountDef(ManagedObject): """This is NfsMountDef class.""" consts = NfsMountDefConsts() naming_props = set([u'name']) mo_meta = MoMeta("NfsMountDef", "nfsMountDef", "nfs-mount-def-[name]", VersionMeta.Version101a, "InputOutput", 0x3f, [], ["admin"], [u'consumerInst'], [], [None]) prop_meta = { "admin_state": MoPropertyMeta("admin_state", "adminState", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["disabled", "enabled", "suspended"], []), "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version101a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "descr": MoPropertyMeta("descr", "descr", "string", VersionMeta.Version101a, MoPropertyMeta.READ_WRITE, 0x2, None, None, r"""[ !#$%&\(\)\*\+,\-\./:;\?@\[\]_\{\|\}~a-zA-Z0-9]{0,256}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "flt_aggr": MoPropertyMeta("flt_aggr", "fltAggr", "ulong", VersionMeta.Version101a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "int_id": MoPropertyMeta("int_id", "intId", "string", VersionMeta.Version101a, MoPropertyMeta.INTERNAL, None, None, None, None, ["none"], ["0-4294967295"]), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version101a, MoPropertyMeta.NAMING, 0x8, 1, 128, None, [], []), "policy_level": MoPropertyMeta("policy_level", "policyLevel", "uint", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []), "policy_owner": MoPropertyMeta("policy_owner", "policyOwner", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["local", "pending-policy", "policy", "unspecified"], []), "purpose": MoPropertyMeta("purpose", "purpose", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["backup", "image"], []), "remote_dir": MoPropertyMeta("remote_dir", "remoteDir", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []), "server": MoPropertyMeta("server", "server", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version101a, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } prop_map = { "adminState": "admin_state", "childAction": "child_action", "descr": "descr", "dn": "dn", "fltAggr": "flt_aggr", "intId": "int_id", "name": "name", "policyLevel": "policy_level", "policyOwner": "policy_owner", "purpose": "purpose", "remoteDir": "remote_dir", "rn": "rn", "server": "server", "status": "status", } def __init__(self, parent_mo_or_dn, name, **kwargs): self._dirty_mask = 0 self.name = name self.admin_state = None self.child_action = None self.descr = None self.flt_aggr = None self.int_id = None self.policy_level = None self.policy_owner = None self.purpose = None self.remote_dir = None self.server = None self.status = None ManagedObject.__init__(self, "NfsMountDef", parent_mo_or_dn, **kwargs)
angelgomezsa/Cplusplus
Consolidation 3/11 - P63370 - Jutge (2)/ex11.cc
<filename>Consolidation 3/11 - P63370 - Jutge (2)/ex11.cc #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; struct Enviament { string dni; string exer; int temps; string res; }; typedef vector<Enviament> Historia; bool compara(Enviament e1,Enviament e2) { return e1.exer<e2.exer or (e1.exer==e2.exer and e1.dni<e2.dni); } int main() { int n; cin>>n; Historia h(n); for (int i=0;i<n;i++) cin>>h[i].dni>>h[i].exer>>h[i].temps>>h[i].res; sort(h.begin(),h.end(),compara); int ih=0; int maximonumverdes=0; string exmaximonumverdes="-"; int maximonumejerciciosverdes=0; string exmaximonumejerciciosverdes="-"; int maximonumejerciciosrojos=0; string exmaximonumejerciciosrojos="-"; int maximonumintentos=0; string exmaximonumintentos="-"; int maximotiempoenvio=-1; string exmaximotiempoenvio="-"; while (ih<n) { string exer=h[ih].exer; int numverdes=0; int numejerciciosverdes=0; int numejerciciosrojos=0; int numintentos=0; while (ih<n and h[ih].exer==exer) { numintentos++; string dni=h[ih].dni; bool algunverde=false; bool algunrojo=false; for (int i=ih;i<n and h[ih].exer==exer and h[ih].dni==dni;i++) { if (h[ih].res=="vermell") { algunrojo=true; } if (h[ih].temps>maximotiempoenvio) { maximotiempoenvio=h[ih].temps; exmaximotiempoenvio=exer; } } while (ih<n and h[ih].exer==exer and h[ih].dni==dni) { if (h[ih].res=="verd") { algunverde=true; numverdes++; } if (algunrojo and (h[ih].res=="verd" or h[ih].res=="groc")) { algunrojo = false; } if (h[ih].temps>maximotiempoenvio) { maximotiempoenvio=h[ih].temps; exmaximotiempoenvio=exer; } ih++; } if (algunverde) numejerciciosverdes++; if (algunrojo) numejerciciosrojos++; } if (numverdes>maximonumverdes) { maximonumverdes=numverdes; exmaximonumverdes=exer; } if (numejerciciosverdes>maximonumejerciciosverdes) { maximonumejerciciosverdes=numejerciciosverdes; exmaximonumejerciciosverdes=exer; } if (numejerciciosrojos>maximonumejerciciosrojos) { maximonumejerciciosrojos=numejerciciosrojos; exmaximonumejerciciosrojos=exer; } if (numintentos>maximonumintentos) { maximonumintentos=numintentos; exmaximonumintentos=exer; } } if (maximonumverdes>0) cout << "exercici amb mes enviaments verds: "<<exmaximonumverdes<<" ("<<maximonumverdes<<")"<<endl; else cout << "exercici amb mes enviaments verds: "<<exmaximonumverdes<<endl; if (maximonumejerciciosverdes>0) cout << "exercici amb mes alumnes verds: "<<exmaximonumejerciciosverdes<<" ("<<maximonumejerciciosverdes<<")"<<endl; else cout << "exercici amb mes alumnes verds: "<<exmaximonumejerciciosverdes<<endl; if (maximonumejerciciosrojos>0) cout << "exercici amb mes alumnes vermells: "<<exmaximonumejerciciosrojos<<" ("<<maximonumejerciciosrojos<<")"<<endl; else cout << "exercici amb mes alumnes vermells: "<<exmaximonumejerciciosrojos<<endl; if (maximonumintentos>0) cout << "exercici que mes alumnes han intentat: "<<exmaximonumintentos<<" ("<<maximonumintentos<<")"<<endl; else cout << "exercici que mes alumnes han intentat: "<<exmaximonumintentos<<endl; cout << "exercici de l'ultim enviament: "<<exmaximotiempoenvio<<endl; }
jgnagy/moneta
spec/moneta/proxies/transformer/transformer_bert_spec.rb
<reponame>jgnagy/moneta<gh_stars>100-1000 describe 'transformer_bert', unsupported: defined?(JRUBY_VERSION), proxy: :Transformer do moneta_build do Moneta.build do use :Transformer, key: :bert, value: :bert adapter :Memory end end moneta_loader do |value| ::BERT.decode(value) end moneta_specs TRANSFORMER_SPECS.simplekeys_only.simplevalues_only.with_each_key it 'compile transformer class' do store.should_not be_nil Moneta::Transformer::BertKeyBertValue.should_not be_nil end end
WolfieWerewolf/intellij-haxe
src/common/com/intellij/plugins/haxe/model/type/HaxeTypeCompatible.java
<filename>src/common/com/intellij/plugins/haxe/model/type/HaxeTypeCompatible.java<gh_stars>10-100 /* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2015 AS3Boyan * Copyright 2014-2014 <NAME> * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.plugins.haxe.model.type; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; public class HaxeTypeCompatible { static public boolean canApplyBinaryOperator(SpecificTypeReference left, SpecificTypeReference right, String operator) { // @TODO: Stub. Implement. return true; } static public boolean canAssignToFrom(SpecificTypeReference to, ResultHolder from) { return canAssignToFrom(to, from.getType()); } static public boolean canAssignToFrom(ResultHolder to, ResultHolder from) { if (to.isUnknown()) { to.setType(from.getType().withoutConstantValue()); } else if (from.isUnknown()) { from.setType(to.getType().withoutConstantValue()); } return canAssignToFrom(to.getType(), from.getType()); } static public boolean canAssignToFrom( @Nullable SpecificTypeReference to, @Nullable SpecificTypeReference from ) { if (to == null || from == null) return false; if (to.isDynamic() || from.isDynamic()) return true; if (to instanceof SpecificFunctionReference && from instanceof SpecificFunctionReference) { return canAssignToFromFunction((SpecificFunctionReference)to, (SpecificFunctionReference)from); } if (to instanceof SpecificHaxeClassReference && from instanceof SpecificHaxeClassReference) { return canAssignToFromType((SpecificHaxeClassReference)to, (SpecificHaxeClassReference)from); } return false; } static private boolean canAssignToFromFunction( @NotNull SpecificFunctionReference to, @NotNull SpecificFunctionReference from ) { if (to.arguments.size() != from.arguments.size()) return false; for (int n = 0; n < to.arguments.size(); n++) { if (!to.arguments.get(n).canAssign(from.arguments.get(n))) return false; } // Void return on the to just means that the value isn't used/cared about. See // the Haxe manual, section 3.5.4 at https://haxe.org/manual/type-system-unification-function-return.html return to.returnValue.isVoid() || to.returnValue.canAssign(from.returnValue); } static private boolean canAssignToFromType( @NotNull SpecificHaxeClassReference to, @NotNull SpecificHaxeClassReference from ) { if (to.isDynamic() || from.isDynamic()) { return true; } if (from.isUnknown()) { return true; } if (to.getHaxeClassReference().equals(from.getHaxeClassReference())) { if (to.getSpecifics().length == from.getSpecifics().length) { int specificsLength = to.getSpecifics().length; for (int n = 0; n < specificsLength; n++) { if (!canAssignToFrom(to.getSpecifics()[n], from.getSpecifics()[n])) { return false; } } return true; } // issue #388: allow `public var m:Map<String, String> = new Map();` else if(from.getSpecifics().length == 0) { return true; } } Set<SpecificHaxeClassReference> compatibleTypes = to.getCompatibleTypes(); for (SpecificHaxeClassReference compatibleType : compatibleTypes) { if (compatibleType.toStringWithoutConstant().equals(from.toStringWithoutConstant())) return true; } compatibleTypes = from.getInferTypes(); for (SpecificHaxeClassReference compatibleType : compatibleTypes) { if (compatibleType.toStringWithoutConstant().equals(to.toStringWithoutConstant())) return true; } return to.toStringWithoutConstant().equals(from.toStringWithoutConstant()); } }
ppartarr/azure-sdk-for-java
sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/ConnectionMonitorEndpoint.java
<gh_stars>1-10 /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_06_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Describes the connection monitor endpoint. */ public class ConnectionMonitorEndpoint { /** * The name of the connection monitor endpoint. */ @JsonProperty(value = "name", required = true) private String name; /** * The endpoint type. Possible values include: 'AzureVM', 'AzureVNet', * 'AzureSubnet', 'ExternalAddress', 'MMAWorkspaceMachine', * 'MMAWorkspaceNetwork'. */ @JsonProperty(value = "type") private EndpointType type; /** * Resource ID of the connection monitor endpoint. */ @JsonProperty(value = "resourceId") private String resourceId; /** * Address of the connection monitor endpoint (IP or domain name). */ @JsonProperty(value = "address") private String address; /** * Filter for sub-items within the endpoint. */ @JsonProperty(value = "filter") private ConnectionMonitorEndpointFilter filter; /** * Endpoint scope. */ @JsonProperty(value = "scope") private ConnectionMonitorEndpointScope scope; /** * Test coverage for the endpoint. Possible values include: 'Default', * 'Low', 'BelowAverage', 'Average', 'AboveAverage', 'Full'. */ @JsonProperty(value = "coverageLevel") private CoverageLevel coverageLevel; /** * Get the name of the connection monitor endpoint. * * @return the name value */ public String name() { return this.name; } /** * Set the name of the connection monitor endpoint. * * @param name the name value to set * @return the ConnectionMonitorEndpoint object itself. */ public ConnectionMonitorEndpoint withName(String name) { this.name = name; return this; } /** * Get the endpoint type. Possible values include: 'AzureVM', 'AzureVNet', 'AzureSubnet', 'ExternalAddress', 'MMAWorkspaceMachine', 'MMAWorkspaceNetwork'. * * @return the type value */ public EndpointType type() { return this.type; } /** * Set the endpoint type. Possible values include: 'AzureVM', 'AzureVNet', 'AzureSubnet', 'ExternalAddress', 'MMAWorkspaceMachine', 'MMAWorkspaceNetwork'. * * @param type the type value to set * @return the ConnectionMonitorEndpoint object itself. */ public ConnectionMonitorEndpoint withType(EndpointType type) { this.type = type; return this; } /** * Get resource ID of the connection monitor endpoint. * * @return the resourceId value */ public String resourceId() { return this.resourceId; } /** * Set resource ID of the connection monitor endpoint. * * @param resourceId the resourceId value to set * @return the ConnectionMonitorEndpoint object itself. */ public ConnectionMonitorEndpoint withResourceId(String resourceId) { this.resourceId = resourceId; return this; } /** * Get address of the connection monitor endpoint (IP or domain name). * * @return the address value */ public String address() { return this.address; } /** * Set address of the connection monitor endpoint (IP or domain name). * * @param address the address value to set * @return the ConnectionMonitorEndpoint object itself. */ public ConnectionMonitorEndpoint withAddress(String address) { this.address = address; return this; } /** * Get filter for sub-items within the endpoint. * * @return the filter value */ public ConnectionMonitorEndpointFilter filter() { return this.filter; } /** * Set filter for sub-items within the endpoint. * * @param filter the filter value to set * @return the ConnectionMonitorEndpoint object itself. */ public ConnectionMonitorEndpoint withFilter(ConnectionMonitorEndpointFilter filter) { this.filter = filter; return this; } /** * Get endpoint scope. * * @return the scope value */ public ConnectionMonitorEndpointScope scope() { return this.scope; } /** * Set endpoint scope. * * @param scope the scope value to set * @return the ConnectionMonitorEndpoint object itself. */ public ConnectionMonitorEndpoint withScope(ConnectionMonitorEndpointScope scope) { this.scope = scope; return this; } /** * Get test coverage for the endpoint. Possible values include: 'Default', 'Low', 'BelowAverage', 'Average', 'AboveAverage', 'Full'. * * @return the coverageLevel value */ public CoverageLevel coverageLevel() { return this.coverageLevel; } /** * Set test coverage for the endpoint. Possible values include: 'Default', 'Low', 'BelowAverage', 'Average', 'AboveAverage', 'Full'. * * @param coverageLevel the coverageLevel value to set * @return the ConnectionMonitorEndpoint object itself. */ public ConnectionMonitorEndpoint withCoverageLevel(CoverageLevel coverageLevel) { this.coverageLevel = coverageLevel; return this; } }
s-stark/aos-Video
src/leanback/java/com/archos/mediacenter/video/leanback/network/NetworkRootActivity.java
// Copyright 2017 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.archos.mediacenter.video.leanback.network; import android.app.Fragment; import android.os.SystemClock; import android.view.KeyEvent; import android.widget.Toast; import com.archos.mediacenter.video.R; import com.archos.mediacenter.video.leanback.SingleFragmentActivity; public class NetworkRootActivity extends SingleFragmentActivity { @Override public Fragment getFragmentInstance() { return new NetworkRootFragment(); } /** * Temp stuff to show the rescan button that is for now hidden (not ready for prime-time) * (to remove once re-scan feature is published) * @param keyCode * @param event * @return */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode==KeyEvent.KEYCODE_DPAD_UP) { keyupCount++; if (keyupTrainStartTimeMs==0) { keyupTrainStartTimeMs = SystemClock.elapsedRealtime(); } // Check for 5 press in less than 1 second if (keyupCount>4 && (SystemClock.elapsedRealtime()-keyupTrainStartTimeMs<1000)) { // display re-scan item Fragment f = getFragmentManager().findFragmentById(R.id.fragment_container); if (f!=null && f instanceof NetworkRootFragment) { ((NetworkRootFragment)f).displayRescanItem(); Toast.makeText(this, "Displaying Re-scan item (caution it is Debug only for now)", Toast.LENGTH_SHORT).show(); } } } else { // reset if another key is pressed keyupCount=0; keyupTrainStartTimeMs=0; } return super.onKeyDown(keyCode, event); } private int keyupCount = 0; private long keyupTrainStartTimeMs = 0; }
unascribed/NotEnoughCreativity
src/main/java/com/unascribed/notenoughcreativity/mixin/MixinEntity.java
package com.unascribed.notenoughcreativity.mixin; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import com.unascribed.notenoughcreativity.Ability; import com.unascribed.notenoughcreativity.AbilityCheck; import com.unascribed.notenoughcreativity.network.MessageOtherNoclipping; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityPose; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.server.network.ServerPlayerEntity; @Mixin(Entity.class) public class MixinEntity { @Shadow public boolean noClip; @Inject(at=@At("HEAD"), method="wouldPoseNotCollide(Lnet/minecraft/entity/EntityPose;)Z", cancellable=true) public void wouldPoseNotCollide(EntityPose pose, CallbackInfoReturnable<Boolean> ci) { if (noClip) ci.setReturnValue(true); } @Inject(at=@At("HEAD"), method="onStartedTrackingBy(Lnet/minecraft/server/network/ServerPlayerEntity;)V") public void onStartedTrackingBy(ServerPlayerEntity tracker, CallbackInfo ci) { Entity self = (Entity)(Object)this; if (self instanceof PlayerEntity) { new MessageOtherNoclipping(self.getEntityId(), AbilityCheck.enabled((PlayerEntity)self, Ability.NOCLIP)).sendTo(tracker); } } }
cm-heclouds/onenet-studio-api-java-sdk
src/main/java/com/github/cm/heclouds/onenet/studio/api/entity/common/Event.java
package com.github.cm.heclouds.onenet.studio.api.entity.common; import com.alibaba.fastjson.annotation.JSONField; import com.github.cm.heclouds.onenet.studio.api.entity.enums.FunctionEventType; import com.github.cm.heclouds.onenet.studio.api.json.ValueHolderDeserializer; import com.github.cm.heclouds.onenet.studio.api.json.ValueHolderSerializer; import java.util.List; /** * 功能点类型 事件类型 * @author ChengQi * @date 2020/10/14 */ public class Event extends AbstractFunction { /** * 事件类型 */ @JSONField(serializeUsing = ValueHolderSerializer.class, deserializeUsing = ValueHolderDeserializer.class) private FunctionEventType eventType; /** * 参数 */ private List<Parameter> outputData; public FunctionEventType getEventType() { return eventType; } public void setEventType(FunctionEventType eventType) { this.eventType = eventType; } public List<Parameter> getOutputData() { return outputData; } public void setOutputData(List<Parameter> outputData) { this.outputData = outputData; } }
mark-marshall/twilio-flex-interactive-webchat
flex-webchat-interactive/node_modules/@material-ui/icons/es/SatelliteOutlined.js
<gh_stars>1-10 import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(React.createElement(React.Fragment, null, React.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z" }), React.createElement("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z" }), React.createElement("path", { d: "M8.57 6H6v2.58c1.42 0 2.57-1.16 2.57-2.58zM12 6h-1.71c0 2.36-1.92 4.29-4.29 4.29V12c3.32 0 6-2.69 6-6zM14.14 11.86l-3 3.87L9 13.15 6 17h12z" })), 'SatelliteOutlined');
artivis/micro_ros_raspberrypi_pico_sdk
uros_ws/firmware/build/include/nav_msgs/msg/detail/path__functions.c
// generated from rosidl_generator_c/resource/idl__functions.c.em // with input from nav_msgs:msg/Path.idl // generated code does not contain a copyright notice #include "nav_msgs/msg/detail/path__functions.h" #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> // Include directives for member types // Member `header` #include "std_msgs/msg/detail/header__functions.h" // Member `poses` #include "geometry_msgs/msg/detail/pose_stamped__functions.h" bool nav_msgs__msg__Path__init(nav_msgs__msg__Path * msg) { if (!msg) { return false; } // header if (!std_msgs__msg__Header__init(&msg->header)) { nav_msgs__msg__Path__fini(msg); return false; } // poses if (!geometry_msgs__msg__PoseStamped__Sequence__init(&msg->poses, 0)) { nav_msgs__msg__Path__fini(msg); return false; } return true; } void nav_msgs__msg__Path__fini(nav_msgs__msg__Path * msg) { if (!msg) { return; } // header std_msgs__msg__Header__fini(&msg->header); // poses geometry_msgs__msg__PoseStamped__Sequence__fini(&msg->poses); } nav_msgs__msg__Path * nav_msgs__msg__Path__create() { nav_msgs__msg__Path * msg = (nav_msgs__msg__Path *)malloc(sizeof(nav_msgs__msg__Path)); if (!msg) { return NULL; } memset(msg, 0, sizeof(nav_msgs__msg__Path)); bool success = nav_msgs__msg__Path__init(msg); if (!success) { free(msg); return NULL; } return msg; } void nav_msgs__msg__Path__destroy(nav_msgs__msg__Path * msg) { if (msg) { nav_msgs__msg__Path__fini(msg); } free(msg); } bool nav_msgs__msg__Path__Sequence__init(nav_msgs__msg__Path__Sequence * array, size_t size) { if (!array) { return false; } nav_msgs__msg__Path * data = NULL; if (size) { data = (nav_msgs__msg__Path *)calloc(size, sizeof(nav_msgs__msg__Path)); if (!data) { return false; } // initialize all array elements size_t i; for (i = 0; i < size; ++i) { bool success = nav_msgs__msg__Path__init(&data[i]); if (!success) { break; } } if (i < size) { // if initialization failed finalize the already initialized array elements for (; i > 0; --i) { nav_msgs__msg__Path__fini(&data[i - 1]); } free(data); return false; } } array->data = data; array->size = size; array->capacity = size; return true; } void nav_msgs__msg__Path__Sequence__fini(nav_msgs__msg__Path__Sequence * array) { if (!array) { return; } if (array->data) { // ensure that data and capacity values are consistent assert(array->capacity > 0); // finalize all array elements for (size_t i = 0; i < array->capacity; ++i) { nav_msgs__msg__Path__fini(&array->data[i]); } free(array->data); array->data = NULL; array->size = 0; array->capacity = 0; } else { // ensure that data, size, and capacity values are consistent assert(0 == array->size); assert(0 == array->capacity); } } nav_msgs__msg__Path__Sequence * nav_msgs__msg__Path__Sequence__create(size_t size) { nav_msgs__msg__Path__Sequence * array = (nav_msgs__msg__Path__Sequence *)malloc(sizeof(nav_msgs__msg__Path__Sequence)); if (!array) { return NULL; } bool success = nav_msgs__msg__Path__Sequence__init(array, size); if (!success) { free(array); return NULL; } return array; } void nav_msgs__msg__Path__Sequence__destroy(nav_msgs__msg__Path__Sequence * array) { if (array) { nav_msgs__msg__Path__Sequence__fini(array); } free(array); }
stsiwo/e-commerce-starter-kits
api/src/main/java/com/iwaodev/application/mapper/CompanyMapper.java
package com.iwaodev.application.mapper; import com.iwaodev.application.dto.company.CompanyDTO; import com.iwaodev.application.dto.company.PublicCompanyDTO; import com.iwaodev.infrastructure.model.Company; import com.iwaodev.ui.criteria.user.UserCompanyCriteria; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.factory.Mappers; @Mapper public interface CompanyMapper { CompanyMapper INSTANCE = Mappers.getMapper( CompanyMapper.class ); @Mapping(source = "company.user.userId", target = "userId") CompanyDTO toCompanyDTO(Company company); @Mapping(source = "company.user.userId", target = "userId") PublicCompanyDTO toPublicCompanyDTO(Company company); Company toCompanyEntityFromCompanyCriteria(UserCompanyCriteria company); }
altshiftcreative/checkout-sdk-java
src/main/java/com/checkout/workflows/four/events/Event.java
<reponame>altshiftcreative/checkout-sdk-java package com.checkout.workflows.four.events; import com.google.gson.annotations.SerializedName; import lombok.Data; @Data public final class Event { private String id; @SerializedName("display_name") private String displayName; private String description; }
tkashi-github/IMXRT1060-EVK
IMXRT1060-EVK_APL/source/UserDriver/SPIFlash/SPIFlash.c
<filename>IMXRT1060-EVK_APL/source/UserDriver/SPIFlash/SPIFlash.c /* * Copyright (c) 2016, Freescale Semiconductor, Inc. * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #include "SPIFlash/SPIFlash.h" #include "board.h" #include "mimiclib.h" #include "pin_mux.h" #include "board.h" #include "clock_config.h" #include "fsl_common.h" #include "common.h" /******************************************************************************* * Definitions ******************************************************************************/ #define FLASH_SIZE 0x2000 /* 64Mb/KByte */ #define FLASH_PAGE_SIZE 256 #define SECTOR_SIZE 0x1000 /* 4K */ #define FLEXSPI_CLOCK kCLOCK_FlexSpi #define DEF_DUMMY_SECTOR (0x600) #define NOR_CMD_LUT_SEQ_IDX_READ_NORMAL 0 #define NOR_CMD_LUT_SEQ_IDX_READ_FAST 1 #define NOR_CMD_LUT_SEQ_IDX_READ_FAST_QUAD 2 #define NOR_CMD_LUT_SEQ_IDX_READSTATUS 3 #define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE 4 #define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 #define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM_SINGLE 6 #define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM_QUAD 7 #define NOR_CMD_LUT_SEQ_IDX_READID 8 #define NOR_CMD_LUT_SEQ_IDX_WRITESTATUSREG 9 #define NOR_CMD_LUT_SEQ_IDX_ENTERQPI 10 #define NOR_CMD_LUT_SEQ_IDX_EXITQPI 11 #define NOR_CMD_LUT_SEQ_IDX_READSTATUSREG 12 #define CUSTOM_LUT_LENGTH 60 #define FLASH_BUSY_STATUS_POL 1 #define FLASH_BUSY_STATUS_OFFSET 0 /******************************************************************************* * Prototypes ******************************************************************************/ /******************************************************************************* * Variables ******************************************************************************/ static uint8_t s_nor_program_buffer[FLASH_PAGE_SIZE]; static uint8_t s_nor_read_buffer[FLASH_PAGE_SIZE]; /******************************************************************************* * Code ******************************************************************************/ static flexspi_device_config_t deviceconfig = { .flexspiRootClk = 120000000, .flashSize = FLASH_SIZE, .CSIntervalUnit = kFLEXSPI_CsIntervalUnit1SckCycle, .CSInterval = 2, .CSHoldTime = 3, .CSSetupTime = 3, .dataValidTime = 0, .columnspace = 0, .enableWordAddress = 0, .AWRSeqIndex = 0, .AWRSeqNumber = 0, .ARDSeqIndex = NOR_CMD_LUT_SEQ_IDX_READ_FAST_QUAD, .ARDSeqNumber = 1, .AHBWriteWaitUnit = kFLEXSPI_AhbWriteWaitUnit2AhbCycle, .AHBWriteWaitInterval = 0, }; static const uint32_t customLUT[CUSTOM_LUT_LENGTH] = { /* Normal read mode -SDR */ [4 * NOR_CMD_LUT_SEQ_IDX_READ_NORMAL] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x03, kFLEXSPI_Command_RADDR_SDR, kFLEXSPI_1PAD, 0x18), [4 * NOR_CMD_LUT_SEQ_IDX_READ_NORMAL + 1] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_READ_SDR, kFLEXSPI_1PAD, 0x04, kFLEXSPI_Command_STOP, kFLEXSPI_1PAD, 0), /* Fast read mode - SDR */ [4 * NOR_CMD_LUT_SEQ_IDX_READ_FAST] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x0B, kFLEXSPI_Command_RADDR_SDR, kFLEXSPI_1PAD, 0x18), [4 * NOR_CMD_LUT_SEQ_IDX_READ_FAST + 1] = FLEXSPI_LUT_SEQ( kFLEXSPI_Command_DUMMY_SDR, kFLEXSPI_1PAD, 0x08, kFLEXSPI_Command_READ_SDR, kFLEXSPI_1PAD, 0x04), /* Fast read quad mode - SDR */ [4 * NOR_CMD_LUT_SEQ_IDX_READ_FAST_QUAD] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x6B, kFLEXSPI_Command_RADDR_SDR, kFLEXSPI_1PAD, 0x18), [4 * NOR_CMD_LUT_SEQ_IDX_READ_FAST_QUAD + 1] = FLEXSPI_LUT_SEQ( kFLEXSPI_Command_DUMMY_SDR, kFLEXSPI_4PAD, 0x08, kFLEXSPI_Command_READ_SDR, kFLEXSPI_4PAD, 0x04), /* Read extend parameters */ [4 * NOR_CMD_LUT_SEQ_IDX_READSTATUS] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x81, kFLEXSPI_Command_READ_SDR, kFLEXSPI_1PAD, 0x04), /* Write Enable */ [4 * NOR_CMD_LUT_SEQ_IDX_WRITEENABLE] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x06, kFLEXSPI_Command_STOP, kFLEXSPI_1PAD, 0), /* Erase Sector */ [4 * NOR_CMD_LUT_SEQ_IDX_ERASESECTOR] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0xD7, kFLEXSPI_Command_RADDR_SDR, kFLEXSPI_1PAD, 0x18), /* Page Program - single mode */ [4 * NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM_SINGLE] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x02, kFLEXSPI_Command_RADDR_SDR, kFLEXSPI_1PAD, 0x18), [4 * NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM_SINGLE + 1] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_WRITE_SDR, kFLEXSPI_1PAD, 0x04, kFLEXSPI_Command_STOP, kFLEXSPI_1PAD, 0), /* Page Program - quad mode */ [4 * NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM_QUAD] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x32, kFLEXSPI_Command_RADDR_SDR, kFLEXSPI_1PAD, 0x18), [4 * NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM_QUAD + 1] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_WRITE_SDR, kFLEXSPI_4PAD, 0x04, kFLEXSPI_Command_STOP, kFLEXSPI_1PAD, 0), /* Read ID */ [4 * NOR_CMD_LUT_SEQ_IDX_READID] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0xAB, kFLEXSPI_Command_DUMMY_SDR, kFLEXSPI_1PAD, 0x18), [4 * NOR_CMD_LUT_SEQ_IDX_READID + 1] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_READ_SDR, kFLEXSPI_1PAD, 0x04, kFLEXSPI_Command_STOP, kFLEXSPI_1PAD, 0), /* Enable Quad mode */ [4 * NOR_CMD_LUT_SEQ_IDX_WRITESTATUSREG] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x01, kFLEXSPI_Command_WRITE_SDR, kFLEXSPI_1PAD, 0x04), /* Enter QPI mode */ [4 * NOR_CMD_LUT_SEQ_IDX_ENTERQPI] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x35, kFLEXSPI_Command_STOP, kFLEXSPI_1PAD, 0), /* Exit QPI mode */ [4 * NOR_CMD_LUT_SEQ_IDX_EXITQPI] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_4PAD, 0xF5, kFLEXSPI_Command_STOP, kFLEXSPI_1PAD, 0), /* Read status register */ [4 * NOR_CMD_LUT_SEQ_IDX_READSTATUSREG] = FLEXSPI_LUT_SEQ(kFLEXSPI_Command_SDR, kFLEXSPI_1PAD, 0x05, kFLEXSPI_Command_READ_SDR, kFLEXSPI_1PAD, 0x04), }; static status_t flexspi_nor_write_enable(FLEXSPI_Type *base, uint32_t baseAddr) { flexspi_transfer_t flashXfer; status_t status; /* Write neable */ flashXfer.deviceAddress = baseAddr; flashXfer.port = kFLEXSPI_PortA1; flashXfer.cmdType = kFLEXSPI_Command; flashXfer.SeqNumber = 1; flashXfer.seqIndex = NOR_CMD_LUT_SEQ_IDX_WRITEENABLE; status = FLEXSPI_TransferBlocking(base, &flashXfer); return status; } static status_t flexspi_nor_wait_bus_busy(FLEXSPI_Type *base) { /* Wait status ready. */ bool isBusy; uint32_t readValue; status_t status; flexspi_transfer_t flashXfer; flashXfer.deviceAddress = 0; flashXfer.port = kFLEXSPI_PortA1; flashXfer.cmdType = kFLEXSPI_Read; flashXfer.SeqNumber = 1; flashXfer.seqIndex = NOR_CMD_LUT_SEQ_IDX_READSTATUSREG; flashXfer.data = &readValue; flashXfer.dataSize = 1; do { status = FLEXSPI_TransferBlocking(base, &flashXfer); if (status != kStatus_Success) { return status; } if (FLASH_BUSY_STATUS_POL) { if (readValue & (1U << FLASH_BUSY_STATUS_OFFSET)) { isBusy = true; } else { isBusy = false; } } else { if (readValue & (1U << FLASH_BUSY_STATUS_OFFSET)) { isBusy = false; } else { isBusy = true; } } } while (isBusy); return status; } static status_t flexspi_nor_enable_quad_mode(FLEXSPI_Type *base) { flexspi_transfer_t flashXfer; status_t status; uint32_t writeValue = 0x40; /* Write neable */ status = flexspi_nor_write_enable(base, 0); if (status != kStatus_Success) { return status; } /* Enable quad mode. */ flashXfer.deviceAddress = 0; flashXfer.port = kFLEXSPI_PortA1; flashXfer.cmdType = kFLEXSPI_Write; flashXfer.SeqNumber = 1; flashXfer.seqIndex = NOR_CMD_LUT_SEQ_IDX_WRITESTATUSREG; flashXfer.data = &writeValue; flashXfer.dataSize = 1; status = FLEXSPI_TransferBlocking(base, &flashXfer); if (status != kStatus_Success) { return status; } status = flexspi_nor_wait_bus_busy(base); return status; } static status_t flexspi_nor_flash_erase_sector(FLEXSPI_Type *base, uint32_t address) { status_t status; flexspi_transfer_t flashXfer; /* Write enable */ flashXfer.deviceAddress = address; flashXfer.port = kFLEXSPI_PortA1; flashXfer.cmdType = kFLEXSPI_Command; flashXfer.SeqNumber = 1; flashXfer.seqIndex = NOR_CMD_LUT_SEQ_IDX_WRITEENABLE; status = FLEXSPI_TransferBlocking(base, &flashXfer); if (status != kStatus_Success) { return status; } flashXfer.deviceAddress = address; flashXfer.port = kFLEXSPI_PortA1; flashXfer.cmdType = kFLEXSPI_Command; flashXfer.SeqNumber = 1; flashXfer.seqIndex = NOR_CMD_LUT_SEQ_IDX_ERASESECTOR; status = FLEXSPI_TransferBlocking(base, &flashXfer); if (status != kStatus_Success) { return status; } status = flexspi_nor_wait_bus_busy(base); return status; } static status_t flexspi_nor_flash_page_program(FLEXSPI_Type *base, uint32_t dstAddr, const uint32_t *src) { status_t status; flexspi_transfer_t flashXfer; /* Write neable */ status = flexspi_nor_write_enable(base, dstAddr); if (status != kStatus_Success) { return status; } /* Prepare page program command */ flashXfer.deviceAddress = dstAddr; flashXfer.port = kFLEXSPI_PortA1; flashXfer.cmdType = kFLEXSPI_Write; flashXfer.SeqNumber = 1; flashXfer.seqIndex = NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM_QUAD; flashXfer.data = (uint32_t *)src; flashXfer.dataSize = FLASH_PAGE_SIZE; status = FLEXSPI_TransferBlocking(base, &flashXfer); if (status != kStatus_Success) { return status; } status = flexspi_nor_wait_bus_busy(base); return status; } status_t flexspi_nor_get_vendor_id(FLEXSPI_Type *base, uint8_t *vendorId) { uint32_t temp; flexspi_transfer_t flashXfer; flashXfer.deviceAddress = 0; flashXfer.port = kFLEXSPI_PortA1; flashXfer.cmdType = kFLEXSPI_Read; flashXfer.SeqNumber = 1; flashXfer.seqIndex = NOR_CMD_LUT_SEQ_IDX_READID; flashXfer.data = &temp; flashXfer.dataSize = 1; status_t status = FLEXSPI_TransferBlocking(base, &flashXfer); *vendorId = temp; return status; } status_t SPIFlashInit(void) { flexspi_config_t config; status_t status; uint8_t vendorID = 0; const clock_usb_pll_config_t g_ccmConfigUsbPll = {.loopDivider = 0U}; CLOCK_InitUsb1Pll(&g_ccmConfigUsbPll); CLOCK_InitUsb1Pfd(kCLOCK_Pfd0, 24); /* Set PLL3 PFD0 clock 360MHZ. */ CLOCK_SetMux(kCLOCK_FlexspiMux, 0x3); /* Choose PLL3 PFD0 clock as flexspi source clock. */ CLOCK_SetDiv(kCLOCK_FlexspiDiv, 2); /* flexspi clock 120M. */ /*Get FLEXSPI default settings and configure the flexspi. */ FLEXSPI_GetDefaultConfig(&config); /*Set AHB buffer size for reading data through AHB bus. */ config.ahbConfig.enableAHBPrefetch = true; config.rxSampleClock = kFLEXSPI_ReadSampleClkLoopbackFromDqsPad; FLEXSPI_Init(FLEXSPI, &config); /* Configure flash settings according to serial flash feature. */ FLEXSPI_SetFlashConfig(FLEXSPI, &deviceconfig, kFLEXSPI_PortA1); /* Update LUT table. */ FLEXSPI_UpdateLUT(FLEXSPI, 0, customLUT, CUSTOM_LUT_LENGTH); status = flexspi_nor_wait_bus_busy(FLEXSPI); if (status != kStatus_Success) { mimic_printf("flexspi_nor_wait_bus_busy NG\r\n"); return status; } /* Get vendor ID. */ status = flexspi_nor_get_vendor_id(FLEXSPI, &vendorID); if (status != kStatus_Success) { mimic_printf("flexspi_nor_get_vendor_id NG\r\n"); return status; } mimic_printf("Vendor ID: 0x%x\r\n", vendorID); /* Enter quad mode. */ status = flexspi_nor_enable_quad_mode(FLEXSPI); return status; } _Bool SPIFlashWriteData(uint32_t u32StartSectorNo, const uint8_t pu8[], uint32_t u32ByteCnt) { status_t status; _Bool bret = true; SCB_DisableDCache(); /* Erase sectors. */ mimic_printf("Erasing Serial NOR over FlexSPI...\r\n"); uint32_t u32Loop = u32ByteCnt / SECTOR_SIZE; if((u32ByteCnt % SECTOR_SIZE) != 0) { u32Loop++; } for(uint32_t i=0;i<u32Loop;i++) { mimic_printf("Erase Area = 0x%08lX - 0x%08lX ", FlexSPI_AMBA_BASE + (i + u32StartSectorNo) * SECTOR_SIZE, FlexSPI_AMBA_BASE + (i + u32StartSectorNo + 1) * SECTOR_SIZE- 1 ); status = flexspi_nor_flash_erase_sector(FLEXSPI, (i + u32StartSectorNo) * SECTOR_SIZE); if (status != kStatus_Success) { mimic_printf("NG\r\n"); bret = false; goto _END; } for(uint32_t j=0;j<SECTOR_SIZE;j++){ uint8_t *pu8 = (uint8_t *)(FlexSPI_AMBA_BASE + (i + u32StartSectorNo) * SECTOR_SIZE); if(pu8[j] != 0xFF){ MemDump((uintptr_t)s_nor_read_buffer, sizeof(s_nor_read_buffer)); mimic_printf("NG\r\n "); bret = false; goto _END; } } mimic_printf("OK\r\n"); mimic_printf("Program Area = 0x%08lX - 0x%08lX\r\n", FlexSPI_AMBA_BASE + (i + u32StartSectorNo) * SECTOR_SIZE, FlexSPI_AMBA_BASE + (i + u32StartSectorNo + 1) * SECTOR_SIZE- 1 ); for (uint32_t j = 0; j < (SECTOR_SIZE / FLASH_PAGE_SIZE); j++) { for (uint32_t k = 0; k < FLASH_PAGE_SIZE; k++) { s_nor_program_buffer[k] = pu8[k + j * FLASH_PAGE_SIZE + i * SECTOR_SIZE]; } __DMB(); status = flexspi_nor_flash_page_program(FLEXSPI, (i+u32StartSectorNo) * SECTOR_SIZE + j*FLASH_PAGE_SIZE, (void *)s_nor_program_buffer); if (status != kStatus_Success) { mimic_printf("Page program failure !\r\n"); FLEXSPI_SoftwareReset(FLEXSPI); bret = false; goto _END; } } /* Do software reset to reset AHB buffer. */ FLEXSPI_SoftwareReset(FLEXSPI); __DMB(); for (uint32_t j = 0; j < (SECTOR_SIZE / FLASH_PAGE_SIZE); j++) { for (uint32_t k = 0; k < FLASH_PAGE_SIZE; k++) { s_nor_program_buffer[k] = pu8[k + j * FLASH_PAGE_SIZE + i * SECTOR_SIZE]; } memcpy(s_nor_read_buffer, (void *)(FlexSPI_AMBA_BASE + (i+u32StartSectorNo) * SECTOR_SIZE + j*FLASH_PAGE_SIZE), sizeof(s_nor_read_buffer)); __DMB(); if (memcmp(s_nor_read_buffer, s_nor_program_buffer, sizeof(s_nor_program_buffer)) != 0) { mimic_printf("Program data - read out data value incorrect !\r\n"); MemDump((uintptr_t)s_nor_read_buffer, sizeof(s_nor_read_buffer)); bret = false; goto _END; } } } mimic_printf("Prpgram Update OK\r\n\r\n"); _END: SCB_EnableDCache(); return bret; } static uint8_t s_u8[SECTOR_SIZE] = {0}; void CmdSFROM(uint32_t argc, const char *argv[]) { for(uint32_t i=0;i<((BOARD_FLASH_SIZE / SECTOR_SIZE) / 4);i++){ if(SPIFlashWriteData(DEF_DUMMY_SECTOR + i, s_u8, sizeof(s_u8)) == false){ break; } } }
davinder2385/iot-edge-samples
IoT_Edge/persistence-service-ref-app/app/src/main/java/com/sap/persistenceservice/refapp/iot/model/SensorType.java
package com.sap.persistenceservice.refapp.iot.model; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; @Getter @Setter @JsonIgnoreProperties(ignoreUnknown = true) public class SensorType { private static final Logger log = LoggerFactory.getLogger(SensorType.class); @JsonProperty("id") String id; @JsonProperty("alternateId") String alternateId; @JsonProperty("name") String name; @JsonProperty("capabilities") List<CapabilityAssignment> capabilities; /** * This method returns if the sensor type is valid or not * * @param sensorType * @return */ public boolean isValid() { if (id == null || id.isEmpty()) { log.error("Sensor type id is empty or invalid"); return false; } if (name == null || name.isEmpty()) { log.error("Sensor type with id {} has no name associated with it", id); return false; } if (capabilities == null || capabilities.isEmpty()) { log.error("Sensor type with id {} has no capabilities associated with it", id); return false; } return true; } }
mehrabik/az
modules/entities/dataset/filtered_dataset.py
<gh_stars>10-100 import logging from modules.entities.entity import Entity from modules.services.apk_evaluator import ApkEvaluator class FilteredDataset(Entity): def __init__(self, source=None, criteria=None): self.source = source self.criteria = criteria self.apk_evaluator = ApkEvaluator(criteria) self.length = 0 logging.info(f'CREATE DATASET BY CRITERIA: {self.apk_evaluator.criteria}') def _key(self): return self.criteria def __iter__(self): return self def __next__(self): try: apk = next(self.source) logging.debug(f'EVALUATE {apk.pkg_name}') while not self.apk_evaluator.satisfies(apk): logging.debug(f'EVALUATE {apk.pkg_name}') apk = next(self.source) self.length += 1 return apk except StopIteration: logging.info(f'DATASET HAS BEEN CREATED. {self.length} APKS SATISFY CRITERIA') raise StopIteration
mczenko/agile-toolbox
AgileToolbox/Questions/TableViewCells/EPAttributedTextTableViewCell.h
<filename>AgileToolbox/Questions/TableViewCells/EPAttributedTextTableViewCell.h<gh_stars>0 // // EPAttributedTextTableViewCell.h // AgileToolbox // // Created by <NAME> on 13/02/14. // // #import <UIKit/UIKit.h> #import "Question.h" @interface EPAttributedTextTableViewCell : UITableViewCell - (id)initWithTextView:(UITextView*)textView; @end
keilaoko/nuclide
src/menu-fn/m_viewreadme.c
/* * Copyright (c) 2016-2020 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ CWidget vr_readme; CMainButton vr_btnDone; CFrame vr_frReadme; CListBox vr_lbReadme; CScrollbar vr_sbReadme; void vr_btndone_start(void) { static void vr_btndone_end(void) { g_menupage = PAGE_MAIN; } localsound("../media/launch_dnmenu1.wav"); header.SetStartEndPos(45,45,70,376); header.SetStartEndSize(460,80,156,26); header.m_lerp = 0.0f; header.m_visible = TRUE; header.SetHeader(HEAD_README); header.SetExecute(vr_btndone_end); } void vr_sbreadme_changed(int val) { vr_lbReadme.SetScroll(val); } void menu_viewreadme_init(void) { vr_readme = spawn(CWidget); vr_btnDone = spawn(CMainButton); vr_btnDone.SetImage(BTN_DONE); vr_btnDone.SetExecute(vr_btndone_start); vr_btnDone.SetPos(50,140); Widget_Add(vr_readme, vr_btnDone); vr_frReadme = spawn(CFrame); vr_frReadme.SetPos(225,140); vr_frReadme.SetSize(364,290); Widget_Add(vr_readme, vr_frReadme); vr_lbReadme = spawn(CListBox); vr_lbReadme.SetPos(229,143); vr_lbReadme.SetSize(342,284); Widget_Add(vr_readme, vr_lbReadme); vr_sbReadme = spawn(CScrollbar); vr_sbReadme.SetPos(571,143); vr_sbReadme.SetHeight(284); vr_sbReadme.SetCallback(vr_sbreadme_changed); Widget_Add(vr_readme, vr_sbReadme); filestream rdme; string lstline; rdme = fopen(games[gameinfo_current].readme, FILE_READ); if (rdme >= 0) { while((lstline = fgets(rdme))) { vr_lbReadme.AddWrapped(lstline); } fclose(rdme); } vr_sbReadme.SetMax(vr_lbReadme.GetCount()); } void menu_viewreadme_draw(void) { Widget_Draw(vr_readme); Header_Draw(HEAD_README); } void menu_viewreadme_input(float evtype, float scanx, float chary, float devid) { Widget_Input(vr_readme, evtype, scanx, chary, devid); }
shisheng-1/tapestry-5
tapestry-http/src/main/java/org/apache/tapestry5/http/Link.java
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.http; import java.util.List; import org.apache.commons.codec.net.URLCodec; import org.apache.tapestry5.http.services.BaseURLSource; import org.apache.tapestry5.http.services.Request; import org.apache.tapestry5.ioc.annotations.IncompatibleChange; /** * A link is the Tapestry representation of a URL or URI that triggers dynamic behavior. This link is in three parts: a * path portion, an optional anchor, and a set of query parameters. A request for a link will ultimately be recognized * by a {@link org.apache.tapestry5.http.services.Dispatcher}. * * Query parameter values are kept separate from the path portion to support encoding those values into hidden form * fields (where appropriate). */ public interface Link { /** * Returns the names of any additional query parameters for the URI. Query parameters store less regular or less * often used values that can not be expressed in the path. They also are used to store, or link to, persistent * state. * * @return list of query parameter names, is alphabetical order */ List<String> getParameterNames(); /** * Returns the value of a specifically named query parameter, or <code>null</code> if no such query parameter is stored * in the link. * * Use this method only when you are sure the parameter has only one value. If the parameter might have more than * one value, use {@link #getParameterValues}. * * If you use this method with a multivalued parameter, the value returned is equal to the first value in the * array returned by <code>getParameterValues</code>. * * @return a string representing the single value of the named parameter */ String getParameterValue(String name); /** * Adds a parameter value. The value will be added, as is, to the URL. In many cases, the value should be URL * encoded via {@link URLCodec}. * * @param parameterName * the name of the parameter to store * @param value * the value to store, a null or blank value is allowed (as of Tapestry 5.3) * @return this Link, to support method chaining */ @IncompatibleChange(release = "5.4", details = "changed from void to Link") Link addParameter(String parameterName, String value); /** * Adds a parameter value as a value object; the value object is converted to a string via * <a href="http://tapestry.apache.org/current/apidocs/src-html/org/apache/tapestry5/services/ContextPathEncoder.html#line.31">ContextPathEncoder.encodeValue(Object)</a> * from tapestry-core and the result is added via {@link #addParameter(String, String)}. * The Link object is returned for further configuration. * * @since 5.2.2 */ Link addParameterValue(String parameterName, Object value); /** * Removes a parameter value, which is occasionally useful when transforming a parameter into a portion of * the path. * * @return this Link, to support method chaining * @since 5.2.0 */ @IncompatibleChange(release = "5.4", details = "changed from void to Link") Link removeParameter(String parameterName); /** * Returns the completely unadorned base path. Other methods (such as {@link #toURI()}), may append * an anchor or query parameters. * * @since 5.2.0 */ String getBasePath(); /** * Creates a copy of this link that has the same parameters, anchor, and other attributes, but a different * {@linkplain #getBasePath() base path}. * * @return a new Link instance * @since 5.2.0 */ Link copyWithBasePath(String basePath); /** * Returns the URI portion of the link. When the link is created for a form, this will not include query parameters. * This is the same value returned from toString(). * * @return the URI, ready to be added as an element attribute */ String toURI(); /** * Returns the link as a redirect URI. The URI includes any query parameters. */ String toRedirectURI(); /** * Returns the link anchor. If this link does not have an anchor, this method returns <code>null</code>. * * @return the link anchor */ String getAnchor(); /** * Sets the link anchor. Null and empty anchors will be ignored when building the link URI. * * @param anchor * the link anchor * @return this Link, to support method chaining */ @IncompatibleChange(release = "5.4", details = "changed from void to Link") Link setAnchor(String anchor); /** * Returns the absolute URL, which includes the scheme, hostname and possibly port (as per * {@link BaseURLSource#getBaseURL(boolean)}). * By default, the scheme is chosen to match the {@linkplain Request#isSecure() security} of the current request. * * Note: the semantics of this method changed between Tapestry 5.1 and 5.2. Most code should use toString() or * {@link #toURI()} (which are equivalent) instead. * * @return the complete, qualified URL, including query parameters. */ String toAbsoluteURI(); /** * Returns either the secure or insecure URL, with complete scheme, hostname and possibly port (as per * {@link BaseURLSource#getBaseURL(boolean)}). * * @return the complete, qualified URL, including query parameters. * @since 5.2.2 */ String toAbsoluteURI(boolean secure); /** * Changes the link's security, which can be useful to force a link to be either secure or insecure * when normally it might not be. * * @param newSecurity * new security value, not null, typically {@link LinkSecurity#FORCE_SECURE} or {@link LinkSecurity#FORCE_INSECURE} * @since 5.3 */ @IncompatibleChange(release = "5.4", details = "LinkSecurity class moved from internal package to org.apache.tapestry5.") void setSecurity(LinkSecurity newSecurity); /** * Returns the current security for this link, which reflects whether the targeted page is itself secure or insecure. * * @since 5.3 */ @IncompatibleChange(release = "5.4", details = "LinkSecurity class moved from internal package to org.apache.tapestry5.") LinkSecurity getSecurity(); /** * Returns the parameter values for the given name. Returns null if no such parameter is stored in the link. */ String[] getParameterValues(String parameterName); }
youssriaboelseod/pyerp
apps/base/urls/plugin.py
<filename>apps/base/urls/plugin.py """uRLs para gestionar los plugin """ # Django Library from django.urls import path # Localfolder Library from ..views.plugin import ( PluginInstall, PluginListView, PluginUninstall, PluginUpdate) app_name = 'PyPlugin' urlpatterns = [ path('', PluginListView.as_view(), name='list'), path('update', PluginUpdate, name='update'), path('install/<int:pk>/', PluginInstall, name='create'), path('uninstall/<int:pk>/', PluginUninstall, name='delete'), ]
cyberstormdotmu/azure-tools-for-java
Utils/hdinsight-node-common/src/com/microsoft/azure/hdinsight/spark/jobs/framework/IRequest.java
<gh_stars>100-1000 /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ package com.microsoft.azure.hdinsight.spark.jobs.framework; import com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail; import com.microsoft.azuretools.azurecommons.helpers.NotNull; /** * Rest API request object * */ public interface IRequest { @NotNull String getRequestUrl(); @NotNull IClusterDetail getCluster(); @NotNull HttpRequestType getRestType(); }
CamW/servicetalk
servicetalk-http-security-jersey/src/main/java/io/servicetalk/http/security/auth/basic/jersey/AbstractBasicAuthSecurityContextFilter.java
/* * Copyright © 2019 Apple Inc. and the ServiceTalk project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.servicetalk.http.security.auth.basic.jersey; import io.servicetalk.concurrent.api.AsyncContext; import io.servicetalk.concurrent.api.AsyncContextMap.Key; import java.util.function.BiFunction; import javax.annotation.Nullable; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.SecurityContext; abstract class AbstractBasicAuthSecurityContextFilter<UserInfo> implements ContainerRequestFilter { @Nullable private final Key<UserInfo> userInfoKey; private final BiFunction<ContainerRequestContext, UserInfo, SecurityContext> securityContextFunction; AbstractBasicAuthSecurityContextFilter( @Nullable final Key<UserInfo> userInfoKey, final BiFunction<ContainerRequestContext, UserInfo, SecurityContext> securityContextFunction) { this.userInfoKey = userInfoKey; this.securityContextFunction = securityContextFunction; } @Override public void filter(final ContainerRequestContext requestCtx) { final SecurityContext securityContext = securityContext(requestCtx); if (securityContext != null) { requestCtx.setSecurityContext(securityContext); } } @Nullable private SecurityContext securityContext(final ContainerRequestContext requestCtx) { if (userInfoKey == null) { return securityContextFunction.apply(requestCtx, null); } final UserInfo userInfo = AsyncContext.get(userInfoKey); if (userInfo == null) { return null; } return securityContextFunction.apply(requestCtx, userInfo); } }
sapnaBaniya102/vitesse1
node_modules/.pnpm/unplugin-icons@0.12.18_ffe6ba4676d23562dbecd516d3abe553/node_modules/unplugin-icons/dist/loaders.js
<reponame>sapnaBaniya102/vitesse1 "use strict";Object.defineProperty(exports, "__esModule", {value: true}); var _chunkWOL7QKXNjs = require('./chunk-WOL7QKXN.js'); require('./chunk-IJYRCWEX.js'); // src/loaders.ts var _fs = require('fs'); function FileSystemIconLoader(dir) { return (name) => { const pathes = [ `${dir}/${name}.svg`, `${dir}/${_chunkWOL7QKXNjs.camelize.call(void 0, name)}.svg`, `${dir}/${_chunkWOL7QKXNjs.pascalize.call(void 0, name)}.svg` ]; for (const path of pathes) { if (_fs.existsSync.call(void 0, path)) return _fs.promises.readFile(path, "utf-8"); } }; } exports.FileSystemIconLoader = FileSystemIconLoader;
djodjoni/jus
jus-java/src/main/java/io/apptik/comm/jus/converter/ContentTypeBasedRespConverter.java
/* * Copyright (C) 2015 AppTik Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apptik.comm.jus.converter; import java.util.HashMap; import java.util.Map; import io.apptik.comm.jus.Converter; import io.apptik.comm.jus.NetworkResponse; import io.apptik.comm.jus.http.MediaType; /** * * Converter Map which uses different Converter depending on the media type. This is particularly * useful when we expect the the same java Type that can be received in different formats for * example JSON, XML, protobuf etc. * * @param <T> expected Type to convert to */ public class ContentTypeBasedRespConverter<T> extends AbstractSmartResponseConverter<T>{ Map<MediaType, Converter<NetworkResponse, T>> converters = new HashMap<>(); @Override protected Converter<NetworkResponse, T> chooseConverter(NetworkResponse value) { Converter converter = converters.get(value.contentType); if(converter!=null) { return converter; } StringBuilder str = new StringBuilder("Cannot find converter for :" + value + ", tried:"); for(Map.Entry entry:converters.entrySet()) { str.append("\n\t").append(entry.getKey()).append(" : ").append(entry.getValue()); } throw new RuntimeException(str.toString()); } public ContentTypeBasedRespConverter<T> add(MediaType mediaType, Converter<NetworkResponse, T> converter) { converters.put(mediaType, converter); return this; } }
npocmaka/Windows-Server-2003
public/internal/ds/inc/samrpc.h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0361 */ /* Compiler settings for samrpc.idl, samsrv.acf: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, oldnames, robust error checks: allocation ref bounds_check enum stub_data , no_format_optimization VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef __samrpc_h__ #define __samrpc_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ /* header files for imported files */ #include "samimp.h" #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); #ifndef __samr_INTERFACE_DEFINED__ #define __samr_INTERFACE_DEFINED__ /* interface samr */ /* [strict_context_handle][implicit_handle][unique][ms_union][version][uuid] */ typedef struct _RPC_UNICODE_STRING { USHORT Length; USHORT MaximumLength; /* [length_is][size_is] */ PWCH Buffer; } RPC_UNICODE_STRING; typedef struct _RPC_UNICODE_STRING *PRPC_UNICODE_STRING; typedef struct _RPC_STRING { USHORT Length; USHORT MaximumLength; /* [length_is][size_is] */ PCHAR Buffer; } RPC_STRING; typedef struct _RPC_STRING *PRPC_STRING; typedef struct _RPC_STRING RPC_ANSI_STRING; typedef struct _RPC_STRING *PRPC_ANSI_STRING; typedef struct _RPC_SID { UCHAR Revision; UCHAR SubAuthorityCount; SID_IDENTIFIER_AUTHORITY IdentifierAuthority; /* [size_is] */ ULONG SubAuthority[ 1 ]; } RPC_SID; typedef struct _RPC_SID *PRPC_SID; typedef struct _RPC_SID **PPRPC_SID; typedef /* [handle] */ LPWSTR PSAMPR_SERVER_NAME; typedef /* [context_handle] */ PVOID SAMPR_HANDLE; #define SAM_NETWORK_REVISION_1 (1) #define SAM_NETWORK_REVISION_2 (2) #define SAM_NETWORK_REVISION_3 (3) #define SAM_NETWORK_REVISION_LATEST SAM_NETWORK_REVISION_3 #define SAM_CLIENT_PRE_NT5 SAM_NETWORK_REVISION_1 #define SAM_CLIENT_NT5 SAM_NETWORK_REVISION_2 #define SAM_CLIENT_LATEST SAM_NETWORK_REVISION_LATEST #define SAM_EXTENDED_SID_DOMAIN 0x00000001 #define SAM_EXTENDED_SID_DOMAIN_COMPAT_1 0x00000002 #define SAM_EXTENDED_SID_DOMAIN_COMPAT_2 0x00000004 typedef struct _SAMPR_RID_ENUMERATION { ULONG RelativeId; RPC_UNICODE_STRING Name; } SAMPR_RID_ENUMERATION; typedef struct _SAMPR_RID_ENUMERATION *PSAMPR_RID_ENUMERATION; typedef struct _SAMPR_SID_ENUMERATION { PSID Sid; RPC_UNICODE_STRING Name; } SAMPR_SID_ENUMERATION; typedef struct _SAMPR_SID_ENUMERATION *PSAMPR_SID_ENUMERATION; typedef struct _SAMPR_ENUMERATION_BUFFER { ULONG EntriesRead; /* [size_is] */ PSAMPR_RID_ENUMERATION Buffer; } SAMPR_ENUMERATION_BUFFER; typedef struct _SAMPR_ENUMERATION_BUFFER *PSAMPR_ENUMERATION_BUFFER; typedef struct _SAMPR_SR_SECURITY_DESCRIPTOR { /* [range] */ ULONG Length; /* [size_is] */ PUCHAR SecurityDescriptor; } SAMPR_SR_SECURITY_DESCRIPTOR; typedef struct _SAMPR_SR_SECURITY_DESCRIPTOR *PSAMPR_SR_SECURITY_DESCRIPTOR; typedef struct _SAMPR_GET_GROUPS_BUFFER { ULONG MembershipCount; /* [size_is] */ PGROUP_MEMBERSHIP Groups; } SAMPR_GET_GROUPS_BUFFER; typedef struct _SAMPR_GET_GROUPS_BUFFER *PSAMPR_GET_GROUPS_BUFFER; typedef struct _SAMPR_GET_MEMBERS_BUFFER { ULONG MemberCount; /* [size_is] */ PULONG Members; /* [size_is] */ PULONG Attributes; } SAMPR_GET_MEMBERS_BUFFER; typedef struct _SAMPR_GET_MEMBERS_BUFFER *PSAMPR_GET_MEMBERS_BUFFER; typedef struct _SAMPR_LOGON_HOURS { USHORT UnitsPerWeek; /* [length_is][size_is] */ PUCHAR LogonHours; } SAMPR_LOGON_HOURS; typedef struct _SAMPR_LOGON_HOURS *PSAMPR_LOGON_HOURS; typedef struct _SAMPR_ULONG_ARRAY { ULONG Count; /* [size_is] */ ULONG *Element; } SAMPR_ULONG_ARRAY; typedef struct _SAMPR_ULONG_ARRAY *PSAMPR_ULONG_ARRAY; typedef struct _SAMPR_SID_INFORMATION { PRPC_SID SidPointer; } SAMPR_SID_INFORMATION; typedef /* [allocate] */ struct _SAMPR_SID_INFORMATION *PSAMPR_SID_INFORMATION; typedef struct _SAMPR_PSID_ARRAY { /* [range] */ ULONG Count; /* [size_is] */ PSAMPR_SID_INFORMATION Sids; } SAMPR_PSID_ARRAY; typedef struct _SAMPR_PSID_ARRAY *PSAMPR_PSID_ARRAY; typedef struct _SAMPR_PSID_ARRAY_OUT { ULONG Count; /* [size_is] */ PSAMPR_SID_INFORMATION Sids; } SAMPR_PSID_ARRAY_OUT; typedef struct _SAMPR_PSID_ARRAY_OUT *PSAMPR_PSID_ARRAY_OUT; typedef struct _SAMPR_UNICODE_STRING_ARRAY { ULONG Count; /* [size_is] */ RPC_UNICODE_STRING *Element; } SAMPR_UNICODE_STRING_ARRAY; typedef struct _SAMPR_UNICODE_STRING_ARRAY *PSAMPR_UNICODE_STRING_ARRAY; typedef RPC_UNICODE_STRING SAMPR_RETURNED_STRING; typedef RPC_UNICODE_STRING *PSAMPR_RETURNED_STRING; typedef STRING SAMPR_RETURNED_NORMAL_STRING; typedef STRING *PSAMPR_RETURNED_NORMAL_STRING; typedef struct _SAMPR_RETURNED_USTRING_ARRAY { ULONG Count; /* [size_is] */ PSAMPR_RETURNED_STRING Element; } SAMPR_RETURNED_USTRING_ARRAY; typedef struct _SAMPR_RETURNED_USTRING_ARRAY *PSAMPR_RETURNED_USTRING_ARRAY; typedef struct _SAMPR_REVISION_INFO_V1 { ULONG Revision; ULONG SupportedFeatures; } SAMPR_REVISION_INFO_V1; typedef struct _SAMPR_REVISION_INFO_V1 *PSAMPR_REVISION_INFO_V1; typedef /* [public][public][public][switch_type] */ union __MIDL_samr_0001 { /* [case()] */ SAMPR_REVISION_INFO_V1 V1; } SAMPR_REVISION_INFO; typedef /* [switch_type] */ union __MIDL_samr_0001 *PSAMPR_REVISION_INFO; #pragma pack(4) typedef struct _SAMPR_DOMAIN_GENERAL_INFORMATION { OLD_LARGE_INTEGER ForceLogoff; RPC_UNICODE_STRING OemInformation; RPC_UNICODE_STRING DomainName; RPC_UNICODE_STRING ReplicaSourceNodeName; OLD_LARGE_INTEGER DomainModifiedCount; ULONG DomainServerState; ULONG DomainServerRole; BOOLEAN UasCompatibilityRequired; ULONG UserCount; ULONG GroupCount; ULONG AliasCount; } SAMPR_DOMAIN_GENERAL_INFORMATION; typedef struct _SAMPR_DOMAIN_GENERAL_INFORMATION *PSAMPR_DOMAIN_GENERAL_INFORMATION; #pragma pack() #pragma pack(4) typedef struct _SAMPR_DOMAIN_GENERAL_INFORMATION2 { SAMPR_DOMAIN_GENERAL_INFORMATION I1; LARGE_INTEGER LockoutDuration; LARGE_INTEGER LockoutObservationWindow; USHORT LockoutThreshold; } SAMPR_DOMAIN_GENERAL_INFORMATION2; typedef struct _SAMPR_DOMAIN_GENERAL_INFORMATION2 *PSAMPR_DOMAIN_GENERAL_INFORMATION2; #pragma pack() typedef struct _SAMPR_DOMAIN_OEM_INFORMATION { RPC_UNICODE_STRING OemInformation; } SAMPR_DOMAIN_OEM_INFORMATION; typedef struct _SAMPR_DOMAIN_OEM_INFORMATION *PSAMPR_DOMAIN_OEM_INFORMATION; typedef struct _SAMPR_DOMAIN_NAME_INFORMATION { RPC_UNICODE_STRING DomainName; } SAMPR_DOMAIN_NAME_INFORMATION; typedef struct _SAMPR_DOMAIN_NAME_INFORMATION *PSAMPR_DOMAIN_NAME_INFORMATION; typedef struct SAMPR_DOMAIN_REPLICATION_INFORMATION { RPC_UNICODE_STRING ReplicaSourceNodeName; } SAMPR_DOMAIN_REPLICATION_INFORMATION; typedef struct SAMPR_DOMAIN_REPLICATION_INFORMATION *PSAMPR_DOMAIN_REPLICATION_INFORMATION; typedef struct _SAMPR_DOMAIN_LOCKOUT_INFORMATION { LARGE_INTEGER LockoutDuration; LARGE_INTEGER LockoutObservationWindow; USHORT LockoutThreshold; } SAMPR_DOMAIN_LOCKOUT_INFORMATION; typedef struct _SAMPR_DOMAIN_LOCKOUT_INFORMATION *PSAMPR_DOMAIN_LOCKOUT_INFORMATION; typedef /* [switch_type] */ union _SAMPR_DOMAIN_INFO_BUFFER { /* [case()] */ DOMAIN_PASSWORD_INFORMATION Password; /* [case()] */ SAMPR_DOMAIN_GENERAL_INFORMATION General; /* [case()] */ DOMAIN_LOGOFF_INFORMATION Logoff; /* [case()] */ SAMPR_DOMAIN_OEM_INFORMATION Oem; /* [case()] */ SAMPR_DOMAIN_NAME_INFORMATION Name; /* [case()] */ DOMAIN_SERVER_ROLE_INFORMATION Role; /* [case()] */ SAMPR_DOMAIN_REPLICATION_INFORMATION Replication; /* [case()] */ DOMAIN_MODIFIED_INFORMATION Modified; /* [case()] */ DOMAIN_STATE_INFORMATION State; /* [case()] */ SAMPR_DOMAIN_GENERAL_INFORMATION2 General2; /* [case()] */ SAMPR_DOMAIN_LOCKOUT_INFORMATION Lockout; /* [case()] */ DOMAIN_MODIFIED_INFORMATION2 Modified2; } SAMPR_DOMAIN_INFO_BUFFER; typedef /* [switch_type] */ union _SAMPR_DOMAIN_INFO_BUFFER *PSAMPR_DOMAIN_INFO_BUFFER; typedef struct _SAMPR_GROUP_GENERAL_INFORMATION { RPC_UNICODE_STRING Name; ULONG Attributes; ULONG MemberCount; RPC_UNICODE_STRING AdminComment; } SAMPR_GROUP_GENERAL_INFORMATION; typedef struct _SAMPR_GROUP_GENERAL_INFORMATION *PSAMPR_GROUP_GENERAL_INFORMATION; typedef struct _SAMPR_GROUP_NAME_INFORMATION { RPC_UNICODE_STRING Name; } SAMPR_GROUP_NAME_INFORMATION; typedef struct _SAMPR_GROUP_NAME_INFORMATION *PSAMPR_GROUP_NAME_INFORMATION; typedef struct _SAMPR_GROUP_ADM_COMMENT_INFORMATION { RPC_UNICODE_STRING AdminComment; } SAMPR_GROUP_ADM_COMMENT_INFORMATION; typedef struct _SAMPR_GROUP_ADM_COMMENT_INFORMATION *PSAMPR_GROUP_ADM_COMMENT_INFORMATION; typedef /* [switch_type] */ union _SAMPR_GROUP_INFO_BUFFER { /* [case()] */ SAMPR_GROUP_GENERAL_INFORMATION General; /* [case()] */ SAMPR_GROUP_NAME_INFORMATION Name; /* [case()] */ GROUP_ATTRIBUTE_INFORMATION Attribute; /* [case()] */ SAMPR_GROUP_ADM_COMMENT_INFORMATION AdminComment; /* [case()] */ SAMPR_GROUP_GENERAL_INFORMATION DoNotUse; } SAMPR_GROUP_INFO_BUFFER; typedef /* [switch_type] */ union _SAMPR_GROUP_INFO_BUFFER *PSAMPR_GROUP_INFO_BUFFER; typedef struct _SAMPR_ALIAS_GENERAL_INFORMATION { RPC_UNICODE_STRING Name; ULONG MemberCount; RPC_UNICODE_STRING AdminComment; } SAMPR_ALIAS_GENERAL_INFORMATION; typedef struct _SAMPR_ALIAS_GENERAL_INFORMATION *PSAMPR_ALIAS_GENERAL_INFORMATION; typedef struct _SAMPR_ALIAS_NAME_INFORMATION { RPC_UNICODE_STRING Name; } SAMPR_ALIAS_NAME_INFORMATION; typedef struct _SAMPR_ALIAS_NAME_INFORMATION *PSAMPR_ALIAS_NAME_INFORMATION; typedef struct _SAMPR_ALIAS_ADM_COMMENT_INFORMATION { RPC_UNICODE_STRING AdminComment; } SAMPR_ALIAS_ADM_COMMENT_INFORMATION; typedef struct _SAMPR_ALIAS_ADM_COMMENT_INFORMATION *PSAMPR_ALIAS_ADM_COMMENT_INFORMATION; typedef /* [switch_type] */ union _SAMPR_ALIAS_INFO_BUFFER { /* [case()] */ SAMPR_ALIAS_GENERAL_INFORMATION General; /* [case()] */ SAMPR_ALIAS_NAME_INFORMATION Name; /* [case()] */ SAMPR_ALIAS_ADM_COMMENT_INFORMATION AdminComment; } SAMPR_ALIAS_INFO_BUFFER; typedef /* [switch_type] */ union _SAMPR_ALIAS_INFO_BUFFER *PSAMPR_ALIAS_INFO_BUFFER; #pragma pack(4) typedef struct _SAMPR_USER_ALL_INFORMATION { OLD_LARGE_INTEGER LastLogon; OLD_LARGE_INTEGER LastLogoff; OLD_LARGE_INTEGER PasswordLastSet; OLD_LARGE_INTEGER AccountExpires; OLD_LARGE_INTEGER PasswordCanChange; OLD_LARGE_INTEGER PasswordMustChange; RPC_UNICODE_STRING UserName; RPC_UNICODE_STRING FullName; RPC_UNICODE_STRING HomeDirectory; RPC_UNICODE_STRING HomeDirectoryDrive; RPC_UNICODE_STRING ScriptPath; RPC_UNICODE_STRING ProfilePath; RPC_UNICODE_STRING AdminComment; RPC_UNICODE_STRING WorkStations; RPC_UNICODE_STRING UserComment; RPC_UNICODE_STRING Parameters; RPC_UNICODE_STRING LmOwfPassword; RPC_UNICODE_STRING NtOwfPassword; RPC_UNICODE_STRING PrivateData; SAMPR_SR_SECURITY_DESCRIPTOR SecurityDescriptor; ULONG UserId; ULONG PrimaryGroupId; ULONG UserAccountControl; ULONG WhichFields; SAMPR_LOGON_HOURS LogonHours; USHORT BadPasswordCount; USHORT LogonCount; USHORT CountryCode; USHORT CodePage; BOOLEAN LmPasswordPresent; BOOLEAN NtPasswordPresent; BOOLEAN PasswordExpired; BOOLEAN PrivateDataSensitive; } SAMPR_USER_ALL_INFORMATION; typedef struct _SAMPR_USER_ALL_INFORMATION *PSAMPR_USER_ALL_INFORMATION; #pragma pack() #pragma pack(4) typedef struct _SAMPR_USER_INTERNAL3_INFORMATION { SAMPR_USER_ALL_INFORMATION I1; LARGE_INTEGER LastBadPasswordTime; } SAMPR_USER_INTERNAL3_INFORMATION; typedef struct _SAMPR_USER_INTERNAL3_INFORMATION *PSAMPR_USER_INTERNAL3_INFORMATION; #pragma pack() typedef struct _SAMPR_USER_GENERAL_INFORMATION { RPC_UNICODE_STRING UserName; RPC_UNICODE_STRING FullName; ULONG PrimaryGroupId; RPC_UNICODE_STRING AdminComment; RPC_UNICODE_STRING UserComment; } SAMPR_USER_GENERAL_INFORMATION; typedef struct _SAMPR_USER_GENERAL_INFORMATION *PSAMPR_USER_GENERAL_INFORMATION; typedef struct _SAMPR_USER_PREFERENCES_INFORMATION { RPC_UNICODE_STRING UserComment; RPC_UNICODE_STRING Reserved1; USHORT CountryCode; USHORT CodePage; } SAMPR_USER_PREFERENCES_INFORMATION; typedef struct _SAMPR_USER_PREFERENCES_INFORMATION *PSAMPR_USER_PREFERENCES_INFORMATION; typedef struct _SAMPR_USER_PARAMETERS_INFORMATION { RPC_UNICODE_STRING Parameters; } SAMPR_USER_PARAMETERS_INFORMATION; typedef struct _SAMPR_USER_PARAMETERS_INFORMATION *PSAMPR_USER_PARAMETERS_INFORMATION; #pragma pack(4) typedef struct _SAMPR_USER_LOGON_INFORMATION { RPC_UNICODE_STRING UserName; RPC_UNICODE_STRING FullName; ULONG UserId; ULONG PrimaryGroupId; RPC_UNICODE_STRING HomeDirectory; RPC_UNICODE_STRING HomeDirectoryDrive; RPC_UNICODE_STRING ScriptPath; RPC_UNICODE_STRING ProfilePath; RPC_UNICODE_STRING WorkStations; OLD_LARGE_INTEGER LastLogon; OLD_LARGE_INTEGER LastLogoff; OLD_LARGE_INTEGER PasswordLastSet; OLD_LARGE_INTEGER PasswordCanChange; OLD_LARGE_INTEGER PasswordMustChange; SAMPR_LOGON_HOURS LogonHours; USHORT BadPasswordCount; USHORT LogonCount; ULONG UserAccountControl; } SAMPR_USER_LOGON_INFORMATION; typedef struct _SAMPR_USER_LOGON_INFORMATION *PSAMPR_USER_LOGON_INFORMATION; #pragma pack() #pragma pack(4) typedef struct _SAMPR_USER_ACCOUNT_INFORMATION { RPC_UNICODE_STRING UserName; RPC_UNICODE_STRING FullName; ULONG UserId; ULONG PrimaryGroupId; RPC_UNICODE_STRING HomeDirectory; RPC_UNICODE_STRING HomeDirectoryDrive; RPC_UNICODE_STRING ScriptPath; RPC_UNICODE_STRING ProfilePath; RPC_UNICODE_STRING AdminComment; RPC_UNICODE_STRING WorkStations; OLD_LARGE_INTEGER LastLogon; OLD_LARGE_INTEGER LastLogoff; SAMPR_LOGON_HOURS LogonHours; USHORT BadPasswordCount; USHORT LogonCount; OLD_LARGE_INTEGER PasswordLastSet; OLD_LARGE_INTEGER AccountExpires; ULONG UserAccountControl; } SAMPR_USER_ACCOUNT_INFORMATION; typedef struct _SAMPR_USER_ACCOUNT_INFORMATION *PSAMPR_USER_ACCOUNT_INFORMATION; #pragma pack() typedef struct _SAMPR_USER_A_NAME_INFORMATION { RPC_UNICODE_STRING UserName; } SAMPR_USER_A_NAME_INFORMATION; typedef struct _SAMPR_USER_A_NAME_INFORMATION *PSAMPR_USER_A_NAME_INFORMATION; typedef struct _SAMPR_USER_F_NAME_INFORMATION { RPC_UNICODE_STRING FullName; } SAMPR_USER_F_NAME_INFORMATION; typedef struct _SAMPR_USER_F_NAME_INFORMATION *PSAMPR_USER_F_NAME_INFORMATION; typedef struct _SAMPR_USER_NAME_INFORMATION { RPC_UNICODE_STRING UserName; RPC_UNICODE_STRING FullName; } SAMPR_USER_NAME_INFORMATION; typedef struct _SAMPR_USER_NAME_INFORMATION *PSAMPR_USER_NAME_INFORMATION; typedef struct _SAMPR_USER_HOME_INFORMATION { RPC_UNICODE_STRING HomeDirectory; RPC_UNICODE_STRING HomeDirectoryDrive; } SAMPR_USER_HOME_INFORMATION; typedef struct _SAMPR_USER_HOME_INFORMATION *PSAMPR_USER_HOME_INFORMATION; typedef struct _SAMPR_USER_SCRIPT_INFORMATION { RPC_UNICODE_STRING ScriptPath; } SAMPR_USER_SCRIPT_INFORMATION; typedef struct _SAMPR_USER_SCRIPT_INFORMATION *PSAMPR_USER_SCRIPT_INFORMATION; typedef struct _SAMPR_USER_PROFILE_INFORMATION { RPC_UNICODE_STRING ProfilePath; } SAMPR_USER_PROFILE_INFORMATION; typedef struct _SAMPR_USER_PROFILE_INFORMATION *PSAMPR_USER_PROFILE_INFORMATION; typedef struct _SAMPR_USER_ADMIN_COMMENT_INFORMATION { RPC_UNICODE_STRING AdminComment; } SAMPR_USER_ADMIN_COMMENT_INFORMATION; typedef struct _SAMPR_USER_ADMIN_COMMENT_INFORMATION *PSAMPR_USER_ADMIN_COMMENT_INFORMATION; typedef struct _SAMPR_USER_WORKSTATIONS_INFORMATION { RPC_UNICODE_STRING WorkStations; } SAMPR_USER_WORKSTATIONS_INFORMATION; typedef struct _SAMPR_USER_WORKSTATIONS_INFORMATION *PSAMPR_USER_WORKSTATIONS_INFORMATION; typedef struct _SAMPR_USER_LOGON_HOURS_INFORMATION { SAMPR_LOGON_HOURS LogonHours; } SAMPR_USER_LOGON_HOURS_INFORMATION; typedef struct _SAMPR_USER_LOGON_HOURS_INFORMATION *PSAMPR_USER_LOGON_HOURS_INFORMATION; typedef struct _SAMPR_USER_INTERNAL1_INFORMATION { ENCRYPTED_NT_OWF_PASSWORD EncryptedNtOwfPassword; ENCRYPTED_LM_OWF_PASSWORD EncryptedLmOwfPassword; BOOLEAN NtPasswordPresent; BOOLEAN LmPasswordPresent; BOOLEAN PasswordExpired; } SAMPR_USER_INTERNAL1_INFORMATION; typedef struct _SAMPR_USER_INTERNAL1_INFORMATION *PSAMPR_USER_INTERNAL1_INFORMATION; typedef struct _SAMPR_USER_INTERNAL4_INFORMATION { SAMPR_USER_ALL_INFORMATION I1; SAMPR_ENCRYPTED_USER_PASSWORD UserPassword; } SAMPR_USER_INTERNAL4_INFORMATION; typedef struct _SAMPR_USER_INTERNAL4_INFORMATION *PSAMPR_USER_INTERNAL4_INFORMATION; typedef struct _SAMPR_USER_INTERNAL4_INFORMATION_NEW { SAMPR_USER_ALL_INFORMATION I1; SAMPR_ENCRYPTED_USER_PASSWORD_NEW UserPassword; } SAMPR_USER_INTERNAL4_INFORMATION_NEW; typedef struct _SAMPR_USER_INTERNAL4_INFORMATION_NEW *PSAMPR_USER_INTERNAL4_INFORMATION_NEW; typedef struct _SAMPR_USER_INTERNAL5_INFORMATION { SAMPR_ENCRYPTED_USER_PASSWORD UserPassword; BOOLEAN PasswordExpired; } SAMPR_USER_INTERNAL5_INFORMATION; typedef struct _SAMPR_USER_INTERNAL5_INFORMATION *PSAMPR_USER_INTERNAL5_INFORMATION; typedef struct _SAMPR_USER_INTERNAL5_INFORMATION_NEW { SAMPR_ENCRYPTED_USER_PASSWORD_NEW UserPassword; BOOLEAN PasswordExpired; } SAMPR_USER_INTERNAL5_INFORMATION_NEW; typedef struct _SAMPR_USER_INTERNAL5_INFORMATION_NEW *PSAMPR_USER_INTERNAL5_INFORMATION_NEW; typedef /* [switch_type] */ union _SAMPR_USER_INFO_BUFFER { /* [case()] */ SAMPR_USER_GENERAL_INFORMATION General; /* [case()] */ SAMPR_USER_PREFERENCES_INFORMATION Preferences; /* [case()] */ SAMPR_USER_LOGON_INFORMATION Logon; /* [case()] */ SAMPR_USER_LOGON_HOURS_INFORMATION LogonHours; /* [case()] */ SAMPR_USER_ACCOUNT_INFORMATION Account; /* [case()] */ SAMPR_USER_NAME_INFORMATION Name; /* [case()] */ SAMPR_USER_A_NAME_INFORMATION AccountName; /* [case()] */ SAMPR_USER_F_NAME_INFORMATION FullName; /* [case()] */ USER_PRIMARY_GROUP_INFORMATION PrimaryGroup; /* [case()] */ SAMPR_USER_HOME_INFORMATION Home; /* [case()] */ SAMPR_USER_SCRIPT_INFORMATION Script; /* [case()] */ SAMPR_USER_PROFILE_INFORMATION Profile; /* [case()] */ SAMPR_USER_ADMIN_COMMENT_INFORMATION AdminComment; /* [case()] */ SAMPR_USER_WORKSTATIONS_INFORMATION WorkStations; /* [case()] */ USER_CONTROL_INFORMATION Control; /* [case()] */ USER_EXPIRES_INFORMATION Expires; /* [case()] */ SAMPR_USER_INTERNAL1_INFORMATION Internal1; /* [case()] */ USER_INTERNAL2_INFORMATION Internal2; /* [case()] */ SAMPR_USER_PARAMETERS_INFORMATION Parameters; /* [case()] */ SAMPR_USER_ALL_INFORMATION All; /* [case()] */ SAMPR_USER_INTERNAL3_INFORMATION Internal3; /* [case()] */ SAMPR_USER_INTERNAL4_INFORMATION Internal4; /* [case()] */ SAMPR_USER_INTERNAL5_INFORMATION Internal5; /* [case()] */ SAMPR_USER_INTERNAL4_INFORMATION_NEW Internal4New; /* [case()] */ SAMPR_USER_INTERNAL5_INFORMATION_NEW Internal5New; } SAMPR_USER_INFO_BUFFER; typedef /* [switch_type] */ union _SAMPR_USER_INFO_BUFFER *PSAMPR_USER_INFO_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_USER { ULONG Index; ULONG Rid; ULONG AccountControl; SAMPR_RETURNED_STRING LogonName; SAMPR_RETURNED_STRING AdminComment; SAMPR_RETURNED_STRING FullName; } SAMPR_DOMAIN_DISPLAY_USER; typedef struct _SAMPR_DOMAIN_DISPLAY_USER *PSAMPR_DOMAIN_DISPLAY_USER; typedef struct _SAMPR_DOMAIN_DISPLAY_MACHINE { ULONG Index; ULONG Rid; ULONG AccountControl; SAMPR_RETURNED_STRING Machine; SAMPR_RETURNED_STRING Comment; } SAMPR_DOMAIN_DISPLAY_MACHINE; typedef struct _SAMPR_DOMAIN_DISPLAY_MACHINE *PSAMPR_DOMAIN_DISPLAY_MACHINE; typedef struct _SAMPR_DOMAIN_DISPLAY_GROUP { ULONG Index; ULONG Rid; ULONG Attributes; SAMPR_RETURNED_STRING Group; SAMPR_RETURNED_STRING Comment; } SAMPR_DOMAIN_DISPLAY_GROUP; typedef struct _SAMPR_DOMAIN_DISPLAY_GROUP *PSAMPR_DOMAIN_DISPLAY_GROUP; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_USER { ULONG Index; SAMPR_RETURNED_NORMAL_STRING OemUser; } SAMPR_DOMAIN_DISPLAY_OEM_USER; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_USER *PSAMPR_DOMAIN_DISPLAY_OEM_USER; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_GROUP { ULONG Index; SAMPR_RETURNED_NORMAL_STRING OemGroup; } SAMPR_DOMAIN_DISPLAY_OEM_GROUP; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_GROUP *PSAMPR_DOMAIN_DISPLAY_OEM_GROUP; typedef struct _SAMPR_DOMAIN_DISPLAY_USER_BUFFER { ULONG EntriesRead; /* [size_is] */ PSAMPR_DOMAIN_DISPLAY_USER Buffer; } SAMPR_DOMAIN_DISPLAY_USER_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_USER_BUFFER *PSAMPR_DOMAIN_DISPLAY_USER_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER { ULONG EntriesRead; /* [size_is] */ PSAMPR_DOMAIN_DISPLAY_MACHINE Buffer; } SAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER *PSAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_GROUP_BUFFER { ULONG EntriesRead; /* [size_is] */ PSAMPR_DOMAIN_DISPLAY_GROUP Buffer; } SAMPR_DOMAIN_DISPLAY_GROUP_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_GROUP_BUFFER *PSAMPR_DOMAIN_DISPLAY_GROUP_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER { ULONG EntriesRead; /* [size_is] */ PSAMPR_DOMAIN_DISPLAY_OEM_USER Buffer; } SAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER *PSAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER { ULONG EntriesRead; /* [size_is] */ PSAMPR_DOMAIN_DISPLAY_OEM_GROUP Buffer; } SAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER; typedef struct _SAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER *PSAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER; typedef /* [switch_type] */ union _SAMPR_DISPLAY_INFO_BUFFER { /* [case()] */ SAMPR_DOMAIN_DISPLAY_USER_BUFFER UserInformation; /* [case()] */ SAMPR_DOMAIN_DISPLAY_MACHINE_BUFFER MachineInformation; /* [case()] */ SAMPR_DOMAIN_DISPLAY_GROUP_BUFFER GroupInformation; /* [case()] */ SAMPR_DOMAIN_DISPLAY_OEM_USER_BUFFER OemUserInformation; /* [case()] */ SAMPR_DOMAIN_DISPLAY_OEM_GROUP_BUFFER OemGroupInformation; } SAMPR_DISPLAY_INFO_BUFFER; typedef /* [switch_type] */ union _SAMPR_DISPLAY_INFO_BUFFER *PSAMPR_DISPLAY_INFO_BUFFER; NTSTATUS SamrConnect( /* [unique][in] */ PSAMPR_SERVER_NAME ServerName, /* [out] */ SAMPR_HANDLE *ServerHandle, /* [in] */ ACCESS_MASK DesiredAccess); NTSTATUS SamrCloseHandle( /* [out][in] */ SAMPR_HANDLE *SamHandle); NTSTATUS SamrSetSecurityObject( /* [in] */ SAMPR_HANDLE ObjectHandle, /* [in] */ SECURITY_INFORMATION SecurityInformation, /* [in] */ PSAMPR_SR_SECURITY_DESCRIPTOR SecurityDescriptor); NTSTATUS SamrQuerySecurityObject( /* [in] */ SAMPR_HANDLE ObjectHandle, /* [in] */ SECURITY_INFORMATION SecurityInformation, /* [out] */ PSAMPR_SR_SECURITY_DESCRIPTOR *SecurityDescriptor); NTSTATUS SamrShutdownSamServer( /* [in] */ SAMPR_HANDLE ServerHandle); NTSTATUS SamrLookupDomainInSamServer( /* [in] */ SAMPR_HANDLE ServerHandle, /* [in] */ PRPC_UNICODE_STRING Name, /* [out] */ PRPC_SID *DomainId); NTSTATUS SamrEnumerateDomainsInSamServer( /* [in] */ SAMPR_HANDLE ServerHandle, /* [out][in] */ PSAM_ENUMERATE_HANDLE EnumerationContext, /* [out] */ PSAMPR_ENUMERATION_BUFFER *Buffer, /* [in] */ ULONG PreferedMaximumLength, /* [out] */ PULONG CountReturned); NTSTATUS SamrOpenDomain( /* [in] */ SAMPR_HANDLE ServerHandle, /* [in] */ ACCESS_MASK DesiredAccess, /* [in] */ PRPC_SID DomainId, /* [out] */ SAMPR_HANDLE *DomainHandle); NTSTATUS SamrQueryInformationDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_INFORMATION_CLASS DomainInformationClass, /* [switch_is][out] */ PSAMPR_DOMAIN_INFO_BUFFER *Buffer); NTSTATUS SamrSetInformationDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_INFORMATION_CLASS DomainInformationClass, /* [switch_is][in] */ PSAMPR_DOMAIN_INFO_BUFFER DomainInformation); NTSTATUS SamrCreateGroupInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ PRPC_UNICODE_STRING Name, /* [in] */ ACCESS_MASK DesiredAccess, /* [out] */ SAMPR_HANDLE *GroupHandle, /* [out] */ PULONG RelativeId); NTSTATUS SamrEnumerateGroupsInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [out][in] */ PSAM_ENUMERATE_HANDLE EnumerationContext, /* [out] */ PSAMPR_ENUMERATION_BUFFER *Buffer, /* [in] */ ULONG PreferedMaximumLength, /* [out] */ PULONG CountReturned); NTSTATUS SamrCreateUserInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ PRPC_UNICODE_STRING Name, /* [in] */ ACCESS_MASK DesiredAccess, /* [out] */ SAMPR_HANDLE *UserHandle, /* [out] */ PULONG RelativeId); NTSTATUS SamrEnumerateUsersInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [out][in] */ PSAM_ENUMERATE_HANDLE EnumerationContext, /* [in] */ ULONG UserAccountControl, /* [out] */ PSAMPR_ENUMERATION_BUFFER *Buffer, /* [in] */ ULONG PreferedMaximumLength, /* [out] */ PULONG CountReturned); NTSTATUS SamrCreateAliasInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ PRPC_UNICODE_STRING AccountName, /* [in] */ ACCESS_MASK DesiredAccess, /* [out] */ SAMPR_HANDLE *AliasHandle, /* [out] */ PULONG RelativeId); NTSTATUS SamrEnumerateAliasesInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [out][in] */ PSAM_ENUMERATE_HANDLE EnumerationContext, /* [out] */ PSAMPR_ENUMERATION_BUFFER *Buffer, /* [in] */ ULONG PreferedMaximumLength, /* [out] */ PULONG CountReturned); NTSTATUS SamrGetAliasMembership( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ PSAMPR_PSID_ARRAY SidArray, /* [out] */ PSAMPR_ULONG_ARRAY Membership); NTSTATUS SamrLookupNamesInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [range][in] */ ULONG Count, /* [length_is][size_is][in] */ RPC_UNICODE_STRING Names[ ], /* [out] */ PSAMPR_ULONG_ARRAY RelativeIds, /* [out] */ PSAMPR_ULONG_ARRAY Use); NTSTATUS SamrLookupIdsInDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [range][in] */ ULONG Count, /* [length_is][size_is][in] */ PULONG RelativeIds, /* [out] */ PSAMPR_RETURNED_USTRING_ARRAY Names, /* [out] */ PSAMPR_ULONG_ARRAY Use); NTSTATUS SamrOpenGroup( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ ACCESS_MASK DesiredAccess, /* [in] */ ULONG GroupId, /* [out] */ SAMPR_HANDLE *GroupHandle); NTSTATUS SamrQueryInformationGroup( /* [in] */ SAMPR_HANDLE GroupHandle, /* [in] */ GROUP_INFORMATION_CLASS GroupInformationClass, /* [switch_is][out] */ PSAMPR_GROUP_INFO_BUFFER *Buffer); NTSTATUS SamrSetInformationGroup( /* [in] */ SAMPR_HANDLE GroupHandle, /* [in] */ GROUP_INFORMATION_CLASS GroupInformationClass, /* [switch_is][in] */ PSAMPR_GROUP_INFO_BUFFER Buffer); NTSTATUS SamrAddMemberToGroup( /* [in] */ SAMPR_HANDLE GroupHandle, /* [in] */ ULONG MemberId, /* [in] */ ULONG Attributes); NTSTATUS SamrDeleteGroup( /* [out][in] */ SAMPR_HANDLE *GroupHandle); NTSTATUS SamrRemoveMemberFromGroup( /* [in] */ SAMPR_HANDLE GroupHandle, /* [in] */ ULONG MemberId); NTSTATUS SamrGetMembersInGroup( /* [in] */ SAMPR_HANDLE GroupHandle, /* [out] */ PSAMPR_GET_MEMBERS_BUFFER *Members); NTSTATUS SamrSetMemberAttributesOfGroup( /* [in] */ SAMPR_HANDLE GroupHandle, /* [in] */ ULONG MemberId, /* [in] */ ULONG Attributes); NTSTATUS SamrOpenAlias( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ ACCESS_MASK DesiredAccess, /* [in] */ ULONG AliasId, /* [out] */ SAMPR_HANDLE *AliasHandle); NTSTATUS SamrQueryInformationAlias( /* [in] */ SAMPR_HANDLE AliasHandle, /* [in] */ ALIAS_INFORMATION_CLASS AliasInformationClass, /* [switch_is][out] */ PSAMPR_ALIAS_INFO_BUFFER *Buffer); NTSTATUS SamrSetInformationAlias( /* [in] */ SAMPR_HANDLE AliasHandle, /* [in] */ ALIAS_INFORMATION_CLASS AliasInformationClass, /* [switch_is][in] */ PSAMPR_ALIAS_INFO_BUFFER Buffer); NTSTATUS SamrDeleteAlias( /* [out][in] */ SAMPR_HANDLE *AliasHandle); NTSTATUS SamrAddMemberToAlias( /* [in] */ SAMPR_HANDLE AliasHandle, /* [in] */ PRPC_SID MemberId); NTSTATUS SamrRemoveMemberFromAlias( /* [in] */ SAMPR_HANDLE AliasHandle, /* [in] */ PRPC_SID MemberId); NTSTATUS SamrGetMembersInAlias( /* [in] */ SAMPR_HANDLE AliasHandle, /* [out] */ PSAMPR_PSID_ARRAY_OUT Members); NTSTATUS SamrOpenUser( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ ACCESS_MASK DesiredAccess, /* [in] */ ULONG UserId, /* [out] */ SAMPR_HANDLE *UserHandle); NTSTATUS SamrDeleteUser( /* [out][in] */ SAMPR_HANDLE *UserHandle); NTSTATUS SamrQueryInformationUser( /* [in] */ SAMPR_HANDLE UserHandle, /* [in] */ USER_INFORMATION_CLASS UserInformationClass, /* [switch_is][out] */ PSAMPR_USER_INFO_BUFFER *Buffer); NTSTATUS SamrSetInformationUser( /* [in] */ SAMPR_HANDLE UserHandle, /* [in] */ USER_INFORMATION_CLASS UserInformationClass, /* [switch_is][in] */ PSAMPR_USER_INFO_BUFFER Buffer); NTSTATUS SamrChangePasswordUser( /* [in] */ SAMPR_HANDLE UserHandle, /* [in] */ BOOLEAN LmPresent, /* [unique][in] */ PENCRYPTED_LM_OWF_PASSWORD LmOldEncryptedWithLmNew, /* [unique][in] */ PENCRYPTED_LM_OWF_PASSWORD LmNewEncryptedWithLmOld, /* [in] */ BOOLEAN NtPresent, /* [unique][in] */ PENCRYPTED_NT_OWF_PASSWORD NtOldEncryptedWithNtNew, /* [unique][in] */ PENCRYPTED_NT_OWF_PASSWORD NtNewEncryptedWithNtOld, /* [in] */ BOOLEAN NtCrossEncryptionPresent, /* [unique][in] */ PENCRYPTED_NT_OWF_PASSWORD NtNewEncryptedWithLmNew, /* [in] */ BOOLEAN LmCrossEncryptionPresent, /* [unique][in] */ PENCRYPTED_LM_OWF_PASSWORD LmNtNewEncryptedWithNtNew); NTSTATUS SamrGetGroupsForUser( /* [in] */ SAMPR_HANDLE UserHandle, /* [out] */ PSAMPR_GET_GROUPS_BUFFER *Groups); NTSTATUS SamrQueryDisplayInformation( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_DISPLAY_INFORMATION DisplayInformationClass, /* [in] */ ULONG Index, /* [in] */ ULONG EntryCount, /* [in] */ ULONG PreferredMaximumLength, /* [out] */ PULONG TotalAvailable, /* [out] */ PULONG TotalReturned, /* [switch_is][out] */ PSAMPR_DISPLAY_INFO_BUFFER Buffer); NTSTATUS SamrGetDisplayEnumerationIndex( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_DISPLAY_INFORMATION DisplayInformationClass, /* [in] */ PRPC_UNICODE_STRING Prefix, /* [out] */ PULONG Index); NTSTATUS SamrTestPrivateFunctionsDomain( /* [in] */ SAMPR_HANDLE DomainHandle); NTSTATUS SamrTestPrivateFunctionsUser( /* [in] */ SAMPR_HANDLE UserHandle); NTSTATUS SamrGetUserDomainPasswordInformation( /* [in] */ SAMPR_HANDLE UserHandle, /* [out] */ PUSER_DOMAIN_PASSWORD_INFORMATION PasswordInformation); NTSTATUS SamrRemoveMemberFromForeignDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ PRPC_SID MemberSid); NTSTATUS SamrQueryInformationDomain2( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_INFORMATION_CLASS DomainInformationClass, /* [switch_is][out] */ PSAMPR_DOMAIN_INFO_BUFFER *Buffer); NTSTATUS SamrQueryInformationUser2( /* [in] */ SAMPR_HANDLE UserHandle, /* [in] */ USER_INFORMATION_CLASS UserInformationClass, /* [switch_is][out] */ PSAMPR_USER_INFO_BUFFER *Buffer); NTSTATUS SamrQueryDisplayInformation2( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_DISPLAY_INFORMATION DisplayInformationClass, /* [in] */ ULONG Index, /* [in] */ ULONG EntryCount, /* [in] */ ULONG PreferredMaximumLength, /* [out] */ PULONG TotalAvailable, /* [out] */ PULONG TotalReturned, /* [switch_is][out] */ PSAMPR_DISPLAY_INFO_BUFFER Buffer); NTSTATUS SamrGetDisplayEnumerationIndex2( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_DISPLAY_INFORMATION DisplayInformationClass, /* [in] */ PRPC_UNICODE_STRING Prefix, /* [out] */ PULONG Index); NTSTATUS SamrCreateUser2InDomain( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ PRPC_UNICODE_STRING Name, /* [in] */ ULONG AccountType, /* [in] */ ACCESS_MASK DesiredAccess, /* [out] */ SAMPR_HANDLE *UserHandle, /* [out] */ PULONG GrantedAccess, /* [out] */ PULONG RelativeId); NTSTATUS SamrQueryDisplayInformation3( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ DOMAIN_DISPLAY_INFORMATION DisplayInformationClass, /* [in] */ ULONG Index, /* [in] */ ULONG EntryCount, /* [in] */ ULONG PreferredMaximumLength, /* [out] */ PULONG TotalAvailable, /* [out] */ PULONG TotalReturned, /* [switch_is][out] */ PSAMPR_DISPLAY_INFO_BUFFER Buffer); NTSTATUS SamrAddMultipleMembersToAlias( /* [in] */ SAMPR_HANDLE AliasHandle, /* [in] */ PSAMPR_PSID_ARRAY MembersBuffer); NTSTATUS SamrRemoveMultipleMembersFromAlias( /* [in] */ SAMPR_HANDLE AliasHandle, /* [in] */ PSAMPR_PSID_ARRAY MembersBuffer); NTSTATUS SamrOemChangePasswordUser2( /* [in] */ handle_t BindingHandle, /* [unique][in] */ PRPC_STRING ServerName, /* [in] */ PRPC_STRING UserName, /* [unique][in] */ PSAMPR_ENCRYPTED_USER_PASSWORD NewPasswordEncryptedWithOldLm, /* [unique][in] */ PENCRYPTED_LM_OWF_PASSWORD OldLmOwfPassswordEncryptedWithNewLm); NTSTATUS SamrUnicodeChangePasswordUser2( /* [in] */ handle_t BindingHandle, /* [unique][in] */ PRPC_UNICODE_STRING ServerName, /* [in] */ PRPC_UNICODE_STRING UserName, /* [unique][in] */ PSAMPR_ENCRYPTED_USER_PASSWORD NewPasswordEncryptedWithOldNt, /* [unique][in] */ PENCRYPTED_NT_OWF_PASSWORD OldNtOwfPasswordEncryptedWithNewNt, /* [in] */ BOOLEAN LmPresent, /* [unique][in] */ PSAMPR_ENCRYPTED_USER_PASSWORD NewPasswordEncryptedWithOldLm, /* [unique][in] */ PENCRYPTED_LM_OWF_PASSWORD OldLmOwfPassswordEncryptedWithNewLmOrNt); NTSTATUS SamrGetDomainPasswordInformation( /* [in] */ handle_t BindingHandle, /* [unique][in] */ PRPC_UNICODE_STRING ServerName, /* [out] */ PUSER_DOMAIN_PASSWORD_INFORMATION PasswordInformation); NTSTATUS SamrConnect2( /* [string][unique][in] */ PSAMPR_SERVER_NAME ServerName, /* [out] */ SAMPR_HANDLE *ServerHandle, /* [in] */ ACCESS_MASK DesiredAccess); NTSTATUS SamrSetInformationUser2( /* [in] */ SAMPR_HANDLE UserHandle, /* [in] */ USER_INFORMATION_CLASS UserInformationClass, /* [switch_is][in] */ PSAMPR_USER_INFO_BUFFER Buffer); NTSTATUS SamrSetBootKeyInformation( /* [in] */ SAMPR_HANDLE DomainHandle, /* [in] */ SAMPR_BOOT_TYPE BootOptions, /* [unique][in] */ PRPC_UNICODE_STRING OldBootKey, /* [unique][in] */ PRPC_UNICODE_STRING NewBootKey); NTSTATUS SamrGetBootKeyInformation( /* [in] */ SAMPR_HANDLE DomainHandle, /* [out] */ PSAMPR_BOOT_TYPE BootOptions); NTSTATUS SamrConnect3( /* [string][unique][in] */ PSAMPR_SERVER_NAME ServerName, /* [out] */ SAMPR_HANDLE *ServerHandle, /* [in] */ ULONG ClientRevision, /* [in] */ ACCESS_MASK DesiredAccess); NTSTATUS SamrConnect4( /* [string][unique][in] */ PSAMPR_SERVER_NAME ServerName, /* [out] */ SAMPR_HANDLE *ServerHandle, /* [in] */ ULONG ClientRevision, /* [in] */ ACCESS_MASK DesiredAccess); NTSTATUS SamrUnicodeChangePasswordUser3( /* [in] */ handle_t BindingHandle, /* [unique][in] */ PRPC_UNICODE_STRING ServerName, /* [in] */ PRPC_UNICODE_STRING UserName, /* [unique][in] */ PSAMPR_ENCRYPTED_USER_PASSWORD NewPasswordEncryptedWithOldNt, /* [unique][in] */ PENCRYPTED_NT_OWF_PASSWORD OldNtOwfPasswordEncryptedWithNewNt, /* [in] */ BOOLEAN LmPresent, /* [unique][in] */ PSAMPR_ENCRYPTED_USER_PASSWORD NewPasswordEncryptedWithOldLm, /* [unique][in] */ PENCRYPTED_LM_OWF_PASSWORD OldLmOwfPassswordEncryptedWithNewLmOrNt, /* [unique][in] */ PSAMPR_ENCRYPTED_USER_PASSWORD AdditionalData, /* [out] */ PDOMAIN_PASSWORD_INFORMATION *EffectivePasswordPolicy, /* [out] */ PUSER_PWD_CHANGE_FAILURE_INFORMATION *PasswordChangeInfo); NTSTATUS SamrConnect5( /* [string][unique][in] */ PSAMPR_SERVER_NAME ServerName, /* [in] */ ACCESS_MASK DesiredAccess, /* [in] */ ULONG InVersion, /* [switch_is][in] */ SAMPR_REVISION_INFO *InRevisionInfo, /* [out] */ ULONG *OutVersion, /* [switch_is][out] */ SAMPR_REVISION_INFO *OutRevisionInfo, /* [out] */ SAMPR_HANDLE *ServerHandle); NTSTATUS SamrRidToSid( /* [in] */ SAMPR_HANDLE ObjectHandle, /* [in] */ ULONG Rid, /* [out] */ PRPC_SID *Sid); NTSTATUS SamrSetDSRMPassword( /* [in] */ handle_t BindingHandle, /* [unique][in] */ PRPC_UNICODE_STRING ServerName, /* [in] */ ULONG UserId, /* [unique][in] */ PENCRYPTED_NT_OWF_PASSWORD EncryptedNtOwfPassword); NTSTATUS SamrValidatePassword( /* [in] */ handle_t Handle, /* [in] */ PASSWORD_POLICY_VALIDATION_TYPE ValidationType, /* [switch_is][in] */ PSAM_VALIDATE_INPUT_ARG InputArg, /* [switch_is][out] */ PSAM_VALIDATE_OUTPUT_ARG *OutputArg); extern handle_t samsrv_handle; extern RPC_IF_HANDLE samr_ClientIfHandle; extern RPC_IF_HANDLE samr_ServerIfHandle; #endif /* __samr_INTERFACE_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ handle_t __RPC_USER PSAMPR_SERVER_NAME_bind ( PSAMPR_SERVER_NAME ); void __RPC_USER PSAMPR_SERVER_NAME_unbind( PSAMPR_SERVER_NAME, handle_t ); void __RPC_USER SAMPR_HANDLE_rundown( SAMPR_HANDLE ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
matija94/show-me-the-code
learning_django/snippets/views.py
from django.contrib.auth.models import User # Create your views here. from rest_framework import permissions, renderers from rest_framework.reverse import reverse from rest_framework.decorators import api_view from rest_framework.generics import RetrieveUpdateDestroyAPIView, ListCreateAPIView, ListAPIView, RetrieveAPIView, \ GenericAPIView from rest_framework.response import Response from snippets.models import Snippet from snippets.permissions import IsOwnerOrReadOnly from snippets.serializers import SnippetSerializer, UserSerializer class SnippetMixin(object): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) class UserMixin(object): queryset = User.objects.all() serializer_class = UserSerializer @api_view(["GET"]) def api_root(request, format=None): return Response({ 'users': reverse('snippets-api:user-list', request=request, format=format), 'snippets': reverse('snippets-api:snippet-list', request=request, format=format) }) class SnippetHighlight(GenericAPIView): queryset = Snippet.objects.all() renderer_classes = (renderers.StaticHTMLRenderer,) def get(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) class SnippetDetail(SnippetMixin, RetrieveUpdateDestroyAPIView): pass class SnippetList(SnippetMixin, ListCreateAPIView): def perform_create(self, serializer): serializer.save(owner=self.request.user) class UserList(UserMixin, ListAPIView): pass class UserDetail(UserMixin, RetrieveAPIView): pass
Yannic/chromium
content/browser/devtools/protocol/io_handler.h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_DEVTOOLS_PROTOCOL_IO_HANDLER_H_ #define CONTENT_BROWSER_DEVTOOLS_PROTOCOL_IO_HANDLER_H_ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "content/browser/devtools/protocol/devtools_domain_handler.h" #include "content/browser/devtools/protocol/io.h" namespace content { class BrowserContext; class DevToolsIOContext; class StoragePartition; namespace protocol { class IOHandler : public DevToolsDomainHandler, public IO::Backend { public: explicit IOHandler(DevToolsIOContext* io_context); IOHandler(const IOHandler&) = delete; IOHandler& operator=(const IOHandler&) = delete; ~IOHandler() override; void Wire(UberDispatcher* dispatcher) override; void SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) override; // Protocol methods. void Read( const std::string& handle, Maybe<int> offset, Maybe<int> max_size, std::unique_ptr<ReadCallback> callback) override; Response Close(const std::string& handle) override; private: void ReadComplete(std::unique_ptr<ReadCallback> callback, std::unique_ptr<std::string> data, bool base64_encoded, int status); std::unique_ptr<IO::Frontend> frontend_; DevToolsIOContext* io_context_; BrowserContext* browser_context_; StoragePartition* storage_partition_; base::WeakPtrFactory<IOHandler> weak_factory_{this}; }; } // namespace protocol } // namespace content #endif // CONTENT_BROWSER_DEVTOOLS_PROTOCOL_IO_HANDLER_H_
rsearls/jaxb-ri
jaxb-ri/xjc/src/main/java/com/sun/tools/xjc/generator/bean/field/Messages.java
/* * Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.tools.xjc.generator.bean.field; import java.text.MessageFormat; import java.util.ResourceBundle; /** * Message resources */ public enum Messages { DEFAULT_GETTER_JAVADOC, // 1 arg DEFAULT_SETTER_JAVADOC, // 1 arg ; private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName().substring(0, Messages.class.getName().lastIndexOf('.'))+ ".MessageBundle"); public String toString() { return format(); } public String format( Object... args ) { return MessageFormat.format( rb.getString(name()), args ); } }
cryptowilliam/goutil
interpreter/engine_go_yaegi.go
<reponame>cryptowilliam/goutil<gh_stars>1-10 package interpreter import ( "github.com/cryptowilliam/goutil/container/gany" "github.com/traefik/yaegi/interp" "github.com/traefik/yaegi/stdlib" "reflect" ) type ( vmYaegj struct { vmYaegi *interp.Interpreter customLib map[string]map[string]reflect.Value } ) func valYaegi2Comm(yaegiVal reflect.Value) gany.Val { return gany.NewVal(yaegiVal) } func newVMYaegi() (*vmYaegj, error) { res := &vmYaegj{vmYaegi: interp.New(interp.Options{})} res.customLib = make(map[string]map[string]reflect.Value) res.customLib["custom/custom"] = make(map[string]reflect.Value) if err := res.vmYaegi.Use(stdlib.Symbols); err != nil { return nil, err } return res, nil } func (vm *vmYaegj) RunScript(script string) (gany.Val, error) { val, err := vm.vmYaegi.Eval(script) if err != nil { return gany.ValNil, err } return valYaegi2Comm(val), nil } // TODO 确定重复调用这个接口,比如映射两个不同的name、value对, 是可以正常执行的 // 引入的指针和相关的自定义类型(非基础类型)都可以存取,但是默认不可以声明 // 如果需要在脚本中主动声明Go Runtime中的自定义类型,目前知道的方法是在脚本中import该类型所在的包, // MapGoValueToScript allows script to access go runtime `value` with `name`. // Usually `value` is a pointer in the go runtime. func (vm *vmYaegj) MapGoValueToScript(name string, value interface{}) error { vm.customLib["custom/custom"][name] = reflect.ValueOf(value) if err := vm.vmYaegi.Use(vm.customLib); err != nil { return err } vm.customLib["custom/custom"]["ctx"] = reflect.ValueOf(value) if err := vm.vmYaegi.Use(vm.customLib); err != nil { return err } if _, err := vm.vmYaegi.Eval(`import . "custom"`); err != nil { return err } return nil } // MapScriptFuncToGo allows go runtime to access script function. func (vm *vmYaegj) MapScriptFuncToGo(funcName string) (Callable, error) { fn, err := vm.vmYaegi.Eval(funcName) if err != nil { return nil, err } return func(args ...any) ([]gany.Val, error) { var argsSlice []reflect.Value for _, item := range args { argsSlice = append(argsSlice, reflect.ValueOf(item)) } resVals := fn.Call(argsSlice) var res []gany.Val for _, item := range resVals { res = append(res, gany.NewVal(item)) } return res, nil }, nil }
Want100Cookies/GradeMaster
src/main/resources/public/app/services/notification.service.js
<filename>src/main/resources/public/app/services/notification.service.js app.factory('NotificationService', function (API) { this.getNotifications = () => { return API.get({ path: `notifications` }); }; this.readNotification = (notificationId) => { return API.patch({ path: notificationId ? `notifications/${notificationId}` : `notifications` }); }; return this; });
yaoyue123/WHU_SummerTraining
p1/snake_master/src/main.c
<reponame>yaoyue123/WHU_SummerTraining #include "ai.h" #include "file.h" #include "game.h" #include "view.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> int main(int argc, char *argv[]) { srand(time(0)); if (argc != 2) { printf("Usage: ./main file_name\n"); exit(-1); } game_t *game = create_game(argv[1]); while (1) { display(game); direction_t d = get_action(game); set_direction(game->snake, d); if (next_frame(game) != 0) { break; } usleep(game->time_step * 1000000); } destroy_game(game); return 0; }
ApacheSourceCode/kylin
engine-spark/src/test/java/org/apache/kylin/engine/spark/util/KyroMappingGenerator.java
<reponame>ApacheSourceCode/kylin /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.engine.spark.util; import org.apache.kylin.common.util.BytesSerializer; import org.apache.kylin.measure.MeasureIngester; import org.reflections.Reflections; import java.io.Serializable; import java.util.Set; import java.util.TreeSet; /** * Generate Kyro Registrator class, the output will be added into KylinKyroRegistrator manually. No runtime dependency with Reflections. */ public class KyroMappingGenerator { public static void main(String[] args) { Set<Class<? extends Serializable>> subTypesOfSerializable = new Reflections("org.apache.kylin").getSubTypesOf(Serializable.class); String begin = "kyroClasses.add("; String end = ".class);"; TreeSet<String> sortedSet = new TreeSet(); for (Class clazz : subTypesOfSerializable) { if (clazz.getCanonicalName() != null) sortedSet.add(clazz.getCanonicalName()); } Set<Class<? extends BytesSerializer>> subTypesOfBytes = new Reflections("org.apache.kylin.metadata.datatype").getSubTypesOf(BytesSerializer.class); for (Class clazz : subTypesOfBytes) { if (clazz.getCanonicalName() != null) sortedSet.add(clazz.getCanonicalName()); } Set<Class<? extends MeasureIngester>> subTypesOfMeasure = new Reflections("org.apache.kylin.measure").getSubTypesOf(MeasureIngester.class); for (Class clazz : subTypesOfMeasure) { if (clazz.getCanonicalName() != null) sortedSet.add(clazz.getCanonicalName()); } for (String className : sortedSet) { System.out.println(begin + className + end); } } }
pudongping/gin-biz-web-api
internal/controller/example_ctrl/upload_controller.go
package example_ctrl import ( "github.com/gin-gonic/gin" "gin-biz-web-api/pkg/errcode" "gin-biz-web-api/pkg/responses" "gin-biz-web-api/pkg/upload" ) type UploadController struct { } // UploadFile 上传文件 // curl --location --request POST 'localhost:3000/api/example/upload-file' \ // --form 'file=@"/Users/pudongping/Downloads/12.jpg"' \ // --form 'type="image"' func (ctrl *UploadController) UploadFile(c *gin.Context) { response := responses.New(c) file, fileHeader, err := c.Request.FormFile("file") // 读取入参 file 字段的上传文件信息 if err != nil { response.ToErrorResponse(errcode.UnprocessableEntity.WithDetails(err.Error()).Msgf("文件")) return } fileType := c.PostForm("type") // 获取文件上传的类型 if fileHeader == nil || fileType == "" { response.ToErrorResponse(errcode.UnprocessableEntity, "文件读取失败或上传类型不能为空") return } // 上传并保存文件 fileInfo, err := upload.SaveUploadFile(upload.FileType(fileType), file, fileHeader) if err != nil { response.ToErrorResponse(errcode.UnprocessableEntity.WithDetails(err.Error()), "文件上传失败") return } response.ToResponse(fileInfo) } // UploadAvatar 上传用户头像 // curl --location --request POST 'localhost:3000/api/example/upload-avatar' \ // --form 'avatar=@"/Users/pudongping/Downloads/11.jpg"' func (ctrl *UploadController) UploadAvatar(c *gin.Context) { response := responses.New(c) file, fileHeader, err := c.Request.FormFile("avatar") // 读取入参 avatar 字段的上传文件信息 if err != nil { response.ToErrorResponse(errcode.UnprocessableEntity.WithDetails(err.Error()).Msgf("头像文件")) return } fileInfo, err := upload.SaveUploadAvatar(file, fileHeader) if err != nil { response.ToErrorResponse(errcode.UnprocessableEntity.WithDetails(err.Error()), "文件上传失败") return } response.ToResponse(fileInfo) }
woonsan/incubator-s2graph
s2core/src/test/scala/org/apache/s2graph/core/benchmark/OrderingUtilBenchmarkSpec.scala
<filename>s2core/src/test/scala/org/apache/s2graph/core/benchmark/OrderingUtilBenchmarkSpec.scala /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.s2graph.core.benchmark import org.apache.s2graph.core.OrderingUtil._ import org.apache.s2graph.core.{OrderingUtil, SeqMultiOrdering} import play.api.libs.json.{JsNumber, JsValue} import scala.util.Random class OrderingUtilBenchmarkSpec extends BenchmarkCommon { "OrderingUtilBenchmarkSpec" should { "performance MultiOrdering any" >> { val tupLs = (0 until 10) map { i => Random.nextDouble() -> Random.nextLong() } val seqLs = tupLs.map { tup => Seq(tup._1, tup._2) } val sorted1 = duration("TupleOrdering double,long") { (0 until 1000) foreach { _ => tupLs.sortBy { case (x, y) => -x -> -y } } tupLs.sortBy { case (x, y) => -x -> -y } }.map { x => x._1 } val sorted2 = duration("MultiOrdering double,long") { (0 until 1000) foreach { _ => seqLs.sorted(new SeqMultiOrdering[Any](Seq(false, false))) } seqLs.sorted(new SeqMultiOrdering[Any](Seq(false, false))) }.map { x => x.head } sorted1.toString() must_== sorted2.toString() } "performance MultiOrdering double" >> { val tupLs = (0 until 50) map { i => Random.nextDouble() -> Random.nextDouble() } val seqLs = tupLs.map { tup => Seq(tup._1, tup._2) } duration("MultiOrdering double") { (0 until 1000) foreach { _ => seqLs.sorted(new SeqMultiOrdering[Double](Seq(false, false))) } } duration("TupleOrdering double") { (0 until 1000) foreach { _ => tupLs.sortBy { case (x, y) => -x -> -y } } } 1 must_== 1 } "performance MultiOrdering jsvalue" >> { val tupLs = (0 until 50) map { i => Random.nextDouble() -> Random.nextLong() } val seqLs = tupLs.map { tup => Seq(JsNumber(tup._1), JsNumber(tup._2)) } val sorted1 = duration("TupleOrdering double,long") { (0 until 1000) foreach { _ => tupLs.sortBy { case (x, y) => -x -> -y } } tupLs.sortBy { case (x, y) => -x -> -y } } val sorted2 = duration("MultiOrdering jsvalue") { (0 until 1000) foreach { _ => seqLs.sorted(new SeqMultiOrdering[JsValue](Seq(false, false))) } seqLs.sorted(new SeqMultiOrdering[JsValue](Seq(false, false))) } 1 must_== 1 } } }
ckamtsikis/cmssw
RecoTracker/TkHitPairs/test/testCompatKernel.cc
#include "RecoTracker/TkTrackingRegions/interface/HitRZCompatibility.h" #include "RecoTracker/TkTrackingRegions/interface/HitEtaCheck.h" #include "RecoTracker/TkTrackingRegions/interface/HitRCheck.h" #include "RecoTracker/TkTrackingRegions/interface/HitZCheck.h" #include "RecoTracker/TkHitPairs/interface/RecHitsSortedInPhi.h" typedef PixelRecoRange<float> Range; // devirtualizer #include <tuple> namespace { template <typename Algo> struct Kernel { using Base = HitRZCompatibility; void set(Base const *a) { assert(a->algo() == Algo::me); checkRZ = reinterpret_cast<Algo const *>(a); } void operator()(int b, int e, const RecHitsSortedInPhi &innerHitsMap, bool *ok) const { constexpr float nSigmaRZ = 3.46410161514; // std::sqrt(12.f); for (int i = b; i != e; ++i) { Range allowed = checkRZ->range(innerHitsMap.u[i]); float vErr = nSigmaRZ * innerHitsMap.dv[i]; Range hitRZ(innerHitsMap.v[i] - vErr, innerHitsMap.v[i] + vErr); Range crossRange = allowed.intersection(hitRZ); ok[i - b] = !crossRange.empty(); } } Algo const *checkRZ; }; template <typename... Args> using Kernels = std::tuple<Kernel<Args>...>; } // namespace void testR(HitRZCompatibility const *algo, int b, int e, const RecHitsSortedInPhi &innerHitsMap, bool *ok) { Kernel<HitRCheck> k; k.set(algo); k(b, e, innerHitsMap, ok); } void testZ(HitRZCompatibility const *algo, int b, int e, const RecHitsSortedInPhi &innerHitsMap, bool *ok) { Kernel<HitZCheck> k; k.set(algo); k(b, e, innerHitsMap, ok); }
SuperRun/spokenman
ota-web/src/main/java/com/zust/itee/exam/service/exam/member/finish/ExamMemberFinishService.java
<filename>ota-web/src/main/java/com/zust/itee/exam/service/exam/member/finish/ExamMemberFinishService.java package com.zust.itee.exam.service.exam.member.finish; import com.zust.itee.exam.dto.exam.member.DriverInfoInExamManagement; import com.zust.itee.exam.dto.exam.member.ExamFinishInfo; import com.zust.itee.exam.entity.TexamSignup; public interface ExamMemberFinishService { /** * @author sdy * @why 获取已完成考试详情 */ ExamFinishInfo getFinishExamInfo(Integer examId); /** * @author sdy * @why 由实体类获取考试完成显示驾驶员信息 */ DriverInfoInExamManagement transTdriverToDriverInfoInFinishExam(TexamSignup texamSignup); }
nursix/DRKCM
languages/sr.py
<filename>languages/sr.py { 'City': 'Град', 'District': 'Округ', 'Municipality / City': 'Општина / Град', 'Municipality': 'Општина', 'Serbian': 'Српски', }
AjayNandoriya/gitlabhq
spec/frontend/issues_list/components/issue_card_time_info_spec.js
<reponame>AjayNandoriya/gitlabhq<gh_stars>1-10 import { GlIcon, GlLink } from '@gitlab/ui'; import { shallowMount } from '@vue/test-utils'; import { useFakeDate } from 'helpers/fake_date'; import IssueCardTimeInfo from '~/issues_list/components/issue_card_time_info.vue'; describe('IssuesListApp component', () => { useFakeDate(2020, 11, 11); let wrapper; const issue = { milestone: { dueDate: '2020-12-17', startDate: '2020-12-10', title: 'My milestone', webPath: '/milestone/webPath', }, dueDate: '2020-12-12', humanTimeEstimate: '1w', }; const findMilestone = () => wrapper.find('[data-testid="issuable-milestone"]'); const findMilestoneTitle = () => findMilestone().find(GlLink).attributes('title'); const findDueDate = () => wrapper.find('[data-testid="issuable-due-date"]'); const mountComponent = ({ dueDate = issue.dueDate, milestoneDueDate = issue.milestone.dueDate, milestoneStartDate = issue.milestone.startDate, } = {}) => shallowMount(IssueCardTimeInfo, { propsData: { issue: { ...issue, milestone: { ...issue.milestone, dueDate: milestoneDueDate, startDate: milestoneStartDate, }, dueDate, }, }, }); afterEach(() => { wrapper.destroy(); }); describe('milestone', () => { it('renders', () => { wrapper = mountComponent(); const milestone = findMilestone(); expect(milestone.text()).toBe(issue.milestone.title); expect(milestone.find(GlIcon).props('name')).toBe('clock'); expect(milestone.find(GlLink).attributes('href')).toBe(issue.milestone.webPath); }); describe.each` time | text | milestoneDueDate | milestoneStartDate | expected ${'due date is in past'} | ${'Past due'} | ${'2020-09-09'} | ${null} | ${'Sep 9, 2020 (Past due)'} ${'due date is today'} | ${'Today'} | ${'2020-12-11'} | ${null} | ${'Dec 11, 2020 (Today)'} ${'start date is in future'} | ${'Upcoming'} | ${'2021-03-01'} | ${'2021-02-01'} | ${'Mar 1, 2021 (Upcoming)'} ${'due date is in future'} | ${'2 weeks remaining'} | ${'2020-12-25'} | ${null} | ${'Dec 25, 2020 (2 weeks remaining)'} `('when $description', ({ text, milestoneDueDate, milestoneStartDate, expected }) => { it(`renders with "${text}"`, () => { wrapper = mountComponent({ milestoneDueDate, milestoneStartDate }); expect(findMilestoneTitle()).toBe(expected); }); }); }); describe('due date', () => { describe('when upcoming', () => { it('renders', () => { wrapper = mountComponent(); const dueDate = findDueDate(); expect(dueDate.text()).toBe('Dec 12, 2020'); expect(dueDate.attributes('title')).toBe('Due date'); expect(dueDate.find(GlIcon).props('name')).toBe('calendar'); expect(dueDate.classes()).not.toContain('gl-text-red-500'); }); }); describe('when in the past', () => { it('renders in red', () => { wrapper = mountComponent({ dueDate: new Date('2020-10-10') }); expect(findDueDate().classes()).toContain('gl-text-red-500'); }); }); }); it('renders time estimate', () => { wrapper = mountComponent(); const timeEstimate = wrapper.find('[data-testid="time-estimate"]'); expect(timeEstimate.text()).toBe(issue.humanTimeEstimate); expect(timeEstimate.attributes('title')).toBe('Estimate'); expect(timeEstimate.find(GlIcon).props('name')).toBe('timer'); }); });
phlegmaticprogrammer/Babel-17
Babel17_Netbeans_Module/src/com/babel17/netbeans/Babel17ParserFactory.java
package com.babel17.netbeans; import org.netbeans.modules.parsing.spi.*; import org.netbeans.modules.parsing.api.*; import java.util.Collection; public class Babel17ParserFactory extends ParserFactory { @Override public Parser createParser (Collection<Snapshot> snapshots) { return new Babel17Parser (); } }
Lightbass/job4j
chapter_001/src/test/java/ru/job4j/condition/PointTest.java
package ru.job4j.condition; import org.junit.Test; import static org.hamcrest.number.IsCloseTo.closeTo; import static org.junit.Assert.assertThat; /** * JUnit класс для теста класса Point. * @author <NAME> * @since 30.07.18 * @version 0.1 */ public class PointTest { /** * Тест метода distanceTo(). */ @Test public void whenFindDistanceOnPoints() { Point p1 = new Point(2, 2); Point p2 = new Point(6, 6); double result = p1.distanceTo(p2); assertThat(result, closeTo(5.65, 0.1)); } @Test public void whenFindDistanceOnZeroAndTen() { Point p1 = new Point(0, 0, 0); Point p2 = new Point(0, 0, 10); double result = p1.distanceTo3d(p2); assertThat(result, closeTo(10, 0)); } @Test public void whenFindDistanceOnDifferentPointsIn3D() { Point p1 = new Point(1, 1, 1); Point p2 = new Point(3, 4, 5); double result = p1.distanceTo3d(p2); assertThat(result, closeTo(5.38, 0.01)); } }
timedata-org/old-timedata_visualizer
JuceLibraryCode/modules/juce_gui_basics/filebrowser/juce_ImagePreviewComponent.h
<gh_stars>10-100 /* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ #ifndef JUCE_IMAGEPREVIEWCOMPONENT_H_INCLUDED #define JUCE_IMAGEPREVIEWCOMPONENT_H_INCLUDED //============================================================================== /** A simple preview component that shows thumbnails of image files. @see FileChooserDialogBox, FilePreviewComponent */ class JUCE_API ImagePreviewComponent : public FilePreviewComponent, private Timer { public: //============================================================================== /** Creates an ImagePreviewComponent. */ ImagePreviewComponent(); /** Destructor. */ ~ImagePreviewComponent(); //============================================================================== /** @internal */ void selectedFileChanged (const File& newSelectedFile) override; /** @internal */ void paint (Graphics&) override; /** @internal */ void timerCallback() override; private: File fileToLoad; Image currentThumbnail; String currentDetails; void getThumbSize (int& w, int& h) const; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent) }; #endif // JUCE_IMAGEPREVIEWCOMPONENT_H_INCLUDED
wynnw/django-mako-plus
django_mako_plus/templatetags/__init__.py
<filename>django_mako_plus/templatetags/__init__.py # This package contains DJANGO tags in the normal Django style # Don't put regular DMP or Mako things in it.
14ms/Minecraft-Disclosed-Source-Modifications
Astomero/net/minecraft/world/biome/BiomeDecorator.java
<filename>Astomero/net/minecraft/world/biome/BiomeDecorator.java package net.minecraft.world.biome; import net.minecraft.world.*; import java.util.*; import net.minecraft.util.*; import net.minecraft.init.*; import net.minecraft.world.gen.*; import net.minecraft.block.*; import net.minecraft.block.properties.*; import net.minecraft.block.material.*; import net.minecraft.world.gen.feature.*; public class BiomeDecorator { protected World currentWorld; protected Random randomGenerator; protected BlockPos field_180294_c; protected ChunkProviderSettings chunkProviderSettings; protected WorldGenerator clayGen; protected WorldGenerator sandGen; protected WorldGenerator gravelAsSandGen; protected WorldGenerator dirtGen; protected WorldGenerator gravelGen; protected WorldGenerator graniteGen; protected WorldGenerator dioriteGen; protected WorldGenerator andesiteGen; protected WorldGenerator coalGen; protected WorldGenerator ironGen; protected WorldGenerator goldGen; protected WorldGenerator redstoneGen; protected WorldGenerator diamondGen; protected WorldGenerator lapisGen; protected WorldGenFlowers yellowFlowerGen; protected WorldGenerator mushroomBrownGen; protected WorldGenerator mushroomRedGen; protected WorldGenerator bigMushroomGen; protected WorldGenerator reedGen; protected WorldGenerator cactusGen; protected WorldGenerator waterlilyGen; protected int waterlilyPerChunk; protected int treesPerChunk; protected int flowersPerChunk; protected int grassPerChunk; protected int deadBushPerChunk; protected int mushroomsPerChunk; protected int reedsPerChunk; protected int cactiPerChunk; protected int sandPerChunk; protected int sandPerChunk2; protected int clayPerChunk; protected int bigMushroomsPerChunk; public boolean generateLakes; public BiomeDecorator() { this.clayGen = new WorldGenClay(4); this.sandGen = new WorldGenSand(Blocks.sand, 7); this.gravelAsSandGen = new WorldGenSand(Blocks.gravel, 6); this.yellowFlowerGen = new WorldGenFlowers(Blocks.yellow_flower, BlockFlower.EnumFlowerType.DANDELION); this.mushroomBrownGen = new GeneratorBushFeature(Blocks.brown_mushroom); this.mushroomRedGen = new GeneratorBushFeature(Blocks.red_mushroom); this.bigMushroomGen = new WorldGenBigMushroom(); this.reedGen = new WorldGenReed(); this.cactusGen = new WorldGenCactus(); this.waterlilyGen = new WorldGenWaterlily(); this.flowersPerChunk = 2; this.grassPerChunk = 1; this.sandPerChunk = 1; this.sandPerChunk2 = 3; this.clayPerChunk = 1; this.generateLakes = true; } public void decorate(final World worldIn, final Random random, final BiomeGenBase p_180292_3_, final BlockPos p_180292_4_) { if (this.currentWorld != null) { throw new RuntimeException("Already decorating"); } this.currentWorld = worldIn; final String s = worldIn.getWorldInfo().getGeneratorOptions(); if (s != null) { this.chunkProviderSettings = ChunkProviderSettings.Factory.jsonToFactory(s).func_177864_b(); } else { this.chunkProviderSettings = ChunkProviderSettings.Factory.jsonToFactory("").func_177864_b(); } this.randomGenerator = random; this.field_180294_c = p_180292_4_; this.dirtGen = new WorldGenMinable(Blocks.dirt.getDefaultState(), this.chunkProviderSettings.dirtSize); this.gravelGen = new WorldGenMinable(Blocks.gravel.getDefaultState(), this.chunkProviderSettings.gravelSize); this.graniteGen = new WorldGenMinable(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.GRANITE), this.chunkProviderSettings.graniteSize); this.dioriteGen = new WorldGenMinable(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.DIORITE), this.chunkProviderSettings.dioriteSize); this.andesiteGen = new WorldGenMinable(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.ANDESITE), this.chunkProviderSettings.andesiteSize); this.coalGen = new WorldGenMinable(Blocks.coal_ore.getDefaultState(), this.chunkProviderSettings.coalSize); this.ironGen = new WorldGenMinable(Blocks.iron_ore.getDefaultState(), this.chunkProviderSettings.ironSize); this.goldGen = new WorldGenMinable(Blocks.gold_ore.getDefaultState(), this.chunkProviderSettings.goldSize); this.redstoneGen = new WorldGenMinable(Blocks.redstone_ore.getDefaultState(), this.chunkProviderSettings.redstoneSize); this.diamondGen = new WorldGenMinable(Blocks.diamond_ore.getDefaultState(), this.chunkProviderSettings.diamondSize); this.lapisGen = new WorldGenMinable(Blocks.lapis_ore.getDefaultState(), this.chunkProviderSettings.lapisSize); this.genDecorations(p_180292_3_); this.currentWorld = null; this.randomGenerator = null; } protected void genDecorations(final BiomeGenBase biomeGenBaseIn) { this.generateOres(); for (int i = 0; i < this.sandPerChunk2; ++i) { final int j = this.randomGenerator.nextInt(16) + 8; final int k = this.randomGenerator.nextInt(16) + 8; this.sandGen.generate(this.currentWorld, this.randomGenerator, this.currentWorld.getTopSolidOrLiquidBlock(this.field_180294_c.add(j, 0, k))); } for (int i2 = 0; i2 < this.clayPerChunk; ++i2) { final int l1 = this.randomGenerator.nextInt(16) + 8; final int i3 = this.randomGenerator.nextInt(16) + 8; this.clayGen.generate(this.currentWorld, this.randomGenerator, this.currentWorld.getTopSolidOrLiquidBlock(this.field_180294_c.add(l1, 0, i3))); } for (int j2 = 0; j2 < this.sandPerChunk; ++j2) { final int i4 = this.randomGenerator.nextInt(16) + 8; final int j3 = this.randomGenerator.nextInt(16) + 8; this.gravelAsSandGen.generate(this.currentWorld, this.randomGenerator, this.currentWorld.getTopSolidOrLiquidBlock(this.field_180294_c.add(i4, 0, j3))); } int k2 = this.treesPerChunk; if (this.randomGenerator.nextInt(10) == 0) { ++k2; } for (int j4 = 0; j4 < k2; ++j4) { final int k3 = this.randomGenerator.nextInt(16) + 8; final int m = this.randomGenerator.nextInt(16) + 8; final WorldGenAbstractTree worldgenabstracttree = biomeGenBaseIn.genBigTreeChance(this.randomGenerator); worldgenabstracttree.func_175904_e(); final BlockPos blockpos = this.currentWorld.getHeight(this.field_180294_c.add(k3, 0, m)); if (worldgenabstracttree.generate(this.currentWorld, this.randomGenerator, blockpos)) { worldgenabstracttree.func_180711_a(this.currentWorld, this.randomGenerator, blockpos); } } for (int k4 = 0; k4 < this.bigMushroomsPerChunk; ++k4) { final int l2 = this.randomGenerator.nextInt(16) + 8; final int k5 = this.randomGenerator.nextInt(16) + 8; this.bigMushroomGen.generate(this.currentWorld, this.randomGenerator, this.currentWorld.getHeight(this.field_180294_c.add(l2, 0, k5))); } for (int l3 = 0; l3 < this.flowersPerChunk; ++l3) { final int i5 = this.randomGenerator.nextInt(16) + 8; final int l4 = this.randomGenerator.nextInt(16) + 8; final int j5 = this.currentWorld.getHeight(this.field_180294_c.add(i5, 0, l4)).getY() + 32; if (j5 > 0) { final int k6 = this.randomGenerator.nextInt(j5); final BlockPos blockpos2 = this.field_180294_c.add(i5, k6, l4); final BlockFlower.EnumFlowerType blockflower$enumflowertype = biomeGenBaseIn.pickRandomFlower(this.randomGenerator, blockpos2); final BlockFlower blockflower = blockflower$enumflowertype.getBlockType().getBlock(); if (blockflower.getMaterial() != Material.air) { this.yellowFlowerGen.setGeneratedBlock(blockflower, blockflower$enumflowertype); this.yellowFlowerGen.generate(this.currentWorld, this.randomGenerator, blockpos2); } } } for (int i6 = 0; i6 < this.grassPerChunk; ++i6) { final int j6 = this.randomGenerator.nextInt(16) + 8; final int i7 = this.randomGenerator.nextInt(16) + 8; final int k7 = this.currentWorld.getHeight(this.field_180294_c.add(j6, 0, i7)).getY() * 2; if (k7 > 0) { final int l5 = this.randomGenerator.nextInt(k7); biomeGenBaseIn.getRandomWorldGenForGrass(this.randomGenerator).generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(j6, l5, i7)); } } for (int j7 = 0; j7 < this.deadBushPerChunk; ++j7) { final int k8 = this.randomGenerator.nextInt(16) + 8; final int j8 = this.randomGenerator.nextInt(16) + 8; final int l6 = this.currentWorld.getHeight(this.field_180294_c.add(k8, 0, j8)).getY() * 2; if (l6 > 0) { final int i8 = this.randomGenerator.nextInt(l6); new WorldGenDeadBush().generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(k8, i8, j8)); } } for (int k9 = 0; k9 < this.waterlilyPerChunk; ++k9) { final int l7 = this.randomGenerator.nextInt(16) + 8; final int k10 = this.randomGenerator.nextInt(16) + 8; final int i9 = this.currentWorld.getHeight(this.field_180294_c.add(l7, 0, k10)).getY() * 2; if (i9 > 0) { final int j9 = this.randomGenerator.nextInt(i9); BlockPos blockpos3; BlockPos blockpos4; for (blockpos3 = this.field_180294_c.add(l7, j9, k10); blockpos3.getY() > 0; blockpos3 = blockpos4) { blockpos4 = blockpos3.down(); if (!this.currentWorld.isAirBlock(blockpos4)) { break; } } this.waterlilyGen.generate(this.currentWorld, this.randomGenerator, blockpos3); } } for (int l8 = 0; l8 < this.mushroomsPerChunk; ++l8) { if (this.randomGenerator.nextInt(4) == 0) { final int i10 = this.randomGenerator.nextInt(16) + 8; final int l9 = this.randomGenerator.nextInt(16) + 8; final BlockPos blockpos5 = this.currentWorld.getHeight(this.field_180294_c.add(i10, 0, l9)); this.mushroomBrownGen.generate(this.currentWorld, this.randomGenerator, blockpos5); } if (this.randomGenerator.nextInt(8) == 0) { final int j10 = this.randomGenerator.nextInt(16) + 8; final int i11 = this.randomGenerator.nextInt(16) + 8; final int j11 = this.currentWorld.getHeight(this.field_180294_c.add(j10, 0, i11)).getY() * 2; if (j11 > 0) { final int k11 = this.randomGenerator.nextInt(j11); final BlockPos blockpos6 = this.field_180294_c.add(j10, k11, i11); this.mushroomRedGen.generate(this.currentWorld, this.randomGenerator, blockpos6); } } } if (this.randomGenerator.nextInt(4) == 0) { final int i12 = this.randomGenerator.nextInt(16) + 8; final int k12 = this.randomGenerator.nextInt(16) + 8; final int j12 = this.currentWorld.getHeight(this.field_180294_c.add(i12, 0, k12)).getY() * 2; if (j12 > 0) { final int k13 = this.randomGenerator.nextInt(j12); this.mushroomBrownGen.generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(i12, k13, k12)); } } if (this.randomGenerator.nextInt(8) == 0) { final int j13 = this.randomGenerator.nextInt(16) + 8; final int l10 = this.randomGenerator.nextInt(16) + 8; final int k14 = this.currentWorld.getHeight(this.field_180294_c.add(j13, 0, l10)).getY() * 2; if (k14 > 0) { final int l11 = this.randomGenerator.nextInt(k14); this.mushroomRedGen.generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(j13, l11, l10)); } } for (int k15 = 0; k15 < this.reedsPerChunk; ++k15) { final int i13 = this.randomGenerator.nextInt(16) + 8; final int l12 = this.randomGenerator.nextInt(16) + 8; final int i14 = this.currentWorld.getHeight(this.field_180294_c.add(i13, 0, l12)).getY() * 2; if (i14 > 0) { final int l13 = this.randomGenerator.nextInt(i14); this.reedGen.generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(i13, l13, l12)); } } for (int l14 = 0; l14 < 10; ++l14) { final int j14 = this.randomGenerator.nextInt(16) + 8; final int i15 = this.randomGenerator.nextInt(16) + 8; final int j15 = this.currentWorld.getHeight(this.field_180294_c.add(j14, 0, i15)).getY() * 2; if (j15 > 0) { final int i16 = this.randomGenerator.nextInt(j15); this.reedGen.generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(j14, i16, i15)); } } if (this.randomGenerator.nextInt(32) == 0) { final int i17 = this.randomGenerator.nextInt(16) + 8; final int k16 = this.randomGenerator.nextInt(16) + 8; final int j16 = this.currentWorld.getHeight(this.field_180294_c.add(i17, 0, k16)).getY() * 2; if (j16 > 0) { final int k17 = this.randomGenerator.nextInt(j16); new WorldGenPumpkin().generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(i17, k17, k16)); } } for (int j17 = 0; j17 < this.cactiPerChunk; ++j17) { final int l15 = this.randomGenerator.nextInt(16) + 8; final int k18 = this.randomGenerator.nextInt(16) + 8; final int l16 = this.currentWorld.getHeight(this.field_180294_c.add(l15, 0, k18)).getY() * 2; if (l16 > 0) { final int j18 = this.randomGenerator.nextInt(l16); this.cactusGen.generate(this.currentWorld, this.randomGenerator, this.field_180294_c.add(l15, j18, k18)); } } if (this.generateLakes) { for (int k19 = 0; k19 < 50; ++k19) { final int i18 = this.randomGenerator.nextInt(16) + 8; final int l17 = this.randomGenerator.nextInt(16) + 8; final int i19 = this.randomGenerator.nextInt(248) + 8; if (i19 > 0) { final int k20 = this.randomGenerator.nextInt(i19); final BlockPos blockpos7 = this.field_180294_c.add(i18, k20, l17); new WorldGenLiquids(Blocks.flowing_water).generate(this.currentWorld, this.randomGenerator, blockpos7); } } for (int l18 = 0; l18 < 20; ++l18) { final int j19 = this.randomGenerator.nextInt(16) + 8; final int i20 = this.randomGenerator.nextInt(16) + 8; final int j20 = this.randomGenerator.nextInt(this.randomGenerator.nextInt(this.randomGenerator.nextInt(240) + 8) + 8); final BlockPos blockpos8 = this.field_180294_c.add(j19, j20, i20); new WorldGenLiquids(Blocks.flowing_lava).generate(this.currentWorld, this.randomGenerator, blockpos8); } } } protected void genStandardOre1(final int blockCount, final WorldGenerator generator, int minHeight, int maxHeight) { if (maxHeight < minHeight) { final int i = minHeight; minHeight = maxHeight; maxHeight = i; } else if (maxHeight == minHeight) { if (minHeight < 255) { ++maxHeight; } else { --minHeight; } } for (int j = 0; j < blockCount; ++j) { final BlockPos blockpos = this.field_180294_c.add(this.randomGenerator.nextInt(16), this.randomGenerator.nextInt(maxHeight - minHeight) + minHeight, this.randomGenerator.nextInt(16)); generator.generate(this.currentWorld, this.randomGenerator, blockpos); } } protected void genStandardOre2(final int blockCount, final WorldGenerator generator, final int centerHeight, final int spread) { for (int i = 0; i < blockCount; ++i) { final BlockPos blockpos = this.field_180294_c.add(this.randomGenerator.nextInt(16), this.randomGenerator.nextInt(spread) + this.randomGenerator.nextInt(spread) + centerHeight - spread, this.randomGenerator.nextInt(16)); generator.generate(this.currentWorld, this.randomGenerator, blockpos); } } protected void generateOres() { this.genStandardOre1(this.chunkProviderSettings.dirtCount, this.dirtGen, this.chunkProviderSettings.dirtMinHeight, this.chunkProviderSettings.dirtMaxHeight); this.genStandardOre1(this.chunkProviderSettings.gravelCount, this.gravelGen, this.chunkProviderSettings.gravelMinHeight, this.chunkProviderSettings.gravelMaxHeight); this.genStandardOre1(this.chunkProviderSettings.dioriteCount, this.dioriteGen, this.chunkProviderSettings.dioriteMinHeight, this.chunkProviderSettings.dioriteMaxHeight); this.genStandardOre1(this.chunkProviderSettings.graniteCount, this.graniteGen, this.chunkProviderSettings.graniteMinHeight, this.chunkProviderSettings.graniteMaxHeight); this.genStandardOre1(this.chunkProviderSettings.andesiteCount, this.andesiteGen, this.chunkProviderSettings.andesiteMinHeight, this.chunkProviderSettings.andesiteMaxHeight); this.genStandardOre1(this.chunkProviderSettings.coalCount, this.coalGen, this.chunkProviderSettings.coalMinHeight, this.chunkProviderSettings.coalMaxHeight); this.genStandardOre1(this.chunkProviderSettings.ironCount, this.ironGen, this.chunkProviderSettings.ironMinHeight, this.chunkProviderSettings.ironMaxHeight); this.genStandardOre1(this.chunkProviderSettings.goldCount, this.goldGen, this.chunkProviderSettings.goldMinHeight, this.chunkProviderSettings.goldMaxHeight); this.genStandardOre1(this.chunkProviderSettings.redstoneCount, this.redstoneGen, this.chunkProviderSettings.redstoneMinHeight, this.chunkProviderSettings.redstoneMaxHeight); this.genStandardOre1(this.chunkProviderSettings.diamondCount, this.diamondGen, this.chunkProviderSettings.diamondMinHeight, this.chunkProviderSettings.diamondMaxHeight); this.genStandardOre2(this.chunkProviderSettings.lapisCount, this.lapisGen, this.chunkProviderSettings.lapisCenterHeight, this.chunkProviderSettings.lapisSpread); } }
hanisaf/mist4600-spring2019
ArrayExample/src/Example2.java
<reponame>hanisaf/mist4600-spring2019 public class Example2 { public static void main(String[] args) { Restaurant favLunchPlace = new Restaurant(); Restaurant favDinnerPlace = new Restaurant(); favLunchPlace.setName("Central Deli"); favLunchPlace.setRating(4); favDinnerPlace.setName("Friends Cafe"); favDinnerPlace.setRating(5); Restaurant[] restaurants = new Restaurant[2]; restaurants[0] = favLunchPlace; restaurants[1] = favDinnerPlace; // for(int i = 0; i < restaurants.length; i++) { // Restaurant item = restaurants[i]; // item.print(); // } // // System.out.println("Bon apetit"); } }
1160300922/incubator-iotdb
server/src/main/java/org/apache/iotdb/db/query/dataset/AggreResultDataPointReader.java
<gh_stars>1-10 /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.db.query.dataset; import org.apache.iotdb.db.query.aggregation.AggreResultData; import org.apache.iotdb.db.query.reader.IPointReader; import org.apache.iotdb.db.utils.TimeValuePair; import org.apache.iotdb.db.utils.TimeValuePairUtils; public class AggreResultDataPointReader implements IPointReader { private AggreResultData aggreResultData; public AggreResultDataPointReader(AggreResultData aggreResultData) { this.aggreResultData = aggreResultData; } @Override public boolean hasNext() { return aggreResultData.isSetValue(); } @Override public TimeValuePair next() { TimeValuePair timeValuePair = TimeValuePairUtils.getCurrentTimeValuePair(aggreResultData); aggreResultData.reset(); return timeValuePair; } @Override public TimeValuePair current() { return TimeValuePairUtils.getCurrentTimeValuePair(aggreResultData); } @Override public void close() { // batch data doesn't need to close. } }
yanpingli/btm
btm/src/test/java/bitronix/tm/mock/JdbcSharedConnectionTest.java
<gh_stars>0 /* * Copyright (C) 2006-2013 Bitronix Software (http://www.bitronix.be) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package bitronix.tm.mock; import bitronix.tm.BitronixTransactionManager; import bitronix.tm.TransactionManagerServices; import bitronix.tm.resource.jdbc.PooledConnectionProxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.transaction.Transaction; import java.sql.Connection; import java.util.ArrayList; /** * * @author <NAME> */ public class JdbcSharedConnectionTest extends AbstractMockJdbcTest { private final static Logger log = LoggerFactory.getLogger(NewJdbcProperUsageMockTest.class); public void testSharedConnectionMultithreaded() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testSharedConnectionMultithreaded: getting TM"); } final BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.setTransactionTimeout(120); if (log.isDebugEnabled()) { log.debug("*** before begin"); } tm.begin(); if (log.isDebugEnabled()) { log.debug("*** after begin"); } final Transaction suspended = tm.suspend(); final ArrayList twoConnections = new ArrayList(); Thread thread1 = new Thread() { public void run() { try { tm.resume(suspended); if (log.isDebugEnabled()) { log.debug("*** getting connection from DS1"); } Connection connection = poolingDataSource1.getConnection(); connection.createStatement(); twoConnections.add(connection); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }; thread1.start(); thread1.join(); Thread thread2 = new Thread() { public void run() { try { tm.resume(suspended); if (log.isDebugEnabled()) { log.debug("*** getting connection from DS1"); } Connection connection = poolingDataSource1.getConnection(); connection.createStatement(); twoConnections.add(connection); tm.commit(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }; thread2.start(); thread2.join(); PooledConnectionProxy handle1 = (PooledConnectionProxy) twoConnections.get(0); PooledConnectionProxy handle2 = (PooledConnectionProxy) twoConnections.get(1); assertNotSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate()); } public void testUnSharedConnection() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testUnSharedConnection: getting TM"); } BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.setTransactionTimeout(120); if (log.isDebugEnabled()) { log.debug("*** before begin"); } tm.begin(); if (log.isDebugEnabled()) { log.debug("*** after begin"); } if (log.isDebugEnabled()) { log.debug("*** getting connection from DS2"); } Connection connection1 = poolingDataSource2.getConnection(); // createStatement causes enlistment connection1.createStatement(); if (log.isDebugEnabled()) { log.debug("*** getting second connection from DS2"); } Connection connection2 = poolingDataSource2.getConnection(); PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1; PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2; assertNotSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate()); connection1.close(); connection2.close(); tm.commit(); } public void testSharedConnectionInLocalTransaction() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testSharedConnectionInLocalTransaction: getting connection from DS1"); } Connection connection1 = poolingDataSource1.getConnection(); // createStatement causes enlistment connection1.createStatement(); if (log.isDebugEnabled()) { log.debug("*** getting second connection from DS1"); } Connection connection2 = poolingDataSource1.getConnection(); PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1; PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2; assertNotSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate()); connection1.close(); connection2.close(); } public void testUnSharedConnectionInLocalTransaction() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testUnSharedConnectionInLocalTransaction: getting connection from DS2"); } Connection connection1 = poolingDataSource2.getConnection(); // createStatement causes enlistment connection1.createStatement(); if (log.isDebugEnabled()) { log.debug("*** getting second connection from DS2"); } Connection connection2 = poolingDataSource2.getConnection(); PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1; PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2; assertNotSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate()); connection1.close(); connection2.close(); } public void testSharedConnectionInGlobal() throws Exception { if (log.isDebugEnabled()) { log.debug("*** testSharedConnectionInGlobal: Starting getting TM"); } BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.setTransactionTimeout(120); if (log.isDebugEnabled()) { log.debug("*** before begin"); } tm.begin(); if (log.isDebugEnabled()) { log.debug("*** after begin"); } if (log.isDebugEnabled()) { log.debug("*** getting connection from DS1"); } Connection connection1 = poolingDataSource1.getConnection(); if (log.isDebugEnabled()) { log.debug("*** getting second connection from DS1"); } Connection connection2 = poolingDataSource1.getConnection(); PooledConnectionProxy handle1 = (PooledConnectionProxy) connection1; PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2; assertSame(handle1.getProxiedDelegate(), handle2.getProxiedDelegate()); connection1.close(); connection2.close(); tm.commit(); } }
doumKim/surf-client-repo
src/constants/formStyles.js
<reponame>doumKim/surf-client-repo import styled from "@emotion/styled"; import { keyframes } from "@emotion/core"; const slideUp = keyframes` from { transform: translateY(200px); } to { transform: translateY(0px); } `; export const Wrapper = styled.div` position: relative; margin: 0 auto; background-color: #f8f9fa; border: none; border-radius: 5px; animation-duration: 0.25s; animation-timing-function: ease-out; animation-name: ${slideUp}; animation-fill-mode: forwards; width: 480px; height: 780px; padding: 3rem; `; export const Box = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0); `; export const Title = styled.div` display: inline-block; color: #343a40; margin-bottom: 1.5rem; font-size: 3.5rem; font-weight: 700; `; export const Label = styled.p` color: #343a40; margin-bottom: 5px; margin-top: 15px; font-size: 1rem; font-weight: 400; `; export const Input = styled.input` width: 100%; height: 40px; background: #f1f3f5; border: 0.5px solid #dee2e6; border-radius: 3px; font-size: 1rem; margin-bottom: 4px; `; export const SubmitButton = styled.button` cursor: pointer; display: block; color: #fff; background-color: #51cf66; border-radius: 6px; border: none; margin-top: 1.5rem; width: 32%; height: 40px; font-size: 1.2rem; font-weight: 500; `;
bieremayi/carbondata
core/src/main/java/org/apache/carbondata/core/scan/collector/impl/RestructureBasedDictionaryResultCollector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.core.scan.collector.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.carbondata.core.metadata.datatype.DataTypes; import org.apache.carbondata.core.scan.executor.infos.BlockExecutionInfo; import org.apache.carbondata.core.scan.executor.util.RestructureUtil; import org.apache.carbondata.core.scan.filter.GenericQueryType; import org.apache.carbondata.core.scan.model.ProjectionMeasure; import org.apache.carbondata.core.scan.result.BlockletScannedResult; import org.apache.carbondata.core.util.DataTypeUtil; /** * class for handling restructure scenarios for filling result */ public class RestructureBasedDictionaryResultCollector extends DictionaryBasedResultCollector { private Object[] measureDefaultValues = null; public RestructureBasedDictionaryResultCollector(BlockExecutionInfo blockExecutionInfos) { super(blockExecutionInfos); queryDimensions = executionInfo.getActualQueryDimensions(); queryMeasures = executionInfo.getActualQueryMeasures(); measureDefaultValues = new Object[queryMeasures.length]; fillMeasureDefaultValues(); initDimensionAndMeasureIndexesForFillingData(); isDimensionExists = queryDimensions.length > 0; } /** * Fill measure default measure columns */ private void fillMeasureDefaultValues() { for (int i = 0; i < queryMeasures.length; i++) { if (!measureInfo.getMeasureExists()[i]) { measureDefaultValues[i] = RestructureUtil .getMeasureDefaultValueByType(queryMeasures[i].getMeasure().getColumnSchema(), queryMeasures[i].getMeasure().getDefaultValue()); } } } /** * This method will add a record both key and value to list object * it will keep track of how many record is processed, to handle limit scenario */ @Override public List<Object[]> collectResultInRow(BlockletScannedResult scannedResult, int batchSize) { // scan the record and add to list List<Object[]> listBasedResult = new ArrayList<>(batchSize); int rowCounter = 0; int[] surrogateResult; byte[][] noDictionaryKeys; byte[][] complexTypeKeyArray; Map<Integer, GenericQueryType> complexDimensionInfoMap = executionInfo.getComplexDimensionInfoMap(); while (scannedResult.hasNext() && rowCounter < batchSize) { scannedResult.incrementCounter(); if (scannedResult.containsDeletedRow(scannedResult.getCurrentRowId())) { continue; } Object[] row = new Object[queryDimensions.length + queryMeasures.length]; if (isDimensionExists) { surrogateResult = scannedResult.getDictionaryKeyIntegerArray(); noDictionaryKeys = scannedResult.getNoDictionaryKeyArray(); complexTypeKeyArray = scannedResult.getComplexTypeKeyArray(); dictionaryColumnIndex = 0; noDictionaryColumnIndex = 0; complexTypeColumnIndex = 0; int segmentDimensionsIdx = 0; for (int i = 0; i < queryDimensions.length; i++) { // fill default value in case the dimension does not exist in the current block if (!dimensionInfo.getDimensionExists()[i]) { if (queryDimensions[i].getDimension().getDataType() == DataTypes.DATE) { row[order[i]] = dimensionInfo.getDefaultValues()[i]; dictionaryColumnIndex++; } else if (queryDimensions[i].getDimension().getDataType() == DataTypes.STRING) { row[order[i]] = DataTypeUtil.getDataTypeConverter().convertFromByteToUTF8String( (byte[])dimensionInfo.getDefaultValues()[i]); } else { row[order[i]] = dimensionInfo.getDefaultValues()[i]; } continue; } fillDimensionData(scannedResult, surrogateResult, noDictionaryKeys, complexTypeKeyArray, complexDimensionInfoMap, row, i, executionInfo .getProjectionDimensions()[segmentDimensionsIdx++].getDimension().getOrdinal()); } } fillMeasureData(scannedResult, row); listBasedResult.add(row); rowCounter++; } return listBasedResult; } protected void fillMeasureData(Object[] msrValues, int offset, BlockletScannedResult scannedResult) { int measureExistIndex = 0; for (short i = 0; i < measureInfo.getMeasureDataTypes().length; i++) { // if measure exists is block then pass measure column // data chunk to the collector if (measureInfo.getMeasureExists()[i]) { ProjectionMeasure queryMeasure = executionInfo.getProjectionMeasures()[measureExistIndex]; msrValues[i + offset] = getMeasureData( scannedResult.getMeasureChunk(measureInfo.getMeasureOrdinals()[measureExistIndex]), scannedResult.getCurrentRowId(), queryMeasure.getMeasure()); measureExistIndex++; } else if (DataTypes.isDecimal(measureInfo.getMeasureDataTypes()[i])) { // if not then get the default value msrValues[i + offset] = DataTypeUtil.getDataTypeConverter() .convertFromBigDecimalToDecimal(measureDefaultValues[i]); } else { msrValues[i + offset] = measureDefaultValues[i]; } } } }
helios-language/helios
docs/search/classes_5.js
<gh_stars>1-10 var searchData= [ ['parser_5ferror',['parser_error',['../structparser__error.html',1,'']]], ['parser_5ft',['Parser_t',['../structParser__t.html',1,'']]] ];
lechium/iOS1351Headers
usr/lib/libcoreroutine.dylib/RTDevice.h
<reponame>lechium/iOS1351Headers /* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:17:53 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /usr/lib/libcoreroutine.dylib * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <libobjc.A.dylib/RTCoreDataReadable.h> @class NSUUID, NSString, NSDate; @interface RTDevice : NSObject <RTCoreDataReadable> { NSUUID* _identifier; NSString* _deviceName; NSString* _deviceClass; NSString* _deviceModel; NSDate* _creationDate; } @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,readonly) NSUUID * identifier; //@synthesize identifier=_identifier - In the implementation block @property (nonatomic,readonly) NSString * deviceName; //@synthesize deviceName=_deviceName - In the implementation block @property (nonatomic,readonly) NSString * deviceClass; //@synthesize deviceClass=_deviceClass - In the implementation block @property (nonatomic,readonly) NSString * deviceModel; //@synthesize deviceModel=_deviceModel - In the implementation block @property (nonatomic,readonly) NSDate * creationDate; //@synthesize creationDate=_creationDate - In the implementation block +(id)createWithManagedObject:(id)arg1 ; +(id)createWithDeviceMO:(id)arg1 ; -(id)init; -(NSString *)description; -(NSUUID *)identifier; -(NSDate *)creationDate; -(NSString *)deviceName; -(NSString *)deviceClass; -(NSString *)deviceModel; -(id)initWithIdentifier:(id)arg1 deviceName:(id)arg2 deviceClass:(id)arg3 deviceModel:(id)arg4 creationDate:(id)arg5 ; @end
cpetry/AntSim
js/controller.js
<gh_stars>10-100 /** * The Controller enables the user to program his/hers ants behaviour.<br> * It has limited access to some of the ants current values.<br> * The action for the upcoming iteration is to be written by the user.<br> * @module Controller */ define(function() { return class Controller { /** * @ignore */ constructor(animal){ this.life = 0; this.size = 0; this.collidedWithID = -1; this.visibleObjs = {}; this.smelledObjs = {}; this.collidedWithID = -1; this.wasAttacked = false; this.lastDistanceWalked = 0; this.lastRotated = 0; this.memory = { }; this.setAttributes(animal); } /** * @ignore */ setAttributes(animal){ this.life = animal.getLife(); this.size = animal.getSize(); this.visibleObjs = animal.getVisibleObjs(); this.smelledObjs = animal.getSmelledObjs(); this.collidedWithID = (animal.hasCollidedWith() != null ? animal.hasCollidedWith().getID() : -1); this.wasAttacked = animal.wasAttacked(); this.interactionDistance = animal.getInteractionDistance(); this.interactionRange = animal.getInteractionRange(); this.lastDistanceWalked = animal.getLastDistanceWalked(); this.lastRotated = animal.getLastRotated(); } /** * Get the current health of the ant (max: 100) * @return {number} life. */ getLife(){return this.life;} /** * Get the current health of the ant (max: 100) * @return {number} life. */ getSize(){return this.size;} /** * Get a list of all visible objects. * @return {Object[]} visible objects. */ getVisibleObjs(){return this.visibleObjs;} /** * Get a list of all smelled objects. * @return {Object[]} smelled objects. */ getSmelledObjs(){return this.smelledObjs;} /** * Get the maximum distance ants can interact with stuff * @return {number} distance. */ getInteractionDistance(){return this.interactionDistance;} /** * Get the maximum range ants can interact with stuff * @return {number} range in rad. */ getInteractionRange(){return this.interactionRange;} /** * Checks if the ant has collided with something in the previous iteration and returns its id. * Returns -1 if no collision has occured. * @return {number} Collision object ID. */ hasCollidedWithID() {return this.collidedWithID;} getLastDistanceWalked() {return this.lastDistanceWalked;} getLastRotated() {return this.lastRotated;} /** * Returns the action the ant should do in the upcoming iteration.<br> * This has to be an array with an ActionType and parameters.<br> * Some examples:<br> * - [ActionType.MOVE, Direction.NONE, 0] // walks straight forward<br> * - [ActionType.HARVEST, foodObj, 10] // wants to harvest 10 food from foodObj<br> * - [ActionType.GIVEFOOD, hive, 10] // wants to give 10 food to hive<br> * - [ActionType.ATTACK, enemy] // wants to attack an enemy<br> * @return {number[]} Array with type and parameters. */ getAction(){ } getObjectOfID(searchID){ var searchObj = null; // is object of searchID visible? for (var id in this.visibleObjs){ if(this.visibleObjs[id].getID() == searchID){ searchObj = this.visibleObjs[id]; } } if (searchObj == null){ for (var id in this.smelledObjs){ if(this.smelledObjs[id].getID() == searchID){ searchObj = this.smelledObjs[id]; } } } return searchObj; } //convenience functions for user getNearestObjectType(objType){ var minDist = 1000; var nearestOfObjType = null; for (var id in this.visibleObjs){ if (this.visibleObjs[id].getObjectType() == objType && this.visibleObjs[id].getDistanceToObj() < minDist){ minDist = this.visibleObjs[id].getDistanceToObj(); nearestOfObjType = this.visibleObjs[id]; } } if (nearestOfObjType == null){ for (var id in this.smelledObjs){ if (this.smelledObjs[id].getObjectType() == objType && this.smelledObjs[id].getDistanceToObj() < minDist){ minDist = this.smelledObjs[id].getDistanceToObj(); nearestOfObjType = this.smelledObjs[id]; } } } return nearestOfObjType; } } });
paullewallencom/java-978-1-7895-3476-4
_/Section-3/config-service/src/main/java/cloud/nativ/javaee/JsonObjectConverter.java
<reponame>paullewallencom/java-978-1-7895-3476-4 package cloud.nativ.javaee; import org.eclipse.microprofile.config.spi.Converter; import javax.json.Json; import javax.json.JsonException; import javax.json.JsonObject; import java.io.StringReader; /** * A MicroProfile Config converter for {@link JsonObject}. */ public class JsonObjectConverter implements Converter<JsonObject> { @Override public JsonObject convert(String value) { try { return Json.createReader(new StringReader(value)).readObject(); } catch (JsonException e) { throw new IllegalArgumentException(e); } } }
MicrochipTech/aws-iot-winc1500-secure-wifi-board-included-source-files
mcu-firmware/saml21g18b_sensor_board_demo/src/cryptoauthlib/docs/html/search/enums_1.js
var searchData= [ ['i2c_5fread_5fwrite_5fflag',['i2c_read_write_flag',['../a00429.html#gaa3e90779b37cd1b3a4d32321d9d8b772',1,'hal_i2c_bitbang.h']]] ];
enterstudio/mobile-center-cli
src/util/apis/generated/models/testCloudStartTestRunOptions.js
/* * Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the TestCloudStartTestRunOptions class. * @constructor * @summary TestCloudStartTestRunOptions * * Options required to start the test run * * @member {string} testFramework Test framework used by tests. * * @member {string} deviceSelection Device selection string. * * @member {string} [locale] Locale that should be used to run tests. * * @member {string} [testSeries] Name of the test series. * * @member {object} [testParameters] A JSON dictionary with additional test * parameters * */ function TestCloudStartTestRunOptions() { } /** * Defines the metadata of TestCloudStartTestRunOptions * * @returns {object} metadata of TestCloudStartTestRunOptions * */ TestCloudStartTestRunOptions.prototype.mapper = function () { return { required: false, serializedName: 'TestCloudStartTestRunOptions', type: { name: 'Composite', className: 'TestCloudStartTestRunOptions', modelProperties: { testFramework: { required: true, serializedName: 'test_framework', type: { name: 'String' } }, deviceSelection: { required: true, serializedName: 'device_selection', type: { name: 'String' } }, locale: { required: false, serializedName: 'locale', type: { name: 'String' } }, testSeries: { required: false, serializedName: 'test_series', type: { name: 'String' } }, testParameters: { required: false, serializedName: 'test_parameters', type: { name: 'Object' } } } } }; }; module.exports = TestCloudStartTestRunOptions;
svenpopping/acfl-replication-package
data/problems/Math-40/frame-5/tests-pass-evo-+/org/apache/commons/math/analysis/solvers/BracketingNthOrderBrentSolver_ESTest_EvoSuite.java
/* * This file was automatically generated by EvoSuite * Mon Feb 24 16:38:44 GMT 2020 */ package org.apache.commons.math.analysis.solvers; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import org.apache.commons.math.analysis.UnivariateFunction; import org.apache.commons.math.analysis.function.Cbrt; import org.apache.commons.math.analysis.function.Expm1; import org.apache.commons.math.analysis.function.Gaussian; import org.apache.commons.math.analysis.function.Identity; import org.apache.commons.math.analysis.function.Logit; import org.apache.commons.math.analysis.solvers.AllowedSolution; import org.apache.commons.math.analysis.solvers.BracketingNthOrderBrentSolver; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; public class BracketingNthOrderBrentSolver_ESTest_EvoSuite extends BracketingNthOrderBrentSolver_ESTest_scaffolding_EvoSuite { @Test(timeout = 4000) public void test00() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver((-2446.4), (-2446.4), 10.0, 3); Gaussian gaussian0 = new Gaussian(3, 3, 10.0); AllowedSolution allowedSolution0 = AllowedSolution.ABOVE_SIDE; bracketingNthOrderBrentSolver0.solve(1202, (UnivariateFunction) gaussian0, (-2446.4), 816.0, allowedSolution0); } @Test(timeout = 4000) public void test01() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Cbrt cbrt0 = new Cbrt(); AllowedSolution allowedSolution0 = AllowedSolution.ABOVE_SIDE; bracketingNthOrderBrentSolver0.solve(1307, (UnivariateFunction) cbrt0, (-1945.6728), 7.012806239173502E291, (-1470.84), allowedSolution0); } @Test(timeout = 4000) public void test06() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver((-553.822628), 490); Identity identity0 = new Identity(); AllowedSolution allowedSolution0 = AllowedSolution.LEFT_SIDE; bracketingNthOrderBrentSolver0.solve(490, (UnivariateFunction) identity0, (-1.2030229087793677E-8), 1417.88, allowedSolution0); bracketingNthOrderBrentSolver0.doSolve(); } @Test(timeout = 4000) public void test07() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Cbrt cbrt0 = new Cbrt(); AllowedSolution allowedSolution0 = AllowedSolution.LEFT_SIDE; bracketingNthOrderBrentSolver0.solve(1307, (UnivariateFunction) cbrt0, (-1470.2511428237547), 512.8441, allowedSolution0); } @Test(timeout = 4000) public void test08() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Cbrt cbrt0 = new Cbrt(); AllowedSolution allowedSolution0 = AllowedSolution.ABOVE_SIDE; bracketingNthOrderBrentSolver0.solve(1307, (UnivariateFunction) cbrt0, (-1945.6728), 7.012806239173502E291, (-1470.2511428237547), allowedSolution0); } @Test(timeout = 4000) public void test09() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Expm1 expm1_0 = new Expm1(); bracketingNthOrderBrentSolver0.solve(378, (UnivariateFunction) expm1_0, (-162.004623086), (double) 378, (-109.1970313213805)); } @Test(timeout = 4000) public void test10() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Cbrt cbrt0 = new Cbrt(); AllowedSolution allowedSolution0 = AllowedSolution.BELOW_SIDE; bracketingNthOrderBrentSolver0.solve(1307, (UnivariateFunction) cbrt0, (-1924.9834660739182), 7.012806239173502E291, (-1470.2511428237547), allowedSolution0); } @Test(timeout = 4000) public void test11() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Cbrt cbrt0 = new Cbrt(); AllowedSolution allowedSolution0 = AllowedSolution.RIGHT_SIDE; double double0 = bracketingNthOrderBrentSolver0.solve(1307, (UnivariateFunction) cbrt0, (-1945.6728), 7.012806239173502E291, (double) 1307, allowedSolution0); assertEquals(1307.0, bracketingNthOrderBrentSolver0.getStartValue(), 0.01); assertEquals(4.547473508864641E-13, double0, 0.01); } @Test(timeout = 4000) public void test12() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Cbrt cbrt0 = new Cbrt(); AllowedSolution allowedSolution0 = AllowedSolution.LEFT_SIDE; double double0 = bracketingNthOrderBrentSolver0.solve(1307, (UnivariateFunction) cbrt0, (-1945.6728), 7.012806239173502E291, (-1470.2511428237547), allowedSolution0); assertEquals((-1470.2511428237547), bracketingNthOrderBrentSolver0.getStartValue(), 0.01); assertEquals((-2.2737367544323206E-13), double0, 0.01); } @Test(timeout = 4000) public void test13() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver(); Expm1 expm1_0 = new Expm1(); double double0 = bracketingNthOrderBrentSolver0.solve(375, (UnivariateFunction) expm1_0, (-162.004623086), (double) 375, (-109.1970313213805)); assertEquals((-6.564505341220828E-21), double0, 0.01); double double1 = bracketingNthOrderBrentSolver0.doSolve(); assertEquals((-6.564505341220828E-21), double1, 0.01); } @Test(timeout = 4000) public void test15() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver((-2446.4), (-2446.4), 10.0, 3); Gaussian gaussian0 = new Gaussian(3, 3, 10.0); UnivariateFunction univariateFunction0 = gaussian0.derivative(); AllowedSolution allowedSolution0 = AllowedSolution.ABOVE_SIDE; double double0 = bracketingNthOrderBrentSolver0.solve(3, univariateFunction0, 0.0, (double) 3, allowedSolution0); assertEquals(3.0, double0, 0.01); assertEquals(0.0, bracketingNthOrderBrentSolver0.getMin(), 0.01); assertEquals(3, bracketingNthOrderBrentSolver0.getMaximalOrder()); } @Test(timeout = 4000) public void test16() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver((-2446.4), (-2446.4), 10.0, 32); Gaussian gaussian0 = new Gaussian(32, 32, 10.0); UnivariateFunction univariateFunction0 = gaussian0.derivative(); AllowedSolution allowedSolution0 = AllowedSolution.ABOVE_SIDE; double double0 = bracketingNthOrderBrentSolver0.solve(1202, univariateFunction0, 0.0, 816.0, allowedSolution0); assertEquals(32, bracketingNthOrderBrentSolver0.getMaximalOrder()); assertEquals(0.0, double0, 0.01); } @Test(timeout = 4000) public void test17() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver((-2446.4), (-2446.4), 10.0, 3); Gaussian gaussian0 = new Gaussian(3, 3, 10.0); AllowedSolution allowedSolution0 = AllowedSolution.ABOVE_SIDE; bracketingNthOrderBrentSolver0.solve(1202, (UnivariateFunction) gaussian0, 0.0, 816.0, allowedSolution0); double double0 = bracketingNthOrderBrentSolver0.doSolve(); assertEquals(0.0, bracketingNthOrderBrentSolver0.getMin(), 0.01); assertEquals(408.0, double0, 0.01); assertEquals(3, bracketingNthOrderBrentSolver0.getMaximalOrder()); } @Test(timeout = 4000) public void test23() throws Throwable { BracketingNthOrderBrentSolver bracketingNthOrderBrentSolver0 = new BracketingNthOrderBrentSolver((-1658.558), 6.283185307179586, 31); int int0 = bracketingNthOrderBrentSolver0.getMaximalOrder(); assertEquals(31, int0); } }
jszip/jszip-maven-plugin
src/main/java/org/jszip/pseudo/io/NotExistingPseudoFile.java
<gh_stars>1-10 /* * Copyright 2011-2012 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jszip.pseudo.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class NotExistingPseudoFile extends PseudoFile { private final String name; public NotExistingPseudoFile(PseudoFile parent, String name) { super(parent); this.name = name; } /** * {@inheritDoc} */ public boolean canRead() { return false; } /** * {@inheritDoc} */ public boolean canWrite() { return false; } /** * {@inheritDoc} */ public boolean createNewFile() throws IOException { throw new IOException(getPath() + " is a non-existing file"); } /** * {@inheritDoc} */ public boolean delete() { return false; } /** * {@inheritDoc} */ public void deleteOnExit() { } /** * {@inheritDoc} */ public boolean exists() { return false; } /** * {@inheritDoc} */ public String getName() { return name; } /** * {@inheritDoc} */ public boolean isDirectory() { return true; } /** * {@inheritDoc} */ public boolean isFile() { return false; } /** * {@inheritDoc} */ public boolean isHidden() { return false; } /** * {@inheritDoc} */ public long lastModified() { return 0; } /** * {@inheritDoc} */ public long length() { return 0; } /** * {@inheritDoc} */ public boolean mkdir() { return false; } /** * {@inheritDoc} */ public boolean mkdirs() { return false; } /** * {@inheritDoc} */ public boolean renameTo(PseudoFile dest) { return false; } /** * {@inheritDoc} */ public boolean setLastModified(long time) { return false; } /** * {@inheritDoc} */ InputStream $newInputStream() throws IOException { throw new IOException(getPath() + " is a non-existing file"); } /** * {@inheritDoc} */ OutputStream $newOutputStream() throws IOException { throw new IOException(getPath() + " is a non-existing file"); } /** * {@inheritDoc} */ OutputStream $newOutputStream(boolean append) throws IOException { throw new IOException(getPath() + " is a non-existing file"); } }
bubbledoodle/EL-GY-6183-Digital-Signal-Processing-LAB
DSP Lab 6/Lab_6_Shuaiyu_Liang_sl5352/Lab6_Sec1_Ex2_sl5352.py
# plot_micinput_spectrum.py import pyaudio import struct import numpy as np from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages('logarithmatic_spectrum.pdf') plt.ion() # Turn on interactive mode so plot gets updated WIDTH = 2 # bytes per sample CHANNELS = 1 # mono RATE = 16000 # Sampling rate (samples/second) BLOCKSIZE = 1024 DURATION = 10 # Duration in seconds NumBlocks = int( DURATION * RATE / BLOCKSIZE ) print 'BLOCKSIZE =', BLOCKSIZE print 'NumBlocks =', NumBlocks print 'Running for ', DURATION, 'seconds...' # Initialize plot window: plt.figure(1) plt.ylim(0, 20 * np.log10(10 * RATE)) plt.ylabel('Amplitude (dB)') # plt.xlim(0, BLOCKSIZE/2.0) # set x-axis limits # plt.xlabel('Frequency (k)') # f = np.linspace(0, BLOCKSIZE-1, BLOCKSIZE) # # Time axis in units of milliseconds: plt.xlim(0, 1 + np.log10(RATE/2.0)) # set x-axis limits plt.xlabel('Frequency log(Hz)') f = [n*float(RATE/BLOCKSIZE) for n in range(BLOCKSIZE)] line, = plt.plot([], [], color = 'blue') # Create empty line line.set_xdata(np.log10(f)) # x-data of plot (frequency) # Open audio device: p = pyaudio.PyAudio() PA_FORMAT = p.get_format_from_width(WIDTH) stream = p.open(format = PA_FORMAT, channels = CHANNELS, rate = RATE, input = True, output = False) for i in range(0, NumBlocks): input_string = stream.read(BLOCKSIZE) # Read audio input stream input_tuple = struct.unpack('h'*BLOCKSIZE, input_string) # Convert X = np.fft.fft(input_tuple) line.set_ydata(20 * np.log10(abs(X))) # Update y-data of plot plt.draw() # plt.close() plt.savefig(pp, format='pdf') pp.close() stream.stop_stream() stream.close() p.terminate() print '* Done'
afloarea/vertx-json-schema
src/test/java/io/vertx/json/schema/asserts/SchemaRouterAssert.java
/* * Copyright (c) 2011-2020 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.json.schema.asserts; import io.vertx.core.json.pointer.JsonPointer; import io.vertx.json.schema.Schema; import io.vertx.json.schema.SchemaParser; import io.vertx.json.schema.SchemaRouter; import io.vertx.json.schema.common.SchemaImpl; import io.vertx.json.schema.common.URIUtils; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.Condition; import java.net.URI; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class SchemaRouterAssert extends AbstractAssert<SchemaRouterAssert, SchemaRouter> { public SchemaRouterAssert(SchemaRouter actual) { super(actual, SchemaRouterAssert.class); } public SchemaAssert canResolveSchema(String uri, JsonPointer scope, SchemaParser parser) { return canResolveSchema(URIUtils.createJsonPointerFromURI(URI.create(uri)), scope, parser); } public SchemaAssert canResolveSchema(JsonPointer jp, JsonPointer scope, SchemaParser parser) { isNotNull(); try { Schema s = actual.resolveCachedSchema(jp, scope, parser); assertThat(s) .withFailMessage("Cannot resolve schema with pointer '%s' from scope '%s'", jp.toURI(), scope.toURI()) .isNotNull(); return new SchemaAssert(actual.resolveCachedSchema(jp, scope, parser)); } catch (Exception e) { fail(String.format("Cannot resolve schema with pointer '%s' from scope '%s'", jp.toURI(), scope.toURI()), e); return new SchemaAssert(null); } } public SchemaRouterAssert cannotResolveSchema(String uri, JsonPointer scope, SchemaParser parser) { return cannotResolveSchema(URIUtils.createJsonPointerFromURI(URI.create(uri)), scope, parser); } public SchemaRouterAssert cannotResolveSchema(JsonPointer jp, JsonPointer scope, SchemaParser parser) { isNotNull(); assertThat(actual.resolveCachedSchema(jp, scope, parser)).isNull(); return this; } public SchemaRouterAssert containsOnlyOneCachedSchemaWithXId(String expectedXId) { isNotNull(); assertThat(actual.registeredSchemas()) .isNotNull(); assertThat(actual.registeredSchemas()) .filteredOn(s -> s instanceof SchemaImpl) .extracting(s -> ((SchemaImpl) s).getJson()) .extracting(j -> j.getString("x-id")) .areExactly(1, new Condition<>(expectedXId::equals, "Expected id {}", expectedXId)); return this; } public SchemaRouterAssert containsCachedSchemasWithXIds(String... expectedXIds) { for (String id : expectedXIds) { containsOnlyOneCachedSchemaWithXId(id); } return this; } }
dvreeze/tqa2
jvm/src/test/scala/eu/cdevreeze/tqa2/locfreetaxonomy/TestResourceUtil.scala
<reponame>dvreeze/tqa2<filename>jvm/src/test/scala/eu/cdevreeze/tqa2/locfreetaxonomy/TestResourceUtil.scala<gh_stars>0 /* * Copyright 2019-2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.cdevreeze.tqa2.locfreetaxonomy import java.io.File import java.net.URI import eu.cdevreeze.tqa2.docbuilder.DocumentBuilder import eu.cdevreeze.tqa2.docbuilder.UriConverters import eu.cdevreeze.tqa2.docbuilder.jvm.SaxInputSource import eu.cdevreeze.tqa2.docbuilder.jvm.SaxUriResolvers import eu.cdevreeze.tqa2.docbuilder.jvm.saxon.SaxonDocumentBuilder import eu.cdevreeze.tqa2.locfreetaxonomy.taxonomy.BasicTaxonomy import eu.cdevreeze.tqa2.locfreetaxonomy.taxonomy.builder.DefaultDtsUriCollector import eu.cdevreeze.tqa2.locfreetaxonomy.taxonomy.builder.DefaultTaxonomyBuilder import eu.cdevreeze.yaidom2.node.saxon.SaxonDocument import net.sf.saxon.s9api.Processor /** * Support for converting classpath URIs (on the JVM) for testing, and for building documents from such relative URIs, * and for bootstrapping BasicTaxonomy instances from classpath resources. * * @author <NAME> */ object TestResourceUtil { /** * Converts a relative URI, interpreted as relative to the root of the classpath, to an absolute "file" URI. */ def convertClasspathUriToAbsoluteUri(relativeFilePath: URI): URI = { require( !relativeFilePath.isAbsolute, s"Expected relative URI, to be resolved against the root of the classpath, but got '$relativeFilePath'") TestResourceUtil.getClass.getResource("/" + relativeFilePath.toString).toURI } /** * Builds a Saxon document from the given relative URI, interpreted as relative to the root of the classpath. */ def buildSaxonDocumentFromClasspathResource(relativeFilePath: URI, processor: Processor): SaxonDocument = { val uri: URI = TestResourceUtil.convertClasspathUriToAbsoluteUri(relativeFilePath) val docBuilder = SaxonDocumentBuilder(processor, SaxUriResolvers.fromUriConverter(UriConverters.identity)) docBuilder.build(uri) } def buildTaxonomyFromClasspath(entrypointUri: URI, localRootUriRelativeToClasspathRoot: URI, processor: Processor): BasicTaxonomy = { buildTaxonomyFromClasspath(Set(entrypointUri), localRootUriRelativeToClasspathRoot, processor) } def buildTaxonomyFromClasspath( urisOfEntrypoint: Set[URI], localRootUriRelativeToClasspathRoot: URI, processor: Processor): BasicTaxonomy = { require(!localRootUriRelativeToClasspathRoot.isAbsolute) require(localRootUriRelativeToClasspathRoot.toString.endsWith("/")) val localRootDir: File = new File(convertClasspathUriToAbsoluteUri(localRootUriRelativeToClasspathRoot)) val uriResolver: URI => SaxInputSource = SaxUriResolvers.fromLocalMirrorRootDirectoryWithoutScheme(localRootDir) val docBuilder: DocumentBuilder = SaxonDocumentBuilder(processor, uriResolver) DefaultTaxonomyBuilder .withDocumentBuilder(docBuilder) .withDtsUriCollector(DefaultDtsUriCollector) .withDefaultRelationshipFactory .build(urisOfEntrypoint) } }
chuckwondo/iter-tools
src/impls/$includes-seq/async-includes-seq.js
/** * @generated-from ./$includes-seq.js * This file is autogenerated from a template. Please do not edit it directly. * To rebuild it from its template use the command * > npm run generate * More information can be found in CONTRIBUTING.md */ import { asyncIterableCurry, asyncEnsureIterable } from '../../internal/async-iterable.js'; import { __asyncIncludesAnySeq } from '../$includes-any-seq/async-includes-any-seq.js'; export function __asyncIncludesSeq(iterable, seq, same = Object.is) { return __asyncIncludesAnySeq(iterable, [seq], same); } export const asyncIncludesSeq = /*#__PURE__*/ asyncIterableCurry(__asyncIncludesSeq, { minArgs: 1, maxArgs: 2, reduces: true, validateArgs(args) { args[1] = asyncEnsureIterable(args[1]); }, });
KoizumiSinya/DemoProject
Widgets/SlidingMenuDelete/src/main/java/sap_mobile_newapi/demo_slidingmenudelete/SecondActivity.java
package sap_mobile_newapi.demo_slidingmenudelete; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import sap_mobile_newapi.demo_slidingmenudelete.widget.MySlidingMenu; public class SecondActivity extends Activity { private MySlidingMenu slidingMenu; private RelativeLayout contentLayout; private TextView delete; private View txt_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.menu_delete); slidingMenu = (MySlidingMenu) findViewById(R.id.sliding_layout); contentLayout = (RelativeLayout) findViewById(R.id.content_layout); txt_content = findViewById(R.id.txt_content); delete = (TextView) findViewById(R.id.delete); slidingMenu.setScrollEvent(txt_content); contentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (slidingMenu.isRightLayoutVisible()) { Log.i("Sinya", "归位"); slidingMenu.scrollToRightLayout(); } } }); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(SecondActivity.this, "删除", Toast.LENGTH_SHORT).show(); } }); } }
todotresde/microservices
server-app2/src/main/java/com/todotresde/myapp/app2/repository/package-info.java
/** * Spring Data JPA repositories. */ package com.todotresde.myapp.app2.repository;
rnedit/workflow
src/main/java/kz/spring/workflow/service/DAL/UserService.java
<gh_stars>0 package kz.spring.workflow.service.DAL; import kz.spring.workflow.domain.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; import java.util.Set; public interface UserService { Optional<User> findByUsername(String username); void save(User user); void delete(User user); Page<User> findAll(Pageable pageable); User getByUsername(String username); User getById(String id); User getByRefreshJwt(String username); Boolean existsByUsername(String username); Boolean existsByEmail(String email); Optional<User> findById(String id); Set<User> getUsersByParentIdProfileIsNull(); }
rui278/rui278.github.io
hevc/loopfilter_8h.js
var loopfilter_8h = [ [ "x265_saoCuOrgE0_sse4", "loopfilter_8h.html#ac15eed7eebf32159c0a6d8a166ee2ab9", null ] ];
warelab/sciapps
agavedancer/public/javascripts/components/appsItem.js
<reponame>warelab/sciapps 'use strict'; import React from 'react'; import AppsActions from '../actions/appsActions.js'; import DsActions from '../actions/dsActions.js'; import {ListGroupItem} from 'react-bootstrap'; const AppsItem=React.createClass({ /* ### Description loading apps form in main panel */ showApp: function() { AppsActions.showApp(this.props.data.id, 'default'); let title=this.props.data.id; let urlbase="?app_id="; let url=urlbase.concat(title); if (typeof (history.pushState) !== "undefined") { let obj = { Title: title, Url: url }; history.pushState(obj, obj.Title, obj.Url); } else { alert("Browser does not support HTML5."); } }, render: function() { return ( <ListGroupItem onClick={this.showApp}> {this.props.data.id} </ListGroupItem> ); } }); module.exports= AppsItem;
s0/hid_api
api/services/GSSSyncService.js
const fs = require('fs'); const { OAuth2Client } = require('google-auth-library'); const { google } = require('googleapis'); const Boom = require('@hapi/boom'); const GSSSync = require('../models/GSSSync'); const List = require('../models/List'); const User = require('../models/User'); const config = require('../../config/env')[process.env.NODE_ENV]; const { logger } = config; /** * @module GSSSyncService * @description GSSSync Service */ function getRowFromUser(elt) { const organization = elt.organization ? elt.organization.name : ''; let country = ''; let region = ''; let skype = ''; let bundles = ''; let roles = ''; if (elt.location && elt.location.country) { country = elt.location.country.name; } if (elt.location && elt.location.region) { region = elt.location.region.name; } if (elt.voips && elt.voips.length) { elt.voips.forEach((voip) => { if (voip.type === 'Skype') { skype = voip.username; } }); } if (elt.bundles && elt.bundles.length) { elt.bundles.forEach((bundle) => { bundles += `${bundle.name};`; }); } if (elt.functional_roles && elt.functional_roles.length) { elt.functional_roles.forEach((role) => { roles += `${role.name};`; }); } return [ elt._id, elt.given_name, elt.family_name, elt.job_title, organization, bundles, roles, country, region, elt.phone_number, skype, elt.email, elt.status, ]; } function getAuthClient(user) { // Authenticate with Google const creds = JSON.parse(fs.readFileSync('keys/client_secrets.json')); const authClient = new OAuth2Client(creds.web.client_id, creds.web.client_secret, '<PASSWORD>'); authClient.setCredentials(user.googleCredentials); return authClient; } async function writeUser(gsssync, authClient, user, index) { const sheets = google.sheets('v4'); const values = getRowFromUser(user); const body = { values: [values], }; try { await sheets.spreadsheets.values.update({ spreadsheetId: gsssync.spreadsheet, range: `A${index}:M${index}`, valueInputOption: 'RAW', resource: body, auth: authClient, }); logger.info( `[GSSSyncService->writeUser] Successfully wrote user ${user._id} in ${gsssync.spreadsheet}`, ); } catch (err) { logger.error( `[GSSSyncService->writeUser] Error writing user to spreadsheet ${gsssync.spreadsheet}`, { error: err }, ); if (err.code === 404 || err.code === 403) { // Spreadsheet has been deleted, remove the synchronization gsssync.remove(); } } } /** * Add a user to a spreadsheet */ async function addUser(agsssync, user) { const sheets = google.sheets('v4'); const gsssync = await agsssync .populate('list user') .execPopulate(); const authClient = agsssync.getAuthClient(); // Find users const criteria = gsssync.getUserCriteria(); if (Object.keys(criteria).length === 0) { logger.warn( '[GSSSyncService->addUser] User is not authorized to view this list', ); throw Boom.unauthorized('You are not authorized to view this list'); } const users = await User .find(criteria) .select(GSSSync.getUserAttributes()) .sort('name') .lean(); try { const column = await sheets.spreadsheets.values.get({ spreadsheetId: gsssync.spreadsheet, range: 'A:A', auth: authClient, }); if (!column || !column.data || !column.data.values) { logger.warn( `[GSSSyncService->addUser] column or column.data.values is undefined on spreadsheet ${gsssync.spreadsheet}`, ); throw Boom.badImplementation(`column or column.data.values is undefined on spreadsheet ${gsssync.spreadsheet}`); } let row = 1; let index = 0; users.forEach((tmpUser) => { if (row >= column.data.values.length) { index = row; } else if (column.data.values[row][0] !== tmpUser._id.toString() && index === 0) { index = row; } row += 1; }); if (index !== 0) { const body = { requests: [{ insertDimension: { range: { sheetId: gsssync.sheetId, dimension: 'ROWS', startIndex: index, endIndex: index + 1, }, }, }], }; await sheets.spreadsheets.batchUpdate({ spreadsheetId: gsssync.spreadsheet, resource: body, auth: authClient, }); logger.info( `[GSSSyncService->addUser] Successfully updated spreadsheet ${gsssync.spreadsheet}`, ); const writeIndex = index + 1; await writeUser(gsssync, authClient, user, writeIndex); } else { logger.warn( `[GSSSyncService->addUser] Could not add user ${user._id} to spreadsheet ${gsssync.spreadsheet}`, ); throw Boom.badRequest('Could not add user'); } } catch (err) { logger.error( `[GSSSyncService->writeUser] Error adding user to spreadsheet ${gsssync.spreadsheet}`, { error: err }, ); if (err.code === 404 || err.code === 403) { // Spreadsheet has been deleted, remove the synchronization gsssync.remove(); } } } async function deleteUser(agsssync, hid) { const sheets = google.sheets('v4'); const gsssync = await agsssync .populate('list user') .execPopulate(); const authClient = agsssync.getAuthClient(); try { const column = await sheets.spreadsheets.values.get({ spreadsheetId: gsssync.spreadsheet, range: 'A:A', auth: authClient, }); if (!column || !column.data || !column.data.values) { logger.warn( `[GSSSyncService->deleteUser] column or column.data.values is undefined on spreadsheet ${gsssync.spreadsheet}`, ); throw Boom.badImplementation(`column or column.values is undefined on spreadsheet ${gsssync.spreadsheet}`); } let row = 0; let index = 0; column.data.values.forEach((elt) => { if (elt[0] === hid) { index = row; } row += 1; }); if (index !== 0) { const body = { requests: [{ deleteDimension: { range: { sheetId: gsssync.sheetId, dimension: 'ROWS', startIndex: index, endIndex: index + 1, }, }, }], }; await sheets.spreadsheets.batchUpdate({ spreadsheetId: gsssync.spreadsheet, resource: body, auth: authClient, }); logger.info( `[GSSSyncService->deleteUser] Successfully updated spreadsheet ${gsssync.spreadsheet}`, ); } else { logger.warn( `[GSSSyncService->deleteUser] Could not find user ${hid} in spreadsheet ${gsssync.spreadsheet}`, ); throw Boom.badRequest('Could not find user'); } } catch (err) { logger.error( `[GSSSyncService->deleteUser] Error removing user from spreadsheet ${gsssync.spreadsheet}`, { error: err }, ); if (err.code === 404 || err.code === 403) { // Spreadsheet has been deleted, remove the synchronization gsssync.remove(); } } } async function updateUser(agsssync, user) { const sheets = google.sheets('v4'); const gsssync = await agsssync .populate('list user') .execPopulate(); const authClient = agsssync.getAuthClient(); try { const column = await sheets.spreadsheets.values.get({ spreadsheetId: gsssync.spreadsheet, range: 'A:A', auth: authClient, }); if (!column || !column.data || !column.data.values) { logger.warn( `[GSSSyncService->updateUser] column or column.data.values is undefined on spreadsheet ${gsssync.spreadsheet}`, ); throw new Error(`column or column.values is undefined on spreadsheet ${gsssync.spreadsheet}`); } let row = 0; let index = 0; column.data.values.forEach((elt) => { if (elt[0] === user._id.toString()) { index = row + 1; } row += 1; }); if (index !== 0) { await writeUser(gsssync, authClient, user, index); } else { logger.warn( `[GSSSyncService->updateUser] Could not find user ${user._id} in spreadsheet ${gsssync.spreadsheet}`, ); throw new Error(`Could not find user ${user._id.toString()} for spreadsheet ${gsssync.spreadsheet}`); } } catch (err) { logger.error( `[GSSSyncService->updateUser] Error updating user in spreadsheet ${gsssync.spreadsheet}`, { error: err }, ); if (err.code === 404 || err.code === 403) { // Spreadsheet has been deleted, remove the synchronization gsssync.remove(); } } } module.exports = { async addUserToSpreadsheets(listId, user) { const gsssyncs = await GSSSync.find({ list: listId }); const actions = gsssyncs.map(async (gsssync) => { await addUser(gsssync, user); }); return Promise.all(actions); }, async deleteUserFromSpreadsheets(listId, hid) { const gsssyncs = await GSSSync.find({ list: listId }); const actions = gsssyncs.map(async (gsssync) => { await deleteUser(gsssync, hid); }); return Promise.all(actions); }, async synchronizeUser(user) { // Get all lists from user const listIds = user.getListIds(); // Find the gsssyncs associated to the lists const gsssyncs = await GSSSync.find({ list: { $in: listIds } }); // For each gsssync, call updateUser const actions = gsssyncs.map(async (gsssync) => { await updateUser(gsssync, user); }); return Promise.all(actions); }, async createSpreadsheet(user, listId) { const list = await List.findOne({ _id: listId }); if (!list) { logger.warn( `[GSSSyncService->createSpreadsheet] Could not find list ${listId}`, ); throw new Error('List not found'); } const authClient = getAuthClient(user); const sheets = google.sheets('v4'); const request = { resource: { properties: { title: list.name, }, sheets: [{ properties: { gridProperties: { rowCount: 10000, }, }, }], }, auth: authClient, }; const response = await sheets.spreadsheets.create(request); logger.info( '[GSSSyncService->createSpreadsheet] Successfully created spreadsheet', ); return response; }, async getSheetId(agsssync) { const gsssync = await agsssync.populate('user').execPopulate(); const authClient = agsssync.getAuthClient(); const sheets = google.sheets('v4'); const sheet = await sheets.spreadsheets.get({ spreadsheetId: gsssync.spreadsheet, auth: authClient, }); if (sheet) { return sheet.sheets[0].properties.sheetId; } return ''; }, async synchronizeAll(agsssync) { const headers = GSSSync.getSpreadsheetHeaders(); const gsssync = await agsssync.populate('list user').execPopulate(); const authClient = agsssync.getAuthClient(); const criteria = gsssync.getUserCriteria(); if (Object.keys(criteria).length === 0) { logger.warn( '[GSSSyncService->synchronizeAll] User is not authorized to view this list', ); throw Boom.unauthorized('You are not authorized to view this list'); } const users = await User .find(criteria) .select(GSSSync.getUserAttributes()) .sort('name') .lean(); // Export users to spreadsheet const data = []; let index = 2; let row = []; data.push({ range: 'A1:M1', values: [headers], }); users.forEach((elt) => { row = getRowFromUser(elt); data.push({ range: `A${index}:M${index}`, values: [row], }); index += 1; }); const body = { data, valueInputOption: 'RAW', }; const sheets = google.sheets('v4'); return sheets.spreadsheets.values.batchUpdate({ spreadsheetId: gsssync.spreadsheet, resource: body, auth: authClient, }); }, };
jikanghz/jianli
code/server/sys/src/main/java/com/jianli/sys/workflow/dao/WorkflowActivityDao.java
package com.jianli.sys.workflow.dao; import com.jianli.sys.workflow.domain.WorkflowActivity; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; import java.util.LinkedHashMap; import java.util.List; public interface WorkflowActivityDao extends Mapper<WorkflowActivity>, MySqlMapper<WorkflowActivity> { @Select("SELECT * FROM workflow_activity WHERE instanceId = #{instanceId} AND flowId = #{flowId} AND id <> #{id} AND deleted = 0 ORDER BY id") public List<WorkflowActivity> listOtherActivity(@Param("instanceId") Long instanceId, @Param("flowId") Long flowId, @Param("id") Long id); @Select("SELECT * FROM workflow_activity WHERE instanceId = #{instanceId} AND deleted = 0 ORDER BY id DESC") public List<WorkflowActivity> list(@Param("instanceId") Long instanceId); @Select("SELECT workflow_activity.id, workflow_step.stepName, workflow_step.stepType, workflow_step.countersign, workflow_activity.createTime, sys_user.userName AS activityUser, workflow_activity.status, workflow_activity.remark,workflow_activity.fromStepId, workflow_activity.stepId FROM workflow_activity LEFT JOIN workflow_step ON workflow_step.id = workflow_activity.stepId LEFT JOIN sys_user ON sys_user.id = workflow_activity.userId WHERE instanceId = (SELECT id FROM workflow_instance WHERE entityId = #{entityId} AND workflowId = (SELECT id FROM workflow WHERE workflowName = #{workflowName} ORDER BY id DESC limit 1)) ORDER BY workflow_activity.flowId DESC, workflow_activity.status ASC") public List<LinkedHashMap<String, Object>> listActivity(@Param("entityId") Long entityId, @Param("workflowName") String workflowName); @Select("SELECT id FROM sys_user WHERE id IN (SELECT userId FROM sys_user_role WHERE roleId = #{roleId}) ORDER BY id") public List<Long> listUserIds(@Param("roleId") Long roleId); @Select("SELECT id FROM sys_user WHERE id IN (SELECT userId FROM sys_user_role WHERE roleId = #{roleId}) AND orgId IN (${orgIds}) ORDER BY id") public List<Long> listOrgUserIds(@Param("roleId") Long roleId, @Param("orgIds") String orgIds); }
ByteHamster/silt
fawnds/fawnds_partition.cc
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "fawnds_partition.h" #include "fawnds_factory.h" #include "debug.h" #include "bit_access.hpp" #include <sstream> namespace fawn { FawnDS_Partition::FawnDS_Partition() { } FawnDS_Partition::~FawnDS_Partition() { Close(); } FawnDS_Return FawnDS_Partition::Create() { if (stores_.size()) return ERROR; alloc_stores(); for (size_t i = 0; i < partitions_; i++) { if (stores_[i]->Create() != OK) { return ERROR; } } return OK; } FawnDS_Return FawnDS_Partition::Open() { if (stores_.size()) return ERROR; alloc_stores(); for (size_t i = 0; i < partitions_; i++) { if (stores_[i]->Open() != OK) { return ERROR; } } return OK; } FawnDS_Return FawnDS_Partition::Flush() { if (!stores_.size()) return ERROR; for (std::vector<FawnDS*>::iterator it = stores_.begin(); it != stores_.end(); ++it) { FawnDS_Return ret = (*it)->Flush(); if (ret != OK) return ret; } return OK; } FawnDS_Return FawnDS_Partition::Close() { if (!stores_.size()) return ERROR; for (std::vector<FawnDS*>::iterator it = stores_.begin(); it != stores_.end(); ++it) { if (*it) { FawnDS_Return ret = (*it)->Close(); if (ret != OK) return ret; delete *it; *it = NULL; } } stores_.clear(); return OK; } FawnDS_Return FawnDS_Partition::Destroy() { for (size_t i = 0; i < partitions_; i++) { Configuration* storeConfig = new Configuration(config_, true); storeConfig->SetContextNode("child::store"); char buf[1024]; snprintf(buf, sizeof(buf), "%s_%zu", config_->GetStringValue("child::id").c_str(), i); storeConfig->SetStringValue("child::id", buf); FawnDS* store = FawnDS_Factory::New(storeConfig); if (!store) { delete storeConfig; return ERROR; } store->Destroy(); delete store; } return OK; } FawnDS_Return FawnDS_Partition::Status(const FawnDS_StatusType& type, Value& status) const { std::ostringstream oss; switch (type) { case NUM_DATA: case NUM_ACTIVE_DATA: case CAPACITY: case MEMORY_USE: case DISK_USE: { bool first = true; Value status_part; oss << '['; for (std::vector<FawnDS*>::const_iterator it = stores_.begin(); it != stores_.end(); ++it) { if (first) first = false; else oss << ','; FawnDS_Return ret = (*it)->Status(type, status_part); if (ret != OK) return UNSUPPORTED; oss << status_part.str(); } oss << ']'; } break; default: return UNSUPPORTED; } status = NewValue(oss.str()); return OK; } FawnDS_Return FawnDS_Partition::Put(const ConstValue& key, const ConstValue& data) { if (!stores_.size()) return ERROR; size_t p = get_partition(key); return stores_[p]->Put(key, data); } FawnDS_Return FawnDS_Partition::Append(Value& key, const ConstValue& data) { if (!stores_.size()) return ERROR; size_t p = get_partition(key); return stores_[p]->Append(key, data); } FawnDS_Return FawnDS_Partition::Delete(const ConstValue& key) { if (!stores_.size()) return ERROR; size_t p = get_partition(key); return stores_[p]->Delete(key); } FawnDS_Return FawnDS_Partition::Contains(const ConstValue& key) const { if (!stores_.size()) return ERROR; size_t p = get_partition(key); return stores_[p]->Contains(key); } FawnDS_Return FawnDS_Partition::Length(const ConstValue& key, size_t& len) const { if (!stores_.size()) return ERROR; size_t p = get_partition(key); return stores_[p]->Length(key, len); } FawnDS_Return FawnDS_Partition::Get(const ConstValue& key, Value& data, size_t offset, size_t len) const { if (!stores_.size()) return ERROR; size_t p = get_partition(key); return stores_[p]->Get(key, data, offset, len); } FawnDS_ConstIterator FawnDS_Partition::Enumerate() const { IteratorElem* elem = new IteratorElem(this); elem->next_store = 0; elem->Next(); return FawnDS_ConstIterator(elem); } FawnDS_Iterator FawnDS_Partition::Enumerate() { IteratorElem* elem = new IteratorElem(this); elem->next_store = 0; elem->Next(); return FawnDS_Iterator(elem); } FawnDS_ConstIterator FawnDS_Partition::Find(const ConstValue& key) const { if (!stores_.size()) return FawnDS_ConstIterator(); size_t p = get_partition(key); return stores_[p]->Find(key); } FawnDS_Iterator FawnDS_Partition::Find(const ConstValue& key) { if (!stores_.size()) return FawnDS_Iterator(); size_t p = get_partition(key); return stores_[p]->Find(key); } FawnDS_Return FawnDS_Partition::alloc_stores() { skip_bits_ = atoi(config_->GetStringValue("child::skip_bits").c_str()); partitions_ = atoi(config_->GetStringValue("child::partitions").c_str()); partition_bits_ = 0; while ((1u << partition_bits_) < partitions_) partition_bits_++; if (partitions_ == 0) { DPRINTF(2, "FawnDS_Partition::alloc_stores(): non-zero partitions required\n"); return ERROR; } if ((1u << partition_bits_) != partitions_) { DPRINTF(2, "FawnDS_Partition::alloc_stores(): # of partitions should be power of 2\n"); return ERROR; } for (size_t i = 0; i < partitions_; i++) { Configuration* storeConfig = new Configuration(config_, true); storeConfig->SetContextNode("child::store"); char buf[1024]; snprintf(buf, sizeof(buf), "%s_%zu", config_->GetStringValue("child::id").c_str(), i); storeConfig->SetStringValue("child::id", buf); FawnDS* store = FawnDS_Factory::New(storeConfig); if (!store) { delete storeConfig; return ERROR; } stores_.push_back(store); } return OK; } size_t FawnDS_Partition::get_partition(const ConstValue& key) const { std::size_t bits = 0; std::size_t index = 0; while (bits < partition_bits_) { index <<= 1; if ((skip_bits_ + bits) / 8 > key.size()) { // too short key assert(false); break; } if (cindex::bit_access::get(reinterpret_cast<const uint8_t*>(key.data()), skip_bits_ + bits)) index |= 1; bits++; } return index; } FawnDS_Partition::IteratorElem::IteratorElem(const FawnDS_Partition* fawnds) { this->fawnds = fawnds; } FawnDS_Partition::IteratorElem::~IteratorElem() { } FawnDS_IteratorElem* FawnDS_Partition::IteratorElem::Clone() const { IteratorElem* elem = new IteratorElem(static_cast<const FawnDS_Partition*>(fawnds)); *elem = *this; return elem; } void FawnDS_Partition::IteratorElem::Next() { const FawnDS_Partition* fawnds_part = static_cast<const FawnDS_Partition*>(fawnds); if (!store_it.IsEnd()) ++store_it; while (store_it.IsEnd()) { if (next_store >= fawnds_part->stores_.size()) { state = END; return; } store_it = fawnds_part->stores_[next_store++]->Enumerate(); } state = store_it->state; key = store_it->key; data = store_it->data; } } // namespace fawn
mankeyl/elasticsearch
plugins/analysis-icu/src/main/java/org/elasticsearch/plugin/analysis/icu/IcuFoldingTokenFilterFactory.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.plugin.analysis.icu; import com.ibm.icu.text.Normalizer2; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.icu.ICUFoldingFilter; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.analysis.AbstractTokenFilterFactory; import org.elasticsearch.index.analysis.NormalizingTokenFilterFactory; /** * Uses the {@link org.apache.lucene.analysis.icu.ICUFoldingFilter}. * Applies foldings from UTR#30 Character Foldings. * <p> * Can be filtered to handle certain characters in a specified way * (see http://icu-project.org/apiref/icu4j/com/ibm/icu/text/UnicodeSet.html) * E.g national chars that should be retained (filter : "[^åäöÅÄÖ]"). * * <p>The {@code unicodeSetFilter} attribute can be used to provide the * UniCodeSet for filtering. * * @author kimchy (shay.banon) */ public class IcuFoldingTokenFilterFactory extends AbstractTokenFilterFactory implements NormalizingTokenFilterFactory { /** Store here the same Normalizer used by the lucene ICUFoldingFilter */ private static final Normalizer2 ICU_FOLDING_NORMALIZER = Normalizer2.getInstance( ICUFoldingFilter.class.getResourceAsStream("utr30.nrm"), "utr30", Normalizer2.Mode.COMPOSE ); private final Normalizer2 normalizer; public IcuFoldingTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) { super(indexSettings, name, settings); this.normalizer = IcuNormalizerTokenFilterFactory.wrapWithUnicodeSetFilter(indexSettings, ICU_FOLDING_NORMALIZER, settings); } @Override public TokenStream create(TokenStream tokenStream) { return new org.apache.lucene.analysis.icu.ICUNormalizer2Filter(tokenStream, normalizer); } }
kenichiro-kimura/diagrams
diagrams/openstack/optimization.py
<reponame>kenichiro-kimura/diagrams # This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OpenStack class _Optimization(_OpenStack): _type = "optimization" _icon_dir = "resources/openstack/optimization" class Congress(_Optimization): _icon = "congress.png" class Rally(_Optimization): _icon = "rally.png" class Vitrage(_Optimization): _icon = "vitrage.png" class Watcher(_Optimization): _icon = "watcher.png" # Aliases
mkimartinez/Lyfey
init_db_data.py
<filename>init_db_data.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Slackers.settings') import django django.setup() import json import argparse import random import datetime import codecs import os.path as op from library.models import Book, Reader, Borrowing from django.contrib.auth.models import User from faker import Factory fake = Factory.create('zh_CN') def init_reader_data(amount=50): for i in range(amount): u = User.objects.get_or_create(username=fake.phone_number())[0] u.set_password('password') u.save() r = Reader.objects.get_or_create(user=u, name=fake.name(), phone=int(u.username))[0] r.balance = round(random.random() * 100, 2) r.photo = 'images/' + str(r.user_id) + '.jpg' r.save() def init_book_data(): with codecs.open('books.json', 'r', 'utf-8') as f: books = [json.loads(l) for l in f.readlines()] for b in books: if 'description' in b and b['description']: print(b) B = Book.objects.get_or_create(ISBN=b['ISBN'], title=b['title'], author=b['author'], press=b['press'])[0] B.description = b['description'] B.price = b['price'] B.cover = b['cover'] B.quantity = random.randint(0, 7) B.save() def init_borrowing_data(amount=50): for i in range(amount): reader = random.choice(Reader.objects.all()) isbn = random.choice(Book.objects.all()) issued = datetime.date.today() + datetime.timedelta(random.randint(1, 30)) due_to_returned = issued + datetime.timedelta(30) date_returned = issued + datetime.timedelta(random.randint(1, 40)) returned_flag = True if random.randint(1, 100) % 2 == 0: returned_flag = False if returned_flag: if (date_returned - issued).days > 30: fine = ((date_returned - issued).days - 30) * 0.1 else: fine = 0 b = Borrowing.objects.create( reader=reader, ISBN=isbn, date_issued=issued, date_due_to_returned=due_to_returned, date_returned=date_returned, amount_of_fine=fine, ) b.save() else: if reader.max_borrowing > 0 and isbn.quantity > 0: b = Borrowing.objects.create( reader=reader, ISBN=isbn, date_issued=issued, date_due_to_returned=due_to_returned ) reader.max_borrowing -= 1 isbn.quantity -= 1 reader.save() isbn.save() b.save() if __name__ == '__main__': init_book_data() parser = argparse.ArgumentParser() parser.add_argument("data", help=u"你要生成的数据") args = parser.parse_args() if args.data == 'all': init_reader_data() init_book_data() elif args.data == 'book': init_book_data() elif args.data == 'reader': init_reader_data() elif args.data == 'borrowing': init_borrowing_data()
gabrielrussoc/devbox
devbox/common/src/Cli.scala
package devbox.common import scala.annotation.tailrec object Cli{ /** * Additional [[scopt.Read]] instance to teach it how to read Ammonite paths */ implicit def pathScoptRead: scopt.Read[os.Path] = scopt.Read.stringRead.map(os.Path(_, os.pwd)) case class Arg[T, V](name: String, shortName: Option[Char], doc: String, action: (T, V) => T) (implicit val reader: scopt.Read[V]){ def runAction(t: T, s: String) = action(t, reader.reads(s)) } def showArg(arg: Arg[_, _]) = " " + arg.shortName.fold("")("-" + _ + ", ") + "--" + arg.name def formatBlock(args: Seq[Arg[_, _]], leftMargin: Int) = { for(arg <- args) yield { showArg(arg).padTo(leftMargin, ' ').mkString + Predef.augmentString(arg.doc).lines.mkString("\n" + " " * leftMargin) } } def groupArgs[T](flatArgs: List[String], args: Seq[Arg[T, _]], initial: T): Either[String, (T, List[String])] = { val argsMap0: Seq[(String, Arg[T, _])] = args .flatMap{x => Seq(x.name -> x) ++ x.shortName.map(_.toString -> x)} val argsMap = argsMap0.toMap @tailrec def rec(keywordTokens: List[String], current: T): Either[String, (T, List[String])] = { keywordTokens match{ case head :: rest if head(0) == '-' => val realName = if(head(1) == '-') head.drop(2) else head.drop(1) argsMap.get(realName) match { case Some(cliArg) => if (cliArg.reader == scopt.Read.unitRead) { rec(rest, cliArg.runAction(current, "")) } else rest match{ case next :: rest2 => rec(rest2, cliArg.runAction(current, next)) case Nil => Left(s"Expected a value after argument $head") } case None => Right((current, keywordTokens)) } case _ => Right((current, keywordTokens)) } } rec(flatArgs, initial) } def groupArgs2[T, V](flatArgs: List[String], args1: Seq[Arg[T, _]], initial1: T, args2: Seq[Arg[V, _]], initial2: V): Either[String, (T, V, List[String])] = { val argsMap1: Map[String, Arg[T, _]] = args1 .flatMap{x => Seq(x.name -> x) ++ x.shortName.map(_.toString -> x)} .toMap val argsMap2: Map[String, Arg[V, _]] = args2 .flatMap{x => Seq(x.name -> x) ++ x.shortName.map(_.toString -> x)} .toMap @tailrec def rec(keywordTokens: List[String], current1: T, current2: V): Either[String, (T, V, List[String])] = { keywordTokens match{ case head :: rest if head(0) == '-' => val realName = if(head(1) == '-') head.drop(2) else head.drop(1) (argsMap1.get(realName), argsMap2.get(realName)) match { case (Some(cliArg), None) => if (cliArg.reader == scopt.Read.unitRead) { rec(rest, cliArg.runAction(current1, ""), current2) } else rest match{ case next :: rest2 => rec(rest2, cliArg.runAction(current1, next), current2) case Nil => Left(s"Expected a value after argument $head") } case (None, Some(cliArg)) => if (cliArg.reader == scopt.Read.unitRead) { rec(rest, current1, cliArg.runAction(current2, "")) } else rest match{ case next :: rest2 => rec(rest2, current1, cliArg.runAction(current2, next)) case Nil => Left(s"Expected a value after argument $head") } case (None, None) => Right((current1, current2, keywordTokens)) case (Some(a1), Some(a2)) => throw new Exception("Ambiguous argument: " + realName) } case _ => Right((current1, current2, keywordTokens)) } } rec(flatArgs, initial1, initial2) } }
so931/poseidonos
test/unit-tests/journal_manager/replay/replay_volume_deletion_mock.h
<filename>test/unit-tests/journal_manager/replay/replay_volume_deletion_mock.h #include <gmock/gmock.h> #include <string> #include <list> #include <vector> #include "src/journal_manager/replay/replay_volume_deletion.h" namespace pos { class MockReplayVolumeDeletion : public ReplayVolumeDeletion { public: using ReplayVolumeDeletion::ReplayVolumeDeletion; MOCK_METHOD(int, Start, (), (override)); MOCK_METHOD(ReplayTaskId, GetId, (), (override)); MOCK_METHOD(int, GetWeight, (), (override)); MOCK_METHOD(int, GetNumSubTasks, (), (override)); }; } // namespace pos
lrog/gate-nlp-service
service/src/test/java/nlp/service/controller/ServiceControllerTests.java
<gh_stars>0 package nlp.service.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.databind.ObjectMapper; import nlp.common.model.protocol.NlpProcessingResult; import nlp.common.model.protocol.ServiceBulkResponseContent; import nlp.common.model.annotation.GenericAnnotation; import nlp.common.model.document.GenericDocument; import nlp.common.model.protocol.ServiceSingleResponseContent; import nlp.service.utils.TestUtils; /** * This class implements tests for testing the functionality of an example REST Service * controller for extracting annotations from example documents. * For the moment, only GATE controller is used and the example GATE application includes * a simple Drug application identifying common drug names. */ public abstract class ServiceControllerTests { @Autowired private MockMvc mockMvc; final private String PROCESS_ENDPOINT_URL = "/api/process"; final private String PROCESS_BULK_ENDPOINT_URL = "/api/process_bulk"; final private String INFO_ENDPOINT_URL = "/api/info"; @Test public void testGetApplicationInfo() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders .get(INFO_ENDPOINT_URL) .accept(MediaType.APPLICATION_JSON_UTF8)) .andReturn(); int status = result.getResponse().getStatus(); assertEquals(HttpStatus.OK.value(), status, "Incorrect Response Status"); } /** * Test empty or blank documents, one document at time. */ @Test public void testProcessEmptyPayload() throws Exception { GenericDocument inDoc = TestUtils.createEmptyDocument(); MvcResult result = mockMvc.perform(MockMvcRequestBuilders .post(PROCESS_ENDPOINT_URL) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .content(createPayload(inDoc))) .andReturn(); int status = result.getResponse().getStatus(); assertEquals(HttpStatus.BAD_REQUEST.value(), status, "Incorrect Response Status"); } @Test public void testProcessBlankDocuments() throws Exception { List<GenericDocument> inDocs = TestUtils.createBlankDocuments(); for (GenericDocument doc : inDocs) { MvcResult result = mockMvc.perform(MockMvcRequestBuilders .post(PROCESS_ENDPOINT_URL) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .content(createPayload(doc))) .andReturn(); int status = result.getResponse().getStatus(); assertEquals(HttpStatus.OK.value(), status, "Incorrect Response Status"); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); ServiceSingleResponseContent response = mapper.readValue(result.getResponse().getContentAsString(), ServiceSingleResponseContent.class); // check the processing status assertEquals(true, response.getResult().getSuccess(), "Invalid processing status"); // check whether there were any annotations returned assertEquals(0, response.getResult().getAnnotations().size(), "Returned annotations"); } } /** * Test example documents, one document at time. */ @Test public void testProcessExampleDocumentDrugNames() throws Exception { GenericDocument inDoc = TestUtils.createShortDocument(); MvcResult result = mockMvc.perform(MockMvcRequestBuilders .post(PROCESS_ENDPOINT_URL) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .content(createPayload(inDoc))) .andReturn(); int status = result.getResponse().getStatus(); assertEquals(HttpStatus.OK.value(), status, "Incorrect Response Status"); // parse the content ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); ServiceSingleResponseContent response = mapper.readValue(result.getResponse().getContentAsString(), ServiceSingleResponseContent.class); assertEquals(true, response.getResult().getSuccess(), "Invalid processing status"); // should be only one annotation returned List<GenericAnnotation> annotations = response.getResult().getAnnotations(); assertEquals(1, annotations.size(), "Returned annotations"); // this annotation should be Prozac and listed as drug:medication GenericAnnotation ann = annotations.get(0); assertEquals("prozac", ann.getAttributes().get("name").toString().toLowerCase()); assertEquals("drug", ann.getAttributes().get("majorType").toString().toLowerCase()); assertEquals("medication", ann.getAttributes().get("minorType").toString().toLowerCase()); } @Test public void testProcessACMDDocumentDrugNames() throws Exception { GenericDocument inDoc = TestUtils.createACMDocument(); MvcResult result = mockMvc.perform(MockMvcRequestBuilders .post(PROCESS_ENDPOINT_URL) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .content(createPayload(inDoc))) .andReturn(); int status = result.getResponse().getStatus(); assertEquals(HttpStatus.OK.value(), status, "Incorrect Response Status"); // parse the content ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); ServiceSingleResponseContent response = mapper.readValue(result.getResponse().getContentAsString(), ServiceSingleResponseContent.class); assertEquals(true, response.getResult().getSuccess(), "Invalid processing status"); assertNotEquals(0, response.getResult().getAnnotations(), "Returned annotations"); } /** * Process empty or blank documents in bulk. */ @Test public void testProcessBlankDocumentsBulk() throws Exception { List<GenericDocument> inDocs = TestUtils.createBlankDocuments(); MvcResult result = mockMvc.perform(MockMvcRequestBuilders .post(PROCESS_BULK_ENDPOINT_URL) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .content(createPayloadBulk(inDocs))) .andReturn(); int status = result.getResponse().getStatus(); assertEquals(HttpStatus.OK.value(), status, "Incorrect Response Status"); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); ServiceBulkResponseContent response = mapper.readValue(result.getResponse().getContentAsString(), ServiceBulkResponseContent.class); // check the processing status for (NlpProcessingResult res : response.getResult()) { assertEquals(true, res.getSuccess(), "Invalid processing status"); // check whether there were any annotations returned assertEquals(0, res.getAnnotations().size(), "Returned annotations"); } } /** * Process valid documents in bulk mode */ @Test public void processExampleDocumentsBulk() throws Exception { List<GenericDocument> inDocs = new ArrayList<>(); inDocs.add(TestUtils.createShortDocument()); inDocs.add(TestUtils.createACMDocument()); MvcResult result = mockMvc.perform(MockMvcRequestBuilders .post(PROCESS_BULK_ENDPOINT_URL) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .content(createPayloadBulk(inDocs))) .andReturn(); int status = result.getResponse().getStatus(); assertEquals(HttpStatus.OK.value(), status, "Incorrect Response Status"); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); ServiceBulkResponseContent response = mapper.readValue(result.getResponse().getContentAsString(), ServiceBulkResponseContent.class); // check the processing status for (NlpProcessingResult res : response.getResult()) { assertEquals(true, res.getSuccess(), "Invalid processing status"); // check whether there were any annotations returned assertNotEquals(0, res.getAnnotations().size(), "Returned no annotations"); } } /** * Helper functions */ static private String createPayload(GenericDocument doc) throws Exception { JSONObject json = new JSONObject() .put("content", new JSONObject() .put("text", doc.getText())); return json.toString(); } static private String createPayloadBulk(List<GenericDocument> docs) throws Exception { JSONArray jsonContent = new JSONArray(); for (GenericDocument doc : docs) { jsonContent.put(new JSONObject() .put("text", doc.getText())); } JSONObject json = new JSONObject() .put("content", jsonContent); return json.toString(); } }