repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Lzw2016/clever-quartz
clever-quartz-server/src/main/java/org/clever/quartz/mapper/QrtzJobLogMapper.java
<gh_stars>0 package org.clever.quartz.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.quartz.dto.request.JobLogQueryReq; import org.clever.quartz.entity.QrtzJobLog; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * 作者:lizw <br/> * 创建时间:2017/6/1 10:00 <br/> */ @Repository @Mapper public interface QrtzJobLogMapper extends BaseMapper<QrtzJobLog> { /** * 查询所有的定时任务日志 * * @return 触发器日志分页数据 */ List<QrtzJobLog> findByPage(@Param("query") JobLogQueryReq jobLogQueryReq, IPage page); /** * 删除 date 之前创建的日志数据 */ int deleteByTime(@Param("date") Date date); }
dwalluck/gradle-manipulator
common/src/main/java/org/jboss/gm/common/utils/JavaUtils.java
package org.jboss.gm.common.utils; import java.io.File; import java.io.IOException; import lombok.Getter; import lombok.experimental.UtilityClass; import org.commonjava.maven.ext.common.ManipulationException; import org.gradle.internal.jvm.JavaInfo; import org.gradle.internal.jvm.Jvm; @UtilityClass public class JavaUtils { private static final JavaInfo javaInfo = Jvm.current(); @Getter private static final File javaHome = javaInfo.getJavaHome(); public static boolean compareJavaHome(File newHome) throws ManipulationException { try { if (newHome.getCanonicalPath().equals(javaHome.getCanonicalPath())) { return true; } } catch (IOException e) { throw new ManipulationException("Unable to compare java home locations", e); } return false; } }
umeshh/my-aws-sdk
aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/AbstractAmazonRoute53.java
<reponame>umeshh/my-aws-sdk<gh_stars>1-10 /* * Copyright 2011-2016 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.route53; import com.amazonaws.services.route53.model.*; import com.amazonaws.*; import com.amazonaws.services.route53.waiters.AmazonRoute53Waiters; /** * Abstract implementation of {@code AmazonRoute53}. Convenient method forms pass through to the corresponding overload * that takes a request object, which throws an {@code UnsupportedOperationException}. */ public class AbstractAmazonRoute53 implements AmazonRoute53 { protected AbstractAmazonRoute53() { } @Override public void setEndpoint(String endpoint) { throw new java.lang.UnsupportedOperationException(); } @Override public void setRegion(com.amazonaws.regions.Region region) { throw new java.lang.UnsupportedOperationException(); } @Override public AssociateVPCWithHostedZoneResult associateVPCWithHostedZone(AssociateVPCWithHostedZoneRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ChangeResourceRecordSetsResult changeResourceRecordSets(ChangeResourceRecordSetsRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ChangeTagsForResourceResult changeTagsForResource(ChangeTagsForResourceRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public CreateHealthCheckResult createHealthCheck(CreateHealthCheckRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public CreateHostedZoneResult createHostedZone(CreateHostedZoneRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public CreateReusableDelegationSetResult createReusableDelegationSet(CreateReusableDelegationSetRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public CreateTrafficPolicyResult createTrafficPolicy(CreateTrafficPolicyRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public CreateTrafficPolicyInstanceResult createTrafficPolicyInstance(CreateTrafficPolicyInstanceRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public CreateTrafficPolicyVersionResult createTrafficPolicyVersion(CreateTrafficPolicyVersionRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public CreateVPCAssociationAuthorizationResult createVPCAssociationAuthorization(CreateVPCAssociationAuthorizationRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public DeleteHealthCheckResult deleteHealthCheck(DeleteHealthCheckRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public DeleteHostedZoneResult deleteHostedZone(DeleteHostedZoneRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public DeleteReusableDelegationSetResult deleteReusableDelegationSet(DeleteReusableDelegationSetRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public DeleteTrafficPolicyResult deleteTrafficPolicy(DeleteTrafficPolicyRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public DeleteTrafficPolicyInstanceResult deleteTrafficPolicyInstance(DeleteTrafficPolicyInstanceRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public DeleteVPCAssociationAuthorizationResult deleteVPCAssociationAuthorization(DeleteVPCAssociationAuthorizationRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public DisassociateVPCFromHostedZoneResult disassociateVPCFromHostedZone(DisassociateVPCFromHostedZoneRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetChangeResult getChange(GetChangeRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetCheckerIpRangesResult getCheckerIpRanges(GetCheckerIpRangesRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetCheckerIpRangesResult getCheckerIpRanges() { return getCheckerIpRanges(new GetCheckerIpRangesRequest()); } @Override public GetGeoLocationResult getGeoLocation(GetGeoLocationRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetGeoLocationResult getGeoLocation() { return getGeoLocation(new GetGeoLocationRequest()); } @Override public GetHealthCheckResult getHealthCheck(GetHealthCheckRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetHealthCheckCountResult getHealthCheckCount(GetHealthCheckCountRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetHealthCheckCountResult getHealthCheckCount() { return getHealthCheckCount(new GetHealthCheckCountRequest()); } @Override public GetHealthCheckLastFailureReasonResult getHealthCheckLastFailureReason(GetHealthCheckLastFailureReasonRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetHealthCheckStatusResult getHealthCheckStatus(GetHealthCheckStatusRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetHostedZoneResult getHostedZone(GetHostedZoneRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetHostedZoneCountResult getHostedZoneCount(GetHostedZoneCountRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetHostedZoneCountResult getHostedZoneCount() { return getHostedZoneCount(new GetHostedZoneCountRequest()); } @Override public GetReusableDelegationSetResult getReusableDelegationSet(GetReusableDelegationSetRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetTrafficPolicyResult getTrafficPolicy(GetTrafficPolicyRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetTrafficPolicyInstanceResult getTrafficPolicyInstance(GetTrafficPolicyInstanceRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetTrafficPolicyInstanceCountResult getTrafficPolicyInstanceCount(GetTrafficPolicyInstanceCountRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public GetTrafficPolicyInstanceCountResult getTrafficPolicyInstanceCount() { return getTrafficPolicyInstanceCount(new GetTrafficPolicyInstanceCountRequest()); } @Override public ListGeoLocationsResult listGeoLocations(ListGeoLocationsRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListGeoLocationsResult listGeoLocations() { return listGeoLocations(new ListGeoLocationsRequest()); } @Override public ListHealthChecksResult listHealthChecks(ListHealthChecksRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListHealthChecksResult listHealthChecks() { return listHealthChecks(new ListHealthChecksRequest()); } @Override public ListHostedZonesResult listHostedZones(ListHostedZonesRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListHostedZonesResult listHostedZones() { return listHostedZones(new ListHostedZonesRequest()); } @Override public ListHostedZonesByNameResult listHostedZonesByName(ListHostedZonesByNameRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListHostedZonesByNameResult listHostedZonesByName() { return listHostedZonesByName(new ListHostedZonesByNameRequest()); } @Override public ListResourceRecordSetsResult listResourceRecordSets(ListResourceRecordSetsRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListReusableDelegationSetsResult listReusableDelegationSets(ListReusableDelegationSetsRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListReusableDelegationSetsResult listReusableDelegationSets() { return listReusableDelegationSets(new ListReusableDelegationSetsRequest()); } @Override public ListTagsForResourceResult listTagsForResource(ListTagsForResourceRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListTagsForResourcesResult listTagsForResources(ListTagsForResourcesRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListTrafficPoliciesResult listTrafficPolicies(ListTrafficPoliciesRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListTrafficPoliciesResult listTrafficPolicies() { return listTrafficPolicies(new ListTrafficPoliciesRequest()); } @Override public ListTrafficPolicyInstancesResult listTrafficPolicyInstances(ListTrafficPolicyInstancesRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListTrafficPolicyInstancesResult listTrafficPolicyInstances() { return listTrafficPolicyInstances(new ListTrafficPolicyInstancesRequest()); } @Override public ListTrafficPolicyInstancesByHostedZoneResult listTrafficPolicyInstancesByHostedZone(ListTrafficPolicyInstancesByHostedZoneRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListTrafficPolicyInstancesByPolicyResult listTrafficPolicyInstancesByPolicy(ListTrafficPolicyInstancesByPolicyRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListTrafficPolicyVersionsResult listTrafficPolicyVersions(ListTrafficPolicyVersionsRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public ListVPCAssociationAuthorizationsResult listVPCAssociationAuthorizations(ListVPCAssociationAuthorizationsRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public TestDNSAnswerResult testDNSAnswer(TestDNSAnswerRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public UpdateHealthCheckResult updateHealthCheck(UpdateHealthCheckRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public UpdateHostedZoneCommentResult updateHostedZoneComment(UpdateHostedZoneCommentRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public UpdateTrafficPolicyCommentResult updateTrafficPolicyComment(UpdateTrafficPolicyCommentRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public UpdateTrafficPolicyInstanceResult updateTrafficPolicyInstance(UpdateTrafficPolicyInstanceRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public void shutdown() { throw new java.lang.UnsupportedOperationException(); } @Override public com.amazonaws.ResponseMetadata getCachedResponseMetadata(com.amazonaws.AmazonWebServiceRequest request) { throw new java.lang.UnsupportedOperationException(); } @Override public AmazonRoute53Waiters waiters() { throw new java.lang.UnsupportedOperationException(); } }
MaciejPatro/cmake-tidy
cmake_tidy/formatting/utils/format_file.py
<filename>cmake_tidy/formatting/utils/format_file.py ############################################################################### # Copyright <NAME> (<EMAIL>) # MIT License ############################################################################### import re from cmake_tidy.formatting.utils.single_indent import get_single_indent from cmake_tidy.formatting.utils.tokens import Tokens class FormatFile: def __init__(self, settings: dict): self.__settings = settings def __call__(self, data: list) -> str: processed = self.__cleanup_end_invocations(''.join(data)) processed = self.__cleanup_whitespaces_at_line_ends(processed) return self.__cleanup_reindent_all(processed) def __cleanup_end_invocations(self, formatted_file: str) -> str: for pattern in Tokens.get_reindent_patterns_list(3, get_single_indent(self.__settings)): formatted_file = re.sub(pattern, '', formatted_file) return formatted_file @staticmethod def __cleanup_whitespaces_at_line_ends(processed: str) -> str: return re.sub('[ \t]*' + Tokens.remove_spaces(), '', processed) @staticmethod def __cleanup_reindent_all(data: str) -> str: return re.sub('[ \t]*' + Tokens.reindent(), '', data)
xhuohai/nncase
src/importer/onnx/ops/lpnorm.cpp
<reponame>xhuohai/nncase /* Copyright 2020 <NAME> <<EMAIL>> * * 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. */ #include "../onnx_importer.h" #include <cassert> #include <nncase/ir/graph.h> #include <nncase/ir/ops/binary.h> #include <nncase/ir/ops/constant.h> #include <nncase/ir/ops/reduce.h> #include <nncase/ir/ops/unary.h> using namespace nncase; using namespace nncase::importer; using namespace nncase::ir; using namespace onnx; void onnx_importer::convert_op_LpNormalization(const NodeProto &node) { const auto &op_name { generate_name(node) }; const auto &input = node.input()[0]; const auto &output = node.output()[0]; const auto &input_shape = get_shape(input); axis_t reduce_axis { static_cast<int>(real_axis(get_attribute<int>(node, "axis").value(), input_shape.size())) }; const auto p = get_attribute<int>(node, "p").value(); assert(p >= 1 && p <= 2); switch (p) { case 1: { auto abs = graph_.emplace<unary>(unary_abs, input_shape); abs->name(op_name + ".abs(L1Normalization)"); auto sum = graph_.emplace<reduce>(reduce_sum, abs->output().shape(), reduce_axis, 0.f, true); sum->name(op_name + ".reduce_sum(L1Normalization)"); auto div = graph_.emplace<binary>(binary_div, input_shape, sum->output().shape(), value_range<float>::full()); div->name(op_name + ".div(L1Normalization)"); sum->input().connect(abs->output()); div->input_b().connect(sum->output()); input_tensors_.emplace(&abs->input(), input); input_tensors_.emplace(&div->input_a(), input); output_tensors_.emplace(output, &div->output()); break; } case 2: { auto square = graph_.emplace<unary>(unary_square, input_shape); square->name(op_name + ".square(L2Normalization)"); auto sum = graph_.emplace<reduce>(reduce_sum, square->output().shape(), reduce_axis, 0.f, true); sum->name(op_name + ".reduce_sum(L2Normalization)"); auto epsilon = graph_.emplace<constant>(1e-10f); epsilon->name(op_name + ".eps(L2Normalization)"); auto max = graph_.emplace<binary>(binary_max, sum->output().shape(), epsilon->output().shape(), value_range<float>::full()); max->name(op_name + ".stab(L2Normalization)"); auto sqrt = graph_.emplace<unary>(unary_sqrt, max->output().shape()); sqrt->name(op_name + ".sqrt(L2Normalization)"); auto div = graph_.emplace<binary>(binary_div, input_shape, sqrt->output().shape(), value_range<float>::full()); div->name(op_name + ".div(L2Normalization)"); sum->input().connect(square->output()); max->input_a().connect(sum->output()); max->input_b().connect(epsilon->output()); sqrt->input().connect(max->output()); div->input_b().connect(sqrt->output()); input_tensors_.emplace(&square->input(), input); input_tensors_.emplace(&div->input_a(), input); output_tensors_.emplace(output, &div->output()); break; } default: { break; } } }
edugonza/PADAS
src/org/processmining/database/redologs/common/DAGThread.java
<gh_stars>1-10 package org.processmining.database.redologs.common; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Vector; import org.processmining.openslex.SLEXTrace; import org.processmining.database.redologs.dag.DAG; import org.processmining.database.redologs.dag.DAGNode; public class DAGThread extends Thread { private class DAGTask { int action; SLEXTrace t; TraceID tid; Integer v; public DAGTask(int a, SLEXTrace t, TraceID tid, Integer v) { this.action = a; this.t = t; this.tid = tid; this.v = v; } } public static final int ADD_CHILD_TO_ROOT = 0; public static final int ADD_TO_MAP = 1; public static final int ADD_TO_DAG = 2; public static final int ADD_EVENTS_TO_TRACE = 3; public static final int FINISH = 4; private boolean stop = false; private SLEXTrace nullTrace = null; private DAG<SLEXTrace> subtraceDAG = new DAG<>(nullTrace); private Queue<DAGTask> tasksQueue = new LinkedList<>(); private HashMap<SLEXTrace,TraceID> tracesMap = new HashMap<>(); private HashMap<SLEXTrace,Integer> tracesEventsNumMap = new HashMap<>(); private HashMap<Column,HashMap<String,HashSet<SLEXTrace>>> relatedMap = new HashMap<>(); private TraceIDPattern tp = null; private ProgressHandler phandler = null; public DAGThread(TraceIDPattern tp, ProgressHandler phandler) { super("DAGThread"); this.tp = tp; this.phandler = phandler; for (Column cpa: tp.getPAList()) { relatedMap.put(cpa, new HashMap<String,HashSet<SLEXTrace>>()); } } public void addTask(int action, SLEXTrace t, TraceID tid, Integer v) { DAGTask task = new DAGTask(action,t,tid,v); synchronized (tasksQueue) { tasksQueue.offer(task); tasksQueue.notify(); } } public DAG<SLEXTrace> getDAG() { return subtraceDAG; } @Override public synchronized void start() { this.stop = false; super.start(); } public void stopThread() { this.stop = true; } @Override public void run() { try { int taskcounter = 0; int taskspending = 0; while (!stop) { DAGTask task = null; synchronized (tasksQueue) { while (!stop && task == null) { task = tasksQueue.poll(); if (task == null) { tasksQueue.wait(5000); } else { taskspending = tasksQueue.size(); } } } if (task != null) { switch (task.action) { case ADD_CHILD_TO_ROOT: subtraceDAG.addChild(subtraceDAG.getRoot(),task.t); break; case ADD_TO_MAP: tracesMap.put(task.t, task.tid); tracesEventsNumMap.put(task.t, task.v); LogTraceSplitter.addTraceToRelatedMap(task.t,task.tid,relatedMap); break; case ADD_TO_DAG: addTraceToDAG(subtraceDAG,relatedMap,tracesMap,tracesEventsNumMap,task.t,task.tid); break; case ADD_EVENTS_TO_TRACE: int n = tracesEventsNumMap.get(task.t); n+=task.v; tracesEventsNumMap.put(task.t, n); break; case FINISH: stopThread(); break; default: System.err.println("Unknown action"); break; } } taskcounter++; phandler.refreshValue("DAGTasks", "Done: "+String.valueOf(taskcounter)+" Pending: "+taskspending); } } catch (Exception e) { e.printStackTrace(); } } private static final int NODE_IS_UNK = 0; private static final int NODE_IS_SUB = 1; private static final int NODE_IS_SUP = -1; private static final int NODE_IS_NOP = 2; public static int checkTracesInDAG(TraceID tnewId, SLEXTrace tnew, SLEXTrace tb, HashMap<SLEXTrace,TraceID> tracesMap, HashMap<SLEXTrace,Integer> tracesEventNumMap, HashMap<SLEXTrace,Integer> explorationMap, DAG<SLEXTrace> subtraceDAG) { int tbi = 3; if (explorationMap.containsKey(tb)) { tbi = explorationMap.get(tb); } else { tbi = NODE_IS_UNK; } if (tb != null) { if (tnew.getId() == tb.getId()) { tbi = NODE_IS_SUB; explorationMap.put(tb,tbi); } } if (tbi == NODE_IS_SUB || tbi == NODE_IS_SUP || tbi == NODE_IS_NOP) { return tbi; } else if (tbi == NODE_IS_UNK) { TraceID tbId = tracesMap.get(tb); boolean nSUBb = false; boolean nSUPb = false; if (LogTraceSplitter.subtrace(tnewId,tbId)) { nSUBb = true; } if (LogTraceSplitter.supertrace(tnewId,tbId)) { nSUPb = true; } if (nSUBb && nSUPb) { // Find out if it is super or sub trace looking at the events int tnewN = tracesEventNumMap.get(tnew); int tbN = tracesEventNumMap.get(tb); if (tnewN > tbN) { nSUPb = true; nSUBb = false; } else { nSUPb = false; nSUBb = true; } } if (nSUPb) { // tnew is supertrace of tb tbi = NODE_IS_SUB; explorationMap.put(tb,tbi); boolean children_nop = true; List<DAGNode<SLEXTrace>> children = new Vector<>(); for (DAGNode<SLEXTrace> c: subtraceDAG.getNode(tb).getChildren()) { children.add(c); } for (DAGNode<SLEXTrace> c: children) { if (checkTracesInDAG(tnewId, tnew, c.getValue(), tracesMap,tracesEventNumMap, explorationMap, subtraceDAG) != NODE_IS_NOP) { children_nop = false; } } if (children_nop) { // tnew is a child of tb subtraceDAG.addChild(subtraceDAG.getNode(tb), tnew); } } else if (nSUBb) { // tnew is subtrace of tb tbi = NODE_IS_SUP; explorationMap.put(tb,tbi); boolean children_nop = true; List<DAGNode<SLEXTrace>> parents = new Vector<>(); for (DAGNode<SLEXTrace> p: subtraceDAG.getNode(tb).getParents()) { parents.add(p); } for (DAGNode<SLEXTrace> p: parents) { int r = checkTracesInDAG(tnewId, tnew, p.getValue(), tracesMap,tracesEventNumMap, explorationMap, subtraceDAG); if (r != NODE_IS_NOP) { children_nop = false; } if (r == NODE_IS_SUB) { // tnew is a child of p and parent of tb // remove p as parent of tb subtraceDAG.removeParent(subtraceDAG.getNode(tb),p); subtraceDAG.addChild(p,tnew); subtraceDAG.addParent(subtraceDAG.getNode(tb), tnew); } } if (children_nop) { // tnew is parent of tb and child of root subtraceDAG.addChild(subtraceDAG.getRoot(), tnew); subtraceDAG.addParent(subtraceDAG.getNode(tb), tnew); } } else { tbi = NODE_IS_NOP; explorationMap.put(tb,tbi); } return tbi; } else { // WRONG!! System.err.println("ERROR"); } return 3; } public static void addTraceToDAG(DAG<SLEXTrace> subtraceDAG, HashMap<Column, HashMap<String, HashSet<SLEXTrace>>> relatedMap, HashMap<SLEXTrace,TraceID> tracesMap, HashMap<SLEXTrace,Integer> tracesEventsNumMap, SLEXTrace tnew, TraceID tnewId) { /**/ // tnew could be sub or super trace of any of his compatible and related traces HashSet<SLEXTrace> t2CAndR = new HashSet<>(); HashMap<SLEXTrace,Integer> explorationMap = new HashMap<>(); for (SLEXTrace tb: LogTraceSplitter.getRelatedTracesFromMap(tnewId,relatedMap)) { TraceID tbId = tracesMap.get(tb); if (LogTraceSplitter.compatibleTraces(tbId,tnewId)) { // FIXME t2CAndR.add(tb); explorationMap.put(tb,NODE_IS_UNK); } } t2CAndR.remove(tnew); boolean no_sub_or_sup = true; for (SLEXTrace tb: t2CAndR) { int r = checkTracesInDAG(tnewId, tnew, tb, tracesMap, tracesEventsNumMap, explorationMap,subtraceDAG); if (r == NODE_IS_SUB || r == NODE_IS_SUP) { no_sub_or_sup = false; } else if (r != NODE_IS_NOP) { System.err.println("ERROR"); } } if (no_sub_or_sup) { subtraceDAG.addChild(subtraceDAG.getRoot(),tnew); } DAGNode<SLEXTrace> n = subtraceDAG.getNode(tnew); if (n == null) { System.err.println("ERROR"); } /**/ } }
HyunTruth/scrapy
scrapy/utils/multipart.py
""" Transitional module for moving to the w3lib library. For new code, always import from w3lib.form instead of this module """ from w3lib.form import *
nanthakumar1305/incubator-hop
engine/src/main/java/org/apache/hop/www/HopServerWorkflowStatus.java
<reponame>nanthakumar1305/incubator-hop<gh_stars>0 /* * 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.hop.www; import org.apache.hop.core.Const; import org.apache.hop.core.Result; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.util.EnvUtil; import org.apache.hop.core.util.Utils; import org.apache.hop.core.xml.XmlHandler; import org.apache.hop.pipeline.Pipeline; import org.apache.hop.server.HttpUtil; import org.w3c.dom.Document; import org.w3c.dom.Node; import java.io.IOException; import java.util.Date; public class HopServerWorkflowStatus { public static final String XML_TAG = "workflow-status"; private String workflowName; private String id; private String statusDescription; private String errorDescription; private String loggingString; private int firstLoggingLineNr; private int lastLoggingLineNr; private Date logDate; private Result result; public HopServerWorkflowStatus() {} /** * @param pipelineName * @param statusDescription */ public HopServerWorkflowStatus(String pipelineName, String id, String statusDescription) { this(); this.workflowName = pipelineName; this.id = id; this.statusDescription = statusDescription; } public String getXml() throws HopException { boolean sendResultXmlWithStatus = EnvUtil.getSystemProperty("HOP_COMPATIBILITY_SEND_RESULT_XML_WITH_FULL_STATUS", "N") .equalsIgnoreCase("Y"); StringBuilder xml = new StringBuilder(); xml.append(XmlHandler.openTag(XML_TAG)).append(Const.CR); xml.append(" ").append(XmlHandler.addTagValue("workflowname", workflowName)); xml.append(" ").append(XmlHandler.addTagValue("id", id)); xml.append(" ").append(XmlHandler.addTagValue("status_desc", statusDescription)); xml.append(" ").append(XmlHandler.addTagValue("error_desc", errorDescription)); xml.append(" ").append(XmlHandler.addTagValue("log_date", XmlHandler.date2string(logDate))); xml.append(" ") .append(XmlHandler.addTagValue("logging_string", XmlHandler.buildCDATA(loggingString))); xml.append(" ").append(XmlHandler.addTagValue("first_log_line_nr", firstLoggingLineNr)); xml.append(" ").append(XmlHandler.addTagValue("last_log_line_nr", lastLoggingLineNr)); if (result != null) { String resultXML = sendResultXmlWithStatus ? result.getXml() : result.getBasicXml(); xml.append(resultXML); } xml.append(XmlHandler.closeTag(XML_TAG)); return xml.toString(); } public HopServerWorkflowStatus(Node workflowStatusNode) throws HopException { this(); workflowName = XmlHandler.getTagValue(workflowStatusNode, "workflowname"); id = XmlHandler.getTagValue(workflowStatusNode, "id"); statusDescription = XmlHandler.getTagValue(workflowStatusNode, "status_desc"); errorDescription = XmlHandler.getTagValue(workflowStatusNode, "error_desc"); logDate = XmlHandler.stringToDate(XmlHandler.getTagValue(workflowStatusNode, "log_date")); firstLoggingLineNr = Const.toInt(XmlHandler.getTagValue(workflowStatusNode, "first_log_line_nr"), 0); lastLoggingLineNr = Const.toInt(XmlHandler.getTagValue(workflowStatusNode, "last_log_line_nr"), 0); String loggingString64 = XmlHandler.getTagValue(workflowStatusNode, "logging_string"); if (!Utils.isEmpty(loggingString64)) { // This is a CDATA block with a Base64 encoded GZIP compressed stream of data. // String dataString64 = loggingString64.substring( "<![CDATA[".length(), loggingString64.length() - "]]>".length()); try { loggingString = HttpUtil.decodeBase64ZippedString(dataString64); } catch (IOException e) { loggingString = "Unable to decode logging from remote server : " + e.toString() + Const.CR + Const.getSimpleStackTrace(e) + Const.CR + Const.getStackTracker(e); } } else { loggingString = ""; } // get the result object, if there is any... // Node resultNode = XmlHandler.getSubNode(workflowStatusNode, Result.XML_TAG); if (resultNode != null) { try { result = new Result(resultNode); } catch (HopException e) { loggingString += "Unable to serialize result object as XML" + Const.CR + Const.getSimpleStackTrace(e) + Const.CR + Const.getStackTracker(e) + Const.CR; } } } public static HopServerWorkflowStatus fromXml(String xml) throws HopException { Document document = XmlHandler.loadXmlString(xml); HopServerWorkflowStatus status = new HopServerWorkflowStatus(XmlHandler.getSubNode(document, XML_TAG)); return status; } /** @return the statusDescription */ public String getStatusDescription() { return statusDescription; } /** @param statusDescription the statusDescription to set */ public void setStatusDescription(String statusDescription) { this.statusDescription = statusDescription; } /** @return the workflow name */ public String getWorkflowName() { return workflowName; } /** @param workflowName the workflow name to set */ public void setWorkflowName(String workflowName) { this.workflowName = workflowName; } /** @return the errorDescription */ public String getErrorDescription() { return errorDescription; } /** @param errorDescription the errorDescription to set */ public void setErrorDescription(String errorDescription) { this.errorDescription = errorDescription; } /** @return the loggingString */ public String getLoggingString() { return loggingString; } /** @param loggingString the loggingString to set */ public void setLoggingString(String loggingString) { this.loggingString = loggingString; } public boolean isRunning() { if (getStatusDescription() == null) { return false; } return getStatusDescription().equalsIgnoreCase(Pipeline.STRING_RUNNING) || getStatusDescription().equalsIgnoreCase(Pipeline.STRING_INITIALIZING); } public boolean isWaiting() { if (getStatusDescription() == null) { return false; } return getStatusDescription().equalsIgnoreCase(Pipeline.STRING_WAITING); } public boolean isFinished() { if (getStatusDescription() == null) { return false; } return getStatusDescription().equalsIgnoreCase(Pipeline.STRING_FINISHED) || getStatusDescription().equalsIgnoreCase(Pipeline.STRING_FINISHED_WITH_ERRORS); } public boolean isStopped() { if (getStatusDescription() == null) { return false; } return getStatusDescription().equalsIgnoreCase(Pipeline.STRING_STOPPED) || getStatusDescription().equalsIgnoreCase(Pipeline.STRING_STOPPED_WITH_ERRORS); } /** @return the result */ public Result getResult() { return result; } /** @param result the result to set */ public void setResult(Result result) { this.result = result; } /** @return the firstLoggingLineNr */ public int getFirstLoggingLineNr() { return firstLoggingLineNr; } /** @param firstLoggingLineNr the firstLoggingLineNr to set */ public void setFirstLoggingLineNr(int firstLoggingLineNr) { this.firstLoggingLineNr = firstLoggingLineNr; } /** @return the lastLoggingLineNr */ public int getLastLoggingLineNr() { return lastLoggingLineNr; } /** @param lastLoggingLineNr the lastLoggingLineNr to set */ public void setLastLoggingLineNr(int lastLoggingLineNr) { this.lastLoggingLineNr = lastLoggingLineNr; } /** @return the logDate */ public Date getLogDate() { return logDate; } /** @param the logDate */ public void setLogDate(Date logDate) { this.logDate = logDate; } /** @return the id */ public String getId() { return id; } /** @param id the id to set */ public void setId(String id) { this.id = id; } }
alloystory/cs2103t_zerotoone
src/test/java/seedu/zerotoone/logic/parser/schedule/CreateCommandParserTest.java
<filename>src/test/java/seedu/zerotoone/logic/parser/schedule/CreateCommandParserTest.java package seedu.zerotoone.logic.parser.schedule; import static seedu.zerotoone.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.zerotoone.logic.parser.util.ParserUtil.MESSAGE_INVALID_INDEX; import static seedu.zerotoone.testutil.CommandParserTestUtil.assertParseFailure; import static seedu.zerotoone.testutil.CommandParserTestUtil.assertParseSuccess; import static seedu.zerotoone.testutil.CommandTestUtil.PREAMBLE_NON_EMPTY; import static seedu.zerotoone.testutil.TypicalIndexes.INDEX_SECOND_OBJECT; import static seedu.zerotoone.testutil.schedule.ScheduleCommandTestUtil.DATETIME_DESC_JUNE; import static seedu.zerotoone.testutil.schedule.ScheduleCommandTestUtil.INVALID_DATETIME_DESC; import static seedu.zerotoone.testutil.schedule.ScheduleCommandTestUtil.VALID_DATETIME_JUNE; import org.junit.jupiter.api.Test; import seedu.zerotoone.commons.core.index.Index; import seedu.zerotoone.logic.commands.schedule.CreateCommand; import seedu.zerotoone.model.schedule.DateTime; class CreateCommandParserTest { private static final String MESSAGE_INVALID_FORMAT = String.format(MESSAGE_INVALID_COMMAND_FORMAT, CreateCommand.MESSAGE_USAGE); private CreateCommandParser parser = new CreateCommandParser(); @Test public void parse_invalidPreamble_failure() { // negative index assertParseFailure(parser, "-5" + DATETIME_DESC_JUNE, MESSAGE_INVALID_INDEX); // zero index assertParseFailure(parser, "0" + DATETIME_DESC_JUNE, MESSAGE_INVALID_INDEX); // invalid arguments being parsed as preamble assertParseFailure(parser, "1 some random string", MESSAGE_INVALID_FORMAT); // invalid prefix being parsed as preamble assertParseFailure(parser, "1 i/ string", MESSAGE_INVALID_FORMAT); } @Test public void parse_invalidValue_failure() { // invalid name assertParseFailure(parser, "1" + INVALID_DATETIME_DESC, DateTime.MESSAGE_CONSTRAINTS); // non-empty preamble assertParseFailure(parser, PREAMBLE_NON_EMPTY + DATETIME_DESC_JUNE, MESSAGE_INVALID_INDEX); } @Test void parse_allFieldsPresent_success() { Index targetIndex = INDEX_SECOND_OBJECT; String userInput = targetIndex.getOneBased() + DATETIME_DESC_JUNE; CreateCommand expectedCommand = new CreateCommand(targetIndex, new DateTime(VALID_DATETIME_JUNE)); assertParseSuccess(parser, userInput, expectedCommand); } }
npocmaka/Windows-Server-2003
windows/advcore/ctf/uim/saa.cpp
// // saa.cpp // // CSharedAnchorArray // #include "private.h" #include "saa.h" #include "immxutil.h" //+--------------------------------------------------------------------------- // // _MergeSort // // NB: rgArrays is freed before the method exits. // Caller must release the out array. // // perf: some possible optimizations: // quick check if the arrays don't overlap // find some way to anticipate dups //---------------------------------------------------------------------------- /* static */ CSharedAnchorArray *CSharedAnchorArray::_MergeSort(CSharedAnchorArray **rgArrays, ULONG cArrays) { LONG l; IAnchor *pa; IAnchor **ppaDst; IAnchor **ppa1; IAnchor **ppaEnd1; IAnchor **ppa2; IAnchor **ppaEnd2; CSharedAnchorArray *prgAnchors1 = NULL; CSharedAnchorArray *prgAnchors2 = NULL; CSharedAnchorArray *prgAnchors = NULL; BOOL fRet = FALSE; // recursion if (cArrays > 2) { if (cArrays == 3) { // avoid unnecessary mem alloc here prgAnchors1 = rgArrays[0]; } else { prgAnchors1 = _MergeSort(rgArrays, cArrays / 2); } prgAnchors2 = _MergeSort(rgArrays + cArrays / 2, cArrays - cArrays / 2); } else { Assert(cArrays == 2); prgAnchors1 = rgArrays[0]; prgAnchors2 = rgArrays[1]; } // check for out-of-mem after the recursion, so we at least free the entire source array if (prgAnchors1 == NULL || prgAnchors2 == NULL) goto Exit; // allocate some memory // perf: we could do something complicated and do everything in place if ((prgAnchors = new CSharedAnchorArray) == NULL) goto Exit; if (prgAnchors1->Count() + prgAnchors2->Count() == 0) { Assert(!prgAnchors->Count()); fRet = TRUE; goto Exit; } if (!prgAnchors->Append(prgAnchors1->Count() + prgAnchors2->Count())) goto Exit; // the actual combination ppaDst = prgAnchors->GetPtr(0); ppa1 = prgAnchors1->GetPtr(0); ppa2 = prgAnchors2->GetPtr(0); ppaEnd1 = prgAnchors1->GetPtr(prgAnchors1->Count()); ppaEnd2 = prgAnchors2->GetPtr(prgAnchors2->Count()); // do a one pass merge sort -- both prgAnchors1 and prgAnchors2 are sorted already while (ppa1 < ppaEnd1 || ppa2 < ppaEnd2) { if (ppa1 < ppaEnd1) { if (ppa2 < ppaEnd2) { l = CompareAnchors(*ppa1, *ppa2); if (l < 0) { pa = *ppa1++; } else if (l > 0) { pa = *ppa2++; } else // equal { pa = *ppa1++; (*ppa2++)->Release(); } } else { pa = *ppa1++; } } else // ppa2 < ppaEnd2 { pa = *ppa2++; } *ppaDst++ = pa; } // taking ownership, so no AddRef // clear the elems counts so we don't Release in the destructors prgAnchors1->SetCount(0); prgAnchors2->SetCount(0); // we might have removed dups, so calc a new size prgAnchors->SetCount((int)(ppaDst - prgAnchors->GetPtr(0))); fRet = TRUE; Exit: if (prgAnchors1 != NULL) { prgAnchors1->_Release(); } if (prgAnchors2 != NULL) { prgAnchors2->_Release(); } if (!fRet) { if (prgAnchors != NULL) { prgAnchors->_Release(); } prgAnchors = NULL; } return prgAnchors; }
thm-mni-ii/sea
test/scciterator_test.cpp
#include "sealib/iterator/scciterator.h" #include <gtest/gtest.h> #include <vector> #include "sealib/graph/graphcreator.h" using namespace Sealib; // NOLINT TEST(SCCIteratorTest, noDuplicates) { DirectedGraph g = GraphCreator::kOutdegree(50, 2); SCCIterator s(g); s.init(); s.more(); s.next(); SUCCEED(); }
sdaschner/liberty-ci.maven
liberty-maven-plugin/src/it/appsdirectory-configdropins-it/src/test/java/net/wasdev/wlp/maven/test/app/ConfigDropinsTest.java
<gh_stars>10-100 package net.wasdev.wlp.maven.test.app; import static org.junit.Assert.*; import java.io.File; import org.junit.Test; /** * * Web application test case * */ public class ConfigDropinsTest { public final String CONFIG_XML = "liberty-plugin-config.xml"; @Test public void testApplicationFileExist() throws Exception { File f = new File("liberty/usr/servers/test/apps/appsdirectory-configdropins-it.war"); assertTrue(f.getCanonicalFile() + " doesn't exist", f.exists()); } @Test public void testConfigDirectoryFileExist() throws Exception { File f = new File("liberty/usr/servers/test/configDropins/overrides"); assertTrue(f.getCanonicalFile() + " doesn't exist", f.exists()); } }
vntborgesjr/Python-Mundo-01
aula009.py
<reponame>vntborgesjr/Python-Mundo-01 frase = 'Curso em Video Python' print(frase[3]) print(frase[3:12]) print(frase[:12]) print(frase[13:]) print(frase[:15]) print(frase[1:15:2]) print(frase[::2]) print(len(frase)) print(frase.count('o')) print(frase.count('o', 0, 13)) print(frase.find('deo')) print(frase.find('Android')) # valor -1 significa que a string não existe print('Curso' in frase) print(frase.replace('Python', 'Android')) print(frase.upper()) frase = frase.lower() print(frase) print(frase.lower().find('video')) frase = frase.capitalize() print(frase) frase = frase.title() print(frase) frase = ' Aprenda Python ' print(frase) print(frase.strip()) print(frase.rstrip()) print(frase.lstrip()) frase = 'Curso em Video Python' print(frase.split()) frase = 'Curso em Video Python'.split print(frase) frase = 'Curso em Video Python' frase = '-'.join(frase) print(frase) print(len(frase)) print(frase.find(' ')) print(frase.count(' ')) print(len(frase.split()[0]))
aaron218/Crux
crux-core/src/test/java/net/newstring/crux/core/sort/QuickSort.java
package net.newstring.crux.core.sort; /** * Created by Aaron on 2017/3/14. */ public class QuickSort { //选定划分元素位置的 public static int partitionP(int[] value, int start, int end, int pivotId) { int temp = value[pivotId]; value[pivotId] = value[end]; value[end] = temp; return partition(value,start,end); } //利用给定值进行划分 public static int partitionK(int[] value,int start,int end,int pivot){ int i = start, j = start; while (j < end) { if (value[j] < pivot) { if (i != j) { int temp = value[i]; value[i] = value[j]; value[j] = temp; } i++; } j++; } return i; } //不选定顺序的 单线扫描 public static int partition(int[] value, int start, int end) { int i = start, j = start; int pivot = value[end]; while (j < end) { if (value[j] < pivot) { if (i != j) { int temp = value[i]; value[i] = value[j]; value[j] = temp; } i++; } j++; } //pivot 归位 int temp = value[i]; value[i] = pivot; value[end] = temp; return i; } //双向扫描方法 public static int partitionD(int value[], int start, int end) { int left = start, right = end - 1; while (true) { while (value[left] <= value[end] && left < end) { left++; } while (value[right] > value[end] && right >= 1) { right--; } if (left >= right) break; /** * 交换 * */ int temp = value[left]; value[left] = value[right]; value[right] = temp; left++; right--; } int temp = value[left]; value[left] = value[end]; value[end] = temp; return left; } public static int BFPRT(int[] value,int start, int end, int K){ if(end-start<=4){ //小于5个数字直接插入排序获取中间位置 InsertionSort.insertionSort(value,start,end); return value[start+K]; } int t = start - 1; //当前替换到前面的中位数的下标 for (int st = start, ed; (ed = st + 4) <= end; st += 5) //每5个进行处理 { InsertionSort.insertionSort(value, st, ed); //5个数的排序 t++; int temp = value[t]; value[t] = value[st+2]; value[st+2] = temp; } //从start 到 start + t 就是所有算出来的中位数区间,右移一位直接获取对应中位数的中位数的偏移量 int pivot = start +t >> 1; BFPRT(value, start, t, pivot-start+1);//不关心中位数的值,保证中位数在正确的位置 int m = partitionP(value, start, end, pivot), cur = m - start + 1; if (K == cur) return value[m]; //刚好是第id个数 else if(K < cur) return BFPRT(value, start, m-1, K);//第id个数在左边 else return BFPRT(value, m+1, end, K-cur); //第id个数在右边 } public static void QuickSort(int[] value, int start, int end) { if (start < end) { int pivot = partitionD(value, start, end); QuickSort(value, start, pivot - 1); QuickSort(value, pivot + 1, end); } } public static void main(String[] args) { // QuickSort(ConstantValues.random1, 0, ConstantValues.random1.length - 1); // for (int i : ConstantValues.random1) { // System.out.print(i + ","); // } int mid= BFPRT(ConstantValues.random1,0,ConstantValues.random1.length-1,48); System.out.println("MID value"+mid); partitionK(ConstantValues.random1,0,ConstantValues.random1.length-1,mid); for(int i : ConstantValues.random1){ System.out.print(i + ","); } } }
marcodotsh/programmazione-in-c-esercizi
Capitolo 5/Progetti/1/digits.c
<gh_stars>0 #include <stdio.h> int main(void) { int n, tmp,dig; dig = 0; printf("Enter a number: "); scanf("%d", &n); tmp = n; if(tmp!=0) { while(tmp!=0) { dig++; tmp /= 10; } } else { dig = 1; } printf("The number %d has %d digits\n", n, dig); return 0; }
loafofpiecrust/lfant
project-template/src/launcher/main.cpp
//#pragma once #include <iostream> #include <functional> #include <string> #include <boost/extension/shared_library.hpp> #include <boost/function.hpp> #if WIN32 # define EXT ".dll" # include <windows.h> #elif __APPLE__ # define EXT ".dylib" # define UNIX 1 #elif __linux # define EXT ".so" # define UNIX 1 #endif #if UNIX # include <unistd.h> #endif using namespace boost::extensions; using namespace std; shared_library loadlib( std::string name ) { shared_library lib( name, true ); if (!lib.open()) { cout << "Failed to load " << name << "\n" << dlerror() << "\n"; } return lib; } int main( void ) { //Launch(); shared_library lib = loadlib( "libprojectName" EXT ); boost::function<void()> func = lib.get<void>( "Launch" ); if (func) { cout << "Succeeded to load game\n"; func(); } else { cout << "Couldn't find Launch function\n"; } return 0; }
sethcoder/cc65
src/cc65/coptpush.c
/*****************************************************************************/ /* */ /* coptpush.c */ /* */ /* Optimize push sequences */ /* */ /* */ /* */ /* (C) 2001-2012, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptpush.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned OptPush1 (CodeSeg* S) /* Given a sequence ** ** jsr ldaxysp ** jsr pushax ** ** If a/x are not used later, and Y is known, replace that by ** ** ldy #xx+2 ** jsr pushwysp ** ** saving 3 bytes and several cycles. */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "ldaxysp") && RegValIsKnown (L[0]->RI->In.RegY) && L[0]->RI->In.RegY < 0xFE && (L[1] = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (L[1]) && CE_IsCallTo (L[1], "pushax") && !RegAXUsed (S, I+2)) { /* Insert new code behind the pushax */ const char* Arg; CodeEntry* X; /* ldy #xx+1 */ Arg = MakeHexArg (L[0]->RI->In.RegY+2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+2); /* jsr pushwysp */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "pushwysp", 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* Delete the old code */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPush2 (CodeSeg* S) /* A sequence ** ** jsr ldaxidx ** jsr pushax ** ** may get replaced by ** ** jsr pushwidx */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "ldaxidx") && (L[1] = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (L[1]) && CE_IsCallTo (L[1], "pushax")) { /* Insert new code behind the pushax */ CodeEntry* X; /* jsr pushwidx */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "pushwidx", 0, L[1]->LI); CS_InsertEntry (S, X, I+2); /* Delete the old code */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
mat128/wicket
wicket-core/src/main/java/org/apache/wicket/settings/StoreSettings.java
<gh_stars>0 /* * 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.wicket.settings; import java.io.File; import java.io.IOException; import org.apache.wicket.Application; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.lang.Bytes; /** * A class for settings related to the the storages where page instances are persisted, used by * {@link org.apache.wicket.pageStore.IPageStore} {@link org.apache.wicket.page.IPageManager}. * <p> * For more information about page storages read <a * href="https://cwiki.apache.org/confluence/x/qIaoAQ">Page Storage - Wiki page</a> * </p> * * @since 1.5 */ public class StoreSettings { private static final Bytes DEFAULT_MAX_SIZE_PER_SESSION = Bytes.megabytes(10); private static final int DEFAULT_ASYNCHRONOUS_QUEUE_CAPACITY = 100; private Bytes maxSizePerSession = DEFAULT_MAX_SIZE_PER_SESSION; private File fileStoreFolder = null; private int asynchronousQueueCapacity = DEFAULT_ASYNCHRONOUS_QUEUE_CAPACITY; private boolean asynchronous = true; private boolean encrypted = false; /** * Construct. * * @param application */ public StoreSettings(final Application application) { } /** * @return maximum page size. After this size is exceeded, * the {@link org.apache.wicket.pageStore.DiskPageStore} will start saving the * pages at the beginning of file. */ public Bytes getMaxSizePerSession() { return maxSizePerSession; } /** * Sets the maximum size of the {@link File} where page instances per session are stored. After * reaching this size the {@link org.apache.wicket.pageStore.DiskPageStore} will start overriding the * oldest pages at the beginning of the file. * * @param maxSizePerSession * the maximum size of the file where page instances are stored per session. In * bytes. * @return {@code this} object for chaining */ public StoreSettings setMaxSizePerSession(final Bytes maxSizePerSession) { this.maxSizePerSession = Args.notNull(maxSizePerSession, "maxSizePerSession"); return this; } /** * @return the location of the folder where {@link org.apache.wicket.pageStore.DiskPageStore} will store the files with page * instances per session */ public File getFileStoreFolder() { if (fileStoreFolder == null) { if (WebApplication.exists()) { fileStoreFolder = (File) WebApplication.get().getServletContext() .getAttribute("jakarta.servlet.context.tempdir"); } if (fileStoreFolder != null) { return fileStoreFolder; } try { fileStoreFolder = File.createTempFile("file-prefix", null).getParentFile(); } catch (IOException e) { throw new WicketRuntimeException(e); } } return fileStoreFolder; } /** * Sets the folder where {@link org.apache.wicket.pageStore.DiskPageStore} will store the files with page instances per * session * * @param fileStoreFolder * the new location * @return {@code this} object for chaining */ public StoreSettings setFileStoreFolder(final File fileStoreFolder) { this.fileStoreFolder = Args.notNull(fileStoreFolder, "fileStoreFolder"); return this; } /** * @return the capacity of the queue used to store the pages which will be stored asynchronously * @see org.apache.wicket.pageStore.AsynchronousPageStore */ public int getAsynchronousQueueCapacity() { return asynchronousQueueCapacity; } /** * Sets the capacity of the queue used to store the pages which will be stored asynchronously * * @param queueCapacity * the capacity of the queue * @see org.apache.wicket.pageStore.AsynchronousPageStore * @return {@code this} object for chaining */ public StoreSettings setAsynchronousQueueCapacity(int queueCapacity) { if (queueCapacity < 1) { throw new IllegalArgumentException( "The capacity of the asynchronous queue should be at least 1."); } asynchronousQueueCapacity = queueCapacity; return this; } /** * Sets a flag whether to wrap the configured {@link org.apache.wicket.pageStore.IPageStore} with * {@link org.apache.wicket.pageStore.AsynchronousPageStore}. By doing this the HTTP worker thread will not wait for the * actual write of the page's bytes into the wrapped {@link org.apache.wicket.pageStore.IPageStore}. * * @param async * {@code true} to make it asynchronous, {@code false} - otherwise * @return {@code this} object for chaining */ public StoreSettings setAsynchronous(boolean async) { asynchronous = async; return this; } /** * @return {@code true} if the storing of page is asynchronous */ public boolean isAsynchronous() { return asynchronous; } /** * Sets a flag whether to wrap the configured {@link org.apache.wicket.pageStore.IPageStore} with * {@link org.apache.wicket.pageStore.CryptingPageStore}. * * @param encrypted * {@code true} to encrypt, {@code false} - otherwise * @return {@code this} object for chaining */ public StoreSettings setEncrypted(boolean encrypted) { this.encrypted = encrypted; return this; } /** * @return {@code true} if the storing of page is encrypted */ public boolean isEncrypted() { return encrypted; } }
garciart/Automation
labs/old/lab002-ping.py
<reponame>garciart/Automation<gh_stars>0 #!/usr/bin/python # -*- coding: utf-8 -*- """Lab 002: Configure a device for Ethernet (Layer 3) connections. To run this lab: * Start GNS3 by executing "gns3_run" in a Terminal window. * Setup the lab environment according to lab002-ping.md. * Start all devices. * Run this script (i.e., "python lab002-ping.py") Project: Automation Requirements: * Python 2.7+ * pexpect * subprocess * GNS3 """ from __future__ import print_function import shlex import subprocess import sys import time import pexpect # Module metadata dunders __author__ = "<NAME>" __license__ = "MIT" def main(): try: print("Connecting to the device and configuring for Layer 3 connectivity...") # Connect to the device and allow time for any boot messages to clear console_ports = ("5000", "5001", "5002", "5003", "5004", "5005", None,) for port in console_ports: child = pexpect.spawn("telnet 192.168.1.1 {0}".format(port)) index = child.expect(["Press RETURN to get started.", pexpect.EOF, ]) if port is None: raise RuntimeError("Cannot connect to console port: Out of range.") if index == 0: break time.sleep(5) child.sendline("\r") # Check for a prompt, either R1> (User EXEC mode) or R1# (Privileged EXEC Mode) # and enable Privileged EXEC Mode if in User EXEC mode. index = child.expect_exact(["R1>", "R1#", ]) if index == 0: child.sendline("enable\r") child.expect_exact("R1#") # Enter Privileged EXEC mode child.sendline("configure terminal\r") child.expect_exact("R1(config)#") # Access Ethernet port child.sendline("interface FastEthernet0/0\r") child.expect_exact("R1(config-if)#") # Assign an IPv4 address and subnet mask child.sendline("ip address 192.168.1.20 255.255.255.0\r") child.expect_exact("R1(config-if)#") # Bring the Ethernet port up child.sendline("no shutdown\r") time.sleep(5) child.expect_exact("R1(config-if)#") child.sendline("exit\r") child.expect_exact("R1(config)#") child.sendline("end\r") child.expect_exact("R1#") # Save the configuration child.sendline("write memory\r") """ Building configuration... [OK] R1# """ child.expect_exact("[OK]", timeout=120) # Set the new configuration as default child.sendline("copy running-config startup-config\r") child.expect_exact("Destination filename [startup-config]?") child.sendline("\r") """ Building configuration... [OK] R1# """ child.expect_exact("[OK]", timeout=120) print("Configuration successful.") print("Checking connectivity...") # Ping the host from the device child.sendline("ping 192.168.1.10\r") # Check for the fail condition first, since the child will always return a prompt index = child.expect(["Success rate is 0 percent", "R1#", ], timeout=60) if index == 0: raise RuntimeError("Unable to ping the host from the device.") else: # Ping the device from the host cmd = "ping -c 4 192.168.1.20" # No need to read the output. Ping returns a non-zero value if no packets are received, # which will cause a check_output exception subprocess.check_output(shlex.split(cmd)) # Close Telnet and disconnect from device child.sendcontrol("]") child.sendline("q\r") print("Connectivity to and from the device is good.") # Close Telnet and disconnect from device child.sendcontrol("]") child.sendline("q\r") print("Successfully configured the device and checked connectivity.") except BaseException: e_type, e_value, e_traceback = sys.exc_info() print("Error: Type {0}: {1} in {2} at line {3}.".format( e_type.__name__, e_value, e_traceback.tb_frame.f_code.co_filename, e_traceback.tb_lineno if e_traceback.tb_next is None else e_traceback.tb_next.tb_lineno)) finally: print("Script complete. Have a nice day.") if __name__ == "__main__": print("Welcome to Lab 002: Configure a device for Ethernet (Layer 3) connections.") main()
Dbevan/SunderingShadows
d/koenig/village/dusty7.c
<filename>d/koenig/village/dusty7.c #include <std.h> #include <objects.h> #include "kai.h" inherit ROOM; void create() { ::create(); set_terrain(GRASSLANDS); set_travel(DIRT_ROAD); set_property("light",2); set_property("indoors",0); set_short("Along a dusty road"); set_long( @KAYLA This is a long dusty road, leaving Koenig to the north and leading to a small grove, where a large stream runs through. On the other side of the stream you can see a large hill, perhaps even a small mountain. KAYLA ); set_listen("default","The sound a gentle stream trickles from the south."); set_exits(([ "north" : "/d/koenig/village/dusty6", "east" : "/d/koenig/village/house2", "south" : "/d/koenig/stream/stream1" ] )); set_items(([ "mountain" : "You can't make any details out.", "stream" : "You can't make any details out." ] )); } void init() { ::init(); do_random_encounters( ({ MONDIR+"orc" }), 50,2); }
mihu915/mihu-cms-koa
src/model/menu.model.js
<gh_stars>1-10 const { Model, DataTypes } = require('sequelize') const { errorTypes } = require('../error/error-types') const createMenuModel = sequelize => { class Menu extends Model {} Menu.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, title: { type: DataTypes.STRING, allowNull: false, validate: { notNull: { msg: errorTypes.MISSING_PARAMETER } } }, icon: { type: DataTypes.STRING }, sort: { type: DataTypes.INTEGER, validate: { isInt: { msg: errorTypes.PARAMETER_IS_NOT_LEGAL } } }, type: { type: DataTypes.INTEGER, validate: { is: { args: /^[1-2]$/, msg: errorTypes.PARAMETER_IS_NOT_LEGAL } } }, url: { type: DataTypes.STRING }, parent_id: { type: DataTypes.INTEGER, references: { model: sequelize.models.Menu, key: 'id' } }, created: { type: DataTypes.INTEGER }, updated: { type: DataTypes.INTEGER } }, { tableName: 'mh_menu', sequelize } ) } module.exports = createMenuModel
gubaojian/trylearn
WebLayoutCore/Source/WebCore/platform/graphics/avfoundation/InbandTextTrackPrivateAVF.h
<filename>WebLayoutCore/Source/WebCore/platform/graphics/avfoundation/InbandTextTrackPrivateAVF.h /* * Copyright (C) 2012-2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef InbandTextTrackPrivateAVF_h #define InbandTextTrackPrivateAVF_h #if ENABLE(VIDEO) && (USE(AVFOUNDATION) || PLATFORM(IOS)) #include "InbandTextTrackPrivate.h" #include "InbandTextTrackPrivateClient.h" typedef const struct opaqueCMFormatDescription* CMFormatDescriptionRef; namespace JSC { class ArrayBuffer; } namespace WebCore { class AVFInbandTrackParent { public: virtual ~AVFInbandTrackParent(); virtual void trackModeChanged() = 0; }; class InbandTextTrackPrivateAVF : public InbandTextTrackPrivate { public: virtual ~InbandTextTrackPrivateAVF(); void setMode(InbandTextTrackPrivate::Mode) override; int trackIndex() const override { return m_index; } void setTextTrackIndex(int index) { m_index = index; } virtual void disconnect(); bool hasBeenReported() const { return m_hasBeenReported; } void setHasBeenReported(bool reported) { m_hasBeenReported = reported; } virtual void processCue(CFArrayRef attributedStrings, CFArrayRef nativeSamples, const MediaTime&); virtual void resetCueValues(); void beginSeeking(); void endSeeking() { m_seeking = false; } bool seeking() const { return m_seeking; } enum Category { LegacyClosedCaption, OutOfBand, InBand }; virtual Category textTrackCategory() const = 0; MediaTime startTimeVariance() const override { return MediaTime(1, 4); } virtual bool readNativeSampleBuffer(CFArrayRef nativeSamples, CFIndex, RefPtr<JSC::ArrayBuffer>&, MediaTime&, CMFormatDescriptionRef&); protected: InbandTextTrackPrivateAVF(AVFInbandTrackParent*, CueFormat); void processCueAttributes(CFAttributedStringRef, GenericCueData&); void processAttributedStrings(CFArrayRef, const MediaTime&); void processNativeSamples(CFArrayRef, const MediaTime&); void removeCompletedCues(); Vector<char> m_sampleInputBuffer; private: #if !RELEASE_LOG_DISABLED const char* logClassName() const final { return "InbandTextTrackPrivateAVF"; } #endif MediaTime m_currentCueStartTime; MediaTime m_currentCueEndTime; Vector<RefPtr<GenericCueData>> m_cues; AVFInbandTrackParent* m_owner; enum PendingCueStatus { None, DeliveredDuringSeek, Valid }; PendingCueStatus m_pendingCueStatus; int m_index; bool m_hasBeenReported; bool m_seeking; bool m_haveReportedVTTHeader; }; } // namespace WebCore #endif // ENABLE(VIDEO) && (USE(AVFOUNDATION) || PLATFORM(IOS)) #endif // InbandTextTrackPrivateAVF_h
ankushlt/testsigma
automator/src/com/testsigma/automator/actions/mobile/ios/settings/DisableWIFIAction.java
<reponame>ankushlt/testsigma package com.testsigma.automator.actions.mobile.ios.settings; import com.testsigma.automator.actions.mobile.MobileElementAction; import lombok.extern.log4j.Log4j2; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; @Log4j2 public class DisableWIFIAction extends MobileElementAction { private static final String SUCCESS_MESSAGE = "Successfully disabled WIFI."; private static final String FAILURE_MESSAGE = "Unable to switch off WIFI in settings app.<br>Alternatively you can add steps for opening" + " settings app and navigate to WIFI. Below are the test steps.<br>" + "1.Open application with bundle id <test data> (Ex:com.apple.Preferences for settings app)<br>" + "2.Tap on <Element> (Ex XPATH Locator-{name:Wi-Fi})" + "3.Tap on <Element> (Ex XPATH Locator-{Xpath://XCUIElementTypeSwitch[@name='Wi-Fi']})"; @Override protected void execute() throws Exception { //Switch to settings app getDriver().activateApp("com.apple.Preferences"); WebElement wifiSettingsElement = getDriver().findElement(By.name("Wi-Fi")); wifiSettingsElement.click(); String switchValue = null; for (int i = 0; i < 6; i++) { switchValue = getDriver().findElement(By.xpath("//XCUIElementTypeSwitch[@name='Wi-Fi']")).getAttribute("value"); if (switchValue != null) { break; } } if (switchValue.equals("1")) { //Element is dynamically getting updated in few devices. So we refetch the element and execute a click action. getDriver().findElement(By.xpath("//XCUIElementTypeSwitch[@name='Wi-Fi']")).click(); } //We switch back to parent app. String parentAppBundleID = (String) getDriver().getCapabilities().getCapability("bundleId"); log.info("Parent App bundle ID:" + parentAppBundleID); boolean appRedirected = false; if (parentAppBundleID != null) { try { getDriver().activateApp(parentAppBundleID); appRedirected = true; } catch (Exception e) { //We ignore this exception, User can execute open app with bundleId step if switching failed. log.error("Unable to switch to parent App:", e); } } setSuccessMessage(SUCCESS_MESSAGE); if (!appRedirected) { setSuccessMessage(String.format("%s<br>If the app is not redirected to parent APP, use below step<br>" + "Open application with bundle id <test data>", SUCCESS_MESSAGE)); } } @Override protected void handleException(Exception e) { super.handleException(e); setErrorMessage(FAILURE_MESSAGE + "<br>" + getErrorMessage()); } }
half22/picnic
src/plugins/toggle-password.js
<filename>src/plugins/toggle-password.js<gh_stars>1-10 (function(window, $, picnic) { 'use strict'; function createButton(input) { var button = $('<button type="button" class="c-toggle-password-button" tabindex="-1"></button>'); button.insertAfter(input); return button; } function onClick(button, input) { var isPassword = input.is(':password'); if(isPassword) { input.prop('type', 'text'); button.addClass('is-active'); } else { input.prop('type', 'password'); button.removeClass('is-active'); } input.focus(); return false; } $.extend($.fn, { picnicTogglePassword: function () { return this.each(function (index, domElement) { var input = $(domElement); if (!input.data('plugin-toggle-password')) { var button = createButton(input); button.on('click', function() { onClick(button, input); }); input.data('plugin-toggle-password', true); } }); } }); window.picnic = picnic; if(typeof exports === 'object') { module.exports = $.fn.picnicTogglePassword; } else if(typeof define === 'function' && define.amd) { define(function() { return $.fn.picnicTogglePassword; }); } })(window, jQuery, window.picnic || {});
pierrecagne/mdc
src/event.js
export const INPUT = "@npolar/input"; export const CHANGE = "@npolar/change";
DazEB2/SimplePyScripts
html_parsing/Wikipedia__Timeline_of_release_years/common.py
<filename>html_parsing/Wikipedia__Timeline_of_release_years/common.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from typing import Callable, Any, Optional import requests from bs4 import BeautifulSoup MatchFunc = Callable[[Any], bool] def find_table(url: str, is_match_table_func: MatchFunc=lambda table: True) -> Optional['Table']: rs = requests.get(url) root = BeautifulSoup(rs.content, 'html.parser') for t in root.select('.wikitable'): if not t.caption: continue if is_match_table_func(t): return t return def get_parsed_two_column_wikitable(url: str, is_match_table_func: MatchFunc=lambda table: True, is_match_row_func: MatchFunc=lambda tr: True) -> [(str, str)]: table = find_table(url, is_match_table_func) if not table: raise Exception('Not found table "Timeline of releases"') items = [] year = None # Timeline of release years for tr in table.select('tr'): td_items = tr.select('td') # if len(td_items) != 2: # continue # Если пустой или None if not td_items: continue # Отбрасываем строки с годом, но без игры if len(td_items) == 1 and td_items[0].i is None: continue if len(td_items) == 2: year = td_items[0].text.strip() name = td_items[1].i.text.strip() else: # Сюда попадают игры, попавшие с другими в один и тот же год, например # 2000: Resident Evil Survivor # 2000: Resident Evil – Code: Veronica # # year берется из предыдущей строки # year = ... name = td_items[0].i.text.strip() if not is_match_row_func(tr): continue if year and name: items.append((year, name)) return items
diegoperezl/cf4j
src/main/java/es/upm/etsisi/cf4j/recommender/matrixFactorization/BNMF.java
<reponame>diegoperezl/cf4j<filename>src/main/java/es/upm/etsisi/cf4j/recommender/matrixFactorization/BNMF.java<gh_stars>10-100 package es.upm.etsisi.cf4j.recommender.matrixFactorization; import java.util.Arrays; import java.util.Map; import java.util.Random; import java.util.concurrent.locks.ReentrantLock; import es.upm.etsisi.cf4j.util.process.Parallelizer; import es.upm.etsisi.cf4j.util.process.Partible; import es.upm.etsisi.cf4j.data.DataModel; import es.upm.etsisi.cf4j.data.Item; import es.upm.etsisi.cf4j.recommender.Recommender; import es.upm.etsisi.cf4j.util.Maths; import org.apache.commons.math3.special.Gamma; /** * Implements <NAME>., <NAME>., &amp; <NAME>. (2016). A non negative matrix * factorization for collaborative filtering recommender systems on a Bayesian probabilistic model. * Knowledge-Based Systems, 97, 188-202. */ public class BNMF extends Recommender { protected static final double DEFAULT_R = 4; /** User factors */ protected double[][] a; /** Item factors */ protected double[][] b; /** Gamma parameters */ protected double[][] gamma; /** Epsilon+ parameters */ protected double[][] epsilonPlus; /** Epsilon- parameters */ protected double[][] epsilonMinus; /** * This hyper-parameter is related to the possibility of obtaining overlapping groups of users * sharing the same tastes. */ protected final double alpha; /** * This hyper-parameter represents the amount of evidence that the algorithm requires to deduce * that a group of users likes an item. */ protected final double beta; /** Hyper-parameter of the binomial distribution. */ protected final double r; /** Number of factors */ protected final int numFactors; /** Number of iterations */ protected final int numIters; /** * Model constructor from a Map containing the model's hyper-parameters values. Map object must * contains the following keys: * * <ul> * <li><b>numFactors</b>: int value with the number of latent factors. * <li><b>numIters:</b>: int value with the number of iterations. * <li><b>alpha</b>: double value with the alpha hyper-parameter. This value is related to the * possibility of obtaining overlapping groups of users sharing the same tastes. * <li><b>beta</b>: double value with the beta hyper-parameter. This value represents the amount * of evidences that the algorithm requires to deduce that a group of users likes an item. * <li><b><em>seed</em></b> (optional): random seed for generating random numbers. If missing, * random value is used. * </ul> * * @param datamodel DataModel instance * @param params Model's hyper-parameters values */ public BNMF(DataModel datamodel, Map<String, Object> params) { this( datamodel, (int) params.get("numFactors"), (int) params.get("numIters"), (double) params.get("alpha"), (double) params.get("beta"), params.containsKey("r") ? (double) params.get("r") : DEFAULT_R, params.containsKey("seed") ? (long) params.get("seed") : System.currentTimeMillis()); } /** * Model constructor * * @param datamodel DataModel instance * @param numFactors Number of factors * @param numIters Number of iterations * @param alpha This parameter is related to the possibility of obtaining overlapping groups of * users sharing the same tastes * @param beta Amount of evidences that the algorithm requires to deduce that a group of users * likes an item */ public BNMF(DataModel datamodel, int numFactors, int numIters, double alpha, double beta) { this(datamodel, numFactors, numIters, alpha, beta, DEFAULT_R, System.currentTimeMillis()); } /** * Model constructor * * @param datamodel DataModel instance * @param numFactors Number of factors * @param numIters Number of iterations * @param alpha This parameter is related to the possibility of obtaining overlapping groups of * users sharing the same tastes * @param beta Amount of evidences that the algorithm requires to deduce that a group of users * likes an item * @param seed Seed for random numbers generation */ public BNMF( DataModel datamodel, int numFactors, int numIters, double alpha, double beta, long seed) { this(datamodel, numFactors, numIters, alpha, beta, DEFAULT_R, seed); } /** * Model constructor * * @param datamodel DataModel instance * @param numFactors Number of factors * @param numIters Number of iterations * @param alpha This parameter is related to the possibility of obtaining overlapping groups of * users sharing the same tastes * @param beta Amount of evidences that the algorithm requires to deduce that a group of users * likes an item * @param r Parameter of the binomial distribution (fixed to 4) * @param seed Seed for random numbers generation */ public BNMF( DataModel datamodel, int numFactors, int numIters, double alpha, double beta, double r, long seed) { super(datamodel); this.numFactors = numFactors; this.numIters = numIters; this.alpha = alpha; this.beta = beta; this.r = r; Random rand = new Random(seed); // Users initialization this.gamma = new double[datamodel.getNumberOfUsers()][numFactors]; for (int u = 0; u < datamodel.getNumberOfUsers(); u++) { for (int k = 0; k < numFactors; k++) { this.gamma[u][k] = rand.nextDouble(); } } // Items initialization this.epsilonPlus = new double[datamodel.getNumberOfItems()][numFactors]; this.epsilonMinus = new double[datamodel.getNumberOfItems()][numFactors]; for (int i = 0; i < datamodel.getNumberOfItems(); i++) { for (int k = 0; k < numFactors; k++) { this.epsilonPlus[i][k] = rand.nextDouble(); this.epsilonMinus[i][k] = rand.nextDouble(); } } } /** * Get the number of factors of the model * * @return Number of factors */ public int getNumFactors() { return this.numFactors; } /** * Get the number of iterations * * @return Number of iterations */ public int getNumIters() { return this.numIters; } /** * Get the alpha value * * @return Alpha value */ public double getAlpha() { return this.alpha; } /** * Get the beta value * * @return Beta value */ public double getBeta() { return this.beta; } /** * Get the r value * * @return r value */ public double getR() { return this.r; } /** * Get the gamma vector of an user * * @param userIndex user index * @return User's gamma vector */ public double[] getGamma(int userIndex) { return this.gamma[userIndex]; } /** * Get the epsilon+ vector of an item * * @param itemIndex item index * @return Item's epsilon+ vector */ public double[] getEpsilonPlus(int itemIndex) { return this.epsilonPlus[itemIndex]; } /** * Get the epsilon- vector of an item * * @param itemIndex item index * @return Item's epsilon- vector */ public double[] getEpsilonMinus(int itemIndex) { return this.epsilonMinus[itemIndex]; } /** * Get the latent factors vector of a user (au) * * @param userIndex User * @return Latent factors vector */ public double[] getUserFactors(int userIndex) { return this.a[userIndex]; } /** * Get the latent factors vector of an item (bi) * * @param itemIndex User * @return Latent factors vector */ public double[] getItemFactors(int itemIndex) { return this.b[itemIndex]; } @Override public void fit() { System.out.println("\nFitting " + this.toString()); for (int iter = 1; iter <= this.numIters; iter++) { Parallelizer.exec(datamodel.getItems(), new UpdateModel()); if ((iter % 10) == 0) System.out.print("."); if ((iter % 100) == 0) System.out.println(iter + " iterations"); } // set user factors this.a = new double[this.datamodel.getNumberOfUsers()][this.numFactors]; for (int userIndex = 0; userIndex < this.datamodel.getNumberOfUsers(); userIndex++) { double sum = 0; for (int k = 0; k < this.numFactors; k++) { sum += this.gamma[userIndex][k]; } for (int k = 0; k < this.numFactors; k++) { this.a[userIndex][k] = this.gamma[userIndex][k] / sum; } } // set item factors this.b = new double[this.datamodel.getNumberOfItems()][this.numFactors]; for (int itemIndex = 0; itemIndex < this.datamodel.getNumberOfItems(); itemIndex++) { for (int k = 0; k < this.numFactors; k++) { this.b[itemIndex][k] = this.epsilonPlus[itemIndex][k] / (this.epsilonPlus[itemIndex][k] + this.epsilonMinus[itemIndex][k]); } } } @Override public double predict(int userIndex, int itemIndex) { double prob = Maths.dotProduct(this.a[userIndex], this.b[itemIndex]); prob = Math.max(prob, 1E-10); return Math.ceil(prob * (super.datamodel.getMaxRating() - super.datamodel.getMinRating() + 1)); } @Override public String toString() { return "BNMF(" + "numFactors=" + this.numFactors + "; " + "numIters=" + this.numIters + "; " + "alpha=" + this.alpha + "; " + "beta=" + this.beta + "; " + "r=" + this.r + ")"; } /** Auxiliary inner class to parallelize model update */ private class UpdateModel implements Partible<Item> { private static final int NUM_LOCKS = 100; private final ReentrantLock[] locks; private final double[][] gamma; private final double[][] epsilonPlus; private final double[][] epsilonMinus; public UpdateModel() { // Locks avoid problem while users gammas are updated in different threads this.locks = new ReentrantLock[NUM_LOCKS]; for (int i = 0; i < NUM_LOCKS; i++) { this.locks[i] = new ReentrantLock(); } this.gamma = new double[datamodel.getNumberOfUsers()][numFactors]; this.epsilonPlus = new double[datamodel.getNumberOfItems()][numFactors]; this.epsilonMinus = new double[datamodel.getNumberOfItems()][numFactors]; } @Override public void beforeRun() { // Init gamma for (double[] row : this.gamma) { Arrays.fill(row, alpha); } // Init epsilon+ for (double[] row : this.epsilonPlus) { Arrays.fill(row, beta); } // Init epsilon- for (double[] row : this.epsilonMinus) { Arrays.fill(row, beta); } } @Override public void run(Item item) { int itemIndex = item.getItemIndex(); for (int u = 0; u < item.getNumberOfRatings(); u++) { int userIndex = item.getUserAt(u); double[] lambda = new double[BNMF.this.numFactors]; double rating = (item.getRatingAt(u) - datamodel.getMinRating()) / (datamodel.getMaxRating() - datamodel.getMinRating()); double sum = 0; // Compute lambda for (int k = 0; k < BNMF.this.numFactors; k++) { lambda[k] = Math.exp( Gamma.digamma(BNMF.this.gamma[userIndex][k]) + BNMF.this.r * rating * Gamma.digamma(BNMF.this.epsilonPlus[itemIndex][k]) + BNMF.this.r * (1 - rating) * Gamma.digamma(BNMF.this.epsilonMinus[itemIndex][k]) - BNMF.this.r * Gamma.digamma( BNMF.this.epsilonPlus[itemIndex][k] + BNMF.this.epsilonMinus[itemIndex][k])); sum += lambda[k]; } // Update model for (int k = 0; k < BNMF.this.numFactors; k++) { double l = lambda[k] / sum; // Update E+ & E- this.epsilonPlus[itemIndex][k] += l * BNMF.this.r * rating; this.epsilonMinus[itemIndex][k] += l * BNMF.this.r * (1 - rating); // Update gamma: user must be block to avoid concurrency problems int lockIndex = userIndex % this.locks.length; this.locks[lockIndex].lock(); this.gamma[userIndex][k] += l; this.locks[lockIndex].unlock(); } } } @Override public void afterRun() { BNMF.this.gamma = this.gamma; BNMF.this.epsilonPlus = this.epsilonPlus; BNMF.this.epsilonMinus = this.epsilonMinus; } } }
373974360/deyatech-cms
statistics/statistics-service/src/main/java/com/deyatech/statistics/controller/CatalogDataController.java
package com.deyatech.statistics.controller; import com.deyatech.common.entity.RestResult; import com.deyatech.statistics.service.CatalogDataService; import com.deyatech.statistics.vo.UserDataQueryVo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 描述: * * @Author: MaChaoWei * @Date: 2020/2/5 15:16 */ @Slf4j @RestController @RequestMapping("/statistics/catalogData") @Api(tags = {"栏目数据统计"}) public class CatalogDataController { @Autowired CatalogDataService catalogDataService; /** * 站点数据统计 * * @param queryVo * @return */ @RequestMapping("/getCatalogCountList") @ApiOperation(value="栏目数据统计", notes="栏目数据统计") @ApiImplicitParam(name = "queryVo", value = "对象", required = true, dataType = "UserDataQueryVo", paramType = "query") public RestResult getCatalogCountList(UserDataQueryVo queryVo) { return RestResult.ok(catalogDataService.getCatalogCountList(queryVo)); } }
kfox1111/spire
cmd/spire-server/cli/bundle/show.go
package bundle import ( "context" "flag" "fmt" "github.com/mitchellh/cli" bundlev1 "github.com/spiffe/spire-api-sdk/proto/spire/api/server/bundle/v1" "github.com/spiffe/spire/cmd/spire-server/util" common_cli "github.com/spiffe/spire/pkg/common/cli" ) // NewShowCommand creates a new "show" subcommand for "bundle" command. func NewShowCommand() cli.Command { return newShowCommand(common_cli.DefaultEnv) } func newShowCommand(env *common_cli.Env) cli.Command { return util.AdaptCommand(env, new(showCommand)) } type showCommand struct { format string } func (c *showCommand) Name() string { return "bundle show" } func (c *showCommand) Synopsis() string { return "Prints server CA bundle to stdout" } func (c *showCommand) AppendFlags(fs *flag.FlagSet) { fs.StringVar(&c.format, "format", util.FormatPEM, fmt.Sprintf("The format to show the bundle. Either %q or %q.", util.FormatPEM, util.FormatSPIFFE)) } func (c *showCommand) Run(ctx context.Context, env *common_cli.Env, serverClient util.ServerClient) error { bundleClient := serverClient.NewBundleClient() resp, err := bundleClient.GetBundle(ctx, &bundlev1.GetBundleRequest{}) if err != nil { return err } return printBundleWithFormat(env.Stdout, resp, c.format, false) }
leozd1/Aulas-de-python
aula22b.py
<reponame>leozd1/Aulas-de-python # Exercicio 107 # Crie um módulo chamado moeda.py que tenha as funções incorporadas # aumentar(), # diminuir(), # dobro() e # metade(). # Faça também um programa que importe esse módulo e use algumas dessas funções. ''' Dica: No exercicio ficou tudo dentro de uma pasta, o modulo e o programa principal em arquivos separados. Coloque os modulos dos exercicios dentro da pasta aula22Pacote o modulo moeda107.py > aula22Pacote # Programa Principal from aula22Pacote.moeda107 import metade, dobro, aumentar, diminuir # da pasta.modulo importe a função - # ou # from aula22Pacote import moeda107 - terá que expecificar a função (moeda107.diminuir(p)) # devendo estar na mesma pasta, poderia dar um import so do modulo # mas cuidado ao usar "from pasta import modulo", pois pode causar conflito p = float(input('Digite um preço: \nR$ ')) print('\033[0;33m==\033[m'*20) print(f'A metade de R${p:.2f} é R${metade(p):.2f}') print('\033[0;36m==\033[m'*20) print(f'O dobro de R%{p:.2f} é R${dobro(p):.2f}') print('\033[0;37m==\033[m'*20) print(f'O preço a 10% de aumento, será R${aumentar(p, 10):.2f}') # o valor da taxa é fixa print('\033[0;34m==\033[m'*20) print(f'O preço com 50% de desconto, será R${diminuir(p, 50):.2f}') print('\033[0;34m==\033[m'*20) ''' # Exercicio 108 # Adapte o código do desafio #107, # criando uma função adicional chamada moeda() # que consiga mostrar os números como um valor monetário formatado. ''' from aula22Pacote import moeda107 p = float(input('Digite um preço: \nR$ ')) print('\033[0;33m==\033[m'*20) print(f'A metade de {moeda107.moeda(p)} é {moeda107.moeda(moeda107.metade(p))}') # parte do exercicio 108 print('\033[0;36m==\033[m'*20) print(f'O dobro de {moeda107.moeda(p)} é {moeda107.moeda(moeda107.dobro(p))}') # parte do exercico 107 print('\033[0;37m==\033[m'*20) print(f'O preço a 10% de aumento, será {moeda107.moeda(moeda107.aumentar(p, 10))}') # o valor da taxa é fixa print('\033[0;34m==\033[m'*20) print(f'O preço com 50% de desconto, será {moeda107.moeda(moeda107.diminuir(p, 50))}') print('\033[0;34m==\033[m'*20) ''' # Exercicio 109 # Modifique as funções que foram criadas no desafio 107 para que elas aceitem um parâmetro a mais, # informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), # desenvolvida no desafio 108. ''' Resumindo, mexe no modulo do exercicio 108 pra ficar bonito from aula22Pacote import moeda107 as moedita # as transforma uma palavra em outra, # util em caso de palavras repetidas p = float(input('Digite um preço: \nR$ ')) print('\033[0;33m==\033[m'*20) # pode-se tirar a chamada do modulo do função em excesso print(f'A metade de {moedita.moeda(p)} é {moedita.metade(p, True)}') # parte do exercicio 108 print('\033[0;36m==\033[m'*20) print(f'O dobro de {moedita.moeda(p)} é {moedita.dobro(p)}') # parte do exercico 107 print('\033[0;37m==\033[m'*20) # por não especificar se é false ou true, ele considera como false, por ta vazio print(f'O preço a 10% de aumento, será {moedita.aumentar(p, 10, True)}') # o valor da taxa é fixa print('\033[0;34m==\033[m'*20) # 'so retorne res se formato for False, senão retorne moeda(res), ou seja, bonitinho' print(f'O preço com 50% de desconto, será {moedita.diminuir(p, 50)}') # só atente para as formas de retorno formatada print('\033[0;34m==\033[m'*20) # na hora de retirar os excesso do pacote de modulos das funções ''' # Exercicio 110 # Adicione o módulo moeda.py criado nos desafios anteriores, uma função chamada resumo(), # que mostre na tela algumas informações geradas pelas funções que já temos no módulo criado até aqui. ''' Continue mexendo no modulo moeda107 from aula22Pacote import exer110 as moeda # as transforma uma palavra em outra, # util em caso de palavras repetidas p = float(input('Digite um preço: \nR$ ')) moeda.resumo(p) ''' # Exercicio 111 # Crie um pacote chamado utilidadesCeV que tenha dois módulos internos chamados moeda e dado. # Transfira todas as funções utilizadas nos desafios 107, 108 e 109 para o primeiro pacote # e mantenha tudo funcionando. ''' basicamente colocar o modulo com as funções em uma pasta(pacote) dentro de outra pasta(pacote) e chamar ele das seguites formas, atraves do arquivo __init__.py: from aula22Pacote.utilidadesCeV import moeda from aula22Pacote.utilidadesCeV import moeda, dado (caso precise importar os dois pacotes) import aula22Pacote.utilidadesCeV (mas ai precisa escrever todo o caminho no programa principal) aula22Pacote.utilidadesCeV.moeda.resumo(p) from aula22Pacote.utilidadesCeV import moeda # sendo esse mais simples e usado o chamado # da pasta aula, dentro de utilidade, importe moeda p = float(input('Digite um preço: \nR$ ')) moeda.resumo(p) ''' # Exercicio 112 # Dentro do pacote utilidadesCeV que criamos no desafio 111, temos um módulo chamado dado. # Crie uma função chamada leiaDinheiro() que seja capaz de funcionar como a função imputa(), # mas com uma validação de dados para aceitar apenas valores que seja monetários. from aula22Pacote.utilidadesCeV import moeda # sendo esse mais simples e usado o chamado # da pasta aula, dentro de utilidade, importe moeda from aula22Pacote.utilidadesCeV import dado p = dado.escreva("Digite um valor: \nR$ ") moeda.resumo(p, 10, 10)
Ravyo/Department-Portal
CSDP/main/views.py
from django.shortcuts import redirect, render from main.models import Meeting, ToDo, EventGallery from teachers.models import Teacher from students.models import Student def home(request): students= Student.objects.all() teachers = Teacher.objects.all() # for teacher counter # for club counter meetings = Meeting.objects.all() # for meetings todos = ToDo.objects.order_by('-todo_time') # for todo events = EventGallery.objects.order_by('-date') # for events context = { 'teachers': teachers, 'meetings': meetings, 'todos': todos, 'events': events, } return render(request, 'index.html', context) def redirectView(request): response = redirect('/welcome/') return response
DimensionalDevelopment/Statues
src/main/java/org/dimdev/statues/shared/gui/SlotPickBlock.java
<gh_stars>0 package org.dimdev.statues.shared.gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class SlotPickBlock extends Slot { ContainerPickBlock container; public SlotPickBlock(ContainerPickBlock c, int index, int x, int y) { super(c.inventory, index, x, y); container = c; } void click(EntityPlayer player, ItemStack itemstack, int count) { player.inventory.setItemStack(null); if (itemstack == null) { return; } if (container.gui == null) { return; } putStack(new ItemStack(itemstack.getItem(), itemstack.getCount(), itemstack.getItemDamage())); int newSize; if (container.resultSlot == this) { newSize = itemstack.getCount() - count; } else { newSize = itemstack.getCount(); ItemStack otherstack = container.resultSlot.getStack(); if (otherstack != null && otherstack.getItem().equals(itemstack.getItem()) && otherstack.getItemDamage() == itemstack.getItemDamage()) { newSize = otherstack.getCount() + count; } else { newSize = count; } } if (newSize > 64) { newSize = 64; } container.resultSlot.putStack(newSize <= 0 ? null : new ItemStack(itemstack.getItem(), newSize, itemstack.getItemDamage())); } @Override public ItemStack onTake(EntityPlayer thePlayer, ItemStack stack) { ItemStack item = super.onTake(thePlayer, stack); click(thePlayer, stack, 1); return item; } public ItemStack transferStackInSlot(EntityPlayer player) { click(player, getStack(), 64); return null; } }
kkauder/spack
var/spack/repos/builtin/packages/py-kombu/package.py
<gh_stars>1-10 # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyKombu(PythonPackage): """Messaging library for Python.""" pypi = "kombu/kombu-4.3.0.tar.gz" version('5.0.2', sha256='f4965fba0a4718d47d470beeb5d6446e3357a62402b16c510b6a2f251e05ac3c') version('4.6.11', sha256='ca1b45faac8c0b18493d02a8571792f3c40291cf2bcf1f55afed3d8f3aa7ba74') version('4.6.6', sha256='1760b54b1d15a547c9a26d3598a1c8cdaf2436386ac1f5561934bc8a3cbbbd86') version('4.5.0', sha256='389ba09e03b15b55b1a7371a441c894fd8121d174f5583bbbca032b9ea8c9edd') version('4.3.0', sha256='529df9e0ecc0bad9fc2b376c3ce4796c41b482cf697b78b71aea6ebe7ca353c8') depends_on('python@2.7:2.8,3.5:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('py-amqp@2.5.2:2.5.999', when="@:4.6.6", type=('build', 'run')) depends_on('py-amqp@2.6.0:2.6.999', when="@4.6.7:4.999", type=('build', 'run')) depends_on('py-amqp@5.0.0:5.999', when="@5.0.0:", type=('build', 'run')) depends_on('py-importlib-metadata@0.18:', type=('build', 'run'))
flex-seongbok/java-slack-sdk
slack-api-model/src/main/java/com/slack/api/model/event/GroupDeletedEvent.java
<gh_stars>100-1000 package com.slack.api.model.event; import lombok.Data; /** * The group_deleted event is sent to all members of a private channel when it is deleted. * Clients can use this to update their local list of private channels. * <p> * https://api.slack.com/events/group_deleted */ @Data public class GroupDeletedEvent implements Event { public static final String TYPE_NAME = "group_deleted"; private final String type = TYPE_NAME; private String channel; private Integer dateDeleted; private String actorId; private String eventTs; }
pdv-ru/ClickHouse
src/Functions/IFunction.h
<gh_stars>1-10 #pragma once #include <Core/ColumnNumbers.h> #include <Core/ColumnsWithTypeAndName.h> #include <Core/Names.h> #include <DataTypes/IDataType.h> #include "config_core.h" #include <memory> /// This file contains user interface for functions. namespace llvm { class LLVMContext; class Value; class IRBuilderBase; } namespace DB { namespace ErrorCodes { extern const int NOT_IMPLEMENTED; extern const int ILLEGAL_TYPE_OF_ARGUMENT; } class Field; /// The simplest executable object. /// Motivation: /// * Prepare something heavy once before main execution loop instead of doing it for each columns. /// * Provide const interface for IFunctionBase (later). /// * Create one executable function per thread to use caches without synchronization (later). class IExecutableFunction { public: virtual ~IExecutableFunction() = default; /// Get the main function name. virtual String getName() const = 0; ColumnPtr execute(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count, bool dry_run) const; protected: virtual ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const = 0; virtual ColumnPtr executeDryRunImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const { return executeImpl(arguments, result_type, input_rows_count); } /** Default implementation in presence of Nullable arguments or NULL constants as arguments is the following: * if some of arguments are NULL constants then return NULL constant, * if some of arguments are Nullable, then execute function as usual for columns, * where Nullable columns are substituted with nested columns (they have arbitrary values in rows corresponding to NULL value) * and wrap result in Nullable column where NULLs are in all rows where any of arguments are NULL. */ virtual bool useDefaultImplementationForNulls() const { return true; } /** If the function have non-zero number of arguments, * and if all arguments are constant, that we could automatically provide default implementation: * arguments are converted to ordinary columns with single value, then function is executed as usual, * and then the result is converted to constant column. */ virtual bool useDefaultImplementationForConstants() const { return false; } /** If function arguments has single low cardinality column and all other arguments are constants, call function on nested column. * Otherwise, convert all low cardinality columns to ordinary columns. * Returns ColumnLowCardinality if at least one argument is ColumnLowCardinality. */ virtual bool useDefaultImplementationForLowCardinalityColumns() const { return true; } /** If function arguments has single sparse column and all other arguments are constants, call function on nested column. * Otherwise, convert all sparse columns to ordinary columns. * If default value doesn't change after function execution, returns sparse column as a result. * Otherwise, result column is converted to full. */ virtual bool useDefaultImplementationForSparseColumns() const { return true; } /** Some arguments could remain constant during this implementation. */ virtual ColumnNumbers getArgumentsThatAreAlwaysConstant() const { return {}; } /** True if function can be called on default arguments (include Nullable's) and won't throw. * Counterexample: modulo(0, 0) */ virtual bool canBeExecutedOnDefaultArguments() const { return true; } private: ColumnPtr defaultImplementationForConstantArguments( const ColumnsWithTypeAndName & args, const DataTypePtr & result_type, size_t input_rows_count, bool dry_run) const; ColumnPtr defaultImplementationForNulls( const ColumnsWithTypeAndName & args, const DataTypePtr & result_type, size_t input_rows_count, bool dry_run) const; ColumnPtr executeWithoutLowCardinalityColumns( const ColumnsWithTypeAndName & args, const DataTypePtr & result_type, size_t input_rows_count, bool dry_run) const; ColumnPtr executeWithoutSparseColumns( const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count, bool dry_run) const; }; using ExecutableFunctionPtr = std::shared_ptr<IExecutableFunction>; using Values = std::vector<llvm::Value *>; /** Function with known arguments and return type (when the specific overload was chosen). * It is also the point where all function-specific properties are known. */ class IFunctionBase { public: virtual ~IFunctionBase() = default; virtual ColumnPtr execute( const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count, bool dry_run = false) const { return prepare(arguments)->execute(arguments, result_type, input_rows_count, dry_run); } /// Get the main function name. virtual String getName() const = 0; virtual const DataTypes & getArgumentTypes() const = 0; virtual const DataTypePtr & getResultType() const = 0; /// Do preparations and return executable. /// sample_columns should contain data types of arguments and values of constants, if relevant. virtual ExecutableFunctionPtr prepare(const ColumnsWithTypeAndName & arguments) const = 0; #if USE_EMBEDDED_COMPILER virtual bool isCompilable() const { return false; } /** Produce LLVM IR code that operates on scalar values. See `toNativeType` in DataTypes/Native.h * for supported value types and how they map to LLVM types. * * NOTE: the builder is actually guaranteed to be exactly `llvm::IRBuilder<>`, so you may safely * downcast it to that type. This method is specified with `IRBuilderBase` because forward-declaring * templates with default arguments is impossible and including LLVM in such a generic header * as this one is a major pain. */ virtual llvm::Value * compile(llvm::IRBuilderBase & /*builder*/, Values /*values*/) const { throw Exception(getName() + " is not JIT-compilable", ErrorCodes::NOT_IMPLEMENTED); } #endif virtual bool isStateful() const { return false; } /** Should we evaluate this function while constant folding, if arguments are constants? * Usually this is true. Notable counterexample is function 'sleep'. * If we will call it during query analysis, we will sleep extra amount of time. */ virtual bool isSuitableForConstantFolding() const { return true; } /** If function isSuitableForConstantFolding then, this method will be called during query analyzis * if some arguments are constants. For example logical functions (AndFunction, OrFunction) can * return they result based on some constant arguments. * Arguments are passed without modifications, useDefaultImplementationForNulls, useDefaultImplementationForConstants, * useDefaultImplementationForLowCardinality are not applied. */ virtual ColumnPtr getConstantResultForNonConstArguments( const ColumnsWithTypeAndName & /* arguments */, const DataTypePtr & /* result_type */) const { return nullptr; } /** Function is called "injective" if it returns different result for different values of arguments. * Example: hex, negate, tuple... * * Function could be injective with some arguments fixed to some constant values. * Examples: * plus(const, x); * multiply(const, x) where x is an integer and constant is not divisible by two; * concat(x, 'const'); * concat(x, 'const', y) where const contain at least one non-numeric character; * concat with FixedString * dictGet... functions takes name of dictionary as its argument, * and some dictionaries could be explicitly defined as injective. * * It could be used, for example, to remove useless function applications from GROUP BY. * * Sometimes, function is not really injective, but considered as injective, for purpose of query optimization. * For example, toString function is not injective for Float64 data type, * as it returns 'nan' for many different representation of NaNs. * But we assume, that it is injective. This could be documented as implementation-specific behaviour. * * sample_columns should contain data types of arguments and values of constants, if relevant. * NOTE: to check is function injective with any arguments, you can pass * empty columns as sample_columns (since most of the time function will * ignore it anyway, and creating arguments just for checking is * function injective or not is overkill). */ virtual bool isInjective(const ColumnsWithTypeAndName & /*sample_columns*/) const { return false; } /** Function is called "deterministic", if it returns same result for same values of arguments. * Most of functions are deterministic. Notable counterexample is rand(). * Sometimes, functions are "deterministic" in scope of single query * (even for distributed query), but not deterministic it general. * Example: now(). Another example: functions that work with periodically updated dictionaries. */ virtual bool isDeterministic() const { return true; } virtual bool isDeterministicInScopeOfQuery() const { return true; } /** Lets you know if the function is monotonic in a range of values. * This is used to work with the index in a sorted chunk of data. * And allows to use the index not only when it is written, for example `date >= const`, but also, for example, `toMonth(date) >= 11`. * All this is considered only for functions of one argument. */ virtual bool hasInformationAboutMonotonicity() const { return false; } struct ShortCircuitSettings { /// Should we enable lazy execution for the first argument of short-circuit function? /// Example: if(cond, then, else), we don't need to execute cond lazily. bool enable_lazy_execution_for_first_argument; /// Should we enable lazy execution for functions, that are common descendants of /// different short-circuit function arguments? /// Example 1: if (cond, expr1(..., expr, ...), expr2(..., expr, ...)), we don't need /// to execute expr lazily, because it's used in both branches. /// Example 2: and(expr1, expr2(..., expr, ...), expr3(..., expr, ...)), here we /// should enable lazy execution for expr, because it must be filtered by expr1. bool enable_lazy_execution_for_common_descendants_of_arguments; /// Should we enable lazy execution without checking isSuitableForShortCircuitArgumentsExecution? /// Example: toTypeName(expr), even if expr contains functions that are not suitable for /// lazy execution (because of their simplicity), we shouldn't execute them at all. bool force_enable_lazy_execution; }; /** Function is called "short-circuit" if it's arguments can be evaluated lazily * (examples: and, or, if, multiIf). If function is short circuit, it should be * able to work with lazy executed arguments, * this method will be called before function execution. * If function is short circuit, it must define all fields in settings for * appropriate preparations. Number of arguments is provided because some settings might depend on it. * Example: multiIf(cond, else, then) and multiIf(cond1, else1, cond2, else2, ...), the first * version can enable enable_lazy_execution_for_common_descendants_of_arguments setting, the second - not. */ virtual bool isShortCircuit(ShortCircuitSettings & /*settings*/, size_t /*number_of_arguments*/) const { return false; } /** Should we evaluate this function lazily in short-circuit function arguments? * If function can throw an exception or it's computationally heavy, then * it's suitable, otherwise it's not (due to the overhead of lazy execution). * Suitability may depend on function arguments. */ virtual bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const = 0; /// The property of monotonicity for a certain range. struct Monotonicity { bool is_monotonic = false; /// Is the function monotonous (non-decreasing or non-increasing). bool is_positive = true; /// true if the function is non-decreasing, false if non-increasing. If is_monotonic = false, then it does not matter. bool is_always_monotonic = false; /// Is true if function is monotonic on the whole input range I }; /** Get information about monotonicity on a range of values. Call only if hasInformationAboutMonotonicity. * NULL can be passed as one of the arguments. This means that the corresponding range is unlimited on the left or on the right. */ virtual Monotonicity getMonotonicityForRange(const IDataType & /*type*/, const Field & /*left*/, const Field & /*right*/) const { throw Exception("Function " + getName() + " has no information about its monotonicity.", ErrorCodes::NOT_IMPLEMENTED); } }; using FunctionBasePtr = std::shared_ptr<IFunctionBase>; /** Creates IFunctionBase from argument types list (chooses one function overload). */ class IFunctionOverloadResolver { public: virtual ~IFunctionOverloadResolver() = default; virtual FunctionBasePtr build(const ColumnsWithTypeAndName & arguments) const; void getLambdaArgumentTypes(DataTypes & arguments) const; void checkNumberOfArguments(size_t number_of_arguments) const; /// Get the main function name. virtual String getName() const = 0; /// For non-variadic functions, return number of arguments; otherwise return zero (that should be ignored). virtual size_t getNumberOfArguments() const = 0; /// TODO: This method should not be duplicated here and in IFunctionBase /// See the comment for the same method in IFunctionBase virtual bool isDeterministic() const { return true; } virtual bool isDeterministicInScopeOfQuery() const { return true; } virtual bool isInjective(const ColumnsWithTypeAndName &) const { return false; } /// Override and return true if function needs to depend on the state of the data. virtual bool isStateful() const { return false; } /// Override and return true if function could take different number of arguments. virtual bool isVariadic() const { return false; } /// For non-variadic functions, return number of arguments; otherwise return zero (that should be ignored). /// For higher-order functions (functions, that have lambda expression as at least one argument). /// You pass data types with empty DataTypeFunction for lambda arguments. /// This function will replace it with DataTypeFunction containing actual types. virtual void getLambdaArgumentTypesImpl(DataTypes & arguments [[maybe_unused]]) const { throw Exception("Function " + getName() + " can't have lambda-expressions as arguments", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); } /// Returns indexes of arguments, that must be ColumnConst virtual ColumnNumbers getArgumentsThatAreAlwaysConstant() const { return {}; } /// Returns indexes if arguments, that can be Nullable without making result of function Nullable /// (for functions like isNull(x)) virtual ColumnNumbers getArgumentsThatDontImplyNullableReturnType(size_t number_of_arguments [[maybe_unused]]) const { return {}; } protected: virtual FunctionBasePtr buildImpl(const ColumnsWithTypeAndName & /* arguments */, const DataTypePtr & /* result_type */) const { throw Exception("buildImpl is not implemented for " + getName(), ErrorCodes::NOT_IMPLEMENTED); } virtual DataTypePtr getReturnTypeImpl(const DataTypes & /*arguments*/) const { throw Exception("getReturnType is not implemented for " + getName(), ErrorCodes::NOT_IMPLEMENTED); } /// This function will be called in default implementation. You can overload it or the previous one. virtual DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const { DataTypes data_types(arguments.size()); for (size_t i = 0; i < arguments.size(); ++i) data_types[i] = arguments[i].type; return getReturnTypeImpl(data_types); } /** If useDefaultImplementationForNulls() is true, then change arguments for getReturnType() and build(): * if some of arguments are Nullable(Nothing) then don't call getReturnType(), call build() with return_type = Nullable(Nothing), * if some of arguments are Nullable, then: * - Nullable types are substituted with nested types for getReturnType() function * - wrap getReturnType() result in Nullable type and pass to build * * Otherwise build returns build(arguments, getReturnType(arguments)); */ virtual bool useDefaultImplementationForNulls() const { return true; } /** If useDefaultImplementationForNulls() is true, then change arguments for getReturnType() and build(). * If function arguments has low cardinality types, convert them to ordinary types. * getReturnType returns ColumnLowCardinality if at least one argument type is ColumnLowCardinality. */ virtual bool useDefaultImplementationForLowCardinalityColumns() const { return true; } /** If function arguments has single sparse column and all other arguments are constants, call function on nested column. * Otherwise, convert all sparse columns to ordinary columns. * If default value doesn't change after function execution, returns sparse column as a result. * Otherwise, result column is converted to full. */ virtual bool useDefaultImplementationForSparseColumns() const { return true; } // /// If it isn't, will convert all ColumnLowCardinality arguments to full columns. virtual bool canBeExecutedOnLowCardinalityDictionary() const { return true; } private: DataTypePtr getReturnType(const ColumnsWithTypeAndName & arguments) const; DataTypePtr getReturnTypeWithoutLowCardinality(const ColumnsWithTypeAndName & arguments) const; }; using FunctionOverloadResolverPtr = std::shared_ptr<IFunctionOverloadResolver>; /// Old function interface. Check documentation in IFunction.h. /// If client do not need statefull properties it can implement this interface. class IFunction { public: virtual ~IFunction() = default; virtual String getName() const = 0; virtual ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const = 0; virtual ColumnPtr executeImplDryRun(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const { return executeImpl(arguments, result_type, input_rows_count); } /** Default implementation in presence of Nullable arguments or NULL constants as arguments is the following: * if some of arguments are NULL constants then return NULL constant, * if some of arguments are Nullable, then execute function as usual for columns, * where Nullable columns are substituted with nested columns (they have arbitrary values in rows corresponding to NULL value) * and wrap result in Nullable column where NULLs are in all rows where any of arguments are NULL. */ virtual bool useDefaultImplementationForNulls() const { return true; } /** If the function have non-zero number of arguments, * and if all arguments are constant, that we could automatically provide default implementation: * arguments are converted to ordinary columns with single value, then function is executed as usual, * and then the result is converted to constant column. */ virtual bool useDefaultImplementationForConstants() const { return false; } /** Some arguments could remain constant during this implementation. */ virtual ColumnNumbers getArgumentsThatAreAlwaysConstant() const { return {}; } /** If function arguments has single low cardinality column and all other arguments are constants, call function on nested column. * Otherwise, convert all low cardinality columns to ordinary columns. * Returns ColumnLowCardinality if at least one argument is ColumnLowCardinality. */ virtual bool useDefaultImplementationForLowCardinalityColumns() const { return true; } /** If function arguments has single sparse column and all other arguments are constants, call function on nested column. * Otherwise, convert all sparse columns to ordinary columns. * If default value doesn't change after function execution, returns sparse column as a result. * Otherwise, result column is converted to full. */ virtual bool useDefaultImplementationForSparseColumns() const { return true; } /// If it isn't, will convert all ColumnLowCardinality arguments to full columns. virtual bool canBeExecutedOnLowCardinalityDictionary() const { return true; } /** True if function can be called on default arguments (include Nullable's) and won't throw. * Counterexample: modulo(0, 0) */ virtual bool canBeExecutedOnDefaultArguments() const { return true; } /// Properties from IFunctionBase (see IFunction.h) virtual bool isSuitableForConstantFolding() const { return true; } virtual ColumnPtr getConstantResultForNonConstArguments(const ColumnsWithTypeAndName & /*arguments*/, const DataTypePtr & /*result_type*/) const { return nullptr; } virtual bool isInjective(const ColumnsWithTypeAndName & /*sample_columns*/) const { return false; } virtual bool isDeterministic() const { return true; } virtual bool isDeterministicInScopeOfQuery() const { return true; } virtual bool isStateful() const { return false; } using ShortCircuitSettings = IFunctionBase::ShortCircuitSettings; virtual bool isShortCircuit(ShortCircuitSettings & /*settings*/, size_t /*number_of_arguments*/) const { return false; } virtual bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const = 0; virtual bool hasInformationAboutMonotonicity() const { return false; } using Monotonicity = IFunctionBase::Monotonicity; virtual Monotonicity getMonotonicityForRange(const IDataType & /*type*/, const Field & /*left*/, const Field & /*right*/) const { throw Exception("Function " + getName() + " has no information about its monotonicity.", ErrorCodes::NOT_IMPLEMENTED); } /// For non-variadic functions, return number of arguments; otherwise return zero (that should be ignored). virtual size_t getNumberOfArguments() const = 0; virtual DataTypePtr getReturnTypeImpl(const DataTypes & /*arguments*/) const { throw Exception("getReturnType is not implemented for " + getName(), ErrorCodes::NOT_IMPLEMENTED); } /// Get the result type by argument type. If the function does not apply to these arguments, throw an exception. virtual DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const { DataTypes data_types(arguments.size()); for (size_t i = 0; i < arguments.size(); ++i) data_types[i] = arguments[i].type; return getReturnTypeImpl(data_types); } virtual bool isVariadic() const { return false; } virtual void getLambdaArgumentTypes(DataTypes & /*arguments*/) const { throw Exception("Function " + getName() + " can't have lambda-expressions as arguments", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); } virtual ColumnNumbers getArgumentsThatDontImplyNullableReturnType(size_t /*number_of_arguments*/) const { return {}; } #if USE_EMBEDDED_COMPILER bool isCompilable(const DataTypes & arguments) const; llvm::Value * compile(llvm::IRBuilderBase &, const DataTypes & arguments, Values values) const; #endif protected: #if USE_EMBEDDED_COMPILER virtual bool isCompilableImpl(const DataTypes &) const { return false; } virtual llvm::Value * compileImpl(llvm::IRBuilderBase &, const DataTypes &, Values) const { throw Exception(getName() + " is not JIT-compilable", ErrorCodes::NOT_IMPLEMENTED); } #endif }; using FunctionPtr = std::shared_ptr<IFunction>; }
assert0/hackasat-qualifier-2021
errcorr/solver/shifttester.py
import sys # def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): def text_from_bits(bits, encoding='utf-8', errors='ignore'): try: n = int(bits, 2) val = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0' return val except Exception as e: # print(f"An exception occurred in text_from_bits() - {e}\n") return None def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) if __name__ == "__main__": try: filename = sys.argv[1] number_of_bytes_to_read_at_a_time = 1024 shift_window_width = 512 fp = open(filename, 'rb') while True: line = fp.read(number_of_bytes_to_read_at_a_time) if len(line) == 0: break line = line.hex() # print(line) line = bin(int(line, 16))[2:] for i in range(0, len(line), 1): try: string = line[i-shift_window_width:i+shift_window_width] var = text_from_bits(string) if 'flag{' in var and '}' in var: print(var) print("Congratulations! You recovered the flag!\n") exit(0) except Exception as e: continue fp.close() except Exception as e: print("An error occurred.\n") print(e)
wuruijie/LXZAPP
HongKZH_IOS/Classes/LeSeeManager/LeSeeModel/SelfMediaModel/CategoryTop10ListRespone.h
<reponame>wuruijie/LXZAPP<gh_stars>1-10 // //Created by ESJsonFormatForMac on 18/09/15. // #import <Foundation/Foundation.h> #import "HKBaseModelRespone.h" @class CategoryTop10ListModel; @interface CategoryTop10ListRespone : HKBaseModelRespone @property (nonatomic, copy) NSString *msg; @property (nonatomic, strong) NSArray<CategoryTop10ListModel *> *data; @end @interface CategoryTop10ListModel : NSObject @property (nonatomic, copy) NSString *userId; @property (nonatomic, copy) NSString *coverImgSrc; @property (nonatomic, copy) NSString *ID; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *praiseCount; @property (nonatomic, copy) NSString *headImg; @property (nonatomic, copy) NSString *uName; @property (nonatomic, copy)NSString *categoryName; @end
microsoftly/botbuilder-js
libraries/botbuilder-dialogs/lib/waterfall.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Dialog optimized for prompting a user with a series of questions. Waterfalls accept a stack of * functions which will be executed in sequence. Each waterfall step can ask a question of the user * by calling either a prompt or another dialog. When the called dialog completes control will be * returned to the next step of the waterfall and any input collected by the prompt or other dialog * will be passed to the step as an argument. * * When a step is executed it should call either `context.begin()`, `context.end()`, * `context.replace()`, `context.cancelDialog()`, or a prompt. Failing to do so will result * in the dialog automatically ending the next time the user replies. * * Similarly, calling a dialog/prompt from within the last step of the waterfall will result in * the waterfall automatically ending once the dialog/prompt completes. This is often desired * though as the result from tha called dialog/prompt will be passed to the waterfalls parent * dialog. */ class Waterfall { /** * Creates a new waterfall dialog containing the given array of steps. * @param steps Array of waterfall steps. */ constructor(steps) { this.steps = (steps || []).slice(0); } begin(context, dialogs, args) { const instance = dialogs.getInstance(context); instance.step = 0; return this.runStep(context, dialogs, args); } resume(context, dialogs, result) { const instance = dialogs.getInstance(context); instance.step += 1; return this.runStep(context, dialogs, result); } runStep(context, dialogs, result) { try { const instance = dialogs.getInstance(context); const step = instance.step; if (step >= 0 && step < this.steps.length) { // Execute step return Promise.resolve(this.steps[step](context, result, (r) => { // Skip to next step instance.step += 1; return this.runStep(context, r); })); } else { // End of waterfall so just return to parent return dialogs.end(context); } } catch (err) { return Promise.reject(err); } } } exports.Waterfall = Waterfall; //# sourceMappingURL=waterfall.js.map
King0987654/windows2000
private/ntos/ps/alpha/psctxalp.c
/*++ Copyright (c) 1990 Microsoft Corporation Copyright (c) 1993 Digital Equipment Corporation Module Name: psctxalp.c Abstract: This module implements functions to get and set the context of a thread. Author: <NAME> (davec) 1-Oct-1990 Revision History: <NAME> (tvb) 18-May-1992 Adapted for Alpha AXP. --*/ #include "psp.h" VOID PspGetContext ( IN PKTRAP_FRAME TrapFrame, IN PKNONVOLATILE_CONTEXT_POINTERS ContextPointers, IN OUT PCONTEXT ContextRecord ) /*++ Routine Description: This function selectively moves the contents of the specified trap frame and nonvolatile context to the specified context record. Arguments: TrapFrame - Supplies a pointer to a trap frame. ContextPointers - Supplies the address of context pointers record. ContextRecord - Supplies the address of a context record. Return Value: None. --*/ { // // Get control information if specified. // if ((ContextRecord->ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL) { // // Get integer registers gp, ra, sp, FIR, and PSR from trap frame. // ContextRecord->IntGp = TrapFrame->IntGp; ContextRecord->IntSp = TrapFrame->IntSp; ContextRecord->IntRa = TrapFrame->IntRa; ContextRecord->Fir = TrapFrame->Fir; ContextRecord->Psr = TrapFrame->Psr; } // // Get integer register contents if specified. // if ((ContextRecord->ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER) { // // Get volatile integer registers v0 and t0 - t7 from trap frame. // ContextRecord->IntV0 = TrapFrame->IntV0; ContextRecord->IntT0 = TrapFrame->IntT0; ContextRecord->IntT1 = TrapFrame->IntT1; ContextRecord->IntT2 = TrapFrame->IntT2; ContextRecord->IntT3 = TrapFrame->IntT3; ContextRecord->IntT4 = TrapFrame->IntT4; ContextRecord->IntT5 = TrapFrame->IntT5; ContextRecord->IntT6 = TrapFrame->IntT6; ContextRecord->IntT7 = TrapFrame->IntT7; // // Get nonvolatile integer registers s0 - s5 through context pointers. // ContextRecord->IntS0 = *ContextPointers->IntS0; ContextRecord->IntS1 = *ContextPointers->IntS1; ContextRecord->IntS2 = *ContextPointers->IntS2; ContextRecord->IntS3 = *ContextPointers->IntS3; ContextRecord->IntS4 = *ContextPointers->IntS4; ContextRecord->IntS5 = *ContextPointers->IntS5; // // Get volatile integer registers fp/s6, a0 - a5, and t8 - t12 from // trap frame. // ContextRecord->IntFp = TrapFrame->IntFp; ContextRecord->IntA0 = TrapFrame->IntA0; ContextRecord->IntA1 = TrapFrame->IntA1; ContextRecord->IntA2 = TrapFrame->IntA2; ContextRecord->IntA3 = TrapFrame->IntA3; ContextRecord->IntA4 = TrapFrame->IntA4; ContextRecord->IntA5 = TrapFrame->IntA5; ContextRecord->IntT8 = TrapFrame->IntT8; ContextRecord->IntT9 = TrapFrame->IntT9; ContextRecord->IntT10 = TrapFrame->IntT10; ContextRecord->IntT11 = TrapFrame->IntT11; ContextRecord->IntT12 = TrapFrame->IntT12; // // Get volatile integer register AT from trap frame. // Get integer register zero. // ContextRecord->IntAt = TrapFrame->IntAt; ContextRecord->IntZero = 0; } // // Get floating register contents if specified. // if ((ContextRecord->ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT) { // // Get volatile floating registers f0 - f1 from trap frame. // ContextRecord->FltF0 = TrapFrame->FltF0; ContextRecord->FltF1 = TrapFrame->FltF1; // // Get volatile floating registers f10 - f30 from trap frame. // This assumes that f10 - f30 are contiguous in the trap frame. // ASSERT((&ContextRecord->FltF30 - &ContextRecord->FltF10) == 20); RtlMoveMemory(&ContextRecord->FltF10, &TrapFrame->FltF10, sizeof(ULONGLONG) * 21); ContextRecord->FltF31 = 0; // // Get nonvolatile floating registers f2 - f9 through context pointers. // ContextRecord->FltF2 = *ContextPointers->FltF2; ContextRecord->FltF3 = *ContextPointers->FltF3; ContextRecord->FltF4 = *ContextPointers->FltF4; ContextRecord->FltF5 = *ContextPointers->FltF5; ContextRecord->FltF6 = *ContextPointers->FltF6; ContextRecord->FltF7 = *ContextPointers->FltF7; ContextRecord->FltF8 = *ContextPointers->FltF8; ContextRecord->FltF9 = *ContextPointers->FltF9; // // Get floating point control register from trap frame. // Get the current software FPCR value from the TEB. // ContextRecord->Fpcr = TrapFrame->Fpcr; try { ContextRecord->SoftFpcr = (ULONGLONG)(NtCurrentTeb()->FpSoftwareStatusRegister); } except (EXCEPTION_EXECUTE_HANDLER) { ContextRecord->SoftFpcr = 0; } } return; } VOID PspSetContext ( IN OUT PKTRAP_FRAME TrapFrame, IN PKNONVOLATILE_CONTEXT_POINTERS ContextPointers, IN PCONTEXT ContextRecord, IN KPROCESSOR_MODE ProcessorMode ) /*++ Routine Description: This function selectively moves the contents of the specified context record to the specified trap frame and nonvolatile context. Arguments: TrapFrame - Supplies the address of a trap frame. ContextPointers - Supplies the address of a context pointers record. ContextRecord - Supplies the address of a context record. ProcessorMode - Supplies the processor mode to use when sanitizing the PSR and FSR. Return Value: None. --*/ { // // Set control information if specified. // if ((ContextRecord->ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL) { // // Set integer registers gp, sp, ra, FIR, and PSR in trap frame. // TrapFrame->IntGp = ContextRecord->IntGp; TrapFrame->IntSp = ContextRecord->IntSp; TrapFrame->IntRa = ContextRecord->IntRa; TrapFrame->Fir = ContextRecord->Fir; TrapFrame->Psr = SANITIZE_PSR(ContextRecord->Psr, ProcessorMode); } // // Set integer register contents if specified. // if ((ContextRecord->ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER) { // // Set volatile integer registers v0 and t0 - t7 in trap frame. // TrapFrame->IntV0 = ContextRecord->IntV0; TrapFrame->IntT0 = ContextRecord->IntT0; TrapFrame->IntT1 = ContextRecord->IntT1; TrapFrame->IntT2 = ContextRecord->IntT2; TrapFrame->IntT3 = ContextRecord->IntT3; TrapFrame->IntT4 = ContextRecord->IntT4; TrapFrame->IntT5 = ContextRecord->IntT5; TrapFrame->IntT6 = ContextRecord->IntT6; TrapFrame->IntT7 = ContextRecord->IntT7; // // Set nonvolatile integer registers s0 - s5 through context pointers. // *ContextPointers->IntS0 = ContextRecord->IntS0; *ContextPointers->IntS1 = ContextRecord->IntS1; *ContextPointers->IntS2 = ContextRecord->IntS2; *ContextPointers->IntS3 = ContextRecord->IntS3; *ContextPointers->IntS4 = ContextRecord->IntS4; *ContextPointers->IntS5 = ContextRecord->IntS5; // // Set volatile integer registers fp/s6, a0 - a5, t8 - t12, and AT // in trap frame. // TrapFrame->IntFp = ContextRecord->IntFp; TrapFrame->IntA0 = ContextRecord->IntA0; TrapFrame->IntA1 = ContextRecord->IntA1; TrapFrame->IntA2 = ContextRecord->IntA2; TrapFrame->IntA3 = ContextRecord->IntA3; TrapFrame->IntA4 = ContextRecord->IntA4; TrapFrame->IntA5 = ContextRecord->IntA5; TrapFrame->IntT8 = ContextRecord->IntT8; TrapFrame->IntT9 = ContextRecord->IntT9; TrapFrame->IntT10 = ContextRecord->IntT10; TrapFrame->IntT11 = ContextRecord->IntT11; TrapFrame->IntT12 = ContextRecord->IntT12; TrapFrame->IntAt = ContextRecord->IntAt; } // // Set floating register contents if specified. // if ((ContextRecord->ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT) { // // Set volatile floating registers f0 - f1 in trap frame. // TrapFrame->FltF0 = ContextRecord->FltF0; TrapFrame->FltF1 = ContextRecord->FltF1; // // Set volatile floating registers f10 - f30 in trap frame. // This assumes that f10 - f30 are contiguous in the trap frame. // ASSERT((&ContextRecord->FltF30 - &ContextRecord->FltF10) == 20); RtlMoveMemory(&TrapFrame->FltF10, &ContextRecord->FltF10, sizeof(ULONGLONG) * 21); // // Set nonvolatile floating registers f2 - f9 through context pointers. // *ContextPointers->FltF2 = ContextRecord->FltF2; *ContextPointers->FltF3 = ContextRecord->FltF3; *ContextPointers->FltF4 = ContextRecord->FltF4; *ContextPointers->FltF5 = ContextRecord->FltF5; *ContextPointers->FltF6 = ContextRecord->FltF6; *ContextPointers->FltF7 = ContextRecord->FltF7; *ContextPointers->FltF8 = ContextRecord->FltF8; *ContextPointers->FltF9 = ContextRecord->FltF9; // // Set floating point control register in trap frame. // Set the current software FPCR value in the TEB. // TrapFrame->Fpcr = ContextRecord->Fpcr; try { NtCurrentTeb()->FpSoftwareStatusRegister = (ULONG)ContextRecord->SoftFpcr; } except (EXCEPTION_EXECUTE_HANDLER) { NOTHING; } } return; } VOID PspGetSetContextSpecialApcMain ( IN PKAPC Apc, IN PKNORMAL_ROUTINE *NormalRoutine, IN PVOID *NormalContext, IN PVOID *SystemArgument1, IN PVOID *SystemArgument2 ) /*++ Routine Description: This function either captures the user mode state of the current thread, or sets the user mode state of the current thread. The operation type is determined by the value of SystemArgument1. A zero value is used for get context, and a nonzero value is used for set context. Arguments: Apc - Supplies a pointer to the APC control object that caused entry into this routine. NormalRoutine - Supplies a pointer to the normal routine function that was specified when the APC was initialized. This parameter is not used. NormalContext - Supplies a pointer to an arbitrary data structure that was specified when the APC was initialized. This parameter is not used. SystemArgument1, SystemArgument2 - Supplies a set of two pointer to two arguments that contain untyped data. These parameters are not used. Return Value: None. --*/ { PGETSETCONTEXT ContextBlock; KNONVOLATILE_CONTEXT_POINTERS ContextPointers; CONTEXT ContextRecord; ULONG_PTR ControlPc; FRAME_POINTERS EstablisherFrame; PRUNTIME_FUNCTION FunctionEntry; BOOLEAN InFunction; PETHREAD Thread; ULONGLONG TrapFrame1; ULONGLONG TrapFrame2; // // Get the address of the context block and compute the address of the // system entry trap frame. // ContextBlock = CONTAINING_RECORD(Apc, GETSETCONTEXT, Apc); Thread = PsGetCurrentThread(); TrapFrame1 = (ULONGLONG)(LONG_PTR)Thread->Tcb.InitialStack - KTRAP_FRAME_LENGTH; // // The lower bounds for locating the first system service trap frame on // the kernel stack is one trap frame below TrapFrame1. // TrapFrame2 = TrapFrame1 - KTRAP_FRAME_LENGTH; // // Capture the current thread context and set the initial control PC // value. // RtlCaptureContext(&ContextRecord); ControlPc = (ULONG_PTR)ContextRecord.IntRa; // // Initialize context pointers for the nonvolatile integer and floating // registers. // ContextPointers.IntS0 = &ContextRecord.IntS0; ContextPointers.IntS1 = &ContextRecord.IntS1; ContextPointers.IntS2 = &ContextRecord.IntS2; ContextPointers.IntS3 = &ContextRecord.IntS3; ContextPointers.IntS4 = &ContextRecord.IntS4; ContextPointers.IntS5 = &ContextRecord.IntS5; ContextPointers.FltF2 = &ContextRecord.FltF2; ContextPointers.FltF3 = &ContextRecord.FltF3; ContextPointers.FltF4 = &ContextRecord.FltF4; ContextPointers.FltF5 = &ContextRecord.FltF5; ContextPointers.FltF6 = &ContextRecord.FltF6; ContextPointers.FltF7 = &ContextRecord.FltF7; ContextPointers.FltF8 = &ContextRecord.FltF8; ContextPointers.FltF9 = &ContextRecord.FltF9; // // Start with the frame specified by the context record and virtually // unwind call frames until the system entry trap frame is encountered. // do { // // Lookup the function table entry using the point at which control // left the procedure. // FunctionEntry = RtlLookupFunctionEntry(ControlPc); // // If there is a function table entry for the routine, then virtually // unwind to the caller of the current routine to obtain the address // where control left the caller. Otherwise, the function is a leaf // function and the return address register contains the address of // where control left the caller. // if (FunctionEntry != NULL) { ControlPc = RtlVirtualUnwind(ControlPc, FunctionEntry, &ContextRecord, &InFunction, &EstablisherFrame, &ContextPointers); } else { ControlPc = (ULONG_PTR)ContextRecord.IntRa; } // // N.B. The virtual frame pointer of the kernel frame just below the // trap frame may not be exactly equal to TrapFrame1 since the trap // code can allocate additional stack space (for local variables or // system service arguments). Therefore we must check for a range of // values at or below TrapFrame1, but also above TrapFrame2 (so in // case there is more than one trap frame on the stack, we get the // one at the top. // } while ((ContextRecord.IntSp != TrapFrame1) && ((ContextRecord.IntSp < TrapFrame2) || (ControlPc < PCR->SystemServiceDispatchStart) || (ControlPc >= PCR->SystemServiceDispatchEnd))); // // If system argument one is nonzero, then set the context of the current // thread. Otherwise, get the context of the current thread. // if (Apc->SystemArgument1 != 0) { // // Set context of current thread. // PspSetContext((PKTRAP_FRAME)TrapFrame1, &ContextPointers, &ContextBlock->Context, ContextBlock->Mode); } else { // // Get context of current thread. // PspGetContext((PKTRAP_FRAME)TrapFrame1, &ContextPointers, &ContextBlock->Context); } KeSetEvent(&ContextBlock->OperationComplete, 0, FALSE); return; }
darkless456/Python
def_function.py
# coding:utf8 # def_function.py def print_two (*args): # 参数个数不确定 arg1, arg2 = args # 参数解包 print ("arg1: %r, arg2: %r"% (arg1, arg2)) # 传递参数 return def print_two_again (arg1, arg2): print ("arg1: %r, arg2: %r"% (arg1, arg2)) return def print_one (arg1): print ("arg1: %r"% arg1) return def print_none(): print ("I go nothing.") return print_two ("kevin", "bob") print_two ('kevin', 'bob') print_one ("hello") print_none()
mjrgh/mbed
libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/device/MK64F12/MK64F12_crc.h
<reponame>mjrgh/mbed /* * Copyright (c) 2014, Freescale Semiconductor, Inc. * All rights reserved. * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL FREESCALE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_CRC_REGISTERS_H__ #define __HW_CRC_REGISTERS_H__ #include "regs.h" /* * MK64F12 CRC * * Cyclic Redundancy Check * * Registers defined in this header file: * - HW_CRC_DATAL - CRC_DATAL register. * - HW_CRC_DATAH - CRC_DATAH register. * - HW_CRC_DATALL - CRC_DATALL register. * - HW_CRC_DATALU - CRC_DATALU register. * - HW_CRC_DATAHL - CRC_DATAHL register. * - HW_CRC_DATAHU - CRC_DATAHU register. * - HW_CRC_DATA - CRC Data register * - HW_CRC_GPOLY - CRC Polynomial register * - HW_CRC_GPOLYL - CRC_GPOLYL register. * - HW_CRC_GPOLYH - CRC_GPOLYH register. * - HW_CRC_GPOLYLL - CRC_GPOLYLL register. * - HW_CRC_GPOLYLU - CRC_GPOLYLU register. * - HW_CRC_GPOLYHL - CRC_GPOLYHL register. * - HW_CRC_GPOLYHU - CRC_GPOLYHU register. * - HW_CRC_CTRL - CRC Control register * - HW_CRC_CTRLHU - CRC_CTRLHU register. * * - hw_crc_t - Struct containing all module registers. */ //! @name Module base addresses //@{ #ifndef REGS_CRC_BASE #define HW_CRC_INSTANCE_COUNT (1U) //!< Number of instances of the CRC module. #define REGS_CRC_BASE (0x40032000U) //!< Base address for CRC. #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_DATAL - CRC_DATAL register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_DATAL - CRC_DATAL register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_datal { uint16_t U; struct _hw_crc_datal_bitfields { uint16_t DATAL : 16; //!< [15:0] DATAL stores the lower 16 bits of //! the 16/32 bit CRC } B; } hw_crc_datal_t; #endif /*! * @name Constants and macros for entire CRC_DATAL register */ //@{ #define HW_CRC_DATAL_ADDR (REGS_CRC_BASE + 0x0U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_DATAL (*(__IO hw_crc_datal_t *) HW_CRC_DATAL_ADDR) #define HW_CRC_DATAL_RD() (HW_CRC_DATAL.U) #define HW_CRC_DATAL_WR(v) (HW_CRC_DATAL.U = (v)) #define HW_CRC_DATAL_SET(v) (HW_CRC_DATAL_WR(HW_CRC_DATAL_RD() | (v))) #define HW_CRC_DATAL_CLR(v) (HW_CRC_DATAL_WR(HW_CRC_DATAL_RD() & ~(v))) #define HW_CRC_DATAL_TOG(v) (HW_CRC_DATAL_WR(HW_CRC_DATAL_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_DATAL bitfields */ /*! * @name Register CRC_DATAL, field DATAL[15:0] (RW) */ //@{ #define BP_CRC_DATAL_DATAL (0U) //!< Bit position for CRC_DATAL_DATAL. #define BM_CRC_DATAL_DATAL (0xFFFFU) //!< Bit mask for CRC_DATAL_DATAL. #define BS_CRC_DATAL_DATAL (16U) //!< Bit field size in bits for CRC_DATAL_DATAL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATAL_DATAL field. #define BR_CRC_DATAL_DATAL (HW_CRC_DATAL.U) #endif //! @brief Format value for bitfield CRC_DATAL_DATAL. #define BF_CRC_DATAL_DATAL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint16_t) << BP_CRC_DATAL_DATAL), uint16_t) & BM_CRC_DATAL_DATAL) #ifndef __LANGUAGE_ASM__ //! @brief Set the DATAL field to a new value. #define BW_CRC_DATAL_DATAL(v) (HW_CRC_DATAL_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_DATAH - CRC_DATAH register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_DATAH - CRC_DATAH register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_datah { uint16_t U; struct _hw_crc_datah_bitfields { uint16_t DATAH : 16; //!< [15:0] DATAH stores the high 16 bits of the //! 16/32 bit CRC } B; } hw_crc_datah_t; #endif /*! * @name Constants and macros for entire CRC_DATAH register */ //@{ #define HW_CRC_DATAH_ADDR (REGS_CRC_BASE + 0x2U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_DATAH (*(__IO hw_crc_datah_t *) HW_CRC_DATAH_ADDR) #define HW_CRC_DATAH_RD() (HW_CRC_DATAH.U) #define HW_CRC_DATAH_WR(v) (HW_CRC_DATAH.U = (v)) #define HW_CRC_DATAH_SET(v) (HW_CRC_DATAH_WR(HW_CRC_DATAH_RD() | (v))) #define HW_CRC_DATAH_CLR(v) (HW_CRC_DATAH_WR(HW_CRC_DATAH_RD() & ~(v))) #define HW_CRC_DATAH_TOG(v) (HW_CRC_DATAH_WR(HW_CRC_DATAH_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_DATAH bitfields */ /*! * @name Register CRC_DATAH, field DATAH[15:0] (RW) */ //@{ #define BP_CRC_DATAH_DATAH (0U) //!< Bit position for CRC_DATAH_DATAH. #define BM_CRC_DATAH_DATAH (0xFFFFU) //!< Bit mask for CRC_DATAH_DATAH. #define BS_CRC_DATAH_DATAH (16U) //!< Bit field size in bits for CRC_DATAH_DATAH. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATAH_DATAH field. #define BR_CRC_DATAH_DATAH (HW_CRC_DATAH.U) #endif //! @brief Format value for bitfield CRC_DATAH_DATAH. #define BF_CRC_DATAH_DATAH(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint16_t) << BP_CRC_DATAH_DATAH), uint16_t) & BM_CRC_DATAH_DATAH) #ifndef __LANGUAGE_ASM__ //! @brief Set the DATAH field to a new value. #define BW_CRC_DATAH_DATAH(v) (HW_CRC_DATAH_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_DATALL - CRC_DATALL register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_DATALL - CRC_DATALL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datall { uint8_t U; struct _hw_crc_datall_bitfields { uint8_t DATALL : 8; //!< [7:0] CRCLL stores the first 8 bits of the //! 32 bit DATA } B; } hw_crc_datall_t; #endif /*! * @name Constants and macros for entire CRC_DATALL register */ //@{ #define HW_CRC_DATALL_ADDR (REGS_CRC_BASE + 0x0U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_DATALL (*(__IO hw_crc_datall_t *) HW_CRC_DATALL_ADDR) #define HW_CRC_DATALL_RD() (HW_CRC_DATALL.U) #define HW_CRC_DATALL_WR(v) (HW_CRC_DATALL.U = (v)) #define HW_CRC_DATALL_SET(v) (HW_CRC_DATALL_WR(HW_CRC_DATALL_RD() | (v))) #define HW_CRC_DATALL_CLR(v) (HW_CRC_DATALL_WR(HW_CRC_DATALL_RD() & ~(v))) #define HW_CRC_DATALL_TOG(v) (HW_CRC_DATALL_WR(HW_CRC_DATALL_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_DATALL bitfields */ /*! * @name Register CRC_DATALL, field DATALL[7:0] (RW) */ //@{ #define BP_CRC_DATALL_DATALL (0U) //!< Bit position for CRC_DATALL_DATALL. #define BM_CRC_DATALL_DATALL (0xFFU) //!< Bit mask for CRC_DATALL_DATALL. #define BS_CRC_DATALL_DATALL (8U) //!< Bit field size in bits for CRC_DATALL_DATALL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATALL_DATALL field. #define BR_CRC_DATALL_DATALL (HW_CRC_DATALL.U) #endif //! @brief Format value for bitfield CRC_DATALL_DATALL. #define BF_CRC_DATALL_DATALL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_DATALL_DATALL), uint8_t) & BM_CRC_DATALL_DATALL) #ifndef __LANGUAGE_ASM__ //! @brief Set the DATALL field to a new value. #define BW_CRC_DATALL_DATALL(v) (HW_CRC_DATALL_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_DATALU - CRC_DATALU register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_DATALU - CRC_DATALU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datalu { uint8_t U; struct _hw_crc_datalu_bitfields { uint8_t DATALU : 8; //!< [7:0] DATALL stores the second 8 bits of the //! 32 bit CRC } B; } hw_crc_datalu_t; #endif /*! * @name Constants and macros for entire CRC_DATALU register */ //@{ #define HW_CRC_DATALU_ADDR (REGS_CRC_BASE + 0x1U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_DATALU (*(__IO hw_crc_datalu_t *) HW_CRC_DATALU_ADDR) #define HW_CRC_DATALU_RD() (HW_CRC_DATALU.U) #define HW_CRC_DATALU_WR(v) (HW_CRC_DATALU.U = (v)) #define HW_CRC_DATALU_SET(v) (HW_CRC_DATALU_WR(HW_CRC_DATALU_RD() | (v))) #define HW_CRC_DATALU_CLR(v) (HW_CRC_DATALU_WR(HW_CRC_DATALU_RD() & ~(v))) #define HW_CRC_DATALU_TOG(v) (HW_CRC_DATALU_WR(HW_CRC_DATALU_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_DATALU bitfields */ /*! * @name Register CRC_DATALU, field DATALU[7:0] (RW) */ //@{ #define BP_CRC_DATALU_DATALU (0U) //!< Bit position for CRC_DATALU_DATALU. #define BM_CRC_DATALU_DATALU (0xFFU) //!< Bit mask for CRC_DATALU_DATALU. #define BS_CRC_DATALU_DATALU (8U) //!< Bit field size in bits for CRC_DATALU_DATALU. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATALU_DATALU field. #define BR_CRC_DATALU_DATALU (HW_CRC_DATALU.U) #endif //! @brief Format value for bitfield CRC_DATALU_DATALU. #define BF_CRC_DATALU_DATALU(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_DATALU_DATALU), uint8_t) & BM_CRC_DATALU_DATALU) #ifndef __LANGUAGE_ASM__ //! @brief Set the DATALU field to a new value. #define BW_CRC_DATALU_DATALU(v) (HW_CRC_DATALU_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_DATAHL - CRC_DATAHL register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_DATAHL - CRC_DATAHL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datahl { uint8_t U; struct _hw_crc_datahl_bitfields { uint8_t DATAHL : 8; //!< [7:0] DATAHL stores the third 8 bits of the //! 32 bit CRC } B; } hw_crc_datahl_t; #endif /*! * @name Constants and macros for entire CRC_DATAHL register */ //@{ #define HW_CRC_DATAHL_ADDR (REGS_CRC_BASE + 0x2U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_DATAHL (*(__IO hw_crc_datahl_t *) HW_CRC_DATAHL_ADDR) #define HW_CRC_DATAHL_RD() (HW_CRC_DATAHL.U) #define HW_CRC_DATAHL_WR(v) (HW_CRC_DATAHL.U = (v)) #define HW_CRC_DATAHL_SET(v) (HW_CRC_DATAHL_WR(HW_CRC_DATAHL_RD() | (v))) #define HW_CRC_DATAHL_CLR(v) (HW_CRC_DATAHL_WR(HW_CRC_DATAHL_RD() & ~(v))) #define HW_CRC_DATAHL_TOG(v) (HW_CRC_DATAHL_WR(HW_CRC_DATAHL_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_DATAHL bitfields */ /*! * @name Register CRC_DATAHL, field DATAHL[7:0] (RW) */ //@{ #define BP_CRC_DATAHL_DATAHL (0U) //!< Bit position for CRC_DATAHL_DATAHL. #define BM_CRC_DATAHL_DATAHL (0xFFU) //!< Bit mask for CRC_DATAHL_DATAHL. #define BS_CRC_DATAHL_DATAHL (8U) //!< Bit field size in bits for CRC_DATAHL_DATAHL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATAHL_DATAHL field. #define BR_CRC_DATAHL_DATAHL (HW_CRC_DATAHL.U) #endif //! @brief Format value for bitfield CRC_DATAHL_DATAHL. #define BF_CRC_DATAHL_DATAHL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_DATAHL_DATAHL), uint8_t) & BM_CRC_DATAHL_DATAHL) #ifndef __LANGUAGE_ASM__ //! @brief Set the DATAHL field to a new value. #define BW_CRC_DATAHL_DATAHL(v) (HW_CRC_DATAHL_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_DATAHU - CRC_DATAHU register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_DATAHU - CRC_DATAHU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_datahu { uint8_t U; struct _hw_crc_datahu_bitfields { uint8_t DATAHU : 8; //!< [7:0] DATAHU stores the fourth 8 bits of the //! 32 bit CRC } B; } hw_crc_datahu_t; #endif /*! * @name Constants and macros for entire CRC_DATAHU register */ //@{ #define HW_CRC_DATAHU_ADDR (REGS_CRC_BASE + 0x3U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_DATAHU (*(__IO hw_crc_datahu_t *) HW_CRC_DATAHU_ADDR) #define HW_CRC_DATAHU_RD() (HW_CRC_DATAHU.U) #define HW_CRC_DATAHU_WR(v) (HW_CRC_DATAHU.U = (v)) #define HW_CRC_DATAHU_SET(v) (HW_CRC_DATAHU_WR(HW_CRC_DATAHU_RD() | (v))) #define HW_CRC_DATAHU_CLR(v) (HW_CRC_DATAHU_WR(HW_CRC_DATAHU_RD() & ~(v))) #define HW_CRC_DATAHU_TOG(v) (HW_CRC_DATAHU_WR(HW_CRC_DATAHU_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_DATAHU bitfields */ /*! * @name Register CRC_DATAHU, field DATAHU[7:0] (RW) */ //@{ #define BP_CRC_DATAHU_DATAHU (0U) //!< Bit position for CRC_DATAHU_DATAHU. #define BM_CRC_DATAHU_DATAHU (0xFFU) //!< Bit mask for CRC_DATAHU_DATAHU. #define BS_CRC_DATAHU_DATAHU (8U) //!< Bit field size in bits for CRC_DATAHU_DATAHU. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATAHU_DATAHU field. #define BR_CRC_DATAHU_DATAHU (HW_CRC_DATAHU.U) #endif //! @brief Format value for bitfield CRC_DATAHU_DATAHU. #define BF_CRC_DATAHU_DATAHU(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_DATAHU_DATAHU), uint8_t) & BM_CRC_DATAHU_DATAHU) #ifndef __LANGUAGE_ASM__ //! @brief Set the DATAHU field to a new value. #define BW_CRC_DATAHU_DATAHU(v) (HW_CRC_DATAHU_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_DATA - CRC Data register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_DATA - CRC Data register (RW) * * Reset value: 0xFFFFFFFFU * * The CRC Data register contains the value of the seed, data, and checksum. * When CTRL[WAS] is set, any write to the data register is regarded as the seed * value. When CTRL[WAS] is cleared, any write to the data register is regarded as * data for general CRC computation. In 16-bit CRC mode, the HU and HL fields are * not used for programming the seed value, and reads of these fields return an * indeterminate value. In 32-bit CRC mode, all fields are used for programming * the seed value. When programming data values, the values can be written 8 bits, * 16 bits, or 32 bits at a time, provided all bytes are contiguous; with MSB of * data value written first. After all data values are written, the CRC result * can be read from this data register. In 16-bit CRC mode, the CRC result is * available in the LU and LL fields. In 32-bit CRC mode, all fields contain the * result. Reads of this register at any time return the intermediate CRC value, * provided the CRC module is configured. */ typedef union _hw_crc_data { uint32_t U; struct _hw_crc_data_bitfields { uint32_t LL : 8; //!< [7:0] CRC Low Lower Byte uint32_t LU : 8; //!< [15:8] CRC Low Upper Byte uint32_t HL : 8; //!< [23:16] CRC High Lower Byte uint32_t HU : 8; //!< [31:24] CRC High Upper Byte } B; } hw_crc_data_t; #endif /*! * @name Constants and macros for entire CRC_DATA register */ //@{ #define HW_CRC_DATA_ADDR (REGS_CRC_BASE + 0x0U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_DATA (*(__IO hw_crc_data_t *) HW_CRC_DATA_ADDR) #define HW_CRC_DATA_RD() (HW_CRC_DATA.U) #define HW_CRC_DATA_WR(v) (HW_CRC_DATA.U = (v)) #define HW_CRC_DATA_SET(v) (HW_CRC_DATA_WR(HW_CRC_DATA_RD() | (v))) #define HW_CRC_DATA_CLR(v) (HW_CRC_DATA_WR(HW_CRC_DATA_RD() & ~(v))) #define HW_CRC_DATA_TOG(v) (HW_CRC_DATA_WR(HW_CRC_DATA_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_DATA bitfields */ /*! * @name Register CRC_DATA, field LL[7:0] (RW) * * When CTRL[WAS] is 1, values written to this field are part of the seed value. * When CTRL[WAS] is 0, data written to this field is used for CRC checksum * generation. */ //@{ #define BP_CRC_DATA_LL (0U) //!< Bit position for CRC_DATA_LL. #define BM_CRC_DATA_LL (0x000000FFU) //!< Bit mask for CRC_DATA_LL. #define BS_CRC_DATA_LL (8U) //!< Bit field size in bits for CRC_DATA_LL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATA_LL field. #define BR_CRC_DATA_LL (HW_CRC_DATA.B.LL) #endif //! @brief Format value for bitfield CRC_DATA_LL. #define BF_CRC_DATA_LL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_DATA_LL), uint32_t) & BM_CRC_DATA_LL) #ifndef __LANGUAGE_ASM__ //! @brief Set the LL field to a new value. #define BW_CRC_DATA_LL(v) (HW_CRC_DATA_WR((HW_CRC_DATA_RD() & ~BM_CRC_DATA_LL) | BF_CRC_DATA_LL(v))) #endif //@} /*! * @name Register CRC_DATA, field LU[15:8] (RW) * * When CTRL[WAS] is 1, values written to this field are part of the seed value. * When CTRL[WAS] is 0, data written to this field is used for CRC checksum * generation. */ //@{ #define BP_CRC_DATA_LU (8U) //!< Bit position for CRC_DATA_LU. #define BM_CRC_DATA_LU (0x0000FF00U) //!< Bit mask for CRC_DATA_LU. #define BS_CRC_DATA_LU (8U) //!< Bit field size in bits for CRC_DATA_LU. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATA_LU field. #define BR_CRC_DATA_LU (HW_CRC_DATA.B.LU) #endif //! @brief Format value for bitfield CRC_DATA_LU. #define BF_CRC_DATA_LU(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_DATA_LU), uint32_t) & BM_CRC_DATA_LU) #ifndef __LANGUAGE_ASM__ //! @brief Set the LU field to a new value. #define BW_CRC_DATA_LU(v) (HW_CRC_DATA_WR((HW_CRC_DATA_RD() & ~BM_CRC_DATA_LU) | BF_CRC_DATA_LU(v))) #endif //@} /*! * @name Register CRC_DATA, field HL[23:16] (RW) * * In 16-bit CRC mode (CTRL[TCRC] is 0), this field is not used for programming * a seed value. In 32-bit CRC mode (CTRL[TCRC] is 1), values written to this * field are part of the seed value when CTRL[WAS] is 1. When CTRL[WAS] is 0, data * written to this field is used for CRC checksum generation in both 16-bit and * 32-bit CRC modes. */ //@{ #define BP_CRC_DATA_HL (16U) //!< Bit position for CRC_DATA_HL. #define BM_CRC_DATA_HL (0x00FF0000U) //!< Bit mask for CRC_DATA_HL. #define BS_CRC_DATA_HL (8U) //!< Bit field size in bits for CRC_DATA_HL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATA_HL field. #define BR_CRC_DATA_HL (HW_CRC_DATA.B.HL) #endif //! @brief Format value for bitfield CRC_DATA_HL. #define BF_CRC_DATA_HL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_DATA_HL), uint32_t) & BM_CRC_DATA_HL) #ifndef __LANGUAGE_ASM__ //! @brief Set the HL field to a new value. #define BW_CRC_DATA_HL(v) (HW_CRC_DATA_WR((HW_CRC_DATA_RD() & ~BM_CRC_DATA_HL) | BF_CRC_DATA_HL(v))) #endif //@} /*! * @name Register CRC_DATA, field HU[31:24] (RW) * * In 16-bit CRC mode (CTRL[TCRC] is 0), this field is not used for programming * a seed value. In 32-bit CRC mode (CTRL[TCRC] is 1), values written to this * field are part of the seed value when CTRL[WAS] is 1. When CTRL[WAS] is 0, data * written to this field is used for CRC checksum generation in both 16-bit and * 32-bit CRC modes. */ //@{ #define BP_CRC_DATA_HU (24U) //!< Bit position for CRC_DATA_HU. #define BM_CRC_DATA_HU (0xFF000000U) //!< Bit mask for CRC_DATA_HU. #define BS_CRC_DATA_HU (8U) //!< Bit field size in bits for CRC_DATA_HU. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_DATA_HU field. #define BR_CRC_DATA_HU (HW_CRC_DATA.B.HU) #endif //! @brief Format value for bitfield CRC_DATA_HU. #define BF_CRC_DATA_HU(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_DATA_HU), uint32_t) & BM_CRC_DATA_HU) #ifndef __LANGUAGE_ASM__ //! @brief Set the HU field to a new value. #define BW_CRC_DATA_HU(v) (HW_CRC_DATA_WR((HW_CRC_DATA_RD() & ~BM_CRC_DATA_HU) | BF_CRC_DATA_HU(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_GPOLY - CRC Polynomial register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_GPOLY - CRC Polynomial register (RW) * * Reset value: 0x00001021U * * This register contains the value of the polynomial for the CRC calculation. * The HIGH field contains the upper 16 bits of the CRC polynomial, which are used * only in 32-bit CRC mode. Writes to the HIGH field are ignored in 16-bit CRC * mode. The LOW field contains the lower 16 bits of the CRC polynomial, which are * used in both 16- and 32-bit CRC modes. */ typedef union _hw_crc_gpoly { uint32_t U; struct _hw_crc_gpoly_bitfields { uint32_t LOW : 16; //!< [15:0] Low Polynominal Half-word uint32_t HIGH : 16; //!< [31:16] High Polynominal Half-word } B; } hw_crc_gpoly_t; #endif /*! * @name Constants and macros for entire CRC_GPOLY register */ //@{ #define HW_CRC_GPOLY_ADDR (REGS_CRC_BASE + 0x4U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_GPOLY (*(__IO hw_crc_gpoly_t *) HW_CRC_GPOLY_ADDR) #define HW_CRC_GPOLY_RD() (HW_CRC_GPOLY.U) #define HW_CRC_GPOLY_WR(v) (HW_CRC_GPOLY.U = (v)) #define HW_CRC_GPOLY_SET(v) (HW_CRC_GPOLY_WR(HW_CRC_GPOLY_RD() | (v))) #define HW_CRC_GPOLY_CLR(v) (HW_CRC_GPOLY_WR(HW_CRC_GPOLY_RD() & ~(v))) #define HW_CRC_GPOLY_TOG(v) (HW_CRC_GPOLY_WR(HW_CRC_GPOLY_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_GPOLY bitfields */ /*! * @name Register CRC_GPOLY, field LOW[15:0] (RW) * * Writable and readable in both 32-bit and 16-bit CRC modes. */ //@{ #define BP_CRC_GPOLY_LOW (0U) //!< Bit position for CRC_GPOLY_LOW. #define BM_CRC_GPOLY_LOW (0x0000FFFFU) //!< Bit mask for CRC_GPOLY_LOW. #define BS_CRC_GPOLY_LOW (16U) //!< Bit field size in bits for CRC_GPOLY_LOW. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLY_LOW field. #define BR_CRC_GPOLY_LOW (HW_CRC_GPOLY.B.LOW) #endif //! @brief Format value for bitfield CRC_GPOLY_LOW. #define BF_CRC_GPOLY_LOW(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_GPOLY_LOW), uint32_t) & BM_CRC_GPOLY_LOW) #ifndef __LANGUAGE_ASM__ //! @brief Set the LOW field to a new value. #define BW_CRC_GPOLY_LOW(v) (HW_CRC_GPOLY_WR((HW_CRC_GPOLY_RD() & ~BM_CRC_GPOLY_LOW) | BF_CRC_GPOLY_LOW(v))) #endif //@} /*! * @name Register CRC_GPOLY, field HIGH[31:16] (RW) * * Writable and readable in 32-bit CRC mode (CTRL[TCRC] is 1). This field is not * writable in 16-bit CRC mode (CTRL[TCRC] is 0). */ //@{ #define BP_CRC_GPOLY_HIGH (16U) //!< Bit position for CRC_GPOLY_HIGH. #define BM_CRC_GPOLY_HIGH (0xFFFF0000U) //!< Bit mask for CRC_GPOLY_HIGH. #define BS_CRC_GPOLY_HIGH (16U) //!< Bit field size in bits for CRC_GPOLY_HIGH. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLY_HIGH field. #define BR_CRC_GPOLY_HIGH (HW_CRC_GPOLY.B.HIGH) #endif //! @brief Format value for bitfield CRC_GPOLY_HIGH. #define BF_CRC_GPOLY_HIGH(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_GPOLY_HIGH), uint32_t) & BM_CRC_GPOLY_HIGH) #ifndef __LANGUAGE_ASM__ //! @brief Set the HIGH field to a new value. #define BW_CRC_GPOLY_HIGH(v) (HW_CRC_GPOLY_WR((HW_CRC_GPOLY_RD() & ~BM_CRC_GPOLY_HIGH) | BF_CRC_GPOLY_HIGH(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_GPOLYL - CRC_GPOLYL register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_GPOLYL - CRC_GPOLYL register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_gpolyl { uint16_t U; struct _hw_crc_gpolyl_bitfields { uint16_t GPOLYL : 16; //!< [15:0] POLYL stores the lower 16 bits of //! the 16/32 bit CRC polynomial value } B; } hw_crc_gpolyl_t; #endif /*! * @name Constants and macros for entire CRC_GPOLYL register */ //@{ #define HW_CRC_GPOLYL_ADDR (REGS_CRC_BASE + 0x4U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_GPOLYL (*(__IO hw_crc_gpolyl_t *) HW_CRC_GPOLYL_ADDR) #define HW_CRC_GPOLYL_RD() (HW_CRC_GPOLYL.U) #define HW_CRC_GPOLYL_WR(v) (HW_CRC_GPOLYL.U = (v)) #define HW_CRC_GPOLYL_SET(v) (HW_CRC_GPOLYL_WR(HW_CRC_GPOLYL_RD() | (v))) #define HW_CRC_GPOLYL_CLR(v) (HW_CRC_GPOLYL_WR(HW_CRC_GPOLYL_RD() & ~(v))) #define HW_CRC_GPOLYL_TOG(v) (HW_CRC_GPOLYL_WR(HW_CRC_GPOLYL_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_GPOLYL bitfields */ /*! * @name Register CRC_GPOLYL, field GPOLYL[15:0] (RW) */ //@{ #define BP_CRC_GPOLYL_GPOLYL (0U) //!< Bit position for CRC_GPOLYL_GPOLYL. #define BM_CRC_GPOLYL_GPOLYL (0xFFFFU) //!< Bit mask for CRC_GPOLYL_GPOLYL. #define BS_CRC_GPOLYL_GPOLYL (16U) //!< Bit field size in bits for CRC_GPOLYL_GPOLYL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLYL_GPOLYL field. #define BR_CRC_GPOLYL_GPOLYL (HW_CRC_GPOLYL.U) #endif //! @brief Format value for bitfield CRC_GPOLYL_GPOLYL. #define BF_CRC_GPOLYL_GPOLYL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint16_t) << BP_CRC_GPOLYL_GPOLYL), uint16_t) & BM_CRC_GPOLYL_GPOLYL) #ifndef __LANGUAGE_ASM__ //! @brief Set the GPOLYL field to a new value. #define BW_CRC_GPOLYL_GPOLYL(v) (HW_CRC_GPOLYL_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_GPOLYH - CRC_GPOLYH register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_GPOLYH - CRC_GPOLYH register. (RW) * * Reset value: 0xFFFFU */ typedef union _hw_crc_gpolyh { uint16_t U; struct _hw_crc_gpolyh_bitfields { uint16_t GPOLYH : 16; //!< [15:0] POLYH stores the high 16 bits of //! the 16/32 bit CRC polynomial value } B; } hw_crc_gpolyh_t; #endif /*! * @name Constants and macros for entire CRC_GPOLYH register */ //@{ #define HW_CRC_GPOLYH_ADDR (REGS_CRC_BASE + 0x6U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_GPOLYH (*(__IO hw_crc_gpolyh_t *) HW_CRC_GPOLYH_ADDR) #define HW_CRC_GPOLYH_RD() (HW_CRC_GPOLYH.U) #define HW_CRC_GPOLYH_WR(v) (HW_CRC_GPOLYH.U = (v)) #define HW_CRC_GPOLYH_SET(v) (HW_CRC_GPOLYH_WR(HW_CRC_GPOLYH_RD() | (v))) #define HW_CRC_GPOLYH_CLR(v) (HW_CRC_GPOLYH_WR(HW_CRC_GPOLYH_RD() & ~(v))) #define HW_CRC_GPOLYH_TOG(v) (HW_CRC_GPOLYH_WR(HW_CRC_GPOLYH_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_GPOLYH bitfields */ /*! * @name Register CRC_GPOLYH, field GPOLYH[15:0] (RW) */ //@{ #define BP_CRC_GPOLYH_GPOLYH (0U) //!< Bit position for CRC_GPOLYH_GPOLYH. #define BM_CRC_GPOLYH_GPOLYH (0xFFFFU) //!< Bit mask for CRC_GPOLYH_GPOLYH. #define BS_CRC_GPOLYH_GPOLYH (16U) //!< Bit field size in bits for CRC_GPOLYH_GPOLYH. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLYH_GPOLYH field. #define BR_CRC_GPOLYH_GPOLYH (HW_CRC_GPOLYH.U) #endif //! @brief Format value for bitfield CRC_GPOLYH_GPOLYH. #define BF_CRC_GPOLYH_GPOLYH(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint16_t) << BP_CRC_GPOLYH_GPOLYH), uint16_t) & BM_CRC_GPOLYH_GPOLYH) #ifndef __LANGUAGE_ASM__ //! @brief Set the GPOLYH field to a new value. #define BW_CRC_GPOLYH_GPOLYH(v) (HW_CRC_GPOLYH_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_GPOLYLL - CRC_GPOLYLL register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_GPOLYLL - CRC_GPOLYLL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolyll { uint8_t U; struct _hw_crc_gpolyll_bitfields { uint8_t GPOLYLL : 8; //!< [7:0] POLYLL stores the first 8 bits of the //! 32 bit CRC } B; } hw_crc_gpolyll_t; #endif /*! * @name Constants and macros for entire CRC_GPOLYLL register */ //@{ #define HW_CRC_GPOLYLL_ADDR (REGS_CRC_BASE + 0x4U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_GPOLYLL (*(__IO hw_crc_gpolyll_t *) HW_CRC_GPOLYLL_ADDR) #define HW_CRC_GPOLYLL_RD() (HW_CRC_GPOLYLL.U) #define HW_CRC_GPOLYLL_WR(v) (HW_CRC_GPOLYLL.U = (v)) #define HW_CRC_GPOLYLL_SET(v) (HW_CRC_GPOLYLL_WR(HW_CRC_GPOLYLL_RD() | (v))) #define HW_CRC_GPOLYLL_CLR(v) (HW_CRC_GPOLYLL_WR(HW_CRC_GPOLYLL_RD() & ~(v))) #define HW_CRC_GPOLYLL_TOG(v) (HW_CRC_GPOLYLL_WR(HW_CRC_GPOLYLL_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_GPOLYLL bitfields */ /*! * @name Register CRC_GPOLYLL, field GPOLYLL[7:0] (RW) */ //@{ #define BP_CRC_GPOLYLL_GPOLYLL (0U) //!< Bit position for CRC_GPOLYLL_GPOLYLL. #define BM_CRC_GPOLYLL_GPOLYLL (0xFFU) //!< Bit mask for CRC_GPOLYLL_GPOLYLL. #define BS_CRC_GPOLYLL_GPOLYLL (8U) //!< Bit field size in bits for CRC_GPOLYLL_GPOLYLL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLYLL_GPOLYLL field. #define BR_CRC_GPOLYLL_GPOLYLL (HW_CRC_GPOLYLL.U) #endif //! @brief Format value for bitfield CRC_GPOLYLL_GPOLYLL. #define BF_CRC_GPOLYLL_GPOLYLL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_GPOLYLL_GPOLYLL), uint8_t) & BM_CRC_GPOLYLL_GPOLYLL) #ifndef __LANGUAGE_ASM__ //! @brief Set the GPOLYLL field to a new value. #define BW_CRC_GPOLYLL_GPOLYLL(v) (HW_CRC_GPOLYLL_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_GPOLYLU - CRC_GPOLYLU register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_GPOLYLU - CRC_GPOLYLU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolylu { uint8_t U; struct _hw_crc_gpolylu_bitfields { uint8_t GPOLYLU : 8; //!< [7:0] POLYLL stores the second 8 bits of //! the 32 bit CRC } B; } hw_crc_gpolylu_t; #endif /*! * @name Constants and macros for entire CRC_GPOLYLU register */ //@{ #define HW_CRC_GPOLYLU_ADDR (REGS_CRC_BASE + 0x5U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_GPOLYLU (*(__IO hw_crc_gpolylu_t *) HW_CRC_GPOLYLU_ADDR) #define HW_CRC_GPOLYLU_RD() (HW_CRC_GPOLYLU.U) #define HW_CRC_GPOLYLU_WR(v) (HW_CRC_GPOLYLU.U = (v)) #define HW_CRC_GPOLYLU_SET(v) (HW_CRC_GPOLYLU_WR(HW_CRC_GPOLYLU_RD() | (v))) #define HW_CRC_GPOLYLU_CLR(v) (HW_CRC_GPOLYLU_WR(HW_CRC_GPOLYLU_RD() & ~(v))) #define HW_CRC_GPOLYLU_TOG(v) (HW_CRC_GPOLYLU_WR(HW_CRC_GPOLYLU_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_GPOLYLU bitfields */ /*! * @name Register CRC_GPOLYLU, field GPOLYLU[7:0] (RW) */ //@{ #define BP_CRC_GPOLYLU_GPOLYLU (0U) //!< Bit position for CRC_GPOLYLU_GPOLYLU. #define BM_CRC_GPOLYLU_GPOLYLU (0xFFU) //!< Bit mask for CRC_GPOLYLU_GPOLYLU. #define BS_CRC_GPOLYLU_GPOLYLU (8U) //!< Bit field size in bits for CRC_GPOLYLU_GPOLYLU. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLYLU_GPOLYLU field. #define BR_CRC_GPOLYLU_GPOLYLU (HW_CRC_GPOLYLU.U) #endif //! @brief Format value for bitfield CRC_GPOLYLU_GPOLYLU. #define BF_CRC_GPOLYLU_GPOLYLU(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_GPOLYLU_GPOLYLU), uint8_t) & BM_CRC_GPOLYLU_GPOLYLU) #ifndef __LANGUAGE_ASM__ //! @brief Set the GPOLYLU field to a new value. #define BW_CRC_GPOLYLU_GPOLYLU(v) (HW_CRC_GPOLYLU_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_GPOLYHL - CRC_GPOLYHL register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_GPOLYHL - CRC_GPOLYHL register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolyhl { uint8_t U; struct _hw_crc_gpolyhl_bitfields { uint8_t GPOLYHL : 8; //!< [7:0] POLYHL stores the third 8 bits of the //! 32 bit CRC } B; } hw_crc_gpolyhl_t; #endif /*! * @name Constants and macros for entire CRC_GPOLYHL register */ //@{ #define HW_CRC_GPOLYHL_ADDR (REGS_CRC_BASE + 0x6U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_GPOLYHL (*(__IO hw_crc_gpolyhl_t *) HW_CRC_GPOLYHL_ADDR) #define HW_CRC_GPOLYHL_RD() (HW_CRC_GPOLYHL.U) #define HW_CRC_GPOLYHL_WR(v) (HW_CRC_GPOLYHL.U = (v)) #define HW_CRC_GPOLYHL_SET(v) (HW_CRC_GPOLYHL_WR(HW_CRC_GPOLYHL_RD() | (v))) #define HW_CRC_GPOLYHL_CLR(v) (HW_CRC_GPOLYHL_WR(HW_CRC_GPOLYHL_RD() & ~(v))) #define HW_CRC_GPOLYHL_TOG(v) (HW_CRC_GPOLYHL_WR(HW_CRC_GPOLYHL_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_GPOLYHL bitfields */ /*! * @name Register CRC_GPOLYHL, field GPOLYHL[7:0] (RW) */ //@{ #define BP_CRC_GPOLYHL_GPOLYHL (0U) //!< Bit position for CRC_GPOLYHL_GPOLYHL. #define BM_CRC_GPOLYHL_GPOLYHL (0xFFU) //!< Bit mask for CRC_GPOLYHL_GPOLYHL. #define BS_CRC_GPOLYHL_GPOLYHL (8U) //!< Bit field size in bits for CRC_GPOLYHL_GPOLYHL. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLYHL_GPOLYHL field. #define BR_CRC_GPOLYHL_GPOLYHL (HW_CRC_GPOLYHL.U) #endif //! @brief Format value for bitfield CRC_GPOLYHL_GPOLYHL. #define BF_CRC_GPOLYHL_GPOLYHL(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_GPOLYHL_GPOLYHL), uint8_t) & BM_CRC_GPOLYHL_GPOLYHL) #ifndef __LANGUAGE_ASM__ //! @brief Set the GPOLYHL field to a new value. #define BW_CRC_GPOLYHL_GPOLYHL(v) (HW_CRC_GPOLYHL_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_GPOLYHU - CRC_GPOLYHU register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_GPOLYHU - CRC_GPOLYHU register. (RW) * * Reset value: 0xFFU */ typedef union _hw_crc_gpolyhu { uint8_t U; struct _hw_crc_gpolyhu_bitfields { uint8_t GPOLYHU : 8; //!< [7:0] POLYHU stores the fourth 8 bits of //! the 32 bit CRC } B; } hw_crc_gpolyhu_t; #endif /*! * @name Constants and macros for entire CRC_GPOLYHU register */ //@{ #define HW_CRC_GPOLYHU_ADDR (REGS_CRC_BASE + 0x7U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_GPOLYHU (*(__IO hw_crc_gpolyhu_t *) HW_CRC_GPOLYHU_ADDR) #define HW_CRC_GPOLYHU_RD() (HW_CRC_GPOLYHU.U) #define HW_CRC_GPOLYHU_WR(v) (HW_CRC_GPOLYHU.U = (v)) #define HW_CRC_GPOLYHU_SET(v) (HW_CRC_GPOLYHU_WR(HW_CRC_GPOLYHU_RD() | (v))) #define HW_CRC_GPOLYHU_CLR(v) (HW_CRC_GPOLYHU_WR(HW_CRC_GPOLYHU_RD() & ~(v))) #define HW_CRC_GPOLYHU_TOG(v) (HW_CRC_GPOLYHU_WR(HW_CRC_GPOLYHU_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_GPOLYHU bitfields */ /*! * @name Register CRC_GPOLYHU, field GPOLYHU[7:0] (RW) */ //@{ #define BP_CRC_GPOLYHU_GPOLYHU (0U) //!< Bit position for CRC_GPOLYHU_GPOLYHU. #define BM_CRC_GPOLYHU_GPOLYHU (0xFFU) //!< Bit mask for CRC_GPOLYHU_GPOLYHU. #define BS_CRC_GPOLYHU_GPOLYHU (8U) //!< Bit field size in bits for CRC_GPOLYHU_GPOLYHU. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_GPOLYHU_GPOLYHU field. #define BR_CRC_GPOLYHU_GPOLYHU (HW_CRC_GPOLYHU.U) #endif //! @brief Format value for bitfield CRC_GPOLYHU_GPOLYHU. #define BF_CRC_GPOLYHU_GPOLYHU(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_GPOLYHU_GPOLYHU), uint8_t) & BM_CRC_GPOLYHU_GPOLYHU) #ifndef __LANGUAGE_ASM__ //! @brief Set the GPOLYHU field to a new value. #define BW_CRC_GPOLYHU_GPOLYHU(v) (HW_CRC_GPOLYHU_WR(v)) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_CTRL - CRC Control register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_CTRL - CRC Control register (RW) * * Reset value: 0x00000000U * * This register controls the configuration and working of the CRC module. * Appropriate bits must be set before starting a new CRC calculation. A new CRC * calculation is initialized by asserting CTRL[WAS] and then writing the seed into * the CRC data register. */ typedef union _hw_crc_ctrl { uint32_t U; struct _hw_crc_ctrl_bitfields { uint32_t RESERVED0 : 24; //!< [23:0] uint32_t TCRC : 1; //!< [24] uint32_t WAS : 1; //!< [25] Write CRC Data Register As Seed uint32_t FXOR : 1; //!< [26] Complement Read Of CRC Data Register uint32_t RESERVED1 : 1; //!< [27] uint32_t TOTR : 2; //!< [29:28] Type Of Transpose For Read uint32_t TOT : 2; //!< [31:30] Type Of Transpose For Writes } B; } hw_crc_ctrl_t; #endif /*! * @name Constants and macros for entire CRC_CTRL register */ //@{ #define HW_CRC_CTRL_ADDR (REGS_CRC_BASE + 0x8U) #ifndef __LANGUAGE_ASM__ #define HW_CRC_CTRL (*(__IO hw_crc_ctrl_t *) HW_CRC_CTRL_ADDR) #define HW_CRC_CTRL_RD() (HW_CRC_CTRL.U) #define HW_CRC_CTRL_WR(v) (HW_CRC_CTRL.U = (v)) #define HW_CRC_CTRL_SET(v) (HW_CRC_CTRL_WR(HW_CRC_CTRL_RD() | (v))) #define HW_CRC_CTRL_CLR(v) (HW_CRC_CTRL_WR(HW_CRC_CTRL_RD() & ~(v))) #define HW_CRC_CTRL_TOG(v) (HW_CRC_CTRL_WR(HW_CRC_CTRL_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_CTRL bitfields */ /*! * @name Register CRC_CTRL, field TCRC[24] (RW) * * Width of CRC protocol. * * Values: * - 0 - 16-bit CRC protocol. * - 1 - 32-bit CRC protocol. */ //@{ #define BP_CRC_CTRL_TCRC (24U) //!< Bit position for CRC_CTRL_TCRC. #define BM_CRC_CTRL_TCRC (0x01000000U) //!< Bit mask for CRC_CTRL_TCRC. #define BS_CRC_CTRL_TCRC (1U) //!< Bit field size in bits for CRC_CTRL_TCRC. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRL_TCRC field. #define BR_CRC_CTRL_TCRC (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR, BP_CRC_CTRL_TCRC)) #endif //! @brief Format value for bitfield CRC_CTRL_TCRC. #define BF_CRC_CTRL_TCRC(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_CTRL_TCRC), uint32_t) & BM_CRC_CTRL_TCRC) #ifndef __LANGUAGE_ASM__ //! @brief Set the TCRC field to a new value. #define BW_CRC_CTRL_TCRC(v) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR, BP_CRC_CTRL_TCRC) = (v)) #endif //@} /*! * @name Register CRC_CTRL, field WAS[25] (RW) * * When asserted, a value written to the CRC data register is considered a seed * value. When deasserted, a value written to the CRC data register is taken as * data for CRC computation. * * Values: * - 0 - Writes to the CRC data register are data values. * - 1 - Writes to the CRC data register are seed values. */ //@{ #define BP_CRC_CTRL_WAS (25U) //!< Bit position for CRC_CTRL_WAS. #define BM_CRC_CTRL_WAS (0x02000000U) //!< Bit mask for CRC_CTRL_WAS. #define BS_CRC_CTRL_WAS (1U) //!< Bit field size in bits for CRC_CTRL_WAS. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRL_WAS field. #define BR_CRC_CTRL_WAS (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR, BP_CRC_CTRL_WAS)) #endif //! @brief Format value for bitfield CRC_CTRL_WAS. #define BF_CRC_CTRL_WAS(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_CTRL_WAS), uint32_t) & BM_CRC_CTRL_WAS) #ifndef __LANGUAGE_ASM__ //! @brief Set the WAS field to a new value. #define BW_CRC_CTRL_WAS(v) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR, BP_CRC_CTRL_WAS) = (v)) #endif //@} /*! * @name Register CRC_CTRL, field FXOR[26] (RW) * * Some CRC protocols require the final checksum to be XORed with 0xFFFFFFFF or * 0xFFFF. Asserting this bit enables on the fly complementing of read data. * * Values: * - 0 - No XOR on reading. * - 1 - Invert or complement the read value of the CRC Data register. */ //@{ #define BP_CRC_CTRL_FXOR (26U) //!< Bit position for CRC_CTRL_FXOR. #define BM_CRC_CTRL_FXOR (0x04000000U) //!< Bit mask for CRC_CTRL_FXOR. #define BS_CRC_CTRL_FXOR (1U) //!< Bit field size in bits for CRC_CTRL_FXOR. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRL_FXOR field. #define BR_CRC_CTRL_FXOR (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR, BP_CRC_CTRL_FXOR)) #endif //! @brief Format value for bitfield CRC_CTRL_FXOR. #define BF_CRC_CTRL_FXOR(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_CTRL_FXOR), uint32_t) & BM_CRC_CTRL_FXOR) #ifndef __LANGUAGE_ASM__ //! @brief Set the FXOR field to a new value. #define BW_CRC_CTRL_FXOR(v) (BITBAND_ACCESS32(HW_CRC_CTRL_ADDR, BP_CRC_CTRL_FXOR) = (v)) #endif //@} /*! * @name Register CRC_CTRL, field TOTR[29:28] (RW) * * Identifies the transpose configuration of the value read from the CRC Data * register. See the description of the transpose feature for the available * transpose options. * * Values: * - 00 - No transposition. * - 01 - Bits in bytes are transposed; bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ //@{ #define BP_CRC_CTRL_TOTR (28U) //!< Bit position for CRC_CTRL_TOTR. #define BM_CRC_CTRL_TOTR (0x30000000U) //!< Bit mask for CRC_CTRL_TOTR. #define BS_CRC_CTRL_TOTR (2U) //!< Bit field size in bits for CRC_CTRL_TOTR. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRL_TOTR field. #define BR_CRC_CTRL_TOTR (HW_CRC_CTRL.B.TOTR) #endif //! @brief Format value for bitfield CRC_CTRL_TOTR. #define BF_CRC_CTRL_TOTR(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_CTRL_TOTR), uint32_t) & BM_CRC_CTRL_TOTR) #ifndef __LANGUAGE_ASM__ //! @brief Set the TOTR field to a new value. #define BW_CRC_CTRL_TOTR(v) (HW_CRC_CTRL_WR((HW_CRC_CTRL_RD() & ~BM_CRC_CTRL_TOTR) | BF_CRC_CTRL_TOTR(v))) #endif //@} /*! * @name Register CRC_CTRL, field TOT[31:30] (RW) * * Defines the transpose configuration of the data written to the CRC data * register. See the description of the transpose feature for the available transpose * options. * * Values: * - 00 - No transposition. * - 01 - Bits in bytes are transposed; bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ //@{ #define BP_CRC_CTRL_TOT (30U) //!< Bit position for CRC_CTRL_TOT. #define BM_CRC_CTRL_TOT (0xC0000000U) //!< Bit mask for CRC_CTRL_TOT. #define BS_CRC_CTRL_TOT (2U) //!< Bit field size in bits for CRC_CTRL_TOT. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRL_TOT field. #define BR_CRC_CTRL_TOT (HW_CRC_CTRL.B.TOT) #endif //! @brief Format value for bitfield CRC_CTRL_TOT. #define BF_CRC_CTRL_TOT(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint32_t) << BP_CRC_CTRL_TOT), uint32_t) & BM_CRC_CTRL_TOT) #ifndef __LANGUAGE_ASM__ //! @brief Set the TOT field to a new value. #define BW_CRC_CTRL_TOT(v) (HW_CRC_CTRL_WR((HW_CRC_CTRL_RD() & ~BM_CRC_CTRL_TOT) | BF_CRC_CTRL_TOT(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_CRC_CTRLHU - CRC_CTRLHU register. //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_CRC_CTRLHU - CRC_CTRLHU register. (RW) * * Reset value: 0x00U */ typedef union _hw_crc_ctrlhu { uint8_t U; struct _hw_crc_ctrlhu_bitfields { uint8_t TCRC : 1; //!< [0] uint8_t WAS : 1; //!< [1] uint8_t FXOR : 1; //!< [2] uint8_t RESERVED0 : 1; //!< [3] uint8_t TOTR : 2; //!< [5:4] uint8_t TOT : 2; //!< [7:6] } B; } hw_crc_ctrlhu_t; #endif /*! * @name Constants and macros for entire CRC_CTRLHU register */ //@{ #define HW_CRC_CTRLHU_ADDR (REGS_CRC_BASE + 0xBU) #ifndef __LANGUAGE_ASM__ #define HW_CRC_CTRLHU (*(__IO hw_crc_ctrlhu_t *) HW_CRC_CTRLHU_ADDR) #define HW_CRC_CTRLHU_RD() (HW_CRC_CTRLHU.U) #define HW_CRC_CTRLHU_WR(v) (HW_CRC_CTRLHU.U = (v)) #define HW_CRC_CTRLHU_SET(v) (HW_CRC_CTRLHU_WR(HW_CRC_CTRLHU_RD() | (v))) #define HW_CRC_CTRLHU_CLR(v) (HW_CRC_CTRLHU_WR(HW_CRC_CTRLHU_RD() & ~(v))) #define HW_CRC_CTRLHU_TOG(v) (HW_CRC_CTRLHU_WR(HW_CRC_CTRLHU_RD() ^ (v))) #endif //@} /* * Constants & macros for individual CRC_CTRLHU bitfields */ /*! * @name Register CRC_CTRLHU, field TCRC[0] (RW) * * Values: * - 0 - 16-bit CRC protocol. * - 1 - 32-bit CRC protocol. */ //@{ #define BP_CRC_CTRLHU_TCRC (0U) //!< Bit position for CRC_CTRLHU_TCRC. #define BM_CRC_CTRLHU_TCRC (0x01U) //!< Bit mask for CRC_CTRLHU_TCRC. #define BS_CRC_CTRLHU_TCRC (1U) //!< Bit field size in bits for CRC_CTRLHU_TCRC. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRLHU_TCRC field. #define BR_CRC_CTRLHU_TCRC (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR, BP_CRC_CTRLHU_TCRC)) #endif //! @brief Format value for bitfield CRC_CTRLHU_TCRC. #define BF_CRC_CTRLHU_TCRC(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_CTRLHU_TCRC), uint8_t) & BM_CRC_CTRLHU_TCRC) #ifndef __LANGUAGE_ASM__ //! @brief Set the TCRC field to a new value. #define BW_CRC_CTRLHU_TCRC(v) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR, BP_CRC_CTRLHU_TCRC) = (v)) #endif //@} /*! * @name Register CRC_CTRLHU, field WAS[1] (RW) * * Values: * - 0 - Writes to CRC data register are data values. * - 1 - Writes to CRC data reguster are seed values. */ //@{ #define BP_CRC_CTRLHU_WAS (1U) //!< Bit position for CRC_CTRLHU_WAS. #define BM_CRC_CTRLHU_WAS (0x02U) //!< Bit mask for CRC_CTRLHU_WAS. #define BS_CRC_CTRLHU_WAS (1U) //!< Bit field size in bits for CRC_CTRLHU_WAS. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRLHU_WAS field. #define BR_CRC_CTRLHU_WAS (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR, BP_CRC_CTRLHU_WAS)) #endif //! @brief Format value for bitfield CRC_CTRLHU_WAS. #define BF_CRC_CTRLHU_WAS(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_CTRLHU_WAS), uint8_t) & BM_CRC_CTRLHU_WAS) #ifndef __LANGUAGE_ASM__ //! @brief Set the WAS field to a new value. #define BW_CRC_CTRLHU_WAS(v) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR, BP_CRC_CTRLHU_WAS) = (v)) #endif //@} /*! * @name Register CRC_CTRLHU, field FXOR[2] (RW) * * Values: * - 0 - No XOR on reading. * - 1 - Invert or complement the read value of CRC data register. */ //@{ #define BP_CRC_CTRLHU_FXOR (2U) //!< Bit position for CRC_CTRLHU_FXOR. #define BM_CRC_CTRLHU_FXOR (0x04U) //!< Bit mask for CRC_CTRLHU_FXOR. #define BS_CRC_CTRLHU_FXOR (1U) //!< Bit field size in bits for CRC_CTRLHU_FXOR. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRLHU_FXOR field. #define BR_CRC_CTRLHU_FXOR (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR, BP_CRC_CTRLHU_FXOR)) #endif //! @brief Format value for bitfield CRC_CTRLHU_FXOR. #define BF_CRC_CTRLHU_FXOR(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_CTRLHU_FXOR), uint8_t) & BM_CRC_CTRLHU_FXOR) #ifndef __LANGUAGE_ASM__ //! @brief Set the FXOR field to a new value. #define BW_CRC_CTRLHU_FXOR(v) (BITBAND_ACCESS8(HW_CRC_CTRLHU_ADDR, BP_CRC_CTRLHU_FXOR) = (v)) #endif //@} /*! * @name Register CRC_CTRLHU, field TOTR[5:4] (RW) * * Values: * - 00 - No Transposition. * - 01 - Bits in bytes are transposed, bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ //@{ #define BP_CRC_CTRLHU_TOTR (4U) //!< Bit position for CRC_CTRLHU_TOTR. #define BM_CRC_CTRLHU_TOTR (0x30U) //!< Bit mask for CRC_CTRLHU_TOTR. #define BS_CRC_CTRLHU_TOTR (2U) //!< Bit field size in bits for CRC_CTRLHU_TOTR. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRLHU_TOTR field. #define BR_CRC_CTRLHU_TOTR (HW_CRC_CTRLHU.B.TOTR) #endif //! @brief Format value for bitfield CRC_CTRLHU_TOTR. #define BF_CRC_CTRLHU_TOTR(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_CTRLHU_TOTR), uint8_t) & BM_CRC_CTRLHU_TOTR) #ifndef __LANGUAGE_ASM__ //! @brief Set the TOTR field to a new value. #define BW_CRC_CTRLHU_TOTR(v) (HW_CRC_CTRLHU_WR((HW_CRC_CTRLHU_RD() & ~BM_CRC_CTRLHU_TOTR) | BF_CRC_CTRLHU_TOTR(v))) #endif //@} /*! * @name Register CRC_CTRLHU, field TOT[7:6] (RW) * * Values: * - 00 - No Transposition. * - 01 - Bits in bytes are transposed, bytes are not transposed. * - 10 - Both bits in bytes and bytes are transposed. * - 11 - Only bytes are transposed; no bits in a byte are transposed. */ //@{ #define BP_CRC_CTRLHU_TOT (6U) //!< Bit position for CRC_CTRLHU_TOT. #define BM_CRC_CTRLHU_TOT (0xC0U) //!< Bit mask for CRC_CTRLHU_TOT. #define BS_CRC_CTRLHU_TOT (2U) //!< Bit field size in bits for CRC_CTRLHU_TOT. #ifndef __LANGUAGE_ASM__ //! @brief Read current value of the CRC_CTRLHU_TOT field. #define BR_CRC_CTRLHU_TOT (HW_CRC_CTRLHU.B.TOT) #endif //! @brief Format value for bitfield CRC_CTRLHU_TOT. #define BF_CRC_CTRLHU_TOT(v) (__REG_VALUE_TYPE((__REG_VALUE_TYPE((v), uint8_t) << BP_CRC_CTRLHU_TOT), uint8_t) & BM_CRC_CTRLHU_TOT) #ifndef __LANGUAGE_ASM__ //! @brief Set the TOT field to a new value. #define BW_CRC_CTRLHU_TOT(v) (HW_CRC_CTRLHU_WR((HW_CRC_CTRLHU_RD() & ~BM_CRC_CTRLHU_TOT) | BF_CRC_CTRLHU_TOT(v))) #endif //@} //------------------------------------------------------------------------------------------- // hw_crc_t - module struct //------------------------------------------------------------------------------------------- /*! * @brief All CRC module registers. */ #ifndef __LANGUAGE_ASM__ #pragma pack(1) typedef struct _hw_crc { union { struct { __IO hw_crc_datal_t DATAL; //!< [0x0] CRC_DATAL register. __IO hw_crc_datah_t DATAH; //!< [0x2] CRC_DATAH register. } ACCESS16BIT; struct { __IO hw_crc_datall_t DATALL; //!< [0x0] CRC_DATALL register. __IO hw_crc_datalu_t DATALU; //!< [0x1] CRC_DATALU register. __IO hw_crc_datahl_t DATAHL; //!< [0x2] CRC_DATAHL register. __IO hw_crc_datahu_t DATAHU; //!< [0x3] CRC_DATAHU register. } ACCESS8BIT; __IO hw_crc_data_t DATA; //!< [0x0] CRC Data register }; union { __IO hw_crc_gpoly_t GPOLY; //!< [0x4] CRC Polynomial register struct { __IO hw_crc_gpolyl_t GPOLYL; //!< [0x4] CRC_GPOLYL register. __IO hw_crc_gpolyh_t GPOLYH; //!< [0x6] CRC_GPOLYH register. } GPOLY_ACCESS16BIT; struct { __IO hw_crc_gpolyll_t GPOLYLL; //!< [0x4] CRC_GPOLYLL register. __IO hw_crc_gpolylu_t GPOLYLU; //!< [0x5] CRC_GPOLYLU register. __IO hw_crc_gpolyhl_t GPOLYHL; //!< [0x6] CRC_GPOLYHL register. __IO hw_crc_gpolyhu_t GPOLYHU; //!< [0x7] CRC_GPOLYHU register. } GPOLY_ACCESS8BIT; }; union { __IO hw_crc_ctrl_t CTRL; //!< [0x8] CRC Control register struct { uint8_t _reserved0[3]; __IO hw_crc_ctrlhu_t CTRLHU; //!< [0xB] CRC_CTRLHU register. } CTRL_ACCESS8BIT; }; } hw_crc_t; #pragma pack() //! @brief Macro to access all CRC registers. //! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, //! use the '&' operator, like <code>&HW_CRC</code>. #define HW_CRC (*(hw_crc_t *) REGS_CRC_BASE) #endif #endif // __HW_CRC_REGISTERS_H__ // v22/130726/0.9 // EOF
AdamColton/geom
examples/starfield/starfield.go
<reponame>AdamColton/geom package main import ( "fmt" "image/color" "math/rand" "os" "runtime/pprof" "github.com/adamcolton/geom/d3/render/scene" "github.com/adamcolton/geom/d3/render/zbuf" "github.com/adamcolton/geom/d3/shape/plane" "github.com/adamcolton/geom/angle" "github.com/adamcolton/geom/d2" d2poly "github.com/adamcolton/geom/d2/shape/polygon" "github.com/adamcolton/geom/d3" triangle3 "github.com/adamcolton/geom/d3/shape/triangle" "github.com/adamcolton/geom/d3/solid/mesh" ) // For this to run, ffmpeg must be installed const ( // Frames of video to render frames = 100 // Number of stars to render stars = 200 // width sets the size, the aspect ratio is always widescreen width = 500 // Set to between 1.0 and 2.0 // 1.0 is low quality // 2.0 is high quality imageScale = 1.5 // enable the profiler profile = true ) var cr = string([]byte{13}) func main() { if profile { f, err := os.Create("profile.out") if err != nil { panic(err) } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() } m := getMesh() w := width if w%2 == 1 { w++ } h := (w * 9) / 16 if h%2 == 1 { h++ } s := &zbuf.Scene{ Camera: zbuf.Camera{ Camera: scene.Camera{ Width: w, Height: h, Angle: angle.Deg(45), Q: d3.Q{1, 0, 0, 0}, }, Near: 0.1, Far: 200, }, Framerate: 15, Name: "stars", ConstantRateFactor: 25, Background: color.RGBA{255, 255, 255, 255}, ImageScale: 1.25, } stars := defineStarField() for frame := 0; frame < frames; frame++ { d := float64(frame) / float64(frames) s.Camera.Pt.Z = d * -150.0 rot := angle.Rot(d) s.Camera.Q.A, s.Camera.Q.D = rot.Sincos() f := s.NewFrame(len(stars)) for _, star := range stars { if star.Z+0.2 > s.Camera.Pt.Z { continue } f.AddMesh(&m, starShader, star.T(float64(frame))) } f.Render() fmt.Print(cr, "Frame ", frame, " ") } s.Done() } func getMesh() mesh.TriangleMesh { var points = 8 outer := d2poly.RegularPolygonRadius(d2.Pt{0, 0}, 2, angle.Rot(0.25), points) inner := d2poly.RegularPolygonRadius(d2.Pt{0, 0}, 1, angle.Rot(0.25+1.0/float64(points*2)), points) star2d := make([]d2.Pt, points*2) for i, oPt := range outer { star2d[2*i] = oPt star2d[2*i+1] = inner[i] } f := plane.New(d3.Pt{0, 0, 0}, d3.Pt{1, 0, 0}, d3.Pt{0, 1, 0}).ConvertMany(star2d) tm := mesh.TriangleMesh{ Pts: append(f, d3.Pt{0, 0, 0.5}, d3.Pt{0, 0, -0.5}), } up := uint32(points) for i := uint32(0); i < up; i++ { tm.Polygons = append(tm.Polygons, [][3]uint32{ {i * 2, i*2 + 1, (up * 2)}, }, [][3]uint32{ {i * 2, i*2 + 1, (up * 2) + 1}, }, [][3]uint32{ {i*2 + 1, (i*2 + 2) % (up * 2), (up * 2)}, }, [][3]uint32{ {i*2 + 1, (i*2 + 2) % (up * 2), (up * 2) + 1}, }) } return tm } type star struct { d3.V angle.Rad speed angle.Rad } func (s *star) T(frame float64) *d3.T { return d3.Rotation{ s.Rad + s.speed*angle.Rad(frame), d3.XZ, }.T(). T(d3.Translate(s.V).T()) } func defineStarField() []star { out := make([]star, stars) for i := range out { v2 := d2.Polar{ M: rand.Float64()*10 + 3, A: angle.Rot(rand.Float64()), }.V() out[i] = star{ V: d3.V{v2.X, v2.Y, rand.Float64() * -200}, Rad: angle.Rot(rand.Float64()), speed: angle.Rot(rand.Float64()*.05) + .05, } if rand.Intn(2) == 0 { out[i].speed = -out[i].speed } } return out } var black = color.RGBA{0, 0, 0, 255} func starShader(ctx *zbuf.Context) *color.RGBA { if ctx.B.U < 0.03 || ctx.B.V < 0.03 || ctx.B.U+ctx.B.V > 0.97 { return &black } tIdxs := ctx.Original.Polygons[ctx.PolygonIdx][ctx.TriangleIdx] n := (&triangle3.Triangle{ ctx.Space[tIdxs[0]], ctx.Space[tIdxs[1]], ctx.Space[tIdxs[2]], }).Normal().Normal() r := (n.X*0.25 + 0.75) * 255 g := (n.Y*0.25 + 0.75) * 255 return &(color.RGBA{uint8(r), uint8(g), 0, 255}) }
pulquero/mathml
dom/src/main/java/org/w3c/dom/mathml/MathMLCiElement.java
<reponame>pulquero/mathml<filename>dom/src/main/java/org/w3c/dom/mathml/MathMLCiElement.java package org.w3c.dom.mathml; public interface MathMLCiElement extends MathMLContentToken { public String getType(); public void setType(String type); };
kalisio/aktnmap
src/tours/edit-organisation.js
module.exports = [{ target: '#name-field', content: 'tours.organisation.NAME_LABEL', params: { placement: 'bottom' } }, { target: '#avatar-field', content: 'tours.organisation.AVATAR_LABEL', params: { placement: 'bottom' } }, { target: '#color-field', content: 'tours.organisation.COLOR_LABEL', params: { placement: 'bottom' } }, { target: '#apply-button', content: 'tours.organisation.UPDATE_LABEL', params: { placement: 'left' } }]
bizon/mws-sdk
lib/client/parsers/finances/adjustment-event.js
<reponame>bizon/mws-sdk<filename>lib/client/parsers/finances/adjustment-event.js<gh_stars>10-100 const select = require('../select') const nullable = require('../nullable') const {parseStr, parseDate} = require('../base') const parseCurrencyAmount = require('./currency-amount') const parseAdjustmentItem = require('./adjustment-item') module.exports = (key, node) => ({ adjustmentType: parseStr(`${key}/finances:AdjustmentType`, node), adjustmentAmount: nullable(parseCurrencyAmount, `${key}/finances:AdjustmentAmount`, node), adjustmentItemList: select(`${key}/finances:AdjustmentItemList/finances:AdjustmentItem`, node).map(n => parseAdjustmentItem('.', n)), postedDate: parseDate(`${key}/finances:PostedDate`, node), })
hfp/plaidml
pmlc/target/x86/trace_linking.cc
// Copyright 2020 Intel Corporation #include "llvm/Support/FormatVariadic.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "pmlc/target/x86/pass_detail.h" #include "pmlc/util/logging.h" using namespace mlir; // NOLINT[build/namespaces] namespace pmlc::target::x86 { namespace { struct TraceLinkingPass : public TraceLinkingBase<TraceLinkingPass> { void runOnOperation() override { getOperation().walk([](LLVM::LLVMFuncOp op) { if (!op->getAttrOfType<UnitAttr>("trace")) { return; } if (!op.empty()) { return; } auto loc = op.getLoc(); auto *context = op.getContext(); OpBuilder builder(context); auto module = op->getParentOfType<ModuleOp>(); auto traceRef = getOrInsertTrace(loc, builder, module); auto block = op.addEntryBlock(); builder.setInsertionPointToStart(block); auto id = op->getAttrOfType<IntegerAttr>("id").getValue().getZExtValue(); auto msgStr = op->getAttrOfType<StringAttr>("msg").getValue().str(); auto msg = StringRef(msgStr.c_str(), msgStr.size() + 1); auto msgSymbol = llvm::formatv("__trace_msg_{0}", id).str(); auto msgValue = getOrCreateGlobalString(loc, builder, msgSymbol, msg, module); builder.create<LLVM::CallOp>(loc, ArrayRef<Type>{}, traceRef, ArrayRef<Value>{msgValue}); builder.create<LLVM::ReturnOp>(loc, ArrayRef<Value>{}); op.removeAttr("id"); op.removeAttr("msg"); op.removeAttr("trace"); }); } /// Return a value representing an access into a global string with the given /// name, creating the string if necessary. static Value getOrCreateGlobalString(Location loc, OpBuilder &builder, StringRef name, StringRef value, ModuleOp module) { // Create the global at the entry of the module. LLVM::GlobalOp global; if (!(global = module.lookupSymbol<LLVM::GlobalOp>(name))) { OpBuilder::InsertionGuard insertGuard(builder); builder.setInsertionPointToStart(module.getBody()); auto type = LLVM::LLVMArrayType::get(builder.getIntegerType(8), value.size()); global = builder.create<LLVM::GlobalOp>(loc, type, /*isConstant=*/true, LLVM::Linkage::Internal, name, builder.getStringAttr(value)); } // Get the pointer to the first character in the global string. Value globalPtr = builder.create<LLVM::AddressOfOp>(loc, global); Value cst0 = builder.create<LLVM::ConstantOp>(loc, builder.getI64Type(), builder.getIndexAttr(0)); return builder.create<LLVM::GEPOp>( loc, LLVM::LLVMPointerType::get(builder.getIntegerType(8)), globalPtr, ArrayRef<Value>({cst0, cst0})); } static FlatSymbolRefAttr getOrInsertTrace(Location loc, OpBuilder &builder, ModuleOp module) { const char *symbol = "plaidml_rt_trace"; auto *context = module.getContext(); if (module.lookupSymbol(symbol)) { return SymbolRefAttr::get(symbol, context); } OpBuilder::InsertionGuard insertGuard(builder); builder.setInsertionPointToStart(module.getBody()); auto voidTy = LLVM::LLVMVoidType::get(context); auto msgTy = LLVM::LLVMPointerType::get(builder.getIntegerType(8)); auto funcType = LLVM::LLVMFunctionType::get(voidTy, {msgTy}, /*isVarArg=*/false); builder.create<LLVM::LLVMFuncOp>(loc, symbol, funcType); return SymbolRefAttr::get(symbol, context); } }; } // namespace std::unique_ptr<mlir::Pass> createTraceLinkingPass() { return std::make_unique<TraceLinkingPass>(); } } // namespace pmlc::target::x86
JavaQualitasCorpus/myfaces_core-2.1.10
src/myfaces-impl-2.1.10-sources/org/apache/myfaces/view/facelets/tag/jstl/core/ForEachHandler.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.myfaces.view.facelets.tag.jstl.core; import java.io.IOException; import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.el.ELException; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.view.facelets.FaceletContext; import javax.faces.view.facelets.FaceletException; import javax.faces.view.facelets.TagAttribute; import javax.faces.view.facelets.TagAttributeException; import javax.faces.view.facelets.TagConfig; import javax.faces.view.facelets.TagHandler; import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFFaceletAttribute; import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFFaceletTag; import org.apache.myfaces.view.facelets.AbstractFaceletContext; import org.apache.myfaces.view.facelets.FaceletCompositionContext; import org.apache.myfaces.view.facelets.PageContext; import org.apache.myfaces.view.facelets.tag.ComponentContainerHandler; import org.apache.myfaces.view.facelets.tag.jsf.ComponentSupport; /** * The basic iteration tag, accepting many different * collection types and supporting subsetting and other * functionality * * @author <NAME> * @author <NAME> * @version $Id: ForEachHandler.java 1351610 2012-06-19 08:55:52Z lu4242 $ */ @JSFFaceletTag(name="c:forEach") public final class ForEachHandler extends TagHandler implements ComponentContainerHandler { private static class ArrayIterator implements Iterator<Object> { protected final Object array; protected int i; protected final int len; public ArrayIterator(Object src) { this.i = 0; this.array = src; this.len = Array.getLength(src); } public boolean hasNext() { return this.i < this.len; } public Object next() { return Array.get(this.array, this.i++); } public void remove() { throw new UnsupportedOperationException(); } } /** * If items specified: * Iteration begins at the item located at the * specified index. First item of the collection has * index 0. * If items not specified: * Iteration begins with index set at the value * specified. */ @JSFFaceletAttribute(className="int") private final TagAttribute begin; /** * If items specified: * Iteration ends at the item located at the * specified index (inclusive). * If items not specified: * Iteration ends when index reaches the value * specified. */ @JSFFaceletAttribute(className="int") private final TagAttribute end; /** * Collection of items to iterate over. */ @JSFFaceletAttribute(className="javax.el.ValueExpression") private final TagAttribute items; /** * Iteration will only process every step items of * the collection, starting with the first one. */ @JSFFaceletAttribute(className="int") private final TagAttribute step; private final TagAttribute tranzient; /** * Name of the exported scoped variable for the * current item of the iteration. This scoped * variable has nested visibility. Its type depends * on the object of the underlying collection. */ @JSFFaceletAttribute(className="java.lang.String") private final TagAttribute var; /** * Name of the exported scoped variable for the * status of the iteration. */ @JSFFaceletAttribute(className="java.lang.String") private final TagAttribute varStatus; /** * @param config */ public ForEachHandler(TagConfig config) { super(config); this.items = this.getAttribute("items"); this.var = this.getAttribute("var"); this.begin = this.getAttribute("begin"); this.end = this.getAttribute("end"); this.step = this.getAttribute("step"); this.varStatus = this.getAttribute("varStatus"); this.tranzient = this.getAttribute("transient"); if (this.items == null && this.begin != null && this.end == null) { throw new TagAttributeException(this.tag, this.begin, "If the 'items' attribute is not specified, but the 'begin' attribute is, " + "then the 'end' attribute is required"); } } public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { int s = this.getBegin(ctx); int e = this.getEnd(ctx); int m = this.getStep(ctx); Integer sO = this.begin != null ? Integer.valueOf(s) : null; Integer eO = this.end != null ? Integer.valueOf(e) : null; Integer mO = this.step != null ? Integer.valueOf(m) : null; boolean t = this.getTransient(ctx); Object src = null; ValueExpression srcVE = null; if (this.items != null) { srcVE = this.items.getValueExpression(ctx, Object.class); src = srcVE.getValue(ctx); } else { byte[] b = new byte[e + 1]; for (int i = 0; i < b.length; i++) { b[i] = (byte) i; } src = b; } FaceletCompositionContext fcc = FaceletCompositionContext.getCurrentInstance(ctx); if (src != null) { fcc.startComponentUniqueIdSection(); AbstractFaceletContext actx = (AbstractFaceletContext) ctx; PageContext pctx = actx.getPageContext(); Iterator<?> itr = this.toIterator(src); if (itr != null) { int i = 0; // move to start while (i < s && itr.hasNext()) { itr.next(); i++; } String v = this.getVarName(ctx); String vs = this.getVarStatusName(ctx); ValueExpression ve = null; ValueExpression vO = this.capture(v, pctx); ValueExpression vsO = this.capture(vs, pctx); int mi = 0; Object value = null; try { boolean first = true; while (i <= e && itr.hasNext()) { value = itr.next(); // set the var if (v != null) { if (t || srcVE == null) { if (value == null) { pctx.getAttributes().put(v, null); } else { pctx.getAttributes().put(v, ctx.getExpressionFactory().createValueExpression( value, Object.class)); } } else { ve = this.getVarExpr(srcVE, src, value, i); pctx.getAttributes().put(v, ve); } } // set the varStatus if (vs != null) { IterationStatus itrS = new IterationStatus(first, !itr.hasNext(), i, sO, eO, mO, value); if (t || srcVE == null) { if (srcVE == null) { pctx.getAttributes().put(vs, null); } else { pctx.getAttributes().put(vs, ctx.getExpressionFactory().createValueExpression( itrS, Object.class)); } } else { ve = new IterationStatusExpression(itrS); pctx.getAttributes().put(vs, ve); } } // execute body this.nextHandler.apply(ctx, parent); // increment steps mi = 1; while (mi < m && itr.hasNext()) { itr.next(); mi++; i++; } i++; first = false; } } finally { //Remove them from PageContext if (v != null) { pctx.getAttributes().put(v, vO); } else { pctx.getAttributes().remove(v); } if (vs != null) { pctx.getAttributes().put(vs, vsO); } else { pctx.getAttributes().remove(vs); } } } fcc.endComponentUniqueIdSection(); } if (fcc.isUsingPSSOnThisView() && fcc.isRefreshTransientBuildOnPSS() && !fcc.isRefreshingTransientBuild()) { //Mark the parent component to be saved and restored fully. ComponentSupport.markComponentToRestoreFully(ctx.getFacesContext(), parent); } } private final ValueExpression capture(String name, PageContext pctx) { if (name != null) { return pctx.getAttributes().put(name, null); } return null; } private final int getBegin(FaceletContext ctx) { if (this.begin != null) { return this.begin.getInt(ctx); } return 0; } private final int getEnd(FaceletContext ctx) { if (this.end != null) { return this.end.getInt(ctx); } return Integer.MAX_VALUE - 1; // hotspot bug in the JVM } private final int getStep(FaceletContext ctx) { if (this.step != null) { return this.step.getInt(ctx); } return 1; } private final boolean getTransient(FaceletContext ctx) { if (this.tranzient != null) { return this.tranzient.getBoolean(ctx); } return false; } private final ValueExpression getVarExpr(ValueExpression ve, Object src, Object value, int i) { if (src instanceof List || src.getClass().isArray()) { return new IndexedValueExpression(ve, i); } else if (src instanceof Map && value instanceof Map.Entry) { return new MappedValueExpression(ve, (Map.Entry) value); } else if (src instanceof Collection) { return new IteratedValueExpression(ve, value); } throw new IllegalStateException("Cannot create VE for: " + src); } private final String getVarName(FaceletContext ctx) { if (this.var != null) { return this.var.getValue(ctx); } return null; } private final String getVarStatusName(FaceletContext ctx) { if (this.varStatus != null) { return this.varStatus.getValue(ctx); } return null; } private final Iterator<?> toIterator(Object src) { if (src == null) { return null; } else if (src instanceof Collection) { return ((Collection<?>) src).iterator(); } else if (src instanceof Map) { return ((Map<?, ?>) src).entrySet().iterator(); } else if (src.getClass().isArray()) { return new ArrayIterator(src); } else { throw new TagAttributeException(this.tag, this.items, "Must evaluate to a Collection, Map, Array, or null."); } } }
realityforge/replicant-example
vendor/tools/buildr_plus/lib/buildr_plus/features/db.rb
<reponame>realityforge/replicant-example # # 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. # BuildrPlus::FeatureManager.feature(:db) do |f| f.enhance(:Config) do # Return true if the pg gem is present. # Implies this project can run using postgres database def pg_defined? unless @pg_loaded @pg_loaded = true begin require 'pg' rescue LoadError # Ignored end end Object.const_defined?('PG') end # Return true if the tiny_tds gem is present. # Implies this project can run using sql server database def tiny_tds_defined? unless @tiny_tds_loaded @tiny_tds_loaded = true begin require 'tiny_tds' rescue LoadError # Ignored end end Object.const_defined?('TinyTds') end # Return true if the project can be either postgres or sql server def is_multi_database_project? tiny_tds_defined? && pg_defined? end def valid_db_types [:pgsql, :mssql] end def db_type=(db_type) raise "db_type '#{db_type}' is invalid. Expected values #{self.valid_db_types.inspect}" unless self.valid_db_types.include?(db_type) @db_type = db_type end def db_type return @db_type unless @db_type.nil? return :mssql if tiny_tds_defined? && !pg_defined? return :pgsql if !tiny_tds_defined? && pg_defined? return :mssql if ENV['DB_TYPE'].nil? || ENV['DB_TYPE'] == 'mssql' return :pgsql if ENV['DB_TYPE'] == 'pg' raise 'Unable to determine database type' end def mssql?(dbt_type = self.db_type) dbt_type == :mssql end def pgsql?(dbt_type = self.db_type) dbt_type == :pgsql end def artifact_suffix(dbt_type = self.db_type) (is_multi_database_project? && pgsql?(dbt_type)) ? '.pg' : '' end end f.enhance(:ProjectExtension) do after_define do |project| if project.ipr? project.ipr.mssql_dialect_mapping if BuildrPlus::Db.mssql? project.ipr.postgres_dialect_mapping if BuildrPlus::Db.pgsql? end end end end
wandsX/LeetCodeExperience
Offer/Offer-67-ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof.cpp
//写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。 // // // // 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 // // 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连 //续的数字字符组合起来,形成整数。 // // 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 // // 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 // // 在任何情况下,若函数不能进行有效的转换时,请返回 0。 // // 说明: // // 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231, 231 − 1]。如果数值超过这个范围,请返回 INT_MAX (231 // − 1) 或 INT_MIN (−231) 。 // // 示例 1: // // 输入: "42" //输出: 42 // // // 示例 2: // // 输入: " -42" //输出: -42 //解释: 第一个非空白字符为 '-', 它是一个负号。 //  我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 // // // 示例 3: // // 输入: "4193 with words" //输出: 4193 //解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。 // // // 示例 4: // // 输入: "words and 987" //输出: 0 //解释: 第一个非空字符是 'w', 但它不是数字或正、负号。 // 因此无法执行有效的转换。 // // 示例 5: // // 输入: "-91283472332" //输出: -2147483648 //解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 //  因此返回 INT_MIN (−231) 。 // // // // // 注意:本题与主站 8 题相同:https://leetcode-cn.com/problems/string-to-integer-atoi/ // Related Topics 数学 字符串 // 👍 75 👎 0 #include <iostream> #include <vector> #include <algorithm> using namespace std; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public: int strToInt(string str) { if (str.empty()) { return 0; } // remove left space str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](unsigned char ch) { return !std::isspace(ch); })); int i = 0; int sign = 1; int res = 0; int boundry = INT_MAX / 10; if (str[0] == '-') { sign = -1; } if (str[0] == '-' || str[0] == '+') { ++i; } for (int j = i; j < str.length(); j++) { if (str[j] < '0' || str[j] > '9') { break; } if (res > boundry || (res == boundry && str[j] > '7')) { return sign == 1 ? INT_MAX : INT_MIN; } res = res * 10 + (str[j] - '0'); } return sign * res; } }; //leetcode submit region end(Prohibit modification and deletion) int main() { Solution s; vector<int> data{7, 1, 5, 3, 6, 4}; cout << s.strToInt("2147483646"); }
lechium/iOS1351Headers
System/Library/PrivateFrameworks/HealthUI.framework/_HKStretchableImage.h
<filename>System/Library/PrivateFrameworks/HealthUI.framework/_HKStretchableImage.h /* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:22:26 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/HealthUI.framework/HealthUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <HealthUI/HealthUI-Structs.h> @class UIImage; @interface _HKStretchableImage : NSObject { UIImage* _topImage; UIImage* _centerImage; UIImage* _bottomImage; UIImage* _singlePointImage; } @property (nonatomic,retain) UIImage * topImage; //@synthesize topImage=_topImage - In the implementation block @property (nonatomic,retain) UIImage * centerImage; //@synthesize centerImage=_centerImage - In the implementation block @property (nonatomic,retain) UIImage * bottomImage; //@synthesize bottomImage=_bottomImage - In the implementation block @property (nonatomic,retain) UIImage * singlePointImage; //@synthesize singlePointImage=_singlePointImage - In the implementation block -(void)setCenterImage:(UIImage *)arg1 ; -(UIImage *)centerImage; -(double)_desiredWidth; -(void)_renderSingleImageInContext:(CGContextRef)arg1 point:(CGPoint)arg2 contextBounds:(CGRect)arg3 alpha:(double)arg4 ; -(void)_renderStretchedInContext:(CGContextRef)arg1 frame:(CGRect)arg2 contextBounds:(CGRect)arg3 alpha:(double)arg4 ; -(void)renderInContext:(CGContextRef)arg1 topCenter:(CGPoint)arg2 bottomCenter:(CGPoint)arg3 contextBounds:(CGRect)arg4 alpha:(double)arg5 ; -(UIImage *)topImage; -(void)setTopImage:(UIImage *)arg1 ; -(UIImage *)bottomImage; -(void)setBottomImage:(UIImage *)arg1 ; -(UIImage *)singlePointImage; -(void)setSinglePointImage:(UIImage *)arg1 ; @end
AP-Atul/Torpido
torpido/wavelet/wavelets/coif4.py
<reponame>AP-Atul/Torpido """ Coiflets 4 wavelet """ class Coiflets4: """ Properties ---------- near symmetric, orthogonal, biorthogonal All values are from http://wavelets.pybytes.com/wavelet/coif4/ """ __name__ = "Coiflets Wavelet 4" __motherWaveletLength__ = 24 # length of the mother wavelet __transformWaveletLength__ = 2 # minimum wavelength of input signal # decomposition filter # low-pass decompositionLowFilter = [ -1.7849850030882614e-06, -3.2596802368833675e-06, 3.1229875865345646e-05, 6.233903446100713e-05, -0.00025997455248771324, -0.0005890207562443383, 0.0012665619292989445, 0.003751436157278457, -0.00565828668661072, -0.015211731527946259, 0.025082261844864097, 0.03933442712333749, -0.09622044203398798, -0.06662747426342504, 0.4343860564914685, 0.782238930920499, 0.41530840703043026, -0.05607731331675481, -0.08126669968087875, 0.026682300156053072, 0.016068943964776348, -0.0073461663276420935, -0.0016294920126017326, 0.0008923136685823146, ] # high-pass decompositionHighFilter = [ -0.0008923136685823146, -0.0016294920126017326, 0.0073461663276420935, 0.016068943964776348, -0.026682300156053072, -0.08126669968087875, 0.05607731331675481, 0.41530840703043026, -0.782238930920499, 0.4343860564914685, 0.06662747426342504, -0.09622044203398798, -0.03933442712333749, 0.025082261844864097, 0.015211731527946259, -0.00565828668661072, -0.003751436157278457, 0.0012665619292989445, 0.0005890207562443383, -0.00025997455248771324, -6.233903446100713e-05, 3.1229875865345646e-05, 3.2596802368833675e-06, -1.7849850030882614e-06, ] # reconstruction filters # low pass reconstructionLowFilter = [ 0.0008923136685823146, -0.0016294920126017326, -0.0073461663276420935, 0.016068943964776348, 0.026682300156053072, -0.08126669968087875, -0.05607731331675481, 0.41530840703043026, 0.782238930920499, 0.4343860564914685, -0.06662747426342504, -0.09622044203398798, 0.03933442712333749, 0.025082261844864097, -0.015211731527946259, -0.00565828668661072, 0.003751436157278457, 0.0012665619292989445, -0.0005890207562443383, -0.00025997455248771324, 6.233903446100713e-05, 3.1229875865345646e-05, -3.2596802368833675e-06, -1.7849850030882614e-06, ] # high-pass reconstructionHighFilter = [ -1.7849850030882614e-06, 3.2596802368833675e-06, 3.1229875865345646e-05, -6.233903446100713e-05, -0.00025997455248771324, 0.0005890207562443383, 0.0012665619292989445, -0.003751436157278457, -0.00565828668661072, 0.015211731527946259, 0.025082261844864097, -0.03933442712333749, -0.09622044203398798, 0.06662747426342504, 0.4343860564914685, -0.782238930920499, 0.41530840703043026, 0.05607731331675481, -0.08126669968087875, -0.026682300156053072, 0.016068943964776348, 0.0073461663276420935, -0.0016294920126017326, -0.0008923136685823146, ]
snaphy/generator-snaphy
generators/androidSdk/templates/snaphyandroidsdk/src/main/java/com/androidsdk/snaphy/snaphyandroidsdk/models/CustomContainer.java
package com.androidsdk.snaphy.snaphyandroidsdk.models; /** * Created by snaphy on 14/9/16. */ import com.strongloop.android.loopback.callbacks.ObjectCallback; import com.androidsdk.snaphy.snaphyandroidsdk.repository.CustomFileRepository; import com.strongloop.android.loopback.Container; import com.strongloop.android.loopback.RestAdapter; /** * Created by Ravi-Gupta on 2/16/2016. */ public class CustomContainer extends Container { /** * Upload a new file * @param file Content of the file. * @param callback The callback to be executed when finished. */ public void UploadAmazon(java.io.File file, ObjectCallback<ImageModel> callback) { getFileRepository().uploadAmazon(file, callback); } public CustomFileRepository getFileRepository() { RestAdapter adapter = ((RestAdapter)getRepository().getAdapter()); CustomFileRepository repo = adapter.createRepository(CustomFileRepository.class); repo.setContainer(this); return repo; } }
1847123212/YoC-open
solutions/ble_bas_demo/app/src/app_main.c
<filename>solutions/ble_bas_demo/app/src/app_main.c /* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <string.h> #include <aos/aos.h> #include "aos/ble.h" #include "app_main.h" #include "app_init.h" #include "pin_name.h" #include <yoc/bas.h> #define TAG "DEMO" #define DEVICE_NAME "YoC BAS" #define DEVICE_ADDR {0xCC,0x3B,0xE3,0x88,0xBA,0xC0} uint8_t g_battery_level = 0; static int16_t g_conn_handle = -1; static bas_t g_bas; static bas_handle_t g_bas_handle = NULL; static int adv_onging = 0; static void conn_change(ble_event_en event, void *event_data) { evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data; adv_onging = 0; if (e->connected == CONNECTED) { g_conn_handle = e->conn_handle; LOGI(TAG, "Connected"); } else { g_conn_handle = -1; LOGI(TAG, "Disconnected"); } } static void conn_param_update(ble_event_en event, void *event_data) { evt_data_gap_conn_param_update_t *e = event_data; LOGI(TAG, "LE conn param updated: int 0x%04x lat %d to %d\n", e->interval, e->latency, e->timeout); } static void mtu_exchange(ble_event_en event, void *event_data) { evt_data_gatt_mtu_exchange_t *e = (evt_data_gatt_mtu_exchange_t *)event_data; if (e->err == 0) { LOGI(TAG, "mtu exchange, MTU %d", ble_stack_gatt_mtu_get(e->conn_handle)); } else { LOGE(TAG, "mtu exchange fail, %d", e->err); } } static int event_callback(ble_event_en event, void *event_data) { LOGD(TAG, "event %x", event); switch (event) { case EVENT_GAP_CONN_CHANGE: conn_change(event, event_data); break; case EVENT_GAP_CONN_PARAM_UPDATE: conn_param_update(event, event_data); break; case EVENT_GATT_MTU_EXCHANGE: mtu_exchange(event, event_data); break; default: LOGD(TAG, "Unhandle event %x", event); break; } return 0; } static int start_adv() { int ret; ad_data_t ad[2] = {0}; uint8_t flag = AD_FLAG_GENERAL | AD_FLAG_NO_BREDR; ad[0].type = AD_DATA_TYPE_FLAGS; ad[0].data = (uint8_t *)&flag; ad[0].len = 1; uint8_t uuid16_list[] = {0x0f, 0x18}; /* UUID_BAS */ ad[1].type = AD_DATA_TYPE_UUID16_ALL; ad[1].data = (uint8_t *)uuid16_list; ad[1].len = sizeof(uuid16_list); adv_param_t param = { ADV_IND, ad, NULL, BLE_ARRAY_NUM(ad), 0, ADV_FAST_INT_MIN_1, ADV_FAST_INT_MAX_1, }; ret = ble_stack_adv_start(&param); if (ret) { LOGE(TAG, "adv start fail %d!", ret); } else { LOGI(TAG, "adv start!"); adv_onging = 1; } return ret; } static ble_event_cb_t ble_cb = { .callback = event_callback, }; int app_main() { int batter_level = 0; int ret = 0; dev_addr_t addr = {DEV_ADDR_LE_RANDOM, DEVICE_ADDR}; init_param_t init = { .dev_name = DEVICE_NAME, .dev_addr = &addr, .conn_num_max = 1, }; adv_onging = 0; g_battery_level = 0; g_conn_handle = -1; g_bas_handle = NULL; ret = ble_stack_init(&init); if (ret) { LOGE(TAG, "ble stack init faild %d", ret); return -1; } ret = ble_stack_event_register(&ble_cb); if (ret) { LOGE(TAG, "register stack event faild"); return -1; } g_bas_handle = bas_init(&g_bas); if (g_bas_handle == NULL) { LOGE(TAG, "BAS init FAIL!!!!"); return -1; } while (1) { if (!adv_onging && g_conn_handle < 0) { start_adv(); } bas_level_update(g_bas_handle, batter_level++); if (batter_level > 100) { batter_level = 0; } aos_msleep(1000); } return 0; } int main() { board_yoc_init(); LOGI(TAG, "Bluetooth BAS"); app_main(); return 0; }
flash8627/icustom-boot
security/security.core/src/main/java/com/gwtjs/icustom/springsecurity/service/impl/RoleRestService.java
<filename>security/security.core/src/main/java/com/gwtjs/icustom/springsecurity/service/impl/RoleRestService.java<gh_stars>0 package com.gwtjs.icustom.springsecurity.service.impl; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import com.gwtjs.icustom.entity.PageVO; import com.gwtjs.icustom.entity.PagedResult; import com.gwtjs.icustom.springsecurity.dao.ISysRoleDao; import com.gwtjs.icustom.springsecurity.entity.SysRoleVO; import com.gwtjs.icustom.springsecurity.service.IRoleRestService; @Api("/role") public class RoleRestService implements IRoleRestService { @Autowired private ISysRoleDao sysRoleDao; @Override public int insert(SysRoleVO role) { // TODO Auto-generated method stub return 0;//sysRoleDao.insert(role); } @Override public int delete(SysRoleVO role) { // TODO Auto-generated method stub return 0;//sysRoleDao.delete(role); } @Override public int update(SysRoleVO role) { // TODO Auto-generated method stub return 0;//sysRoleDao.update(role); } @Override public PagedResult<SysRoleVO> findRolePage(SysRoleVO role,PageVO page) { System.out.println("role:\n"+role); System.out.println("page:\n"+page); // TODO Auto-generated method stub return sysRoleDao.findRolePage(role, page); } }
EchoThreeLLC/echothree
src/java/com/echothree/model/control/carrier/server/transfer/CarrierServiceTransferCache.java
// -------------------------------------------------------------------------------- // Copyright 2002-2022 Echo Three, LLC // // 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.echothree.model.control.carrier.server.transfer; import com.echothree.model.control.carrier.common.transfer.CarrierServiceTransfer; import com.echothree.model.control.carrier.common.transfer.CarrierTransfer; import com.echothree.model.control.carrier.server.control.CarrierControl; import com.echothree.model.control.selector.common.transfer.SelectorTransfer; import com.echothree.model.control.selector.server.control.SelectorControl; import com.echothree.model.data.carrier.server.entity.CarrierService; import com.echothree.model.data.carrier.server.entity.CarrierServiceDetail; import com.echothree.model.data.selector.server.entity.Selector; import com.echothree.model.data.user.server.entity.UserVisit; import com.echothree.util.server.persistence.Session; public class CarrierServiceTransferCache extends BaseCarrierTransferCache<CarrierService, CarrierServiceTransfer> { SelectorControl selectorControl = Session.getModelController(SelectorControl.class); /** Creates a new instance of CarrierServiceTransferCache */ public CarrierServiceTransferCache(UserVisit userVisit, CarrierControl carrierControl) { super(userVisit, carrierControl); setIncludeEntityInstance(true); } public CarrierServiceTransfer getCarrierServiceTransfer(CarrierService carrierService) { CarrierServiceTransfer carrierServiceTransfer = get(carrierService); if(carrierServiceTransfer == null) { CarrierServiceDetail carrierServiceDetail = carrierService.getLastDetail(); CarrierTransfer carrier = carrierControl.getCarrierTransfer(userVisit, carrierServiceDetail.getCarrierParty()); String carrierServiceName = carrierServiceDetail.getCarrierServiceName(); Selector geoCodeSelector = carrierServiceDetail.getGeoCodeSelector(); SelectorTransfer geoCodeSelectorTransfer = geoCodeSelector == null? null: selectorControl.getSelectorTransfer(userVisit, geoCodeSelector); Selector itemSelector = carrierServiceDetail.getItemSelector(); SelectorTransfer itemSelectorTransfer = itemSelector == null? null: selectorControl.getSelectorTransfer(userVisit, itemSelector); Boolean isDefault = carrierServiceDetail.getIsDefault(); Integer sortOrder = carrierServiceDetail.getSortOrder(); String description = carrierControl.getBestCarrierServiceDescription(carrierService, getLanguage()); carrierServiceTransfer = new CarrierServiceTransfer(carrier, carrierServiceName, geoCodeSelectorTransfer, itemSelectorTransfer, isDefault, sortOrder, description); put(carrierService, carrierServiceTransfer); } return carrierServiceTransfer; } }
smalluniversezzq/core
src/services/admin/core/assist/index.js
import { request, METHOD } from '@/utils/request' // 帮助中心帮助文章相关API const apiList = { AssistIndex: '/admin/core/assist/index', // 文章列表 AssistAdd: '/admin/core/assist/add', // 添加 AssistEdit: '/admin/core/assist/edit', // 编辑 AssistDetail: '/admin/core/assist/detail', // 详情 AssistDisplay: '/admin/core/assist/display', // 显示/隐藏 AssistDel: '/admin/core/assist/del', // 删除 } /** * 帮助文章添加 * parameter: { * @param [String] title 文章标题 * @param [String] content 文章内容 * @param [String] alias 文章别名url使用 * @param [String] keywords 关键字 * @param [Number] sort 排序 * @param [Number] status 状态0不显示;1显示 * @param [Number] c_id 分类id * } */ export function assistAdd(parameter) { return request({ url: apiList.AssistAdd, method: METHOD.POST, data: parameter }) } /** * 帮助文章列表 * parameter: { * @param [Number] page_size 每页数量 * @param [Number] page 页数 * @param [Number] c_id 分类id * @param [String] keyword 搜索关键测 * @param [String] status 状态 * } */ export function getAssistIndex(parameter) { return request({ url: apiList.AssistIndex, method: METHOD.GET, data: parameter }) } /** * 帮助文章详情 * parameter: { * @param [String] id 文章id * } */ export function getAssistDetail(parameter) { return request({ url: apiList.AssistDetail, method: METHOD.GET, data: parameter }) } /** * 文章显示/隐藏 * parameter: { * @param [Array] ids[] id数组 * @param [Number] status 0隐藏;1显示 * } */ export function assistDisplay(parameter) { return request({ url: apiList.AssistDisplay, method: METHOD.POST, data: parameter }) } /** * 文章删除 * parameter: { * @param [Array] ids[] id数组 * } */ export function assistDel(parameter) { return request({ url: apiList.AssistDel, method: METHOD.POST, data: parameter }) } /** * 文章编辑 * parameter: { * @param [String] id 文章id * @param [String] title 文章标题 * @param [String] content 文章内容 * @param [String] alias 文章别名url使用 * @param [String] keywords 关键字 * @param [Number] sort 排序 * @param [Number] status 状态0不显示;1显示 * @param [Number] c_id 分类id * } */ export function assistEdit(parameter) { return request({ url: apiList.AssistEdit, method: METHOD.POST, data: parameter }) }
stephwuh/digitalCloset
client/src/features/outfits/outfits/GetOutfitImage.js
<filename>client/src/features/outfits/outfits/GetOutfitImage.js import React from 'react'; import { useHistory } from 'react-router-dom'; import { Image } from 'cloudinary-react'; import { useDispatch } from 'react-redux'; import { bindActionCreators } from 'redux'; import { actionCreators } from '../../.././redux/index.js'; import '.././outfits.css'; const GetOutfitImage = props => { const history = useHistory(); const dispatch = useDispatch(); const { outfitReset} = bindActionCreators(actionCreators, dispatch); return ( <div className="outfit-container" onClick={() => { history.push({ pathname: '/outfit-details', state: { image: props.image, category: props.category }, }); outfitReset() }} > {props.image.map((image, index) => { return ( <Image className="outfit-image" key={index} cloudName="drfwodrev" publicId={image.image} width="50" crop="scale" /> ); })} </div> ); }; export default GetOutfitImage;
lebarsfa/vpython-wx
src/python/wrap_rgba.cpp
// Copyright (c) 2003, 2004 by <NAME> and others. // See the file license.txt for complete license terms. // See the file authors.txt for a complete list of contributors. #include "util/rgba.hpp" #include <boost/python/to_python_converter.hpp> #include <boost/python/extract.hpp> #include <boost/python/tuple.hpp> #include <boost/python/proxy.hpp> #include <boost/python/class.hpp> // Python 2/3 compatibility #ifndef PyInt_Check #define PyInt_Check PyLong_Check #endif namespace cvisual { namespace py = boost::python; struct rgb_from_seq { rgb_from_seq() { py::converter::registry::push_back( &convertible, &construct, py::type_id<rgb>()); } static void* convertible( PyObject* obj) { using py::handle; using py::allow_null; handle<> obj_iter( allow_null( PyObject_GetIter(obj))); if (!obj_iter.get()) { PyErr_Clear(); return 0; } int obj_size = PyObject_Length(obj); if (obj_size < 0) { PyErr_Clear(); return 0; } if (obj_size != 3) return 0; return obj; } static void construct( PyObject* _obj, py::converter::rvalue_from_python_stage1_data* data) { py::object obj = py::object(py::handle<>(py::borrowed(_obj))); void* storage = ( (py::converter::rvalue_from_python_storage<rgb>*) data)->storage.bytes; new (storage) rgb( py::extract<float>(obj[0]), py::extract<float>(obj[1]), py::extract<float>(obj[2])); data->convertible = storage; } }; struct rgba_from_seq { rgba_from_seq() { py::converter::registry::push_back( &convertible, &construct, py::type_id<rgba>()); } static void* convertible( PyObject* obj) { using py::handle; using py::allow_null; if (PyInt_Check(obj) || PyFloat_Check(obj)) return obj; handle<> obj_iter( allow_null( PyObject_GetIter(obj))); if (!obj_iter.get()) { PyErr_Clear(); return 0; } int obj_size = PyObject_Length(obj); if (obj_size < 0) { PyErr_Clear(); return 0; } if (obj_size != 3 && obj_size != 4) return 0; return obj; } static void construct( PyObject* _obj, py::converter::rvalue_from_python_stage1_data* data) { py::object obj = py::object(py::handle<>(py::borrowed(_obj))); void* storage = ( (py::converter::rvalue_from_python_storage<rgba>*) data)->storage.bytes; int obj_size = PyObject_Length(_obj); if (obj_size == 3) new (storage) rgba( py::extract<float>(obj[0]), py::extract<float>(obj[1]), py::extract<float>(obj[2])); else new (storage) rgba( py::extract<float>(obj[0]), py::extract<float>(obj[1]), py::extract<float>(obj[2]), py::extract<float>(obj[3])); data->convertible = storage; } }; struct rgb_to_tuple { static PyObject* convert( const rgb& color) { py::tuple ret = py::make_tuple( color.red, color.green, color.blue); Py_INCREF(ret.ptr()); return ret.ptr(); } }; struct rgba_to_tuple { static PyObject* convert( const rgba& color) { py::tuple ret = py::make_tuple( color.red, color.green, color.blue, color.opacity); Py_INCREF(ret.ptr()); return ret.ptr(); } }; void wrap_rgba() { rgb_from_seq(); rgba_from_seq(); py::to_python_converter< rgb, rgb_to_tuple>(); py::to_python_converter< rgba, rgba_to_tuple>(); } } // !namespace cvisual
xformation/xformation-compliance-aws-collector
src/main/java/com/synectiks/aws/entities/rds/InternetGateway.java
<filename>src/main/java/com/synectiks/aws/entities/rds/InternetGateway.java package com.synectiks.aws.entities.rds; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class InternetGateway { private String externalID; private List<VpcAttachment> vpcAttachments; private String name; @JsonProperty("externalId") public String getExternalID() { return externalID; } @JsonProperty("externalId") public void setExternalID(String value) { this.externalID = value; } @JsonProperty("vpcAttachments") public List<VpcAttachment> getVpcAttachments() { return vpcAttachments; } @JsonProperty("vpcAttachments") public void setVpcAttachments(List<VpcAttachment> value) { this.vpcAttachments = value; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String value) { this.name = value; } }
ruuvi/ruuvi.dongle_esp.c
main/http.c
/** * @file http.c * @author <NAME> * @date 2019-11-27 * @copyright Ruuvi Innovations Ltd, license BSD-3-Clause. */ #include "http.h" #include <string.h> #include <time.h> #include <errno.h> #include <esp_task_wdt.h> #include "cJSON.h" #include "cjson_wrap.h" #include "esp_http_client.h" #include "ruuvi_gateway.h" #include "http_json.h" #include "leds.h" #include "os_str.h" #include "os_malloc.h" #include "hmac_sha256.h" #include "adv_post.h" #include "fw_update.h" #include "gw_mac.h" #include "str_buf.h" #include "gw_status.h" #define LOG_LOCAL_LEVEL LOG_LEVEL_INFO #include "log.h" #define BASE_10 (10U) typedef int esp_http_client_len_t; typedef int esp_http_client_http_status_code_t; typedef struct http_download_cb_info_t { http_download_cb_on_data_t cb_on_data; void *const p_user_data; esp_http_client_handle_t http_handle; uint32_t content_length; uint32_t offset; bool flag_feed_task_watchdog; } http_download_cb_info_t; typedef struct http_client_config_t { esp_http_client_config_t esp_http_client_config; ruuvi_gw_cfg_http_url_t http_url; ruuvi_gw_cfg_http_user_t http_user; ruuvi_gw_cfg_http_password_t http_pass; } http_client_config_t; typedef struct http_async_info_t { http_client_config_t http_client_config; esp_http_client_handle_t p_http_client_handle; cjson_wrap_str_t cjson_str; bool flag_sending_advs; } http_async_info_t; static const char TAG[] = "http"; static http_async_info_t g_http_async_info; static esp_err_t http_post_event_handler(esp_http_client_event_t *p_evt) { switch (p_evt->event_id) { case HTTP_EVENT_ERROR: LOG_ERR("HTTP_EVENT_ERROR"); break; case HTTP_EVENT_ON_CONNECTED: LOG_DBG("HTTP_EVENT_ON_CONNECTED"); break; case HTTP_EVENT_HEADER_SENT: LOG_DBG("HTTP_EVENT_HEADER_SENT"); break; case HTTP_EVENT_ON_HEADER: LOG_DBG("HTTP_EVENT_ON_HEADER, key=%s, value=%s", p_evt->header_key, p_evt->header_value); if (0 == strcasecmp("Ruuvi-HMAC-KEY", p_evt->header_key)) { if (!hmac_sha256_set_key_str(p_evt->header_value)) { LOG_ERR("Failed to update Ruuvi-HMAC-KEY"); } } else if (0 == strcasecmp("X-Ruuvi-Gateway-Rate", p_evt->header_key)) { uint32_t period_seconds = os_str_to_uint32_cptr(p_evt->header_value, NULL, BASE_10); if ((0 == period_seconds) || (period_seconds > (TIME_UNITS_MINUTES_PER_HOUR * TIME_UNITS_SECONDS_PER_MINUTE))) { LOG_WARN("X-Ruuvi-Gateway-Rate: Got incorrect value: %s", p_evt->header_value); period_seconds = ADV_POST_DEFAULT_INTERVAL_SECONDS; } adv_post_set_period(period_seconds * TIME_UNITS_MS_PER_SECOND); } else { // MISRA C:2012, 15.7 - All if...else if constructs shall be terminated with an else statement } break; case HTTP_EVENT_ON_DATA: LOG_ERR("HTTP_EVENT_ON_DATA, len=%d: %.*s", p_evt->data_len, p_evt->data_len, (char *)p_evt->data); break; case HTTP_EVENT_ON_FINISH: LOG_DBG("HTTP_EVENT_ON_FINISH"); break; case HTTP_EVENT_DISCONNECTED: LOG_DBG("HTTP_EVENT_DISCONNECTED"); break; default: break; } return ESP_OK; } static void http_init_client_config( http_client_config_t *const p_http_client_config, const ruuvi_gw_cfg_http_url_t *const p_url, const ruuvi_gw_cfg_http_user_t *const p_user, const ruuvi_gw_cfg_http_password_t *const p_password) { p_http_client_config->esp_http_client_config = (esp_http_client_config_t) { .url = &p_http_client_config->http_url.buf[0], .host = NULL, .port = 0, .username = &p_http_client_config->http_user.buf[0], .password = &p_http_client_config->http_pass.buf[0], .auth_type = ('\0' != p_user->buf[0]) ? HTTP_AUTH_TYPE_BASIC : HTTP_AUTH_TYPE_NONE, .path = NULL, .query = NULL, .cert_pem = NULL, .client_cert_pem = NULL, .client_key_pem = NULL, .method = HTTP_METHOD_POST, .timeout_ms = 0, .disable_auto_redirect = false, .max_redirection_count = 0, .event_handler = &http_post_event_handler, .transport_type = HTTP_TRANSPORT_UNKNOWN, .buffer_size = 0, .buffer_size_tx = 0, .user_data = NULL, .is_async = true, .use_global_ca_store = false, .skip_cert_common_name_check = false, }; p_http_client_config->http_url = *p_url; p_http_client_config->http_user = *p_user; p_http_client_config->http_pass = *p_password; } static void http_init_client_config_for_http_record(http_client_config_t *const p_http_client_config) { const gw_cfg_t *p_gw_cfg = gw_cfg_lock_ro(); http_init_client_config( p_http_client_config, &p_gw_cfg->ruuvi_cfg.http.http_url, &p_gw_cfg->ruuvi_cfg.http.http_user, &p_gw_cfg->ruuvi_cfg.http.http_pass); gw_cfg_unlock_ro(&p_gw_cfg); } static void http_init_client_config_for_http_status(http_client_config_t *const p_http_client_config) { const gw_cfg_t *p_gw_cfg = gw_cfg_lock_ro(); http_init_client_config( p_http_client_config, &p_gw_cfg->ruuvi_cfg.http_stat.http_stat_url, &p_gw_cfg->ruuvi_cfg.http_stat.http_stat_user, &p_gw_cfg->ruuvi_cfg.http_stat.http_stat_pass); gw_cfg_unlock_ro(&p_gw_cfg); } static bool http_send_async(http_async_info_t *const p_http_async_info) { const esp_http_client_config_t *const p_http_config = &p_http_async_info->http_client_config.esp_http_client_config; const char *const p_msg = p_http_async_info->cjson_str.p_str; LOG_INFO("HTTP POST to URL=%s, DATA:\n%s", p_http_config->url, p_msg); esp_http_client_set_post_field( p_http_async_info->p_http_client_handle, p_msg, (esp_http_client_len_t)strlen(p_msg)); esp_http_client_set_header(p_http_async_info->p_http_client_handle, "Content-Type", "application/json"); const hmac_sha256_str_t hmac_sha256_str = hmac_sha256_calc_str(p_msg); if (hmac_sha256_is_str_valid(&hmac_sha256_str)) { esp_http_client_set_header(p_http_async_info->p_http_client_handle, "Ruuvi-HMAC-SHA256", hmac_sha256_str.buf); } LOG_DBG("esp_http_client_perform"); const esp_err_t err = esp_http_client_perform(p_http_async_info->p_http_client_handle); if (ESP_ERR_HTTP_EAGAIN != err) { LOG_ERR_ESP(err, "HTTP POST to URL=%s: request failed", p_http_config->url); esp_http_client_cleanup(p_http_async_info->p_http_client_handle); p_http_async_info->p_http_client_handle = NULL; return false; } return true; } bool http_send_advs(const adv_report_table_t *const p_reports, const uint32_t nonce, const bool flag_use_timestamps) { const ruuvi_gw_cfg_coordinates_t coordinates = gw_cfg_get_coordinates(); http_async_info_t * p_http_async_info = &g_http_async_info; p_http_async_info->flag_sending_advs = true; p_http_async_info->cjson_str = cjson_wrap_str_null(); if (!http_json_create_records_str( p_reports, flag_use_timestamps, time(NULL), gw_cfg_get_nrf52_mac_addr(), coordinates.buf, true, nonce, &p_http_async_info->cjson_str)) { LOG_ERR("Not enough memory to generate json"); return false; } http_init_client_config_for_http_record(&p_http_async_info->http_client_config); p_http_async_info->p_http_client_handle = esp_http_client_init( &p_http_async_info->http_client_config.esp_http_client_config); if (NULL == p_http_async_info->p_http_client_handle) { LOG_ERR("HTTP POST to URL=%s: Can't init http client", p_http_async_info->http_client_config.http_url.buf); cjson_wrap_free_json_str(&p_http_async_info->cjson_str); return false; } if (!http_send_async(p_http_async_info)) { esp_http_client_cleanup(p_http_async_info->p_http_client_handle); p_http_async_info->p_http_client_handle = NULL; cjson_wrap_free_json_str(&p_http_async_info->cjson_str); return false; } return true; } bool http_send_statistics(const http_json_statistics_info_t *const p_stat_info, const adv_report_table_t *const p_reports) { http_async_info_t *p_http_async_info = &g_http_async_info; p_http_async_info->flag_sending_advs = false; p_http_async_info->cjson_str = cjson_wrap_str_null(); if (!http_json_create_status_str(p_stat_info, p_reports, &p_http_async_info->cjson_str)) { LOG_ERR("Not enough memory to generate status json"); return false; } http_init_client_config_for_http_status(&p_http_async_info->http_client_config); p_http_async_info->p_http_client_handle = esp_http_client_init( &p_http_async_info->http_client_config.esp_http_client_config); if (NULL == p_http_async_info->p_http_client_handle) { LOG_ERR("HTTP POST to URL=%s: Can't init http client", p_http_async_info->http_client_config.http_url.buf); cjson_wrap_free_json_str(&p_http_async_info->cjson_str); return false; } if (!http_send_async(p_http_async_info)) { esp_http_client_cleanup(p_http_async_info->p_http_client_handle); p_http_async_info->p_http_client_handle = NULL; cjson_wrap_free_json_str(&p_http_async_info->cjson_str); return false; } return true; } bool http_async_poll(void) { http_async_info_t *p_http_async_info = &g_http_async_info; LOG_DBG("esp_http_client_perform"); const esp_err_t err = esp_http_client_perform(p_http_async_info->p_http_client_handle); if (ESP_ERR_HTTP_EAGAIN == err) { LOG_DBG("esp_http_client_perform: ESP_ERR_HTTP_EAGAIN"); return false; } bool flag_success = false; if (ESP_OK == err) { const esp_http_client_http_status_code_t http_status = esp_http_client_get_status_code( p_http_async_info->p_http_client_handle); if (HTTP_RESP_CODE_200 == http_status) { LOG_INFO( "HTTP POST to URL=%s: STATUS=%d", p_http_async_info->http_client_config.esp_http_client_config.url, http_status); if (p_http_async_info->flag_sending_advs) { adv_post_last_successful_network_comm_timestamp_update(); } flag_success = true; } else { LOG_ERR( "HTTP POST to URL=%s: STATUS=%d", p_http_async_info->http_client_config.esp_http_client_config.url, http_status); } } else { LOG_ERR_ESP( err, "HTTP POST to URL=%s: failed", p_http_async_info->http_client_config.esp_http_client_config.url); } esp_http_client_cleanup(p_http_async_info->p_http_client_handle); p_http_async_info->p_http_client_handle = NULL; cjson_wrap_free_json_str(&p_http_async_info->cjson_str); p_http_async_info->cjson_str = cjson_wrap_str_null(); if (p_http_async_info->flag_sending_advs) { if (flag_success) { leds_indication_on_network_ok(); if (!fw_update_mark_app_valid_cancel_rollback()) { LOG_ERR("%s failed", "fw_update_mark_app_valid_cancel_rollback"); } } else { leds_indication_network_no_connection(); } } return true; } static void http_download_feed_task_watchdog_if_needed(const bool flag_feed_task_watchdog) { if (flag_feed_task_watchdog) { LOG_DBG("Feed watchdog"); const esp_err_t err = esp_task_wdt_reset(); if (ESP_OK != err) { LOG_ERR_ESP(err, "%s failed", "esp_task_wdt_reset"); } } } static esp_err_t http_download_event_handler(esp_http_client_event_t *p_evt) { http_download_cb_info_t *const p_cb_info = p_evt->user_data; switch (p_evt->event_id) { case HTTP_EVENT_ERROR: LOG_ERR("HTTP_EVENT_ERROR"); http_download_feed_task_watchdog_if_needed(p_cb_info->flag_feed_task_watchdog); break; case HTTP_EVENT_ON_CONNECTED: LOG_INFO("HTTP_EVENT_ON_CONNECTED"); http_download_feed_task_watchdog_if_needed(p_cb_info->flag_feed_task_watchdog); p_cb_info->offset = 0; break; case HTTP_EVENT_HEADER_SENT: LOG_INFO("HTTP_EVENT_HEADER_SENT"); http_download_feed_task_watchdog_if_needed(p_cb_info->flag_feed_task_watchdog); break; case HTTP_EVENT_ON_HEADER: LOG_INFO("HTTP_EVENT_ON_HEADER, key=%s, value=%s", p_evt->header_key, p_evt->header_value); http_download_feed_task_watchdog_if_needed(p_cb_info->flag_feed_task_watchdog); if (0 == strcasecmp(p_evt->header_key, "Content-Length")) { p_cb_info->offset = 0; p_cb_info->content_length = os_str_to_uint32_cptr(p_evt->header_value, NULL, BASE_10); } break; case HTTP_EVENT_ON_DATA: LOG_DBG("HTTP_EVENT_ON_DATA, len=%d", p_evt->data_len); LOG_DUMP_VERBOSE(p_evt->data, p_evt->data_len, "<--:"); http_download_feed_task_watchdog_if_needed(p_cb_info->flag_feed_task_watchdog); if (!p_cb_info->cb_on_data( p_evt->data, p_evt->data_len, p_cb_info->offset, p_cb_info->content_length, (http_resp_code_e)esp_http_client_get_status_code(p_cb_info->http_handle), p_cb_info->p_user_data)) { return ESP_FAIL; } p_cb_info->offset += p_evt->data_len; break; case HTTP_EVENT_ON_FINISH: LOG_INFO("HTTP_EVENT_ON_FINISH"); http_download_feed_task_watchdog_if_needed(p_cb_info->flag_feed_task_watchdog); break; case HTTP_EVENT_DISCONNECTED: LOG_INFO("HTTP_EVENT_DISCONNECTED"); http_download_feed_task_watchdog_if_needed(p_cb_info->flag_feed_task_watchdog); break; default: break; } return ESP_OK; } static bool http_download_by_handle(esp_http_client_handle_t http_handle, const bool flag_feed_task_watchdog) { esp_err_t err = esp_http_client_set_header(http_handle, "Accept", "text/html,application/octet-stream,*/*"); if (ESP_OK != err) { LOG_ERR("%s failed", "esp_http_client_set_header"); return false; } err = esp_http_client_set_header(http_handle, "User-Agent", "RuuviGateway"); if (ESP_OK != err) { LOG_ERR("%s failed", "esp_http_client_set_header"); return false; } LOG_DBG("esp_http_client_perform"); err = esp_http_client_perform(http_handle); if (ESP_OK == err) { LOG_DBG( "HTTP GET Status = %d, content_length = %d", esp_http_client_get_status_code(http_handle), esp_http_client_get_content_length(http_handle)); return true; } if (ESP_ERR_HTTP_EAGAIN != err) { LOG_ERR_ESP( err, "esp_http_client_perform failed, HTTP resp code %d (http_handle=%ld)", (printf_int_t)esp_http_client_get_status_code(http_handle), (printf_long_t)http_handle); return false; } while (true) { LOG_DBG("esp_http_client_perform"); err = esp_http_client_perform(http_handle); if (ESP_OK == err) { LOG_DBG( "HTTP GET Status = %d, content_length = %d", esp_http_client_get_status_code(http_handle), esp_http_client_get_content_length(http_handle)); return true; } if (ESP_ERR_HTTP_EAGAIN == err) { LOG_DBG("esp_http_client_perform: ESP_ERR_HTTP_EAGAIN"); vTaskDelay(pdMS_TO_TICKS(50)); http_download_feed_task_watchdog_if_needed(flag_feed_task_watchdog); } else { LOG_ERR_ESP(err, "%s failed", "esp_http_client_perform"); return false; } } } bool http_download_with_auth( const char *const p_url, const TimeUnitsSeconds_t timeout_seconds, const gw_cfg_remote_auth_type_e gw_cfg_http_auth_type, const ruuvi_gw_cfg_http_auth_t *const p_http_auth, const http_header_item_t *const p_extra_header_item, http_download_cb_on_data_t p_cb_on_data, void *const p_user_data, const bool flag_feed_task_watchdog) { http_download_cb_info_t cb_info = { .cb_on_data = p_cb_on_data, .p_user_data = p_user_data, .http_handle = NULL, .content_length = 0, .offset = 0, .flag_feed_task_watchdog = flag_feed_task_watchdog, }; if ((GW_CFG_REMOTE_AUTH_TYPE_NO != gw_cfg_http_auth_type) && (NULL == p_http_auth)) { LOG_ERR("Auth type is not NONE, but p_http_auth is NULL"); return false; } const esp_http_client_auth_type_t http_client_auth_type = (GW_CFG_REMOTE_AUTH_TYPE_BASIC == gw_cfg_http_auth_type) ? HTTP_AUTH_TYPE_BASIC : HTTP_AUTH_TYPE_NONE; const esp_http_client_config_t http_config = { .url = p_url, .host = NULL, .port = 0, .username = (HTTP_AUTH_TYPE_BASIC == http_client_auth_type) ? p_http_auth->auth_basic.user.buf : NULL, .password = (HTTP_AUTH_TYPE_BASIC == http_client_auth_type) ? p_http_auth->auth_basic.password.buf : NULL, .auth_type = http_client_auth_type, .path = NULL, .query = NULL, .cert_pem = NULL, .client_cert_pem = NULL, .client_key_pem = NULL, .user_agent = NULL, .method = HTTP_METHOD_GET, .timeout_ms = (int)(timeout_seconds * 1000), .disable_auto_redirect = false, .max_redirection_count = 0, .max_authorization_retries = 0, .event_handler = &http_download_event_handler, .transport_type = HTTP_TRANSPORT_UNKNOWN, .buffer_size = 2048, .buffer_size_tx = 1024, .user_data = &cb_info, .is_async = true, .use_global_ca_store = false, .skip_cert_common_name_check = false, .keep_alive_enable = false, .keep_alive_idle = 0, .keep_alive_interval = 0, .keep_alive_count = 0, }; LOG_INFO("http_download: %s", p_url); if (!gw_status_is_network_connected()) { LOG_ERR("HTTP download failed - no network connection"); return false; } cb_info.http_handle = esp_http_client_init(&http_config); if (NULL == cb_info.http_handle) { LOG_ERR("Can't init http client"); return false; } if (GW_CFG_REMOTE_AUTH_TYPE_BEARER == gw_cfg_http_auth_type) { str_buf_t str_buf = str_buf_printf_with_alloc("Bearer %s", p_http_auth->auth_bearer.token.buf); if (NULL == str_buf.buf) { LOG_ERR("Can't allocate memory for bearer token"); return false; } LOG_DBG("Add HTTP header: %s: %s", "Authorization", str_buf.buf); esp_http_client_set_header(cb_info.http_handle, "Authorization", str_buf.buf); str_buf_free_buf(&str_buf); } if (NULL != p_extra_header_item) { LOG_DBG("Add HTTP header: %s: %s", p_extra_header_item->p_key, p_extra_header_item->p_value); esp_http_client_set_header(cb_info.http_handle, p_extra_header_item->p_key, p_extra_header_item->p_value); } LOG_DBG("http_download_by_handle"); const bool result = http_download_by_handle(cb_info.http_handle, flag_feed_task_watchdog); LOG_DBG("esp_http_client_cleanup"); const esp_err_t err = esp_http_client_cleanup(cb_info.http_handle); if (ESP_OK != err) { LOG_ERR_ESP(err, "esp_http_client_cleanup failed"); } return result; } bool http_download( const char *const p_url, const TimeUnitsSeconds_t timeout_seconds, http_download_cb_on_data_t p_cb_on_data, void *const p_user_data, const bool flag_feed_task_watchdog) { return http_download_with_auth( p_url, timeout_seconds, GW_CFG_REMOTE_AUTH_TYPE_NO, NULL, NULL, p_cb_on_data, p_user_data, flag_feed_task_watchdog); }
truekonrads/mirv-metasploit
lib/gemcache/ruby/1.9.1/gems/mail-2.4.4/lib/mail/parsers/received.rb
<gh_stars>10-100 # Autogenerated from a Treetop grammar. Edits may be lost. module Mail module Received include Treetop::Runtime def root @root ||= :primary end include RFC2822 module Primary0 def name_val_list elements[0] end def date_time elements[2] end end def _nt_primary start_index = index if node_cache[:primary].has_key?(index) cached = node_cache[:primary][index] if cached cached = SyntaxNode.new(input, index...(index + 1)) if cached == true @index = cached.interval.end end return cached end i0, s0 = index, [] r1 = _nt_name_val_list s0 << r1 if r1 if has_terminal?(";", false, index) r2 = instantiate_node(SyntaxNode,input, index...(index + 1)) @index += 1 else terminal_parse_failure(";") r2 = nil end s0 << r2 if r2 r3 = _nt_date_time s0 << r3 end end if s0.last r0 = instantiate_node(SyntaxNode,input, i0...index, s0) r0.extend(Primary0) else @index = i0 r0 = nil end node_cache[:primary][start_index] = r0 r0 end end class ReceivedParser < Treetop::Runtime::CompiledParser include Received end end
FlorianBauer/sila-orchestrator
orchestrator-client/src/main/java/de/fau/clients/orchestrator/utils/XmlUtils.java
<reponame>FlorianBauer/sila-orchestrator<gh_stars>1-10 package de.fau.clients.orchestrator.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; import lombok.NonNull; import sila_java.library.core.models.Constraints; import sila_java.library.core.models.DataTypeType; /** * Class with helper functions to manage XML related data. */ public final class XmlUtils { private static final XmlMapper xmlMapper; static { final JacksonXmlModule module = new JacksonXmlModule(); module.setDefaultUseWrapper(false); xmlMapper = new XmlMapper(module); xmlMapper.registerModule(new JaxbAnnotationModule()); } /** * Deserializes the given XML string into a SilA <code>DataTypeType</code>. * * @param typeAsXml The type encoded as XML string. * @return The <code>DataTypeType</code> object form the unmarshalled XML string on success. * @throws JsonProcessingException * @see ..BasicNodeFactory#createAnyType */ public static DataTypeType parseXmlDataType(@NonNull final String typeAsXml) throws JsonProcessingException { return xmlMapper.readValue(typeAsXml, DataTypeType.class); } /** * Deserializes the given XML string into a SilA <code>Constraints</code> object. * * @param constraintsAsXml The constraints type encoded as XML string. * @return The <code>Constraints</code> object form the unmarshalled XML string on success. * @throws JsonProcessingException */ public static Constraints parseXmlConstraints(@NonNull final String constraintsAsXml) throws JsonProcessingException { return xmlMapper.readValue(constraintsAsXml, Constraints.class); } }
dipta007/Competitive-Programming
COACH/zahin vai/182550 - MIST Team Contest/H.cpp
#include <bits/stdc++.h> #define ll long long int #define pii pair <int,int> #define ff first #define ss second #define pi acos(-1.0) #define pb push_back #define INF (ll)1e17 #define N 1002 #define MOD 1000000007 #define BASE 100003 const double EPS = 1e-9; #define eq(a,b) (fabs(a-b)<EPS) //#define FastRead ios_base::sync_with_stdio(0);cin.tie(0) using namespace std; template < class T > inline T gcd(T a, T b) {while(b) {a %= b; swap(a, b);} return a;} template < class T > inline T lcm(T a, T b) {return a/gcd(a, b)*b;} inline int nxt() {int wow; scanf("%d", &wow); return wow;} inline ll lxt() {ll wow; scanf("%lld", &wow); return wow;} inline double dxt() {double wow; scanf("%lf", &wow); return wow;} /***************** Fighters Launched *******************/ int dp[N][N], a[N][N]; int main() { int t = nxt(), cse = 0; while (t--){ memset(dp, 0, sizeof(dp)); int n = nxt(), m = nxt(); for (int i=1; i<=n; i++){ for (int j=1; j<=m; j++){ a[i][j] = nxt(); } } for(int i=1; i<=n; i++) { dp[i][1] = dp[i-1][1] + a[i][1]; } for(int i=1; i<=m; i++) { dp[1][i] = dp[1][i-1] + a[1][i]; } for (int i=2; i<=n; i++){ for (int j=2; j<=m; j++){ dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + a[i][j]; } } printf("Case %d: %d\n", ++cse, dp[n][m]); } return 0; }
fjl121029xx/myWaterdrop
waterdrop-core/src/main/scala/io/github/interestinglab/waterdrop/filter/Replace.scala
<reponame>fjl121029xx/myWaterdrop package io.github.interestinglab.waterdrop.filter import com.typesafe.config.{Config, ConfigFactory} import io.github.interestinglab.waterdrop.apis.BaseFilter import org.apache.spark.sql.{Dataset, Row, SparkSession} import scala.collection.JavaConversions._ import org.apache.spark.sql.functions.{col, regexp_replace} class Replace extends BaseFilter { var conf: Config = ConfigFactory.empty() /** * Set Config. * */ override def setConfig(config: Config): Unit = { this.conf = config } /** * Get Config. * */ override def getConfig(): Config = { this.conf } override def checkConfig(): (Boolean, String) = { // replacement must present and ""(empty string) is its valid value conf.hasPath("pattern") && !conf.getString("pattern").trim.equals("") && conf.hasPath("replacement") match { case true => (true, "") case false => (false, "please specify [pattern] and [replacement] as string") } } override def prepare(spark: SparkSession): Unit = { super.prepare(spark) val defaultConfig = ConfigFactory.parseMap( Map( "source_field" -> "raw_message", "target_field" -> "replaced" ) ) conf = conf.withFallback(defaultConfig) } override def process(spark: SparkSession, df: Dataset[Row]): Dataset[Row] = { df.withColumn( conf.getString("target_field"), regexp_replace(col(conf.getString("source_field")), conf.getString("pattern"), conf.getString("replacement"))) } }
stas-vilchik/bdd-ml
data/5376.js
<reponame>stas-vilchik/bdd-ml { process.stdout.write(adjustToTerminalWidth(`${path.basename(p)}\n`)); process.stdout.write(`${OK}\n`); }
roman-kachanovsky/checkio
tests/scientific_expedition/test_what_is_wrong_with_this_family.py
<reponame>roman-kachanovsky/checkio import unittest from solutions.scientific_expedition.what_is_wrong_with_this_family import my_solution class TestSolution(unittest.TestCase): def test_solution(self): self.assertTrue(my_solution([['Logan', 'Mike']])) self.assertTrue(my_solution([ ['Logan', 'Mike'], ['Logan', 'Jack'] ])) self.assertTrue(my_solution([ ['Logan', 'Mike'], ['Logan', 'Jack'], ['Mike', 'Alexander'] ])) self.assertFalse(my_solution([ ['Logan', 'Mike'], ['Logan', 'Jack'], ['Mike', 'Jack'] ])) self.assertFalse(my_solution([ ['Logan', 'William'], ['Logan', 'Jack'], ['Mike', 'Alexander'] ])) self.assertFalse(my_solution([ ['Logan', 'Mike'], ['Logan', 'Jack'], ['Mike', 'Logan'] ])) if __name__ == '__main___': unittest.main()
kucjac/clego
database/xpg/errors.go
<filename>database/xpg/errors.go package xpg import ( "context" "github.com/go-pg/pg/v10" "github.com/kucjac/cleango/cgerrors" ) const ( errCancelled = "57014" ) // ErrWrapf takes error returned from Postgres and returns structured error. // Basically, we work with three database related kinds of errors: // ErrNotFound for empty results, // Coflict for insert/update violating data integrity, // ErrInternal for all other kind of db errors. func ErrWrapf(e error, process string, fmt string, args ...interface{}) error { // it is better to handle this directly in db functions // with more details about what was not found - see GetByID functions. if cgerrors.Is(e, pg.ErrNoRows) { return cgerrors.ErrNotFoundf(fmt, args...).WithProcess(process) } switch typed := e.(type) { case nil: return nil case pg.Error: if typed.IntegrityViolation() { return cgerrors.ErrAlreadyExistsf(fmt, args...).WithProcess(process) } if typed.Field('C') == errCancelled { fmt += " %v" args = append(args, context.Canceled) return cgerrors.ErrDeadlineExceededf(fmt, args).WithProcess(process) } args = append(args, e.Error()) fmt = fmt + " %s" return cgerrors.ErrInternalf(fmt, args...).WithProcess(process) case *cgerrors.Error: return typed default: args = append(args, e.Error()) fmt = fmt + " %s" return cgerrors.ErrInternalf(fmt, args...).WithProcess(process) } } // ErrWrap takes error returned from Postgres and returns structured error. // Basically, we work with three database related kinds of errors: // ErrNotFound for empty results, // Coflict for insert/update violating data integrity, // ErrInternal for all other kind of db errors. func ErrWrap(e error, process string, args ...interface{}) error { // it is better to handle this directly in db functions // with more details about what was not found - see GetByID functions. if cgerrors.Is(e, pg.ErrNoRows) { return cgerrors.ErrNotFound(args...) } switch typed := e.(type) { case nil: return nil case pg.Error: if typed.IntegrityViolation() { return cgerrors.ErrAlreadyExists(args...) } if typed.Field('C') == errCancelled { return cgerrors.ErrDeadlineExceeded(context.Canceled.Error()) } return cgerrors.ErrInternal(append([]interface{}{args}, e)...) case *cgerrors.Error: return typed default: return cgerrors.ErrInternal(append([]interface{}{args}, e)...) } }
TxConvergentAdmin/f20-bt-impact-local-business
node_modules/@react-navigation/core/lib/module/utils/withDefaultValue.js
export default ((obj, key, defaultValue) => { if (obj.hasOwnProperty(key) && typeof obj[key] !== 'undefined') { return obj; } obj[key] = defaultValue; return obj; }); //# sourceMappingURL=withDefaultValue.js.map
sonia-auv/sonia-behaviors
sonia_flexbe_behaviors/src/sonia_flexbe_behaviors/snake_mouvement_sm.py
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] tags will be kept. # ########################################################### from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger from sonia_flexbe_states.create_pose import create_pose from sonia_flexbe_states.move_to_target import move_to_target # Additional imports can be added inside the following tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT] ''' Created on Mon Nov 15 2021 @author: FA ''' class snake_mouvementSM(Behavior): ''' Search mouvement in a snake partern. Includes 7 moves with a time entered in parameter ''' def __init__(self): super(snake_mouvementSM, self).__init__() self.name = 'snake_mouvement' # parameters of this behavior self.add_parameter('distance_y', 2) self.add_parameter('timeout', 25) # references to used behaviors # Additional initialization code can be added inside the following tags # [MANUAL_INIT] # [/MANUAL_INIT] # Behavior comments: def create(self): # x:633 y:64, x:596 y:201 _state_machine = OperatableStateMachine(outcomes=['finished', 'failed']) # Additional creation code can be added inside the following tags # [MANUAL_CREATE] # [/MANUAL_CREATE] with _state_machine: # x:67 y:67 OperatableStateMachine.add('slide left half pose', create_pose(positionX=0.25, positionY=-self.distance_y/2, positionZ=0, orientationX=0, orientationY=0, orientationZ=0, frame=1, time=self.timeout/2, precision=0, rotation=True), transitions={'continue': 'slide right pose'}, autonomy={'continue': Autonomy.Off}, remapping={'pose': 'slide_left_half'}) # x:773 y:195 OperatableStateMachine.add('half slide left 2', move_to_target(), transitions={'continue': 'finished', 'failed': 'failed'}, autonomy={'continue': Autonomy.Off, 'failed': Autonomy.Off}, remapping={'pose': 'slide_left_half'}) # x:290 y:289 OperatableStateMachine.add('slide left', move_to_target(), transitions={'continue': 'slide right 2', 'failed': 'failed'}, autonomy={'continue': Autonomy.Off, 'failed': Autonomy.Off}, remapping={'pose': 'slide_left'}) # x:550 y:388 OperatableStateMachine.add('slide left 2', move_to_target(), transitions={'continue': 'slide right 3', 'failed': 'failed'}, autonomy={'continue': Autonomy.Off, 'failed': Autonomy.Off}, remapping={'pose': 'slide_left'}) # x:69 y:283 OperatableStateMachine.add('slide left pose', create_pose(positionX=0.5, positionY=-self.distance_y, positionZ=0, orientationX=0, orientationY=0, orientationZ=0, frame=1, time=self.timeout, precision=0, rotation=True), transitions={'continue': 'half slide left'}, autonomy={'continue': Autonomy.Off}, remapping={'pose': 'slide_left'}) # x:287 y:180 OperatableStateMachine.add('slide right', move_to_target(), transitions={'continue': 'slide left', 'failed': 'failed'}, autonomy={'continue': Autonomy.Off, 'failed': Autonomy.Off}, remapping={'pose': 'slide_right'}) # x:290 y:399 OperatableStateMachine.add('slide right 2', move_to_target(), transitions={'continue': 'slide left 2', 'failed': 'failed'}, autonomy={'continue': Autonomy.Off, 'failed': Autonomy.Off}, remapping={'pose': 'slide_right'}) # x:781 y:379 OperatableStateMachine.add('slide right 3', move_to_target(), transitions={'continue': 'half slide left 2', 'failed': 'failed'}, autonomy={'continue': Autonomy.Off, 'failed': Autonomy.Off}, remapping={'pose': 'slide_right'}) # x:67 y:175 OperatableStateMachine.add('slide right pose', create_pose(positionX=0.5, positionY=self.distance_y, positionZ=0, orientationX=0, orientationY=0, orientationZ=0, frame=1, time=self.timeout, precision=0, rotation=True), transitions={'continue': 'slide left pose'}, autonomy={'continue': Autonomy.Off}, remapping={'pose': 'slide_right'}) # x:291 y:56 OperatableStateMachine.add('half slide left', move_to_target(), transitions={'continue': 'slide right', 'failed': 'failed'}, autonomy={'continue': Autonomy.Off, 'failed': Autonomy.Off}, remapping={'pose': 'slide_left_half'}) return _state_machine # Private functions can be added inside the following tags # [MANUAL_FUNC] # [/MANUAL_FUNC]
seinecle/graphstore
store/src/main/java/org/gephi/graph/impl/TimestampsParser.java
<filename>store/src/main/java/org/gephi/graph/impl/TimestampsParser.java<gh_stars>0 /* * Copyright 2012-2013 Gephi Consortium * * 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.gephi.graph.impl; import java.io.IOException; import java.io.StringReader; import java.time.ZonedDateTime; import java.util.ArrayList; import org.gephi.graph.api.AttributeUtils; import static org.gephi.graph.impl.FormattingAndParsingUtils.COMMA; import static org.gephi.graph.impl.FormattingAndParsingUtils.DYNAMIC_TYPE_LEFT_BOUND; import static org.gephi.graph.impl.FormattingAndParsingUtils.DYNAMIC_TYPE_RIGHT_BOUND; import static org.gephi.graph.impl.FormattingAndParsingUtils.LEFT_BOUND_BRACKET; import static org.gephi.graph.impl.FormattingAndParsingUtils.LEFT_BOUND_SQUARE_BRACKET; import static org.gephi.graph.impl.FormattingAndParsingUtils.RIGHT_BOUND_BRACKET; import static org.gephi.graph.impl.FormattingAndParsingUtils.RIGHT_BOUND_SQUARE_BRACKET; import org.gephi.graph.api.types.TimestampBooleanMap; import org.gephi.graph.api.types.TimestampByteMap; import org.gephi.graph.api.types.TimestampCharMap; import org.gephi.graph.api.types.TimestampDoubleMap; import org.gephi.graph.api.types.TimestampFloatMap; import org.gephi.graph.api.types.TimestampIntegerMap; import org.gephi.graph.api.types.TimestampLongMap; import org.gephi.graph.api.types.TimestampMap; import org.gephi.graph.api.types.TimestampSet; import org.gephi.graph.api.types.TimestampShortMap; import org.gephi.graph.api.types.TimestampStringMap; import static org.gephi.graph.impl.FormattingAndParsingUtils.EMPTY_VALUE; /** * <p> * Class for parsing timestamp types. * </p> * * <p> * The standard format for {@link TimestampMap} is &lt;[timestamp, value1]; * [timestamp, value2]&gt;. * </p> * * <p> * The standard format for {@link TimestampSet} is &lt;[timestamp1, timestamp2, * timestamp3, ...]&gt;. * </p> * * <p> * Timestamps values can be both numbers and ISO dates or datetimes. Dates and * datetimes will be converted to their millisecond-precision timestamp. * </p> * * Examples of valid timestamp maps are: * <ul> * <li>&lt;(1, 2, v1); [3, 5, v2]&gt;</li> * <li>[1.15,2.21, "literal value ' \" ,[]()"]</li> * <li>[1.15,2.21, 'literal value " \' ,[]()']</li> * </ul> * * Examples of valid timestamp sets are: * <ul> * <li>&lt;[1,2]; [3, 4]&gt;</li> * <li>[1,2]</li> * <li>[1,2] (5,6)</li> * </ul> * * <p> * The most correct examples are those that include &lt; &gt; and proper commas * and semicolons for separation, but the parser will be indulgent when * possible. * </p> * * @author <NAME> */ public final class TimestampsParser { /** * Parses a {@link TimestampSet} type with one or more timestamps. * * @param input Input string to parse * @param timeZone Time zone to use or null to use default time zone (UTC) * @return Resulting {@link TimestampSet}, or null if the input equals * '&lt;empty&gt;' or is null * @throws IllegalArgumentException Thrown if there are no timestamps in the * input string or bounds cannot be parsed into doubles or * dates/datetimes. */ public static TimestampSet parseTimestampSet(String input, ZonedDateTime timeZone) throws IllegalArgumentException { if (input == null) { return null; } if (input.equalsIgnoreCase(EMPTY_VALUE)) { return new TimestampSet(); } ArrayList<String> values = new ArrayList<String>(); try { StringReader reader = new StringReader(input + ' ');// Add 1 space // so // reader.skip // function // always works // when // necessary // (end of // string not // reached). int r; char c; while ((r = reader.read()) != -1) { c = (char) r; switch (c) { case DYNAMIC_TYPE_LEFT_BOUND: case DYNAMIC_TYPE_RIGHT_BOUND: case RIGHT_BOUND_SQUARE_BRACKET: case RIGHT_BOUND_BRACKET: case LEFT_BOUND_BRACKET: case LEFT_BOUND_SQUARE_BRACKET: case ' ': case '\t': case '\r': case '\n': case COMMA: // Ignore special characters and leading whitespace or // similar until a value or literal starts: break; case '"': case '\'': values.add(FormattingAndParsingUtils.parseLiteral(reader, c)); break; default: reader.skip(-1);// Go backwards 1 position, for reading // start of value values.add(FormattingAndParsingUtils.parseValue(reader)); } } } catch (IOException ex) { throw new RuntimeException("Unexpected expection while parsing timestamps", ex); } TimestampSet result = new TimestampSet(values.size()); for (String value : values) { result.add(FormattingAndParsingUtils.parseDateTimeOrTimestamp(value, timeZone)); } return result; } /** * Parses a {@link TimestampSet} type with one or more timestamps. Default * time zone is used (UTC). * * @param input Input string to parse * @return Resulting {@link TimestampSet}, or null if the input equals * '&lt;empty&gt;' or is null * @throws IllegalArgumentException Thrown if there are no timestamps in the * input string or bounds cannot be parsed into doubles or * dates/datetimes. */ public static TimestampSet parseTimestampSet(String input) throws IllegalArgumentException { return parseTimestampSet(input, null); } /** * Parses a {@link TimestampMap} type with one or more timestamps, and their * associated values. * * @param <T> Underlying type of the {@link TimestampMap} values * @param typeClass Simple type or {@link TimestampMap} subtype for the * result values. * @param input Input string to parse * @param timeZone Time zone to use or null to use default time zone (UTC) * @return Resulting {@link TimestampMap}, or null if the input equals * '&lt;empty&gt;' or is null * @throws IllegalArgumentException Thrown if type class is not supported, * any of the timestamps don't have a value or have an invalid * value, there are no timestamps in the input string or bounds * cannot be parsed into doubles or dates/datetimes. */ public static <T> TimestampMap<T> parseTimestampMap(Class<T> typeClass, String input, ZonedDateTime timeZone) throws IllegalArgumentException { if (typeClass == null) { throw new IllegalArgumentException("typeClass required"); } if (input == null) { return null; } TimestampMap result; typeClass = AttributeUtils.getStandardizedType(typeClass); if (typeClass.equals(String.class)) { result = new TimestampStringMap(); } else if (typeClass.equals(Byte.class)) { result = new TimestampByteMap(); } else if (typeClass.equals(Short.class)) { result = new TimestampShortMap(); } else if (typeClass.equals(Integer.class)) { result = new TimestampIntegerMap(); } else if (typeClass.equals(Long.class)) { result = new TimestampLongMap(); } else if (typeClass.equals(Float.class)) { result = new TimestampFloatMap(); } else if (typeClass.equals(Double.class)) { result = new TimestampDoubleMap(); } else if (typeClass.equals(Boolean.class)) { result = new TimestampBooleanMap(); } else if (typeClass.equals(Character.class)) { result = new TimestampCharMap(); } else { throw new IllegalArgumentException("Unsupported type " + typeClass.getClass().getCanonicalName()); } if (input.equalsIgnoreCase(EMPTY_VALUE)) { return result; } StringReader reader = new StringReader(input + ' ');// Add 1 space so // reader.skip // function always // works when // necessary (end of // string not // reached). try { int r; char c; while ((r = reader.read()) != -1) { c = (char) r; switch (c) { case LEFT_BOUND_SQUARE_BRACKET: case LEFT_BOUND_BRACKET: parseTimestampAndValue(typeClass, reader, result, timeZone); break; default: // Ignore other chars outside of bounds } } } catch (IOException ex) { throw new RuntimeException("Unexpected expection while parsing timestamps", ex); } return result; } /** * Parses a {@link TimestampMap} type with one or more timestamps, and their * associated values. Default time zone is used (UTC). * * @param <T> Underlying type of the {@link TimestampMap} values * @param typeClass Simple type or {@link TimestampMap} subtype for the * result values. * @param input Input string to parse * @return Resulting {@link TimestampMap}, or null if the input equals * '&lt;empty&gt;' or is null * @throws IllegalArgumentException Thrown if type class is not supported, * any of the timestamps don't have a value or have an invalid * value, there are no timestamps in the input string or bounds * cannot be parsed into doubles or dates/datetimes. */ public static <T> TimestampMap<T> parseTimestampMap(Class<T> typeClass, String input) throws IllegalArgumentException { return parseTimestampMap(typeClass, input, null); } private static <T> void parseTimestampAndValue(Class<T> typeClass, StringReader reader, TimestampMap<T> result, ZonedDateTime timeZone) throws IOException { ArrayList<String> values = new ArrayList<String>(); int r; char c; while ((r = reader.read()) != -1) { c = (char) r; switch (c) { case RIGHT_BOUND_SQUARE_BRACKET: case RIGHT_BOUND_BRACKET: addTimestampAndValue(typeClass, values, result, timeZone); return; case ' ': case '\t': case '\r': case '\n': case COMMA: // Ignore leading whitespace or similar until a value or // literal starts: break; case '"': case '\'': values.add(FormattingAndParsingUtils.parseLiteral(reader, c)); break; default: reader.skip(-1);// Go backwards 1 position, for reading // start of value values.add(FormattingAndParsingUtils.parseValue(reader)); } } addTimestampAndValue(typeClass, values, result, timeZone); } private static <T> void addTimestampAndValue(Class<T> typeClass, ArrayList<String> values, TimestampMap<T> result, ZonedDateTime timeZone) { if (values.size() != 2) { throw new IllegalArgumentException("Each timestamp and value array must have 2 values"); } double timestamp = FormattingAndParsingUtils.parseDateTimeOrTimestamp(values.get(0), timeZone); String valString = values.get(1); T value = FormattingAndParsingUtils.convertValue(typeClass, valString); result.put(timestamp, value); } }
panduakas/express-sequelize-boilerplate
app/middlewares/httpRequestLog.js
const clone = require('clone'); const { get } = require('lodash'); const { logInfo } = require('../helpers'); const requestLog = async (req, res, next) => { const { baseUrl, originalUrl, method, query, params, body, ip, headers, } = req; const requestId = get(req, 'headers.requestid'); if (requestId) process.requestId = requestId; const data = { query, params, body, headers, ip, }; const cloneData = clone(data); if (Object.entries(query).length === 0 && query.constructor === Object) delete data.query; if (Object.entries(params).length === 0 && params.constructor === Object) delete data.params; if (Object.entries(body).length === 0 && body.constructor === Object) delete data.body; if (get(cloneData.headers, 'authorization')) cloneData.headers.authorization = '*'; await logInfo({ data: cloneData, method, message: `REQUEST TO: ${baseUrl || originalUrl}`, mep: 'REQUEST', }); res.method = method; next(); }; module.exports = { requestLog, };
ambros-gleixner/rubberband
rubberband/utils/file.py
"""Methods to help with file io.""" from rubberband.constants import FILES_DIR def write_file(filename, contents): """ Save a file on the filesystem. Parameters ---------- filename : string Filename of file to write to. contents : string Contents to write into file. """ path = FILES_DIR + filename with open(path, "wb") as f: f.write(contents) return path
olivierverdier/sfepy
sfepy/solvers/oseen.py
from sfepy.base.base import * from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import NonlinearSolver from nls import conv_test ## # 26.07.2007, c def are_close( a, b, rtol = 0.2, atol = 1e-8 ): return False # return abs( a - b ) <= max( atol, rtol * abs( b ) ) ## # 26.07.2007, c def scale_matrix( mtx, indx, factor ): ptr0 = mtx.indptr[indx.start] ptr1 = mtx.indptr[indx.stop] mtx.data[ptr0:ptr1] *= factor ## # 11.10.2007, c class Oseen( NonlinearSolver ): name = 'nls.oseen' def process_conf( conf ): """ Missing items are set to default values. Example configuration, all items:: solver_1 = { 'name' : 'oseen', 'kind' : 'nls.oseen', 'needs_problem_instance' : True, 'stabilization_hook' : 'create_stabil_mat', 'adimensionalize' : False, 'check_navier_stokes_rezidual' : False, 'i_max' : 10, 'eps_a' : 1e-8, 'eps_r' : 1.0, 'macheps' : 1e-16, 'lin_red' : 1e-2, # Linear system error < (eps_a * lin_red). 'is_plot' : False, 'log' : {'text' : 'oseen_log.txt', 'plot' : 'oseen_log.png'}, } """ get = conf.get_default_attr # Compulsory. needs_problem_instance = get('needs_problem_instance', True) if not needs_problem_instance: msg = 'set solver option "needs_problem_instance" to True!' raise ValueError(msg) stabilization_hook = get('stabilization_hook', None, 'missing "stabilization_hook" in options!') # With defaults. adimensionalize = get( 'adimensionalize', False ) check_navier_stokes_rezidual = get( 'check_navier_stokes_rezidual', False ) i_max = get( 'i_max', 1 ) eps_a = get( 'eps_a', 1e-10 ) eps_r = get( 'eps_r', 1.0 ) macheps = get( 'macheps', nm.finfo( nm.float64 ).eps ) lin_red = get( 'lin_red', 1.0 ) is_plot = get( 'is_plot', False ) log = get_logging_conf(conf) log = Struct(name='log_conf', **log) is_any_log = (log.text is not None) or (log.plot is not None) common = NonlinearSolver.process_conf( conf ) return Struct( **locals() ) + common process_conf = staticmethod( process_conf ) def __init__( self, conf, **kwargs ): NonlinearSolver.__init__( self, conf, **kwargs ) conf = self.conf if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration'], [r'$\gamma$', r'$\max(\delta)$', r'$\max(\tau)$']], xlabels=['', '', 'all iterations'], ylabels=[r'$||r||$', 'iteration', 'stabilization'], yscales=['log', 'linear', 'log'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d'], ['%.8e', '%.8e', '%.8e']]) else: self.log = None def __call__( self, vec_x0, conf = None, fun = None, fun_grad = None, lin_solver = None, status = None, problem = None ): """Oseen solver is problem-specific - it requires a ProblemDefinition instance.""" import sfepy.base.plotutils as plu conf = get_default( conf, self.conf ) fun = get_default( fun, self.fun ) fun_grad = get_default( fun_grad, self.fun_grad ) lin_solver = get_default( lin_solver, self.lin_solver ) status = get_default( status, self.status ) problem = get_default( problem, self.problem ) if problem is None: msg = 'set solver option "needs_problem_instance" to True!' raise ValueError(msg) time_stats = {} hook = problem.functions[conf.stabilization_hook] stabil, ns, ii = hook(problem) variables = problem.get_variables() update_var = variables.non_state_data_from_state make_full_vec = variables.make_full_vec print 'problem size:' print ' velocity: %s' % ii['us'] print ' pressure: %s' % ii['ps'] vec_x = vec_x0.copy() vec_x_prev = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err0 = -1.0 it = 0 while 1: vec_x_prev_f = make_full_vec( vec_x_prev ) update_var( ns['b'], vec_x_prev_f, ns['u'] ) vec_b = vec_x_prev_f[ii['u']] b_norm = nla.norm( vec_b, nm.inf ) print '|b|_max: %.12e' % b_norm vec_x_f = make_full_vec( vec_x ) vec_u = vec_x_f[ii['u']] u_norm = nla.norm( vec_u, nm.inf ) print '|u|_max: %.2e' % u_norm stabil.function.set_extra_args(b_norm = b_norm) stabil.time_update(None, problem.domain, problem.equations) max_pars = stabil.reduce_on_datas( lambda a, b: max( a, b.max() ) ) print 'stabilization parameters:' print ' gamma: %.12e' % max_pars['gamma'] print ' max( delta ): %.12e' % max_pars['delta'] print ' max( tau ): %.12e' % max_pars['tau'] try: print ' max( h^2 ): %.12e' % max_pars['diameters2'] except: pass if (not are_close( b_norm, 1.0 )) and conf.adimensionalize: adimensionalize = True else: adimensionalize = False tt = time.clock() try: vec_r = fun( vec_x ) except ValueError: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: err = nla.norm( vec_r ) if it == 0: err0 = err; else: err += nla.norm( vec_dx ) else: # Failure. output( 'rezidual computation failed for iter %d!' % it ) raise RuntimeError( 'giving up...' ) if self.log is not None: self.log(err, it, max_pars['gamma'], max_pars['delta'], max_pars['tau']) condition = conv_test( conf, it, err, err0 ) if condition >= 0: break if adimensionalize: output( 'adimensionalizing' ) mat.viscosity = viscosity / b_norm vec_r[indx_us] /= b_norm tt = time.clock() try: mtx_a = fun_grad( vec_x ) except ValueError: ok = False else: ok = True time_stats['matrix'] = time.clock() - tt if not ok: raise RuntimeError( 'giving up...' ) tt = time.clock() vec_dx = lin_solver( vec_r, mtx = mtx_a ) time_stats['solve'] = time.clock() - tt vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm( vec_e ) if lerr > (conf.eps_a * conf.lin_red): output( 'linear system not solved! (err = %e)' % lerr ) if adimensionalize: output( 'restoring pressure...' ) vec_dx[indx_ps] *= b_norm dx_norm = nla.norm( vec_dx ) output( '||dx||: %.2e' % dx_norm ) for kv in time_stats.iteritems(): output( '%10s: %7.2f [s]' % kv ) vec_x_prev = vec_x.copy() vec_x -= vec_dx if conf.is_plot: plu.pylab.ion() plu.pylab.gcf().clear() plu.pylab.subplot( 2, 2, 1 ) plu.pylab.plot( vec_x_prev ) plu.pylab.ylabel( r'$x_{i-1}$' ) plu.pylab.subplot( 2, 2, 2 ) plu.pylab.plot( vec_r ) plu.pylab.ylabel( r'$r$' ) plu.pylab.subplot( 2, 2, 4 ) plu.pylab.plot( vec_dx ) plu.pylab.ylabel( r'$\_delta x$' ) plu.pylab.subplot( 2, 2, 3 ) plu.pylab.plot( vec_x ) plu.pylab.ylabel( r'$x_i$' ) plu.pylab.draw() plu.pylab.ioff() pause() it += 1 if conf.check_navier_stokes_rezidual: t1 = '+ dw_div_grad.%s.%s( %s.viscosity, %s, %s )' \ % (ns['i2'], ns['omega'], ns['fluid'], ns['v'], ns['u']) ## t2 = '+ dw_lin_convect.%s( %s, %s, %s )' % (ns['omega'], ## ns['v'], b_name, ns['u']) t2 = '+ dw_convect.%s.%s( %s, %s )' % (ns['i2'], ns['omega'], ns['v'], ns['u']) t3 = '- dw_stokes.%s.%s( %s, %s )' % (ns['i1'], ns['omega'], ns['v'], ns['p']) t4 = 'dw_stokes.%s.%s( %s, %s )' % (ns['i1'], ns['omega'], ns['u'], ns['q']) equations = { 'balance' : ' '.join( (t1, t2, t3) ), 'incompressibility' : t4, } problem.set_equations( equations ) try: vec_rns0 = fun( vec_x0 ) vec_rns = fun( vec_x ) except ValueError: ok = False else: ok = True if not ok: print 'Navier-Stokes rezidual computation failed!' err_ns = err_ns0 = None else: err_ns0 = nla.norm( vec_rns0 ) err_ns = nla.norm( vec_rns ) print 'Navier-Stokes rezidual0: %.8e' % err_ns0 print 'Navier-Stokes rezidual : %.8e' % err_ns print 'b - u: %.8e' % nla.norm( vec_b - vec_u ) print condition ## print vec_rns - vec_rns1 plu.pylab.ion() plu.pylab.gcf().clear() plu.pylab.plot( vec_rns ) ## plu.pylab.gcf().clear() ## plu.pylab.plot( vec_rns1 ) plu.pylab.draw() plu.pylab.ioff() pause() else: err_ns = None if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['err_ns'] = err_ns status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x
brianlindsy/chpl-api
chpl/chpl-service/src/main/java/gov/healthit/chpl/dao/statistics/SummaryStatisticsDAOImpl.java
<gh_stars>0 package gov.healthit.chpl.dao.statistics; import java.util.Date; import java.util.List; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import gov.healthit.chpl.dao.impl.BaseDAOImpl; import gov.healthit.chpl.entity.SummaryStatisticsEntity; import gov.healthit.chpl.exception.EntityCreationException; import gov.healthit.chpl.exception.EntityRetrievalException; @Repository("summaryStatisticsDAO") public class SummaryStatisticsDAOImpl extends BaseDAOImpl implements SummaryStatisticsDAO { @Override @Transactional public SummaryStatisticsEntity create(SummaryStatisticsEntity summaryStatistics) throws EntityCreationException, EntityRetrievalException { summaryStatistics.setCreationDate(new Date()); summaryStatistics.setLastModifiedDate(new Date()); summaryStatistics.setLastModifiedUser(getUserId(SYSTEM_USER_ID)); summaryStatistics.setDeleted(false); entityManager.persist(summaryStatistics); entityManager.flush(); return summaryStatistics; } @Override public SummaryStatisticsEntity getMostRecent() throws EntityRetrievalException { List<SummaryStatisticsEntity> entities = entityManager .createQuery("SELECT stats " + "FROM SummaryStatisticsEntity stats " + "WHERE (stats.deleted <> true) " + "ORDER BY stats.id DESC " + "LIMIT 1", SummaryStatisticsEntity.class) .getResultList(); if (entities.size() > 0) { return entities.get(0); } else { return null; } } }
FizzCorp/fizz-platform
components/api-gateway/src/test/java/io/fizz/common/MockLoggingService.java
<reponame>FizzCorp/fizz-platform package io.fizz.common; import java.util.ArrayList; import java.util.List; public class MockLoggingService extends LoggingService { static class MockLog extends LoggingService.Log { private List<String> logStream = new ArrayList<>(); MockLog(Class<?> clazz) { super(clazz); } @Override void write(final String message) { logStream.add(message); } @Override String getTimestamp() { return "<time>"; } List<String> getLogStream() { return logStream; } } public static MockLog getLogger(Class<?> clazz) { return new MockLog(clazz); } }
dxylove/EVAL-ADICUP360
projects/ADuCM360_demo_cn0337/include/Communication.h
/*! ***************************************************************************** * @file: Communication.h * @brief: * @version: $Revision$ * @date: $Date$ *----------------------------------------------------------------------------- * Copyright (c) 2015-2017 Analog Devices, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Modified versions of the software must be conspicuously marked as such. - This software is licensed solely and exclusively for use with processors manufactured by or for Analog Devices, Inc. - This software may not be combined or merged with other code in any manner that would cause the software to become subject to terms and conditions which differ from those listed here. - Neither the name of Analog Devices, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - The use of this software may or may not infringe the patent rights of one or more patent holders. This license does not release you from the requirement that you obtain separate licenses from these patent holders to use this software. THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES, INC. AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT, TITLE, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANALOG DEVICES, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, DAMAGES ARISING OUT OF CLAIMS OF INTELLECTUAL PROPERTY RIGHTS INFRINGEMENT; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #ifndef _COMMUNICATION_H_ #define _COMMUNICATION_H_ /********************************* Internal defines ****************************/ #define UART_TX_BUFFER_SIZE 1024 /* UART transmit buffer size */ /* Execution status */ #define UART_SUCCESS 0 #define UART_FAILURE -1 #define UART_NO_TX_SPACE -2 #define UART_NO_RX_SPACE -3 /* UART status */ #define UART_TRUE 1 #define UART_FALSE 0 /****************************** Global Data ***********************************/ extern unsigned int uart_tpos, uart_tcnt, uart_cmd, uart_tbusy; extern unsigned char uart_tx_buffer[UART_TX_BUFFER_SIZE]; /****************************** Internal types *********************************/ /* Number of received bytes */ typedef enum { ONE_BYTE = 1, /* Read one byte */ TWO_BYTES /* Read two bytes */ } enReadBytes; /* Write data mode */ typedef enum { UART_WRITE_NO_INT = 1, /* Write data when interrupts are disabled */ UART_WRITE_IN_INT, /* Write data while in an interrupt routine */ UART_WRITE } enWriteData; /*************************** Functions prototypes *****************************/ void SPI_Init(void); uint16_t SPI_Read (uint8_t u8Mode, enReadBytes u8Bytes); void UART_Init(long lBaudrate, int iBits); void UART_ReadChar(char *data); int UART_WriteChar(char data, enWriteData mode); int UART_WriteString(char *string); /**************************** Configuration parameters **********************/ /* CONVST pin AD7091R - P1.2 - output */ #define CONVST_PORT pADI_GP1 #define CONVST_PIN 0x04 #define CONVST_PIN_NUMBER 0x02 #endif /* _COMMUNICATION_H_ */
driehuis/vimmate
lib/active_window/active_column.rb
<filename>lib/active_window/active_column.rb require 'gtk2' module ActiveWindow =begin ActiveColumn is used to define columns for ActiveTreeStore =end class ActiveColumn attr_accessor :id, :name ClassesToSymbols = { TrueClass => :boolean, FalseClass => :boolean, String => :string, Time => :datetime, Date => :datetime, Fixnum => :integer, Bignum => :integer, Integer => :integer, Float => :float, Gdk::Pixbuf => :image } ## ## column: ActiveRecord::ConnectionAdapters::MysqlColumn ## def self.create(id, name, klass=:string, opts={}) klass = ClassesToSymbols[klass] if klass.is_a?(Class) subclass = case klass # ignore warning this creates when :string; ActiveTextColumn when :datetime; ActiveDateColumn when :integer; ActiveIntegerColumn when :float; ActiveFloatColumn when :boolean; ActiveToggleColumn when :image; ActiveImageColumn else; self end return subclass.new(id, name.to_s, opts) end def initialize(id, name, opts={}) self.id = id self.name = name @virtual = opts[:virtual] == true ? true : false @visible = opts[:visible] == false ? false : true #puts 'new column: %s %s' % [self.class, name] end def virtual? @virtual end def hide! @visible = false end def visible? @visible end ## return a Gtk::TreeViewColumn appropriate for showing this column def view raise "There is no way to show #{name} yet." end def renderer raise "There is no way to render #{name} yet." end ## return the class of the value held for this column in the model def data_class Object end ## given an active record object, return the attribute ## value that corresponds to this column. the returned ## value must match the class returned in data_class. ## so, you might have to do some conversion. def data_value(ar_object) ar_object.send(self.name) end def view r = renderer column.pack_start(r, true) column.add_attribute(r, attribute, self.id) column end private def column @gtk_column ||= Gtk::TreeViewColumn.new(self.name) end end ## ## ActiveTextColumn ## ## For columns with string values ## class ActiveTextColumn < ActiveColumn def data_class String end def renderer Gtk::CellRendererText.new end def attribute :text end end class ActiveIntegerColumn < ActiveTextColumn def data_class Integer end end ## ## how to do?: ## renderer.signal_connect('toggled') do |cell, path| ## fixed_toggled(treeview.model, path) ## end ## class ActiveToggleColumn < ActiveColumn def data_class TrueClass end def renderer Gtk::CellRendererToggle.new end def attribute :active end end ## ## TODO: configure the number of digits printed ## class ActiveFloatColumn < ActiveColumn def data_class Float end def renderer Gtk::CellRendererText.new end def attribute :text end def view super.set_cell_data_func(renderer) do |col, renderer, model, iter| renderer.text = sprintf("%.2f", iter[self.id]) end end def data_value(ar_object) super(ar_object) || 0 end end ## ## TODO: configure the date format ## class ActiveDateColumn < ActiveColumn def data_class Time end def renderer Gtk::CellRendererText.new end def attribute :text end def view super.set_cell_data_func(renderer) do |col, renderer, model, iter| renderer.text = sprintf("%x %X", iter[self.id]) end end end class ActiveImageColumn < ActiveColumn def data_class Gdk::Pixbuf end def renderer Gtk::CellRendererPixbuf.new end def attribute :pixbuf end end # pack multiple columns into one class ActiveCompositeColumn < ActiveColumn def initialize(name, opts={}) self.name = name @virtual = true @visible = true end def view column end def add(child_column, expand=true) raise ArgumentError, "give an ActiveColumn, not #{child_column.inspect}" unless child_column.is_a?(ActiveColumn) child_column.hide! rend = child_column.renderer column.pack_start(rend, expand) column.add_attribute(rend, child_column.attribute, child_column.id) end end end
erkambozan/algo-sb
ms-searching-service/src/main/java/fworks/algorithms/searching/search/AlgorithmSearchService.java
package fworks.algorithms.searching.search; import fworks.algorithms.counter.Counter; import fworks.algorithms.searching.model.searchrequest.SearchRequest; import fworks.algorithms.searching.model.searchrequest.SearchResponse; import java.time.Duration; import java.time.Instant; /** * Search Service. * * @author flaviolcastro * */ public interface AlgorithmSearchService { /** * Execute a search on an array. * * @param key to be searched * @param array to find * @param counter of analysed key * @return index of the key if found,<br> * -1 if not found. */ int search(long key, long[] array, Counter counter); /** * Execute a search based on the request. * * @param request params to search * @return search response */ default SearchResponse search(SearchRequest request) { long key = request.getKey(); long[] array = request.getArray(); Counter counter = new Counter(); // execute the search marking the time Instant start = Instant.now(); int result = this.search(key, array, counter); Duration duration = Duration.between(start, Instant.now()); // return the result SearchResponse searchResponse = SearchResponse.builder() // .algorithm(getAlgorithmName()) // .arraySize(array.length) // .index(result) // .numberOfKeysAnalized(counter.getCounter()) // .duration(duration.toNanos() / 1_000_000.0) // .build(); return searchResponse; } /** * Return the algorithm name/implementation. * * @return name */ String getAlgorithmName(); }
i-victor/Smart.DevScripts
go-lang/go/src/github.com/codymalick/simple-raft/main.go
// Simple implementation of the raft concensus algorithm using golang rpc // <NAME> and <NAME> package main import ( "flag" ) const ( numServers = 5 timeout = 5 //seconds ) // Leader Election: Choose a leader // Log replication: Make sure all systems have the same view of the log // Safety: Make sure a leader who is behind cannot be elected func main() { cmdID := flag.Int("id", 0, "Usage: -id <id>") cmdPort := flag.String("port", ":50000", "Usage: -port <portnumber>") cmdState := flag.Int("state", 0, "Usage: -state <start-state>") flag.Parse() server := CreateServer(*cmdID, *cmdPort, *cmdState) // Exit channel keeps the program alive indefinitely exit := make(chan bool) // Tracking state of all declared servers server0 := CreateServer(0, ":50000", 0) server1 := CreateServer(1, ":50001", 0) server2 := CreateServer(2, ":50002", 0) server3 := CreateServer(3, ":50003", 0) server4 := CreateServer(4, ":50004", 0) servers := []*Server{server0,server1,server2,server3,server4} server.Servers = servers go Run(server) // Stay alive <-exit }
LIGHT1213/H750_TouchGFX
libraries/touchgfx_lib/TouchGFX/gui/src/heartline_screen/HeartLinePresenter.cpp
<filename>libraries/touchgfx_lib/TouchGFX/gui/src/heartline_screen/HeartLinePresenter.cpp #include <gui/heartline_screen/HeartLineView.hpp> #include <gui/heartline_screen/HeartLinePresenter.hpp> HeartLinePresenter::HeartLinePresenter(HeartLineView& v) : view(v) { } void HeartLinePresenter::activate() { } void HeartLinePresenter::deactivate() { } void HeartLinePresenter::UpDateHeartRateLine(int i) { view.UpDateHeartRateLine(i); }
saki9478/qqbot_to_osu
awesome/plugins/help/__init__.py
<gh_stars>0 # -*- coding: UTF-8 -*- import nonebot from nonebot import on_command, CommandSession import config from awesome.plugins.help import help_content from . import app @on_command('help_command', only_to_me=False, aliases=(config.HELP, config.HELP_UPPER)) async def help_func(session: CommandSession): """将数据发送给对方客户端""" # 因使用并非是pro版本,因此只能使用文字进行发送 bot = nonebot.get_bot() message_type = session.ctx['message_type'] # 消息类型 if message_type == "group": return await bot.send(context=session.ctx, message=help_content.HELP_CONTEXT)
wztlei/wathub
uwaterlooapi-library/src/main/java/com/deange/uwaterlooapi/model/watcard/Transaction.java
<gh_stars>1-10 package com.deange.uwaterlooapi.model.watcard; import com.deange.uwaterlooapi.model.AbstractModel; import com.google.auto.value.AutoValue; import java.math.BigDecimal; @AutoValue public abstract class Transaction extends AbstractModel { public abstract TransactionDate date(); public abstract BigDecimal amount(); public abstract Type type(); public abstract Vendor vendor(); public static Builder builder() { return new AutoValue_Transaction.Builder(); } @AutoValue.Builder public static abstract class Builder { public abstract Builder setDate(final TransactionDate date); public abstract Builder setAmount(final BigDecimal amount); public abstract Builder setType(final Type type); public abstract Builder setVendor(final Vendor vendor); public abstract Transaction build(); } @AutoValue public static abstract class Type extends AbstractModel { public abstract int code(); public abstract String category(); public static Type create(final int code, final String category) { return new AutoValue_Transaction_Type(code, category); } } @AutoValue public static abstract class Vendor extends AbstractModel { public abstract int code(); public abstract String category(); public static Vendor create(final int code, final String category) { return new AutoValue_Transaction_Vendor(code, category); } } }
lnx00/Fedoraware
Fedoraware/TeamFortress2/TeamFortress2/Hooks/Hooks.h
<gh_stars>10-100 #pragma once #include "../Utils/MinHook/MinHook.h" #include "../SDK/SDK.h" #include <stdexcept> //Credits go entirely to spook953 class CHook { std::string Name; void* OriginalFunction = nullptr; void* InitFunction = nullptr; public: CHook(const std::string& name, void* pInitFunction); void CreateHook(void* pTarget, void* pDetour) { if (MH_CreateHook(pTarget, pDetour, &OriginalFunction) != MH_OK) { throw std::runtime_error("Failed to create hook: " + Name); } } void DisableHook() { if (MH_DisableHook(OriginalFunction) != MH_OK) { throw std::runtime_error("Failed to disable hook: " + Name); } } void Init() { reinterpret_cast<void(__cdecl*)()>(InitFunction)(); } template <typename FN> FN Original() { return reinterpret_cast<FN>(OriginalFunction); } }; #define MAKE_HOOK(name, address, type, callconvo, ...) namespace Hooks \ {\ namespace name\ {\ void Initialize();\ inline CHook Hook(#name, Initialize); \ using FN = type(callconvo*)(__VA_ARGS__); \ type callconvo Detour(__VA_ARGS__); \ }\ } \ void Hooks::name::Initialize() { Hook.CreateHook(reinterpret_cast<void*>(address), Detour); } \ type callconvo Hooks::name::Detour(__VA_ARGS__)
afnanenayet/go-sdk
configutil/env.go
package configutil import ( "time" "github.com/blend/go-sdk/env" ) var ( _ StringSource = (*Env)(nil) _ BoolSource = (*Env)(nil) _ IntSource = (*Env)(nil) _ Float64Source = (*Env)(nil) _ DurationSource = (*Env)(nil) ) // Env is a value provider where the string represents the environment variable name. // It can be used with *any* config.Set___ type. type Env string // String returns a given environment variable as a string. func (e Env) String() (*string, error) { key := string(e) if env.Env().Has(key) { value := env.Env().String(key) return &value, nil } return nil, nil } // Strings returns a given environment variable as strings. func (e Env) Strings() ([]string, error) { key := string(e) if env.Env().Has(key) { return env.Env().CSV(key), nil } return nil, nil } // Bool returns a given environment variable as a bool. func (e Env) Bool() (*bool, error) { key := string(e) if env.Env().Has(key) { value := env.Env().Bool(key) return &value, nil } return nil, nil } // Int returns a given environment variable as an int. func (e Env) Int() (*int, error) { key := string(e) if env.Env().Has(key) { value, err := env.Env().Int(key) if err != nil { return nil, err } return &value, nil } return nil, nil } // Float64 returns a given environment variable as a float64. func (e Env) Float64() (*float64, error) { key := string(e) if env.Env().Has(key) { value, err := env.Env().Float64(key) if err != nil { return nil, err } return &value, nil } return nil, nil } // Duration returns a given environment variable as a time.Duration. func (e Env) Duration() (*time.Duration, error) { key := string(e) if env.Env().Has(key) { value, err := env.Env().Duration(key) if err != nil { return nil, err } return &value, nil } return nil, nil }
piotr-sobczyk/daily-work
src/main/java/org/dailywork/ui/state/InitialState.java
/* * Copyright (c) 2010-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.dailywork.ui.state; import java.awt.Component; import java.awt.Image; import javax.inject.Inject; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JLabel; import org.dailywork.resources.Images; import org.dailywork.ui.Window; public class InitialState extends UiStateSupport { public static final String INITIAL_PROJECT_NAME = "Select a project"; @Inject private Window window; @Inject private Images images; @Override protected String title() { return null; } @Override public void afterRendering() { window.setProjectName(INITIAL_PROJECT_NAME); super.afterRendering(); } @Override protected Component createContent() { Image image = images.tomato(); ImageIcon imageIcon = new ImageIcon(image); return new JLabel(imageIcon); } @Override protected Action[] primaryActions() { return new Action[] { }; } @Override protected Action[] secondaryActions() { return null; } }
pltod2/api-builder-extras
api-builder-plugin-fn-redis/src/index.js
const { createPluginWithContext, isDeveloperMode } = require('./utils'); const createRedisClient = require('./redis-client'); const actions = require('./actions'); /** * Resolves the API Builder plugin. * @returns {object} An API Builder plugin. */ async function getPlugin(pluginConfig, options) { let redisClient; try { // In production we should be able to connect on startup // in development mode we defer this until action is invoked redisClient = await createRedisClient({ pluginConfig, logger: options.logger }); } catch (ex) { options.logger.error( `Failed to connect to Redis server: ${pluginConfig.host}:${pluginConfig.port}. Make sure Redis server is running and conf/redis.default.js is configured` ); if (!isDeveloperMode()) { // In development mode we allow to defer the obtaining of successfull Redis connection. // The promise is rejected only in production. return Promise.reject(ex); } } // All you pass here will be set as context for your actions return createPluginWithContext(actions, { pluginContext: { redisClient }, pluginConfig }); } module.exports = getPlugin;
NilsRenaud/vert.x
src/test/java/io/vertx/core/impl/launcher/commands/ComplexCommand.java
/* * Copyright (c) 2011-2019 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.core.impl.launcher.commands; import io.vertx.core.cli.*; import io.vertx.core.cli.annotations.*; import io.vertx.core.cli.annotations.Argument; import io.vertx.core.cli.annotations.Option; import io.vertx.core.spi.launcher.DefaultCommand; @Summary("A command with options and arguments.") @Description("This is a complex command.") @Name("complex") public class ComplexCommand extends DefaultCommand { private String arg1; private int arg2; private String option1; private boolean option2; @Argument(index = 0, argName = "arg1") public void setArgument1(String arg1) { this.arg1 = arg1; } @Argument(index = 1, argName = "arg2", required = false) public void setArgument2(int arg2) { this.arg2 = arg2; } @Option( longName = "option1", shortName = "o1", argName = "opt", required = true ) public void setOption1(String option1) { this.option1 = option1; } @Option( longName = "option2", shortName = "o2", acceptValue = false, required = false, flag = true ) public void setOption2(boolean option2) { this.option2 = option2; } @Override public void run() throws CLIException { out.println("Option 1 : " + option1); out.println("Option 2 : " + option2); out.println("Arg 1 : " + arg1); out.println("Arg 2 : " + arg2); if (executionContext.commandLine().allArguments().size() > 2) { out.println("All args: " + executionContext.commandLine().allArguments()); } } }
niuchenglei/rankextor
src/Model/FMModel.h
<filename>src/Model/FMModel.h #ifndef FMMODEL_H #define FMMODEL_H #include <sstream> #include <time.h> //#include <sharelib/util/string_util.h> #include <boost/unordered_map.hpp> #include "Utilities/AdUtil.h" #include "Interfaces/ModelBase.h" namespace rank { class fm_coeff_t : public rank::Resource { public: virtual int Load(const std::string& config_file); virtual int GetValue(const std::string& key, std::string* value) { return 0; } virtual int GetValue(std::map<std::string, std::string>* key_value_map) { return 0; } std::map<uint64_t, float> mModelWeights; float mConstWeight; bool mHasConstWeightFlag; int mFactor; uint64_t mFeatureNum; private: std::string mModelFile; bool loadModel(); }; DEFINE_RESOURCE(fm_coeff_t); class FMModel : public ModelBase { public: OBJECT_CLASS(FMModel) FMModel(); ~FMModel(); bool Initialize(model_arg_t& arg, const std::map<std::string, ConditionBase*>& conditions, ResourceManager* resource_manager); bool Transform(const RankRequest& fisher_request, std::vector<RankAdInfo>& ad_list_for_rank, std::vector<RankItemInfo>& item_list_for_rank, RankDataContext& ptd); bool Predict(const RankRequest& fisher_request, std::vector<RankAdInfo>& ad_list_for_rank, std::vector<RankItemInfo>& item_list_for_rank, RankDataContext& ptd); bool Update(); const model_arg_t& getArgument() const { return mArg; }; private: model_arg_t mArg; fm_coeff_t* mpCoeff; std::string mModelDir, mResourceKey; float wTx(const vector<uint64_t>& feature, uint64_t feature_size, fm_coeff_t& model); //float* v1, float* v2, std::string& msg); //float wTx(const uint64_t* feature, uint64_t feature_size, fm_coeff_t& model, float* v1, float* v2, std::string& msg); }; } // namespace rank #endif
Elpis-Development/reactive-websockets
reactive-websockets/src/main/java/org/elpis/reactive/websockets/EnableReactiveSockets.java
<reponame>Elpis-Development/reactive-websockets package org.elpis.reactive.websockets; import org.elpis.reactive.websockets.config.WebSocketConfiguration; import org.springframework.context.annotation.Import; import java.lang.annotation.*; /** * Imports {@link WebSocketConfiguration} class * * @author <NAME> * @see org.springframework.context.annotation.Configuration * @since 0.1.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @Import(WebSocketConfiguration.class) public @interface EnableReactiveSockets { }
kcosta42/Multilayer_Perceptron
libft/losses/mean_squared_error.py
<filename>libft/losses/mean_squared_error.py import libft.backend.math as M from libft.losses.loss import Loss class MeanSquaredError(Loss): """Computes the mean of squares of errors between labels and predictions.""" def call(self, y_true, y_pred): return M.mean(M.square(y_pred - y_true), axis=-1) def gradient(self, y_true, y_pred): return -(y_true - y_pred)
citrum/log-server
log-server-client/src/com/github/winmain/logserver/client/LogWriterClient.scala
package com.github.winmain.logserver.client import java.io.DataOutputStream import java.lang.management.ManagementFactory import java.nio.file.{Files, Path, StandardOpenOption} import java.time.LocalDateTime import java.time.format.DateTimeFormatter import com.github.winmain.logserver.core.RecordId.{EmptyRecordId, IntRecordId, StringRecordId} import com.github.winmain.logserver.core.UInt29Writer.toUInt29WriterOps import com.github.winmain.logserver.core._ import org.slf4j.Logger import scala.annotation.tailrec /** * Клиент записи логов * * @param writeDir Каталог, где будут логи * @param savedFileFormat Формат сохранённых файлов * @param fileLifetimeMillis Время жизни "current" файла в мс * @param addProcessSuffix Добавлять к имени файла "current" id процесса? Актуально для крон-заданий. */ class LogWriterClient(writeDir: Path, savedFileFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'{suffix}.saved'"), fileLifetimeMillis: Long = 5 * 60 * 1000L, addProcessSuffix: Boolean = false, logger: Logger) { import LogWriterClient._ private val lock = new Object private var fileStream: DataOutputStream = _ private var fileEndWrite: Long = 0L private val currentFile = writeDir.resolve( if (addProcessSuffix) "current-" + ManagementFactory.getRuntimeMXBean.getName.split('@')(0) else "current") def append(normalizedTableName: String, timestamp: Long, log: String): Unit = append(normalizedTableName, RecordId.empty, timestamp, log) def append(normalizedTableName: String, id: Int, timestamp: Long, log: String): Unit = append(normalizedTableName, RecordId(id), timestamp, log) def append(normalizedTableName: String, id: String, timestamp: Long, log: String): Unit = append(normalizedTableName, RecordId(id), timestamp, log) def close(): Unit = { if (fileStream != null) { fileStream.close() renameFileToSaved(currentFile) } fileStream = null } // internal private def append(normalizedTableName: String, id: RecordId, timestamp: Long, log: String): Unit = { def writeStr(s: String): Unit = { val bytes = s.getBytes(LogServer.Charset) fileStream.writeUInt29(bytes.length) fileStream.write(bytes) } lock.synchronized { val time = System.currentTimeMillis() // file autorotate if (time >= fileEndWrite) { fileEndWrite = time + fileLifetimeMillis close() autoRenameOldUnclosedFiles(time) val file: Path = currentFile Files.createDirectories(file.getParent) if (!Files.exists(file)) Files.createFile(file) fileStream = new DataOutputStream(Files.newOutputStream(file, StandardOpenOption.APPEND)) fileStream.writeInt(LogServer.StorageVersion) } // write data writeStr(normalizedTableName) writeId(id) fileStream.writeLong(timestamp) writeStr(log) } } private def writeId(id: RecordId): Unit = id match { case id: IntRecordId => fileStream.writeByte(RecordId.IntIdMarker) fileStream.writeInt(id.value) case id: StringRecordId => fileStream.writeByte(RecordId.StringIdMarker) fileStream.writeUInt29(id.value.length) fileStream.write(id.value) case EmptyRecordId => fileStream.writeByte(RecordId.EmptyIdMarker) } /** * Переименовать текущий файл логов в сохранённый. Учитывается коллизия имён, и подбирается * имя файла, который не существует на данный момент. * * @param path Файл, который следует переименовать. */ private def renameFileToSaved(path: Path): Unit = { val dateTime: LocalDateTime = LocalDateTime.now() @tailrec def findFileToSave(suffixIdx: Int): Path = { var name: String = savedFileFormat.format(dateTime) name = name.replace("{suffix}", if (suffixIdx > 0) "-" + suffixIdx else "") val file = writeDir.resolve(name) if (Files.exists(file)) findFileToSave(suffixIdx + 1) else file } Files.move(path, findFileToSave(0)) } /** * Автоматически переименовать все current-файлы в каталоге в saved. * Это действие надо выполнять для случаев внезапной остановки сервера, чтобы лог-файлы не оставались * не сохранёнными. */ private def autoRenameOldUnclosedFiles(now: Long): Unit = { if (Files.exists(writeDir) && Files.isDirectory(writeDir)) { Files.list(writeDir) .filter(_.getFileName.toString.startsWith("current")) .forEach { path => logger.warn("Saving lost log file: " + path.toString) renameFileToSaved(path) } } } } object LogWriterClient { implicit val dataOutputStreamUInt29Writer: UInt29Writer[DataOutputStream] = _.writeByte(_) }
shammishailaj/slashdeploy
lib/tasks/brakeman.rake
namespace :brakeman do desc 'Run Brakeman' task :run do |t| require 'brakeman' Brakeman.run app_path: '.', print_report: true end end
Zardoz89/dcpu_vm
src/dcpu-vm.cpp
<reponame>Zardoz89/dcpu_vm<filename>src/dcpu-vm.cpp #include <iostream> #include <cstdint> #include <algorithm> #include <memory> #include <vector> #include <cstdio> #include <chrono> #include <cmath> #include "config.hpp" // Machine core #include <dcpu/dcpu_opcodes.hpp> #include <dcpu/dcpu.hpp> // Devices #include <dcpu/devices.hpp> // Modules that sues SFML #include <sfml/square_gen.hpp> #include <sfml/KeyboardWindow.hpp> #include <sfml/MonitorWindow.hpp> // Util #include <dcpu/disassembler.hpp> #include <binasm.hpp> #include <tinyxml2/tinyxml2.h> #define FRAMERATE 50 using namespace cpu; // Containers of devices and windows std::vector<std::shared_ptr<AbstractMonitor>> monitors; std::vector<std::shared_ptr<windows::AbstractWindow>> wins; std::vector<std::shared_ptr<m35fd::M35FD>> fdrives; std::vector<std::shared_ptr<m35fd::M35_Floppy>> floppies; std::vector<std::string> floppy_files; std::vector<std::shared_ptr<sf::SoundStream>> sound_streams; auto dcpu = std::make_shared<DCPU>(); bool custom_loadout = false; /// Use a custom loadout bool no_sound=false; /// Disable audio/Speaker // Process loadout from a XML document void process_loadout_xml(tinyxml2::XMLDocument& doc, bool devkit = false); void print_help(std::string program_name) { using namespace std; cout << _PRG_NAME << " " << _VERSION << std::endl; cout << "usage : " << program_name << " [-options] <dcpu16-exe>"; cout << endl; cout << "--------------------------------------------------------"; cout << endl; cout << " options:"; cout << endl; cout << " -assemble (-a) : assemble before load (experimental)"; cout << endl; cout << " -output <filename> (-o) : output assembled filename"; cout << endl; cout << " -debug (-d) : start in debug mode"; cout << endl; cout << " F1 : next step"; cout << endl; cout << " F2 : print CPU status"; cout << endl; cout << " F3 : reset (no need debug mode)"; cout << endl; cout << " F4 : dump the ram"; cout << endl; cout << " F9 : ejects/inserts floppy"; cout << endl; cout << " F10 : switch debug/run"; cout << endl; cout << " -time (-t) : use timed emulation (else refresh based)"; cout << endl; cout << " -vsync (-v) : use vertical synchronisation"; cout << endl; cout << " (more accurate but may bug)"; cout << endl; cout << " Hardware loadout options:"; cout << endl; cout << " -loadout (-l) : XML file that descrives hardware loadout. If isn't using"; cout << endl << " a loadout file, then a default loadout will be used. The default"; cout << endl << " loadout contains a generic clock, a generic keyboard, a monitor,"; cout << endl << " a floppy drive and a sound speaker."; cout << endl << " The next options will be used to change the default loadout of"; cout << endl << " the virtual machine."; cout << endl; cout << " --monitor=<monitor_name> : use the following monitor"; cout << endl; cout << " 1802 -> Lem1802 (default) [c] (-1802)"; cout << endl; cout << " 1803 -> Lem1803 [c] (-1803)"; cout << endl; cout << " cgm -> Colour Graphics Monitor (-cgm)"; cout << endl; cout << " [c] : compatible with Lem1802 0x10c programs"; cout << endl; cout << " --no-sound : disable the sound speaker device"; cout << endl; cout << " -floppy <filenames...> (-fd) : floppy image files"; cout << endl; } int main (int argc, char **argv) { // TODO Debug level should be set at compile time, or have a hidden program // option to set this, like the -v -vv -vvv flags logger::LOG_level = logger::LogLevel::INFO; std::string filename; std::string loadout_filename; std::string outname="a.out"; //output assembled filename int monitor_type=0; bool debug=false; //use vsync for refresh the screen (more accurate than setFrameLimit) bool use_vsync=false; //use time emulation based on sf::Clock; bool use_time=false; //need assemble the file bool assemble=false; //TODO make a function that parse argument into a program struct for (int k=1; k < argc; k++) { //parse arguments std::string disk_filename; if (argv[k][0] == '-') { std::string opt = argv[k]; if (opt=="--help"||opt=="-help"||opt=="-h") { std::string pn = argv[0]; pn.erase(0,pn.find_last_of('\\')+1); //windows pn.erase(0,pn.find_last_of('/')+1); //linux print_help(pn); return 0; } else if (opt=="-debug") debug=true; else if (opt=="-1802"||opt=="--monitor=1802") monitor_type=0; else if (opt=="-1803"||opt=="--monitor=1803") monitor_type=1; else if (opt=="-cgm"||opt=="--monitor=cgm") monitor_type=2; else if (opt.find("--monitor") != std::string::npos) { LOG_WARN << "Unknow monitor type " + opt; } else if (opt=="--no-sound") { no_sound=true; } else if (opt == "-vsync" || opt == "-v") use_vsync=true; else if (opt == "-time" || opt == "-t") use_time=true; else if (opt == "-assemble" || opt == "-a") assemble=true; else if ((opt == "-output" || opt == "-o") && argc > k+1) { assemble=true; outname = argv[++k]; } else if (opt == "-output" || opt == "-o") { LOG_WARN << "Option " + opt + " requierd another argument it will be ignored here"; } else if ((opt == "-floppy" || opt == "-fd") && argc >= k+1) { k++; do { disk_filename = argv[k]; if (disk_filename[0] == '-') break; floppy_files.push_back(disk_filename); } while (++k < argc); } else if (opt == "-floppy" || opt == "-fd") { LOG_WARN << "Option " + opt + " requierd another argument it will be ignored here"; } else if ((opt == "-loadout" || opt == "-l") && argc > k+1) { loadout_filename = argv[++k]; } else if (opt == "-loadout" || opt == "-l") { LOG_WARN << "Option " + opt + " requierd another argument it will be ignored here"; } else { LOG_WARN << "Unknow option " + opt + " it will be ignored !"; } } else { filename = argv[k]; } } // Find extension of input file auto ext_pos= filename.rfind("."); if (ext_pos != std::string::npos) { auto extension = filename.substr(ext_pos); if (extension == ".dasm" || extension == ".asm" || extension == ".dasm16" || extension == ".10c") { // Assembly files assemble = true; } } tinyxml2::XMLDocument xml; // Loadout from XML file if (loadout_filename.size() > 0) { auto ext_pos= loadout_filename.rfind("."); bool devkit = false; if (ext_pos != std::string::npos) { auto extension = loadout_filename.substr(ext_pos); if (extension == ".10csln") { devkit = true; } } // XML loadout of devices if (xml.LoadFile(loadout_filename.c_str()) == tinyxml2::XML_NO_ERROR) { process_loadout_xml(xml, devkit); } } if (assemble) { BinAsm assembler; if (!assembler.load(filename)) return 0xdead; if (!assembler.assemble()) return 0xdead; if (!assembler.resolve_labels()) return 0xdead; if (!assembler.save(outname)) return 0xdead; filename = outname; } if (argc <= 1 || !filename.size()) { LOG_ERROR << "Missing input file, type --help for list options"; return 0; } // Default laodout if (!custom_loadout) { LOG << "Loading devices. Using default loadout"; std::string window_title="dcpu_vm"; auto gclock = std::make_shared<Generic_Clock>(); dcpu->attachHardware (gclock); // Generic Keyboard auto gkeyboard = std::make_shared<keyboard::GKeyboard>(); dcpu->attachHardware (gkeyboard); auto keyb_win = std::make_shared<windows::KeyboardWindow>(gkeyboard); wins.push_back(keyb_win); // Prepare the speaker device auto speaker = std::make_shared<speaker::Speaker>(); if (!no_sound) { dcpu->attachHardware (speaker); auto gen = std::make_shared<audio::SquareGenerator>(); sound_streams.push_back(gen); gen->prepare(); gen->play(); speaker->setFreqCallback(audio::SquareGenerator::WrappeCallback, (void*)gen.get()); } // Floppy drive auto fd = std::make_shared<m35fd::M35FD>(); fdrives.push_back(fd); dcpu->attachHardware (fd); std::string fname = "disk.dsk"; if (!floppy_files.empty()) fname = floppy_files.front(); auto floppy = std::make_shared<m35fd::M35_Floppy>(fname); floppies.push_back(floppy); // Sets appropriated monitor std::shared_ptr<AbstractMonitor> monitor; auto splash_file = "assets/lem_splash.png"; switch (monitor_type) { case 1: monitor=std::make_shared<lem::Lem1803>(); LOG << "use Lem1803 Monitor"; window_title = "Lem 1803"; break; case 2: monitor=std::make_shared<cgm::CGM>(); LOG << "use CGM Monitor"; window_title = "CGM"; splash_file = "assets/cgm_splash.png"; break; default : monitor=std::make_shared<lem::Lem1802>(); LOG << "use Lem1802 Monitor"; window_title = "Lem 1802"; break; } dcpu->attachHardware (monitor); monitors.push_back(monitor); auto window = std::make_shared<windows::MonitorWindow>(monitor, window_title, FRAMERATE); wins.push_back(window); window->setSplashImage(splash_file); } LOG << "Number of floppy images files: " << floppies.size(); if (use_vsync) { LOG_WARN << "vsync activated may bug"; for (auto it = wins.begin(); it != wins.end(); ++it) { (*it)->setVerticalSyncEnabled(true); } } dcpu->reset(); dcpu->loadProgramFromFile(filename); LOG << "Entering main loop"; sf::Clock clock; unsigned long ticks_counter = 0; bool pressed_key = false; // Used to emulate keyDown event bool is_open = true; bool have_focus; while (is_open) { have_focus = false; // Does all windows stuff for (auto it = wins.begin(); it != wins.end(); ++it) { is_open = is_open && (*it)->isOpen(); have_focus = have_focus || (*it)->haveFocus(); (*it)->handleEvents(); (*it)->display(); } // Checks general keyboard events if (have_focus) { if (debug && sf::Keyboard::isKeyPressed (sf::Keyboard::F1)) { if (!pressed_key ) { std::cout << disassembly(dcpu->getMem() +dcpu->getPC(),3); std::cout << std::endl; dcpu->step(); } pressed_key = true; } else if (debug && sf::Keyboard::isKeyPressed (sf::Keyboard::F2)) { if (!pressed_key ) { printf("A : 0x%04X | B : 0x%04X | C : 0x%04X\n", dcpu->getA(),dcpu->getB(),dcpu->getC()); printf("X : 0x%04X | Y : 0x%04X | Z : 0x%04X\n", dcpu->getX(),dcpu->getY(),dcpu->getZ()); printf("I : 0x%04X | J : 0x%04X | IA: 0x%04X\n", dcpu->getI(),dcpu->getJ(),dcpu->getIA()); printf("PC: 0x%04X | SP: 0x%04X | EX: 0x%04X\n", dcpu->getPC(),dcpu->getSP(),dcpu->getEX()); if (dcpu->isQueueing()) printf("Interrupts being push to the queue\n"); if (dcpu->getOnFire()) printf("Catch Fire!\n"); } pressed_key = true; } else if (sf::Keyboard::isKeyPressed (sf::Keyboard::F3)) { if (!pressed_key ) { LOG << "Reset dcpu"; dcpu->reset(); dcpu->loadProgramFromFile(filename); } pressed_key = true; } else if (sf::Keyboard::isKeyPressed (sf::Keyboard::F4)) { if (!pressed_key ) { LOG << "Ram dumped in \"ram_dump:\""; FILE* f=fopen("ram_dump","wb"); fwrite((const char*) dcpu->getMem(),1,cpu::RAM_SIZE*2,f); fclose(f); } pressed_key = true; } else if (sf::Keyboard::isKeyPressed (sf::Keyboard::F9)) { if (!pressed_key ) { int fd_count = 0; // TODO: We need a more powerfull way to handle this // A manager or similar for (auto it = fdrives.begin(); it != fdrives.end(); ++it){ if ((*it)->getState() == m35fd::STATE_CODES::NO_MEDIA && !floppies.empty()) { (*it)->insertFloppy( floppies.at(fd_count++)); } else { (*it)->eject(); } } } pressed_key = true; } else if (sf::Keyboard::isKeyPressed (sf::Keyboard::F10)) { if (!pressed_key ) { debug = !debug; if (debug) LOG << "Debug mode activated"; else LOG << "Debug mode deactivated"; } pressed_key = true; } else { pressed_key = false; } } // DCPU emulation stuff ----------------------------------------------- for (auto it = monitors.begin(); it != monitors.end(); ++it) { (*it)->prepareRender(); } // T period of a 100KHz signal = 10 microseconds const auto delta=clock.getElapsedTime().asMicroseconds(); clock.restart(); if (!debug) { unsigned int tick_needed; double tmp; if (use_time) { tmp = delta / 10.0f; //trash fix Visual don't know the function round lol! } else { tmp = dcpu->getClock() / (double)(FRAMERATE); } tick_needed= (unsigned int)(tmp+0.5); ticks_counter += tick_needed; // Outputs every second (if runs to ~100% of speed) if (ticks_counter > 100000) { ticks_counter -= 100000; //std::cerr << "Delta: " << delta << " ms "; //std::cerr << "Ticks: " << tick_needed << " "; //double tmp = tick_needed*(1 / (double)(dcpu->getClock())); //int64_t rtime = 1000000 * tmp; //std::cerr << "Speed: " << (float)(100*delta)/rtime << std::endl; } dcpu->tick(tick_needed); } } // Stops audio generator/streams for (auto it = sound_streams.begin(); it != sound_streams.end(); ++it){ (*it)->stop(); } return 0; } void process_loadout_xml(tinyxml2::XMLDocument& doc, bool devkit) { using namespace tinyxml2; const XMLNode* node = NULL; LOG << "Parsing XML file. DevKit solution: " << devkit ; if (devkit) { // Finds the first loadout element node = doc.FirstChildElement("solution"); if (node == NULL) { LOG_WARN << "Invalid DevKit solution file." << "Trying parse as XML loadout file"; devkit = false; // Try to parse as normal XML node = doc.FirstChildElement("loadout"); if (node == NULL) { LOG_WARN << "Invalid loadout file."; return; } goto end_devkit; // Try to parse as normal XML } node = node->FirstChildElement("loadout"); if (node == NULL) { LOG_WARN << "Invalid DevKit solution file."; return; } node = node->FirstChildElement("loadout"); if (node == NULL) { LOG_WARN << "Invalid DevKit solution file."; return; } end_devkit: ; } else { node = doc.FirstChildElement("loadout"); if (node == NULL) { LOG_WARN << "Invalid loadout file."; return; } } // Node points to <loadout> node = node->FirstChildElement("hardware"); if (node == NULL) { LOG_WARN << "Invalid loadout file."; return; } std::string defname = "disk"; unsigned fd_counter = 0; for ( auto dev = node->FirstChildElement(); dev != NULL; dev = dev->NextSiblingElement()) { std::string name = dev->Name(); if (name != "device") continue; if (dev->Attribute("type", "GenericClock")) { auto gclock = std::make_shared<Generic_Clock>(); dcpu->attachHardware (gclock); } else if (dev->Attribute("type", "GenericKeyboard")) { auto gkeyboard = std::make_shared<keyboard::GKeyboard>(); dcpu->attachHardware (gkeyboard); auto keyb_win = std::make_shared<windows::KeyboardWindow>(gkeyboard); wins.push_back(keyb_win); // Monitors ----------------------------------------------------------- } else if (dev->Attribute("type", "LEM1802")) { auto monitor = std::make_shared<lem::Lem1802>(); dcpu->attachHardware (monitor); monitors.push_back(monitor); auto window = std::make_shared<windows::MonitorWindow>(monitor, "LEM 1802", FRAMERATE); wins.push_back(window); window->setSplashImage("assets/lem_splash.png"); } else if (dev->Attribute("type", "LEM1803")) { auto monitor = std::make_shared<lem::Lem1803>(); dcpu->attachHardware (monitor); monitors.push_back(monitor); auto window = std::make_shared<windows::MonitorWindow>(monitor, "LEM 1803", FRAMERATE); wins.push_back(window); window->setSplashImage("assets/lem_splash.png"); } else if (dev->Attribute("type", "CGM1084")) { auto monitor = std::make_shared<cgm::CGM >(); dcpu->attachHardware (monitor); monitors.push_back(monitor); auto window = std::make_shared<windows::MonitorWindow>(monitor, "CGM 1084", FRAMERATE); wins.push_back(window); window->setSplashImage("assets/cgm_splash.png"); // Audio -------------------------------------------------------------- } else if (dev->Attribute("type", "SimpleSpeaker")) { auto speaker = std::make_shared<speaker::Speaker>(); dcpu->attachHardware (speaker); if (!no_sound) { auto gen = std::make_shared<audio::SquareGenerator>(); sound_streams.push_back(gen); gen->prepare(); gen->play(); speaker->setFreqCallback( audio::SquareGenerator::WrappeCallback, (void*)gen.get() ); } // Storage ------------------------------------------------------------ } else if (dev->Attribute("type", "M35FD")) { auto fd = std::make_shared<m35fd::M35FD>(); fdrives.push_back(fd); dcpu->attachHardware (fd); std::string fname; if (floppy_files.size() <= fd_counter) { char tmp[10]; // Generates filename "diskX.dsk" std::string fname = defname; snprintf(tmp, 10, "%u", fd_counter); fname.append(tmp); fname.append(".dsk"); LOG << fname; auto floppy = std::make_shared<m35fd::M35_Floppy>(fname); floppies.push_back(floppy); } else { fname = floppy_files.front(); auto floppy = std::make_shared<m35fd::M35_Floppy>(fname); floppies.push_back(floppy); } fd_counter++; } } LOG << "Custom loadout"; custom_loadout = true; }
willylee007/openvidu
openvidu-test/src/main/java/io/openvidu/test/config/RoomTestConfiguration.java
<reponame>willylee007/openvidu<filename>openvidu-test/src/main/java/io/openvidu/test/config/RoomTestConfiguration.java<gh_stars>1-10 /* * (C) Copyright 2017-2019 OpenVidu (https://openvidu.io/) * * 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.openvidu.test.config; import static org.kurento.test.config.TestConfiguration.KMS_WS_URI_DEFAULT; import static org.kurento.test.config.TestConfiguration.KMS_WS_URI_PROP; /** * Kurento Room test properties. * * @author <NAME> (<EMAIL>) * @since 6.2.1 */ public class RoomTestConfiguration { public static final String ROOM_APP_CLASSNAME_PROP = "room.app.classnames"; public static final String ROOM_APP_CLASSNAME_DEFAULT = "[org.kurento.room.basic.KurentoRoomBasicApp," + "org.kurento.room.demo.KurentoRoomDemoApp]"; public static final String EXTRA_KMS_WS_URI_PROP = KMS_WS_URI_PROP + ".extra"; public static final String EXTRA_KMS_WS_URI_DEFAULT = KMS_WS_URI_DEFAULT; public static final String ROOM_PREFIX = "room"; public static final String USER_BROWSER_PREFIX = "browser"; public static final String USER_FAKE_PREFIX = "user"; public static final String DEFAULT_ROOM = ROOM_PREFIX; public final static int DEFAULT_ROOM_INOUT_AWAIT_TIME_IN_SECONDS = 60; public final static int DEFAULT_ACTIVE_LIVE_TOTAL_TIMEOUT_IN_SECONDS = 60; public final static int DEFAULT_PLAY_TIME_IN_SECONDS = 30; public static final int TASKS_TIMEOUT_IN_MINUTES = 15; }
pitfire4653/learning
src/project/Wvsiqhta.java
package project; public class Wvsiqhta { String message = "Wvsiqhta"; public Wvsiqhta() { super(); } public void speak() { System.out.println(message); } }
lucaspereirag/pythonProject
ex016.py
<reponame>lucaspereirag/pythonProject<gh_stars>0 import math catoposto = float(input('Digite o valor do Cateto Oposto: ')) catadj = float(input('Digite o valor do Cateto Adjacente: ')) hipotenusa = math.hypot(catoposto, catadj) print('O valor da Hipotenusa é {:.2f}'.format(hipotenusa))
oroca/oroca_boy3
emulator/emul_doom/src/ap/doom/i_midipipe.c
<reponame>oroca/oroca_boy3 // // Copyright(C) 2013 <NAME> et al. // Copyright(C) 2017 <NAME> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program 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. // // DESCRIPTION: // Client Interface to Midi Server // #if _WIN32 #include <stdlib.h> #include <sys/stat.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "i_midipipe.h" #include "config.h" #include "i_sound.h" #include "i_timer.h" #include "m_misc.h" #include "net_packet.h" #include "../midiproc/proto.h" #if defined(_DEBUG) #define DEBUGOUT(s) puts(s) #else #define DEBUGOUT(s) #endif //============================================================================= // // Public Data // // True if the midi proces was initialized at least once and has not been // explicitly shut down. This remains true if the server is momentarily // unreachable. boolean midi_server_initialized = false; // True if the current track is being handled via the MIDI server. boolean midi_server_registered = false; //============================================================================= // // Data // #define MIDIPIPE_MAX_WAIT 1000 // Max amount of ms to wait for expected data. static HANDLE midi_process_in_reader; // Input stream for midi process. static HANDLE midi_process_in_writer; static HANDLE midi_process_out_reader; // Output stream for midi process. static HANDLE midi_process_out_writer; //============================================================================= // // Private functions // // // FreePipes // // Free all pipes in use by this module. // static void FreePipes() { if (midi_process_in_reader != NULL) { CloseHandle(midi_process_in_reader); midi_process_in_reader = NULL; } if (midi_process_in_writer != NULL) { CloseHandle(midi_process_in_writer); midi_process_in_writer = NULL; } if (midi_process_out_reader != NULL) { CloseHandle(midi_process_out_reader); midi_process_in_reader = NULL; } if (midi_process_out_writer != NULL) { CloseHandle(midi_process_out_writer); midi_process_out_writer = NULL; } } // // UsingNativeMidi // // Enumerate all music decoders and return true if NATIVEMIDI is one of them. // // If this is the case, using the MIDI server is probably necessary. If not, // we're likely using Timidity and thus don't need to start the server. // static boolean UsingNativeMidi() { int i; int decoders = Mix_GetNumMusicDecoders(); for (i = 0; i < decoders; i++) { if (strcmp(Mix_GetMusicDecoder(i), "NATIVEMIDI") == 0) { return true; } } return false; } // // WritePipe // // Writes packet data to the subprocess' standard in. // static boolean WritePipe(net_packet_t *packet) { DWORD bytes_written; BOOL ok = WriteFile(midi_process_in_writer, packet->data, packet->len, &bytes_written, NULL); return ok; } // // ExpectPipe // // Expect the contents of a packet off of the subprocess' stdout. If the // response is unexpected, or doesn't arrive within a specific amuont of time, // assume the subprocess is in an unknown state. // static boolean ExpectPipe(net_packet_t *packet) { int start; BOOL ok; CHAR pipe_buffer[8192]; DWORD pipe_buffer_read = 0; if (packet->len > sizeof(pipe_buffer)) { // The size of the packet we're expecting is larger than our buffer // size, so bail out now. return false; } start = I_GetTimeMS(); do { // Wait until we see exactly the amount of data we expect on the pipe. ok = PeekNamedPipe(midi_process_out_reader, NULL, 0, NULL, &pipe_buffer_read, NULL); if (!ok) { break; } else if (pipe_buffer_read < packet->len) { I_Sleep(1); continue; } // Read precisely the number of bytes we're expecting, and no more. ok = ReadFile(midi_process_out_reader, pipe_buffer, packet->len, &pipe_buffer_read, NULL); if (!ok || pipe_buffer_read != packet->len) { break; } // Compare our data buffer to the packet. if (memcmp(packet->data, pipe_buffer, packet->len) != 0) { break; } return true; // Continue looping as long as we don't exceed our maximum wait time. } while (I_GetTimeMS() - start <= MIDIPIPE_MAX_WAIT); // TODO: Deal with the wedged process? return false; } // // RemoveFileSpec // // A reimplementation of PathRemoveFileSpec that doesn't bring in Shlwapi // void RemoveFileSpec(TCHAR *path, size_t size) { TCHAR *fp = NULL; fp = &path[size]; while (path <= fp && *fp != DIR_SEPARATOR) { fp--; } *(fp + 1) = '\0'; } //============================================================================= // // Protocol Commands // // // I_MidiPipe_RegisterSong // // Tells the MIDI subprocess to load a specific filename for playing. This // function blocks until there is an acknowledgement from the server. // boolean I_MidiPipe_RegisterSong(char *filename) { boolean ok; net_packet_t *packet; packet = NET_NewPacket(64); NET_WriteInt16(packet, MIDIPIPE_PACKET_TYPE_REGISTER_SONG); NET_WriteString(packet, filename); ok = WritePipe(packet); NET_FreePacket(packet); midi_server_registered = false; if (!ok) { DEBUGOUT("I_MidiPipe_RegisterSong failed"); return false; } packet = NET_NewPacket(2); NET_WriteInt16(packet, MIDIPIPE_PACKET_TYPE_REGISTER_SONG_ACK); ok = ExpectPipe(packet); NET_FreePacket(packet); if (!ok) { DEBUGOUT("I_MidiPipe_RegisterSong ack failed"); return false; } midi_server_registered = true; DEBUGOUT("I_MidiPipe_RegisterSong succeeded"); return true; } // // I_MidiPipe_SetVolume // // Tells the MIDI subprocess to set a specific volume for the song. // void I_MidiPipe_SetVolume(int vol) { boolean ok; net_packet_t *packet; packet = NET_NewPacket(6); NET_WriteInt16(packet, MIDIPIPE_PACKET_TYPE_SET_VOLUME); NET_WriteInt32(packet, vol); ok = WritePipe(packet); NET_FreePacket(packet); if (!ok) { DEBUGOUT("I_MidiPipe_SetVolume failed"); return; } DEBUGOUT("I_MidiPipe_SetVolume succeeded"); } // // I_MidiPipe_PlaySong // // Tells the MIDI subprocess to play the currently loaded song. // void I_MidiPipe_PlaySong(int loops) { boolean ok; net_packet_t *packet; packet = NET_NewPacket(6); NET_WriteInt16(packet, MIDIPIPE_PACKET_TYPE_PLAY_SONG); NET_WriteInt32(packet, loops); ok = WritePipe(packet); NET_FreePacket(packet); if (!ok) { DEBUGOUT("I_MidiPipe_PlaySong failed"); return; } DEBUGOUT("I_MidiPipe_PlaySong succeeded"); } // // I_MidiPipe_StopSong // // Tells the MIDI subprocess to stop playing the currently loaded song. // void I_MidiPipe_StopSong() { boolean ok; net_packet_t *packet; packet = NET_NewPacket(2); NET_WriteInt16(packet, MIDIPIPE_PACKET_TYPE_STOP_SONG); ok = WritePipe(packet); NET_FreePacket(packet); midi_server_registered = false; if (!ok) { DEBUGOUT("I_MidiPipe_StopSong failed"); return; } DEBUGOUT("I_MidiPipe_StopSong succeeded"); } // // I_MidiPipe_ShutdownServer // // Tells the MIDI subprocess to shutdown. // void I_MidiPipe_ShutdownServer() { boolean ok; net_packet_t *packet; packet = NET_NewPacket(2); NET_WriteInt16(packet, MIDIPIPE_PACKET_TYPE_SHUTDOWN); ok = WritePipe(packet); NET_FreePacket(packet); FreePipes(); midi_server_initialized = false; if (!ok) { DEBUGOUT("I_MidiPipe_ShutdownServer failed"); return; } DEBUGOUT("I_MidiPipe_ShutdownServer succeeded"); } //============================================================================= // // Public Interface // // // I_MidiPipeInitServer // // Start up the MIDI server. // boolean I_MidiPipe_InitServer() { TCHAR dirname[MAX_PATH + 1]; DWORD dirname_len; char *module = NULL; char *cmdline = NULL; char snd_samplerate_buf[8]; SECURITY_ATTRIBUTES sec_attrs; PROCESS_INFORMATION proc_info; STARTUPINFO startup_info; BOOL ok; if (!UsingNativeMidi() || strlen(snd_musiccmd) > 0) { // If we're not using native MIDI, or if we're playing music through // an exteranl program, we don't need to start the server. return false; } // Get directory name memset(dirname, 0, sizeof(dirname)); dirname_len = GetModuleFileName(NULL, dirname, MAX_PATH); if (dirname_len == 0) { return false; } RemoveFileSpec(dirname, dirname_len); // Define the module. module = PROGRAM_PREFIX "midiproc.exe"; // Define the command line. Version and Sample Rate follow the // executable name. M_snprintf(snd_samplerate_buf, sizeof(snd_samplerate_buf), "%d", snd_samplerate); cmdline = M_StringJoin(module, " \"" PACKAGE_STRING "\"", " ", snd_samplerate_buf, NULL); // Set up pipes memset(&sec_attrs, 0, sizeof(SECURITY_ATTRIBUTES)); sec_attrs.nLength = sizeof(SECURITY_ATTRIBUTES); sec_attrs.bInheritHandle = TRUE; sec_attrs.lpSecurityDescriptor = NULL; if (!CreatePipe(&midi_process_in_reader, &midi_process_in_writer, &sec_attrs, 0)) { DEBUGOUT("Could not initialize midiproc stdin"); return false; } if (!SetHandleInformation(midi_process_in_writer, HANDLE_FLAG_INHERIT, 0)) { DEBUGOUT("Could not disinherit midiproc stdin"); return false; } if (!CreatePipe(&midi_process_out_reader, &midi_process_out_writer, &sec_attrs, 0)) { DEBUGOUT("Could not initialize midiproc stdout/stderr"); return false; } if (!SetHandleInformation(midi_process_out_reader, HANDLE_FLAG_INHERIT, 0)) { DEBUGOUT("Could not disinherit midiproc stdin"); return false; } // Launch the subprocess memset(&proc_info, 0, sizeof(proc_info)); memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(startup_info); startup_info.hStdInput = midi_process_in_reader; startup_info.hStdOutput = midi_process_out_writer; startup_info.dwFlags = STARTF_USESTDHANDLES; ok = CreateProcess(TEXT(module), TEXT(cmdline), NULL, NULL, TRUE, 0, NULL, dirname, &startup_info, &proc_info); if (!ok) { FreePipes(); free(cmdline); return false; } // Since the server has these handles, we don't need them anymore. CloseHandle(midi_process_in_reader); midi_process_in_reader = NULL; CloseHandle(midi_process_out_writer); midi_process_out_writer = NULL; midi_server_initialized = true; return true; } #endif
GazeUI/SpringBoot
src/main/java/io/gazeui/Label.java
// // Copyright (c) 2019-2020 <NAME> (<EMAIL>) // Licensed under the MIT license. See LICENSE file in the project root for full license information. // package io.gazeui; import java.util.Optional; public class Label extends Control { private String text; public Label() { } public Label(String text) { this.setText(text); } public String getText() { return this.text; } public void setText(String text) { this.text = text; } @Override protected void renderCreation(RenderScriptWriter writer) { writer.format("let %s = document.createElement('span');\n", this.getClientId().get()); writer.format("%1$s.id = '%1$s';\n", this.getClientId().get()); // According to the MDN website¹: // // There is still a security risk whenever you use innerHTML to set strings over which you // have no control [...]. For that reason, it is recommended that you do not use innerHTML // when inserting plain text; instead, use Node.textContent. This doesn't parse the passed // content as HTML, but instead inserts it as raw text. // // [1]: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML if (this.getText() != null && !this.getText().isEmpty()) { // TODO: JavaScript escape writer.format("%s.textContent = '%s';\n", this.getClientId().get(), this.getText()); } } @Override protected void renderUpdate(RenderScriptWriter writer, Control previousControlState) { Label previousLabel = (Label)previousControlState; String currentText = Optional.ofNullable(this.getText()).orElse(""); String previousText = Optional.ofNullable(previousLabel.getText()).orElse(""); if (!currentText.equals(previousText)) { writer.print(this.selectionScript()); // TODO: JavaScript escape writer.format("%s.textContent = '%s';\n", this.getClientId().get(), currentText); } } }
GlobalFinPrint/global_finprint
global_finprint/annotation/migrations/0063_new_features.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2018-09-20 17:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('annotation', '0062_test1'), ] operations = [ migrations.AlterField( model_name='animalobservation', name='sex', field=models.CharField(choices=[('U', 'Unknown'), ('F', 'Female'), ('M', 'Male')], default='U', max_length=1), ), migrations.AlterField( model_name='masteranimalobservation', name='sex', field=models.CharField(choices=[('U', 'Unknown'), ('F', 'Female'), ('M', 'Male')], default='U', max_length=1), ), ]
vontikov/stoa
internal/gateway/server_mutex.go
<gh_stars>1-10 package gateway import ( "context" "time" "github.com/golang/protobuf/proto" "github.com/vontikov/stoa/pkg/pb" ) func (s *server) MutexTryLock(ctx context.Context, v *pb.ClientId) (*pb.Result, error) { if err := v.Validate(); err != nil { return nil, err } msg := pb.ClusterCommand{ Command: pb.ClusterCommand_MUTEX_TRY_LOCK, Payload: &pb.ClusterCommand_ClientId{ClientId: v}, } if err := processMetadata(ctx, &msg); err != nil { return nil, err } if msg.BarrierEnabled { fut := s.cluster.Raft().Barrier(time.Duration(msg.BarrierMillis) * time.Millisecond) if err := fut.Error(); err != nil { return nil, err } } cmd, err := proto.Marshal(&msg) if err != nil { return nil, err } fut := s.cluster.Raft().Apply(cmd, 0) if err := fut.Error(); err != nil { return nil, wrapError(err) } if r, ok := fut.Response().(*pb.Result); ok { return r, nil } panic(ErrIncorrectResponseType) } func (s *server) MutexUnlock(ctx context.Context, v *pb.ClientId) (*pb.Result, error) { if err := v.Validate(); err != nil { return nil, err } msg := pb.ClusterCommand{ Command: pb.ClusterCommand_MUTEX_UNLOCK, Payload: &pb.ClusterCommand_ClientId{ClientId: v}, } if err := processMetadata(ctx, &msg); err != nil { return nil, err } if msg.BarrierEnabled { fut := s.cluster.Raft().Barrier(time.Duration(msg.BarrierMillis) * time.Millisecond) if err := fut.Error(); err != nil { return nil, err } } cmd, err := proto.Marshal(&msg) if err != nil { return nil, err } fut := s.cluster.Raft().Apply(cmd, 0) if err := fut.Error(); err != nil { return nil, wrapError(err) } if r, ok := fut.Response().(*pb.Result); ok { return r, nil } panic(ErrIncorrectResponseType) }