repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
augustinebest/app | dashboard/src/components/ContextModal.js | <reponame>augustinebest/app<filename>dashboard/src/components/ContextModal.js
import React from 'react';
export default function(Cm) {
return props =>
((
<div className="bs-BIM">
<div className="ContextualLayer-layer--topleft ContextualLayer-layer--anytop ContextualLayer-layer--anyleft ContextualLayer-context--topleft ContextualLayer-context--anytop ContextualLayer-context--anyleft ContextualLayer-container ContextualLayer--pointerEvents">
<Cm {...props} />
</div>
</div>
).displayName = 'ContextModal');
}
|
JanWarlen/LeetCode | Recursion/src/main/java/com/janwarlen/recursion/second/SearchA2DMatrixII.java | package com.janwarlen.recursion.second;
import java.util.Arrays;
/**
* Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:
* <p>
* Integers in each row are sorted in ascending from left to right.
* Integers in each column are sorted in ascending from top to bottom.
* <p>
* Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
* Output: true
* <p>
* <p>
* Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
* Output: false
* <p>
* Constraints:
* <p>
* m == matrix.length
* n == matrix[i].length
* 1 <= n, m <= 300
* -109 <= matrix[i][j] <= 109
* All the integers in each row are sorted in ascending order.
* All the integers in each column are sorted in ascending order.
* -109 <= target <= 109
*/
public class SearchA2DMatrixII {
public static boolean searchMatrix(int[][] matrix, int target) {
if (null == matrix) {
return Boolean.FALSE;
}
int rows = matrix.length;
int columns = matrix[0].length;
int currentRow = rows - 1;
int currentColumn = 0;
// 初始位置是第一列最大值,最后一行最小值
while (currentRow >= 0 && currentColumn < columns) {
int value = matrix[currentRow][currentColumn];
if (value == target) {
return Boolean.TRUE;
} else if (value < target) {
// 整列是升序的,此时只能行右移
currentColumn++;
} else {
// 整行是升序的,只能列上移
currentRow--;
}
}
return Boolean.FALSE;
}
public static void main(String[] args) {
}
}
|
donn/attend | Android/app/src/main/java/hasebou/prototyping/miniattend/DataHolders.java | package hasebou.prototyping.miniattend;
import android.content.Context;
import android.content.SharedPreferences;
import java.io.Serializable;
/**
*
* contains all classes that will be used for server communication
*/
public class DataHolders{
public static class VerificationInfo implements Serializable{
public String fname;
public String lname;
public String email;
public String password;
public VerificationInfo() {
}
public VerificationInfo(String fname, String lname, String email, String password) {
this.fname = fname;
this.lname = lname;
this.email = email;
this.password = password;
}
public VerificationInfo(String email, String password) {
this.email = email;
this.password = password;
}
}
public static class Response implements Serializable{
public Status status;
public String jwt;
}
public static class Status implements Serializable{
public Integer code;
public String msg;
}
public static class PeopleOfInterest implements Serializable{
public String Email;
public String FirstName;
public String LastName;
public String DoICode;
}
public static class Course implements Serializable
{
public String Title = null;; // introduced only because of inconsistency of api
public String Section = null;;
public Integer TotalEvents = null;
public String MissableEvents = null;
public String ExcusedAbsences = null;
public String AttendedEvents = null;
public PeopleOfInterest[] PeopleOfInterest = null;;
public String Privilege = null;
public String ID = null;
public String DoI = null;
public String Code = null;
}
public static class AlterInvolvement implements Serializable{
public String CourseID;
public String DoICode;
public String Privilege;
public String Email;
}
public static class CoursesList implements Serializable
{
public Course[] response;
public Status status;
}
/**
* adds jwt to the json request
* @param jsonRequest
* @return
*/
public static String wrapInJWT(String jsonRequest,Context context){
SharedPreferences prefs = context.getSharedPreferences(context.
getString(R.string.preferences),
Context.MODE_PRIVATE);
String token = prefs.getString(context.getString(R.string.login_token),null);
String wrap = String.format("{\"jwt\":\"%s\",\"request\":%s}",token,jsonRequest);
return wrap;
}
public static class EventList implements Serializable{
public Event[] response;
}
public static class EventWrapper{
public Status status;
public Event response;
}
public static class Event implements Serializable{
public String ID;
public String CourseID;
public String Title;
public boolean Special;
public String TypicalStartTime;
public Event(String courseID, String title, char special,
int hour, int minute) {
this.CourseID = courseID;
this.Title = title;
this.Special = (special == 'Y');
TypicalStartTime = String.format("%2d:%2d:00", hour, minute);
}
public Event(String ID, String courseID, String title,
boolean special, String typicalStartTime) {
this.ID = ID;
CourseID = courseID;
Title = title;
Special = special;
TypicalStartTime = typicalStartTime;
}
}
public static class EventInstanceList implements Serializable{
public EventInstance[] response;
}
public static class EventInstance implements Serializable{
public EventInstance(int ID, int eventID,
String startTime, String QRString,
boolean QRCodeActive, boolean isLate) {
this.ID = ID;
EventID = eventID;
StartTime = startTime;
this.QRString = QRString;
this.QRCodeActive = QRCodeActive;
IsLate = isLate;
}
public EventInstance() {
}
public int ID;
public int EventID;
public String StartTime;
public String QRString;
public boolean QRCodeActive;
public boolean IsLate;
public int CourseID;
public String Title;
public int UnixStartTime;
}
public static class CourseIDWrapper implements Serializable{
public String CourseID;
}
public static class Attendance implements Serializable{
public String QRString;
}
}
|
vcooline/wechat_open_platform_proxy | app/controllers/concerns/wechat_open_platform_proxy/auth_guard.rb | <reponame>vcooline/wechat_open_platform_proxy<filename>app/controllers/concerns/wechat_open_platform_proxy/auth_guard.rb
module WechatOpenPlatformProxy
module AuthGuard
extend ActiveSupport::Concern
InvalidAuthTypeError = Class.new(StandardError)
InvalidAuthValueError = Class.new(StandardError)
NotAllowedRemoteIpError = Class.new(StandardError)
AuthenticateFailError = Class.new(StandardError)
SupportedAuthTypes = ["PlainUserToken", "PlainClientToken"]
UrlAuthTypeMappings = { auth_token: "<PASSWORD>" }
included do
rescue_from AuthenticateFailError, with: :handle_auth_failure
rescue_from NotAllowedRemoteIpError, with: :handle_remote_ip_not_allowed
end
module ClassMethods
end
private
def authenticate_client
send("authenticate_client_using_#{auth_params[:type].underscore}", auth_params[:value])
rescue => e
logger.error "#{e.class.name}: #{e.message}"
raise AuthenticateFailError, "#{e.class.name}: #{e.message}"
end
def authenticate_client_using_plain_client_token(token_value)
raise InvalidAuthValueError unless token_value == ENVConfig.client_auth_token
end
def auth_params
@auth_params ||= auth_params_from_header || auth_params_from_url
end
def auth_params_from_header
if request.authorization.present?
HashWithIndifferentAccess.new.tap{ |p| p[:type], p[:value] = request.authorization&.split }.tap do |p|
raise(InvalidAuthTypeError, "auth type not supported.") if SupportedAuthTypes.exclude?(p[:type])
raise(InvalidAuthValueError, "auth value is blank.") if p[:value].blank?
end
end
end
def auth_params_from_url
UrlAuthTypeMappings.each do |original_type, type|
return {type: type, value: params[original_type]} if params[original_type].present?
end
return nil
end
def check_remote_ip_whitelisted
unless request.remote_ip.in?(ENVConfig.remote_ip_whitelist.to_s.split(","))
logger.error "remote ip not in whitelist: #{request.remote_ip}"
raise NotAllowedRemoteIpError, "remote ip not in whitelist: #{request.remote_ip}"
end
end
def handle_auth_failure
respond_to do |format|
format.html { render plain: "权限不足,请联系管理员。", status: :forbidden }
format.json { render json: {error: {message: "Unauthenticated"}}, status: :forbidden }
end
end
def handle_remote_ip_not_allowed
respond_to do |format|
format.html { render plain: "请确认访问客户端已加入IP白名单", status: :forbidden }
format.json { render json: {error: {message: "Not in ip whitelist"}}, status: :forbidden }
end
end
end
end
|
zwliew/ctci | solutions/kattis/swaptosort.cc | #include <algorithm>
#include <array>
#include <bitset>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstring>
#include <deque>
#include <ext/pb_ds/assoc_container.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#ifdef LOCAL
#include "../../_library/cc/debug.h"
#define FILE "test"
#else
#define debug(...) 0
#define FILE ""
#endif
struct DSU {
vector<int> p, r;
DSU(int n) {
p.resize(n);
r.resize(n);
iota(p.begin(), p.end(), 0);
}
void join(int u, int v) {
u = find(u);
v = find(v);
if (u == v)
return;
if (r[u] == r[v])
++r[u];
else if (r[u] < r[v])
swap(u, v);
p[v] = u;
}
int find(int u) { return p[u] == u ? u : p[u] = find(p[u]); }
};
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
if (fopen(FILE ".in", "r")) {
freopen(FILE ".in", "r", stdin);
freopen(FILE ".out", "w", stdout);
}
int n, k;
cin >> n >> k;
DSU dsu(n);
while (k--) {
int a, b;
cin >> a >> b;
--a, --b;
dsu.join(a, b);
}
for (int i = 0; i < n; ++i) {
int pos = n - i - 1;
if (dsu.find(i) != dsu.find(pos)) {
cout << "No";
return 0;
}
}
cout << "Yes";
}
|
mpsijm/strategoxt | strategoxt/stratego-libraries/java-backend/java/runtime/org/strategoxt/lang/WeakValueHashMap.java | /***************************************
* *
* JBoss: The OpenSource J2EE WebOS *
* *
* Distributable under LGPL license. *
* See terms of license at gnu.org. *
* *
***************************************/
package org.strategoxt.lang;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.spoofax.terms.util.NotImplementedException;
/**
* This Map will remove entries when the value in the map has been cleaned from
* garbage collection
*
* @version <tt>$Revision: 1.1.1.1 $</tt>
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
@SuppressWarnings("all")
public class WeakValueHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V> {
private static class WeakValueRef extends WeakReference {
public Object key;
private WeakValueRef(Object key, Object val, ReferenceQueue q) {
super(val, q);
this.key = key;
}
private static WeakValueRef create(Object key, Object val, ReferenceQueue q) {
if (val == null)
return null;
else
return new WeakValueRef(key, val, q);
}
}
public Set entrySet() {
processQueue();
// return hash.entrySet();
throw new NotImplementedException();
}
/* Hash table mapping WeakKeys to values */
private Map hash;
/* Reference queue for cleared WeakKeys */
private ReferenceQueue queue = new ReferenceQueue();
/*
* Remove all invalidated entries from the map, that is, remove all entries
* whose values have been discarded.
*/
private void processQueue() {
WeakValueRef ref;
while ((ref = (WeakValueRef) queue.poll()) != null) {
if (ref == (WeakValueRef) hash.get(ref.key)) {
// only remove if it is the *exact* same WeakValueRef
//
hash.remove(ref.key);
}
}
}
/* -- Constructors -- */
/**
* Constructs a new, empty <code>WeakHashMap</code> with the given initial
* capacity and the given load factor.
*
* @param initialCapacity
* The initial capacity of the <code>WeakHashMap</code>
*
* @param loadFactor
* The load factor of the <code>WeakHashMap</code>
*
* @throws IllegalArgumentException
* If the initial capacity is less than zero, or if the load
* factor is nonpositive
*/
public WeakValueHashMap(int initialCapacity, float loadFactor) {
hash = new HashMap(initialCapacity, loadFactor);
}
/**
* Constructs a new, empty <code>WeakHashMap</code> with the given initial
* capacity and the default load factor, which is <code>0.75</code>.
*
* @param initialCapacity
* The initial capacity of the <code>WeakHashMap</code>
*
* @throws IllegalArgumentException
* If the initial capacity is less than zero
*/
public WeakValueHashMap(int initialCapacity) {
hash = new HashMap(initialCapacity);
}
/**
* Constructs a new, empty <code>WeakHashMap</code> with the default initial
* capacity and the default load factor, which is <code>0.75</code>.
*/
public WeakValueHashMap() {
hash = new HashMap();
}
/**
* Constructs a new <code>WeakHashMap</code> with the same mappings as the
* specified <tt>Map</tt>. The <code>WeakHashMap</code> is created with an
* initial capacity of twice the number of mappings in the specified map or
* 11 (whichever is greater), and a default load factor, which is
* <tt>0.75</tt>.
*
* @param t
* the map whose mappings are to be placed in this map.
* @since 1.3
*/
public WeakValueHashMap(Map t) {
this(Math.max(2 * t.size(), 11), 0.75f);
putAll(t);
}
/* -- Simple queries -- */
/**
* Returns the number of key-value mappings in this map.
* <strong>Note:</strong> <em>In contrast with most implementations of the
* <code>Map</code> interface, the time required by this operation is
* linear in the size of the map.</em>
*/
public int size() {
processQueue();
return hash.size();
}
/**
* Returns <code>true</code> if this map contains no key-value mappings.
*/
public boolean isEmpty() {
processQueue();
return hash.isEmpty();
}
/**
* Returns <code>true</code> if this map contains a mapping for the
* specified key.
*
* @param key
* The key whose presence in this map is to be tested
*/
public boolean containsKey(Object key) {
processQueue();
return hash.containsKey(key);
}
/* -- Lookup and modification operations -- */
/**
* Returns the value to which this map maps the specified <code>key</code>.
* If this map does not contain a value for this key, then return
* <code>null</code>.
*
* @param key
* The key whose associated value, if any, is to be returned
*/
public V get(Object key) {
processQueue();
WeakReference ref = (WeakReference) hash.get(key);
if (ref != null)
return (V) ref.get();
return null;
}
/**
* Updates this map so that the given <code>key</code> maps to the given
* <code>value</code>. If the map previously contained a mapping for
* <code>key</code> then that mapping is replaced and the previous value is
* returned.
*
* @param key
* The key that is to be mapped to the given <code>value</code>
* @param value
* The value to which the given <code>key</code> is to be mapped
*
* @return The previous value to which this key was mapped, or
* <code>null</code> if if there was no mapping for the key
*/
public Object put(Object key, Object value) {
processQueue();
Object rtn = hash.put(key, WeakValueRef.create(key, value, queue));
if (rtn != null)
rtn = ((WeakReference) rtn).get();
return rtn;
}
/**
* Removes the mapping for the given <code>key</code> from this map, if
* present.
*
* @param key
* The key whose mapping is to be removed
*
* @return The value to which this key was mapped, or <code>null</code> if
* there was no mapping for the key
*/
public V remove(Object key) {
processQueue();
return ((WeakReference<V>) hash.remove(key)).get();
}
/**
* Removes all mappings from this map.
*/
public void clear() {
processQueue();
hash.clear();
}
}
|
arusinha/incubator-netbeans | php/php.project/src/org/netbeans/modules/php/project/ui/actions/Command.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.netbeans.modules.php.project.ui.actions;
import java.util.logging.Logger;
import org.netbeans.modules.php.api.phpmodule.PhpModule;
import org.netbeans.modules.php.api.util.UiUtils;
import org.netbeans.modules.php.project.PhpProject;
import org.netbeans.modules.php.project.PhpProjectValidator;
import org.netbeans.modules.php.project.ProjectPropertiesSupport;
import org.netbeans.modules.php.project.ui.actions.support.CommandUtils;
import org.netbeans.modules.php.project.ui.actions.support.ConfigAction;
import org.netbeans.modules.php.spi.testing.PhpTestingProvider;
import org.openide.filesystems.FileObject;
import org.openide.util.Lookup;
/**
* @author <NAME>, <NAME>
*/
public abstract class Command {
protected final Logger logger = Logger.getLogger(getClass().getName());
private final PhpProject project;
public Command(PhpProject project) {
assert project != null;
this.project = project;
}
public abstract String getCommandId();
public abstract boolean isActionEnabledInternal(Lookup context);
public abstract void invokeActionInternal(Lookup context);
public final boolean isActionEnabled(Lookup context) {
if (PhpProjectValidator.isFatallyBroken(project)) {
// will be handled in invokeAction(), see below
return true;
}
return isActionEnabledInternal(context);
}
public final void invokeAction(Lookup context) {
if (!validateInvokeAction(context)) {
return;
}
invokeActionInternal(context);
}
protected boolean validateInvokeAction(Lookup context) {
if (PhpProjectValidator.isFatallyBroken(project)) {
UiUtils.warnBrokenProject(project.getPhpModule());
return false;
}
return true;
}
public boolean asyncCallRequired() {
return true;
}
public boolean saveRequired() {
return true;
}
public boolean isFileSensitive() {
return false;
}
public final PhpProject getProject() {
return project;
}
protected ConfigAction getConfigAction() {
return ConfigAction.get(ConfigAction.convert(ProjectPropertiesSupport.getRunAs(project)), project);
}
protected boolean isTestFile(FileObject fileObj) {
// #156939
if (fileObj == null) {
return false;
}
// #188770
PhpModule phpModule = project.getPhpModule();
for (PhpTestingProvider provider : project.getTestingProviders()) {
if (provider.isTestFile(phpModule, fileObj)) {
return true;
}
}
return CommandUtils.isUnderTests(project, fileObj, false);
}
protected boolean isSeleniumFile(FileObject fileObj) {
// #156939
if (fileObj == null) {
return false;
}
return CommandUtils.isUnderSelenium(project, fileObj, false);
}
}
|
Batman001/ExcelImport | src/main/java/com/thinkgem/jeesite/modules/excelimport/web/ImportExcelJspController.java | package com.thinkgem.jeesite.modules.excelimport.web;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.excelimport.process.EntityImport;
import com.thinkgem.jeesite.modules.excelimport.util.ExcelImportService;
import com.thinkgem.jeesite.modules.utils.OperateTipsUtils;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author sunc
* Date 2019/12/4 17:11
* Description
*/
@Controller
@RequestMapping(value = "${adminPath}/import")
public class ImportExcelJspController extends BaseController {
@Autowired
private ExcelImportService excelService;
@RequestMapping(value = "getThread", method = RequestMethod.GET)
public void getThread(String type, String businessId, HttpServletRequest request, HttpServletResponse response) {
String thread = excelService.generateRandomThread();
HttpSession session = request.getSession();
session.setAttribute("thread",thread);
session.setAttribute("content", JSONObject.stringToValue("{}"));
session.setAttribute("type", type);
// session.setAttribute("type", "PsJHKeypointExamine");
session.setAttribute("businessId", businessId);
// session.setAttribute("businessId", "1");
this.renderString(response, thread);
}
@RequestMapping(value = "import", method = RequestMethod.POST)
public void importFile(MultipartFile file, @RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
List<MultipartFile> files = new ArrayList<>();
files.add(file);
HttpSession session = request.getSession();
String entityType = (String)session.getAttribute("type");;
String content = (String)session.getAttribute("content");;
String businessId = (String)session.getAttribute("businessId");;
if (!StringUtils.isBlank(entityType) && !StringUtils.isBlank(content)) {
String monitorId = (String) session.getAttribute("thread");;
if (files == null || files.size() == 0) {
this.renderString(request, response, "请选择文件上传!", true);
}
if (files.size() > 1) {
this.renderString(request, response, "上传的文件多大于1!", true);
}
String upLoadFileName = (files.get(0)).getOriginalFilename();
if (!upLoadFileName.endsWith(".xls") && !upLoadFileName.endsWith(".xlsx")) {
this.renderString(request, response, OperateTipsUtils.operateTips(22, "请上传Excel文件!", ""), true);
} else {
String errorFilePath = request.getSession().getServletContext().getRealPath("/static/errorfile/");
EntityImport entityImport = new EntityImport();
entityImport.setEntityType(entityType);
entityImport.setMonitorId(monitorId);
Map<String, Object> processRes = entityImport.process(files, errorFilePath, entityType, content, businessId);
if (processRes == null) {
this.renderString(request, response, OperateTipsUtils.operateTips(0, "文件上传成功!", ""), true);
} else {
this.renderString(request, response, processRes, true);
}
}
} else {
throw new Exception("ImportExcelController:未传递 entityType 或 content参数!");
}
}
}
|
StephenRogers1/cogent3 | doc/draw_examples/tree/plot_tree-square.py | <reponame>StephenRogers1/cogent3
"""
Display a Phylogenetic Tree with a Square Dendrogram Style
==========================================================
We use a tree saved in `json` format from a likelihood function analysis of a non-stationary model. The tree was derived such that the the branch lengths are now "ENS".
"""
# %%
from cogent3.app import io
reader = io.load_json()
ens_tree = reader("../../data/GN-tree.json")
fig = ens_tree.get_figure(width=600, height=600)
fig.show()
#%%
# Changing scale bar placement
# ############################
fig.scale_bar = "top right"
fig.show()
#%%
# Colouring a set of edges
# ########################
fig.style_edges("AfricanEl", tip2="Manatee", legendgroup="Afrotheria",
line=dict(color="magenta"))
fig.show()
#%%
# With Contemporaneous Tips
# #########################
fig.contemporaneous = True
fig.show()
|
metal/crystal-bootstrap | packages/marble-datatable/test/data/data_simple.js | import Soy from 'metal-soy';
var data_simple = [{
'price': 13.42,
'title': 'Deadpool Classic Vol. 12: Deadpool Corps',
'description': 'Deadpool gears up for an intergalactic adventure, but to succeed, he\'ll need to assemble a crack team of special operatives! So naturally he recruits four other versions of himself! What could go wrong? Lady Deadpool, Kid Deadpool, Dogpool, Headpool and the original Merc With a Mouth form...the Deadpool Corps.',
'cover': 'http://ecx.images-amazon.com/images/I/61bE8lOiP8L._SX321_BO1,204,203,200_.jpg',
'link': 'http://www.amazon.com/Deadpool-Classic-Vol-12-Corps-ebook/dp/B00XZD7ETE/ref=sr_1_10?s=books&ie=UTF8&qid=1439404247&sr=1-10'
}, {
'price': 10.40,
'title': 'Magneto Vol. 3: Shadow Games',
'description': 'As Magneto tries to forge a new stronghold on the devastated island nation of Genosha, the backdrop for his greatest triumphs and most devastating tragedies, he finds himself confronted by S.H.I.E.L.D.! But what ace does Magneto have up his sleeve that might allow him to turn the tables? In the wake of AXIS, Magneto had gathered a group of wayward mutants together on Genosha.',
'cover': 'http://ecx.images-amazon.com/images/I/619G3Hjwf3L._SX323_BO1,204,203,200_.jpg',
'link': 'http://www.amazon.com/Magneto-Vol-Shadow-Games-2014--ebook/dp/B00XZD7FA2/ref=sr_1_12?s=books&ie=UTF8&qid=1439404247&sr=1-12'
}, {
'price': 11.35,
'title': 'Superman: The Men of Tomorrow',
'description': 'The powerful super-being Ulysses is the last son of a doomed planet. Our planet. Thinking Earth’s destruction was at hand, his parents used experimental science to send their son to another dimension. Now he has returned, and Superman has finally found a peer. But will Ulysses become the hero and partner that Superman wants him to be?',
'cover': 'http://ecx.images-amazon.com/images/I/51NifbH-7DL._SX323_BO1,204,203,200_.jpg',
'link': 'http://www.amazon.com/Superman-Men-Tomorrow-Geoff-Johns-ebook/dp/B011QG87HO/ref=sr_1_2?s=books&ie=UTF8&qid=1439404247&sr=1-2'
}, {
'price': 10.49,
'title': 'Wolverine: Old Man Logan',
'description': 'Collects Wolverine (2003) #66-72 and Wolverine: Old Man Logan Giant-Size. In the future, Logan lives a quiet life. But one day an old friend shows up to ask a favor of him. And on a journey across America, the mutant Wolverine will become a hero again.',
'cover': 'http://ecx.images-amazon.com/images/I/515qgXA5lvL._SX323_BO1,204,203,200_.jpg',
'link': 'http://www.amazon.com/Wolverine-Old-Logan-Mark-Millar-ebook/dp/B00AAJR45A/ref=sr_1_70?s=books&ie=UTF8&qid=1439407060&sr=1-70'
}, {
'price': 18.78,
'title': 'Batman: The Killing Joke',
'description': 'Presented for the first time with stark, stunning new coloring by Bolland, BATMAN: THE KILLING JOKE is Alan Moore\'s unforgettable meditation on the razor-thin line between sanity and insanity, heroism and villainy, comedy and tragedy.',
'cover': 'http://ecx.images-amazon.com/images/I/51Y817VtILL._SX311_BO1,204,203,200_.jpg',
'link': 'http://www.amazon.com/Batman-Killing-Deluxe-Alan-Moore-ebook/dp/B009POHHRG/ref=sr_1_1?s=books&ie=UTF8&qid=1439406383&sr=1-1'
}];
var data_simple_expanded_fn = () => {
return {
'type': 'array',
'value': [{
'type': 'object',
'value': {
'price': {
'type': 'number',
'value': 13.42
},
'title': {
'type': 'string',
'value': Soy.toIncDom('Deadpool Classic Vol. 12: Deadpool Corps')
},
'description': {
'type': 'string',
'value': Soy.toIncDom('Deadpool gears up for an intergalactic adventure, but to succeed, he\'ll need to assemble a crack team of special operatives! So naturally he recruits four other versions of himself! What could go wrong? Lady Deadpool, Kid Deadpool, Dogpool, Headpool and the original Merc With a Mouth form...the Deadpool Corps.')
},
'cover': {
'type': 'string',
'value': Soy.toIncDom('http://ecx.images-amazon.com/images/I/61bE8lOiP8L._SX321_BO1,204,203,200_.jpg')
},
'link': {
'type': 'string',
'value': Soy.toIncDom('http://www.amazon.com/Deadpool-Classic-Vol-12-Corps-ebook/dp/B00XZD7ETE/ref=sr_1_10?s=books&ie=UTF8&qid=1439404247&sr=1-10')
}
},
'columns': [
'cover',
'description',
'link',
'price',
'title'
],
'columnsType': {
'price': 'number',
'title': 'string',
'description': 'string',
'cover': 'string',
'link': 'string'
}
}, {
'type': 'object',
'value': {
'price': {
'type': 'number',
'value': 10.4
},
'title': {
'type': 'string',
'value': Soy.toIncDom('Magneto Vol. 3: Shadow Games')
},
'description': {
'type': 'string',
'value': Soy.toIncDom('As Magneto tries to forge a new stronghold on the devastated island nation of Genosha, the backdrop for his greatest triumphs and most devastating tragedies, he finds himself confronted by S.H.I.E.L.D.! But what ace does Magneto have up his sleeve that might allow him to turn the tables? In the wake of AXIS, Magneto had gathered a group of wayward mutants together on Genosha.')
},
'cover': {
'type': 'string',
'value': Soy.toIncDom('http://ecx.images-amazon.com/images/I/619G3Hjwf3L._SX323_BO1,204,203,200_.jpg')
},
'link': {
'type': 'string',
'value': Soy.toIncDom('http://www.amazon.com/Magneto-Vol-Shadow-Games-2014--ebook/dp/B00XZD7FA2/ref=sr_1_12?s=books&ie=UTF8&qid=1439404247&sr=1-12')
}
},
'columns': [
'cover',
'description',
'link',
'price',
'title'
],
'columnsType': {
'price': 'number',
'title': 'string',
'description': 'string',
'cover': 'string',
'link': 'string'
}
}, {
'type': 'object',
'value': {
'price': {
'type': 'number',
'value': 11.35
},
'title': {
'type': 'string',
'value': Soy.toIncDom('Superman: The Men of Tomorrow')
},
'description': {
'type': 'string',
'value': Soy.toIncDom('The powerful super-being Ulysses is the last son of a doomed planet. Our planet. Thinking Earth’s destruction was at hand, his parents used experimental science to send their son to another dimension. Now he has returned, and Superman has finally found a peer. But will Ulysses become the hero and partner that Superman wants him to be?')
},
'cover': {
'type': 'string',
'value': Soy.toIncDom('http://ecx.images-amazon.com/images/I/51NifbH-7DL._SX323_BO1,204,203,200_.jpg')
},
'link': {
'type': 'string',
'value': Soy.toIncDom('http://www.amazon.com/Superman-Men-Tomorrow-Geoff-Johns-ebook/dp/B011QG87HO/ref=sr_1_2?s=books&ie=UTF8&qid=1439404247&sr=1-2')
}
},
'columns': [
'cover',
'description',
'link',
'price',
'title'
],
'columnsType': {
'price': 'number',
'title': 'string',
'description': 'string',
'cover': 'string',
'link': 'string'
}
}, {
'type': 'object',
'value': {
'price': {
'type': 'number',
'value': 10.49
},
'title': {
'type': 'string',
'value': Soy.toIncDom('Wolverine: Old Man Logan')
},
'description': {
'type': 'string',
'value': Soy.toIncDom('Collects Wolverine (2003) #66-72 and Wolverine: Old Man Logan Giant-Size. In the future, Logan lives a quiet life. But one day an old friend shows up to ask a favor of him. And on a journey across America, the mutant Wolverine will become a hero again.')
},
'cover': {
'type': 'string',
'value': Soy.toIncDom('http://ecx.images-amazon.com/images/I/515qgXA5lvL._SX323_BO1,204,203,200_.jpg')
},
'link': {
'type': 'string',
'value': Soy.toIncDom('http://www.amazon.com/Wolverine-Old-Logan-Mark-Millar-ebook/dp/B00AAJR45A/ref=sr_1_70?s=books&ie=UTF8&qid=1439407060&sr=1-70')
}
},
'columns': [
'cover',
'description',
'link',
'price',
'title'
],
'columnsType': {
'price': 'number',
'title': 'string',
'description': 'string',
'cover': 'string',
'link': 'string'
}
}, {
'type': 'object',
'value': {
'price': {
'type': 'number',
'value': 18.78
},
'title': {
'type': 'string',
'value': Soy.toIncDom('Batman: The Killing Joke')
},
'description': {
'type': 'string',
'value': Soy.toIncDom('Presented for the first time with stark, stunning new coloring by Bolland, BATMAN: THE KILLING JOKE is Alan Moore\'s unforgettable meditation on the razor-thin line between sanity and insanity, heroism and villainy, comedy and tragedy.')
},
'cover': {
'type': 'string',
'value': Soy.toIncDom('http://ecx.images-amazon.com/images/I/51Y817VtILL._SX311_BO1,204,203,200_.jpg')
},
'link': {
'type': 'string',
'value': Soy.toIncDom('http://www.amazon.com/Batman-Killing-Deluxe-Alan-Moore-ebook/dp/B009POHHRG/ref=sr_1_1?s=books&ie=UTF8&qid=1439406383&sr=1-1')
}
},
'columns': [
'cover',
'description',
'link',
'price',
'title'
],
'columnsType': {
'price': 'number',
'title': 'string',
'description': 'string',
'cover': 'string',
'link': 'string'
}
}],
'columns': [
'cover',
'description',
'link',
'price',
'title'
],
'columnsType': {
'price': 'number',
'title': 'string',
'description': 'string',
'cover': 'string',
'link': 'string'
}
};
};
export { data_simple, data_simple_expanded_fn };
|
jdarling/radxa-rock | lib/pin.js | <reponame>jdarling/radxa-rock
var util = require('util');
var CONST = require('./gpio_defines');
var GPIO_PATH = CONST.GPIO_PATH;
var NOOP = function(){};
var utils = require('./utils');
var _export = utils.export;
var _unexport = utils.unexport;
var _read = utils.read;
var _write = utils.write;
var isNumeric = utils.isNumeric;
var EventEmitter = require('events').EventEmitter;
var pinEmitter = new EventEmitter();
var checkChanged = (function(){
var values = {};
return function(pinNumber, callback){
var path = GPIO_PATH + 'gpio'+ pinNumber + '/value';
var now = (new Date()).getTime();
var old = values[pinNumber]|| (values[pinNumber] = {
value: null,
lastChecked: false
});
try{
if(!old.lastChecked || (old.lastChecked-now > CONST.PIN_SCAN_TIME||10)){
return _read(path, function(err, value){
if(err){
return callback(err);
}
if(value!==old.value){
pinEmitter.emit('pin'+pinNumber+':change', value, old.value);
pinEmitter.emit('pin:change', pinNumber, value, old.value);
old.value = value;
}
old.lastChecked = (new Date()).getTime();
callback();
});
}
return callback();
}catch(e){
old.lastChecked = (new Date()).getTime();
callback(e);
}
};
})();
var haltScanner = (function(){
var min = Number.MAX_VALUE, max=0, curr = 0;
var keys = Object.keys(CONST);
var reIsPort = /^J\d{1,2}_P\d{1,2}$/;
var halt = false;
keys.forEach(function(key){
val = CONST[key];
if(isNumeric(val) && val > 0 && key.match(reIsPort)){
if(val < min){
min = val;
}
if(val > max){
max = val;
}
}
});
curr = min;
var scanner = function _scanner(){
checkChanged(curr, function(){
curr++;
if(curr>max){
curr = min;
}
if(!halt){
process.nextTick(scanner);
}
});
};
scanner();
return function(){
halt = true;
};
})();
var Pin = function(opts){
var self = this;
var options = isNumeric(opts)?{pin: opts}:opts;
var pinNumber = options.pin;
if(!pinNumber){
throw new Error('No pin number supplied!');
}
self._pin = pinNumber;
self._gpioPath = GPIO_PATH + 'gpio'+ pinNumber;
if(options.mode){
self.setMode(options.mode);
}
};
Pin.prototype.on = function(event, callback){
var self = this;
pinEmitter.on('pin'+self.pin+':'+event, callback);
};
Pin.prototype.once = function(event, callback){
var self = this;
pinEmitter.once('pin'+self.pin+':'+event, callback);
};
Pin.prototype.removeListener = function(event, callback){
var self = this;
pinEmitter.removeListener('pin'+self.pin+':'+event, callback);
};
Pin.prototype.emit = function(event, arg){
var self = this, args = Array.prototype.slice.call(arguments);
args.unshift('pin'+self.pin+':'+event);
EventEmitter.prototype.emit.apply(pinEmitter, args);
};
Pin.prototype.export = function(callback){
var self = this;
_export(self._pin, callback);
};
Pin.prototype.unexport = function(pinNumber, callback){
var self = this;
_unexport(self._pin, callback);
};
Pin.prototype.getMode = function(callback){
var self = this;
var path = self._gpioPath + '/direction';
try{
if(callback){
return _read(path, function(err, dir){
return callback(null, (dir||'undefined').trim());
});
}
return _read(path);
}catch(e){
return 'undefined';
}
};
Pin.prototype.setMode = function(direction, callback){
var self = this;
var mode = direction === 'in' || direction === 'input' ? 'in':'out';
var path = self._gpioPath + '/direction';
var checkErrorSendMode = function(err){
if(err){
return (callback||NOOP)(err);
}
return _read(path, function(err, dir){
return (callback||function(err, val){
return val;
})(null, (dir||'undefined').trim());
});
};
return _read(path, function(err, dir){
if(err){
return self.export(function(err){
if(err){
return callback(err);
}
return _write(path, mode, checkErrorSendMode);
});
}
if(dir.indexOf(mode)===-1){
return _write(path, mode, checkErrorSendMode);
}
return checkErrorSendMode();
});
};
Pin.prototype.mode = function(newMode, callback){
var self = this;
if(typeof(newMode)==='function' || typeof(newMode) === 'undefined'){
return self.getMode(newMode||callback);
}
return self.setMode(newMode, callback);
};
Pin.prototype.get = function(callback){
var self = this;
var path = self._gpioPath + '/value';
return _read(path, callback);
};
Pin.prototype.set = function(value, callback){
var self = this;
var path = self._gpioPath + '/value';
return _write(path, value, function(err){
if(err){
self.emit('error', err);
return (callback||NOOP)(err);
}
return (callback||NOOP)(null, value);
});
};
Pin.prototype.val = function(value, callback){
var self = this;
if(typeof(value)==='function' || typeof(value) === 'undefined'){
return self.get(value||callback);
}
return self.set(value, callback);
};
module.exports = Pin;
module.exports.emitter = pinEmitter;
module.exports.haltScanner = haltScanner;
|
carlosviveros/Soluciones | soluciones/mvc_ejemplo/main.py | """AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
from prototools import Menu
from prototools.colorize import cyan, yellow, magenta
from controllers import Controlador
from models import Modelo
from views import VistaFancy
def main():
menu = Menu(
cyan("Generador de números aleatorios"),
yellow("Ejemplo MVC"),
exit_option_text=magenta("Salir"),
exit_option_color=magenta,
)
controlador = Controlador(Modelo(), VistaFancy())
menu.add_options(
("Configurar", controlador.configurar),
("Mostrar Numeros", controlador.numeros),
("Mostrar Pares", controlador.pares),
("Mostrar Impares", controlador.impares),
)
menu.settings(
subtitle_align="center",
style="double",
color=magenta,
options_color=yellow,
separators=True,
)
menu.run()
if __name__ == '__main__':
main()
|
KPMGE/Projetos-C | others/tic-tac-toe.c | //Simple program, or actually a shit program, for tic-tac-toe game
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
struct point
{
int x;
int y;
};
typedef struct point Point;
void print_matrix(char matrix[][5], Point *p, char c);
void read_move(Point *p, char *c, int Player);
int check_row(char old[][5], int i);
int check_column(char old[][5], int j);
int check_diagonals(char old[][5]);
int end_game(char old[][5]);
int main(void)
{
int i, j, cont = 0;
Point p;
char c, old[3][5];
//creating matrix for game
for (i = 0; i < 3; i++)
{
for (j = 0; j < 5; j++)
{
if (j % 2 == 0)
old[i][j] = '-';
else
old[i][j] = '|';
}
}
printf("-------------------------------------TIC-TAC-TOE-----------------------------------------------\n");
printf("Player 1 = 'x'\nPlayer 2 = 'o'\n");
printf("Ready? Go!\n");
while (TRUE)
{
printf("\nPlayer 1\n");
read_move(&p, &c, 1);
printf("\n");
print_matrix(old, &p, c);
printf("\nPlayer 2\n");
read_move(&p, &c, 2);
print_matrix(old, &p, c);
cont++;
if (end_game(old) == 1)
{
printf("Player 1 won!!");
exit(1);
}
if (end_game(old) == 2)
{
printf("O Player 2 won!!");
exit(1);
}
if (cont == 9)
{
printf("Old!!");
return 0;
}
}
printf("End Game!!");
return 0;
}
void print_matrix(char old[][5], Point *p, char c)
{
int i, j;
old[p->x][p->y] = c;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 5; j++)
{
printf("%c ", old[i][j]);
}
printf("\n");
}
}
void read_move(Point *p, char *c, int Player)
{
while (TRUE)
{
printf("Type a point and a value\n> ");
scanf("%d %d %c", &p->x, &p->y, c);
if (Player == 1)
{
if ('x' != *c)
printf("\nType the letter 'x' to play!!\n");
else if (p->x > 3 || p->y > 4)
printf("\nThere are no this point! Try again!!\n");
else
break;
}
if (Player == 2)
{
if ('o' != *c)
printf("\nType the letter 'o' to play!!\n");
else if (p->x > 3 || p->y > 4)
printf("\nThere are no this point! Try again!!\n");
else
break;
}
}
//adjusting point
p->x -= 1;
if (p->y == 1)
p->y -= 1;
if (p->y == 3)
p->y += 1;
}
int check_row(char old[][5], int i)
{
if ((old[i][0] == 'x' && old[i][2] == 'x' && old[i][4] == 'x'))
return 1;
else if ((old[i][0] == 'o' && old[i][2] == 'o' && old[i][4] == 'o'))
return 2;
}
int check_column(char old[][5], int j)
{
if ((old[0][j] == 'x' && old[1][j] == 'x' && old[2][j] == 'x'))
return 1;
else if ((old[0][j] == 'o' && old[1][j] == 'o' && old[2][j] == 'o'))
return 2;
}
int check_diagonals(char old[][5])
{
if ((old[0][0] == 'x' && old[1][2] == 'x' && old[2][4] == 'x') || (old[0][2] == 'x' && old[1][2] == 'x' && old[0][4] == 'x'))
return 1;
else if ((old[0][0] == 'o' && old[1][2] == 'o' && old[2][4] == 'o') || (old[0][2] == 'x' && old[1][2] == 'x' && old[0][4] == 'x'))
return 2;
}
int end_game(char old[][5])
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 5; j++)
{
if ((check_row(old, i) == 1) || (check_column(old, j) == 1) || (check_diagonals(old) == 1))
return 1;
else if ((check_row(old, i) == 2) || (check_column(old, j) == 2) || (check_diagonals(old) == 2))
return 2;
}
}
}
|
lleo/go-functional-collections | fmap/bitmap.go | <gh_stars>1-10
package fmap
import (
"fmt"
"strings"
"github.com/lleo/go-functional-collections/key/hash"
)
// bitmapShift is 3 because we are using uint8 as the base bitmap type.
const bitmapShift uint = 3
// bitmapSize is the number of uint8 needed to cover hash.IndexLimit bits.
const bitmapSize uint = (hash.IndexLimit + (1 << bitmapShift) - 1) /
(1 << bitmapShift)
type bitmap [bitmapSize]uint8
// bitFmtStr cannot be a constant if I use a library function to convert
// hash.IndexLimit to a string, so I am going to hardcode it manually.
//const bitsFmtStr = fmt.Sprintf("%%0%db", 1<<bitmapShift)
//const bitsFmtStr = "%0" + strconv.Itoa(1<<bitmapShift) + "b"
//const bitsFmtStr = "%032b" //for bitmap being array of uint32 aka bitmapShift=5
const bitsFmtStr = "%08b" //for bitmap being array of uint8 aka bitmapShift=3
const byteMask = (1 << bitmapShift) - 1
func (bm *bitmap) String() string {
// Show all bits in bitmap because hash.IndexLimit is a multiple of the
// bitmap base type.
var strs = make([]string, bitmapSize)
//var fmtStr = fmt.Sprintf("%%0%db", 1<<bitmapShift)
for i := uint(0); i < bitmapSize; i++ {
strs[i] = fmt.Sprintf(bitsFmtStr, bm[i])
}
return strings.Join(strs, " ")
}
// IsSet returns a bool indicating whether the i'th bit is 1(true) or 0(false).
func (bm *bitmap) isSet(idx uint) bool {
var nth = idx >> bitmapShift
var bit = idx & byteMask
return (bm[nth] & (1 << bit)) > 0
}
// Set marks the i'th bit 1.
func (bm *bitmap) set(idx uint) *bitmap {
var nth = idx >> bitmapShift
var bit = idx & byteMask
bm[nth] |= 1 << bit
return bm
}
// Unset marks the i'th bit to 0.
func (bm *bitmap) unset(idx uint) *bitmap {
var nth = idx >> bitmapShift
var bit = idx & byteMask
//if bm[nth]&(1<<bit) > 0 {
// bm[nth] &^= 1 << bit
//}
bm[nth] &^= 1 << bit
return bm
}
// Count returns the numbers of bits set below the i'th bit.
func (bm *bitmap) count(idx uint) uint {
var nth = idx >> bitmapShift
var bit = idx & byteMask
var count uint
for i := uint(0); i < nth; i++ {
count += bitCount8(bm[i])
}
count += bitCount8(bm[nth] & ((1 << bit) - 1))
return count
}
|
alansangeeth/ej2-javascript-samples | src/treeview/localdata.js | this.default = function () {
// Render the TreeView with hierarchical data source
var treeObj = new ej.navigations.TreeView({
fields: { dataSource: window.continentData, id: 'code', text: 'name', child: 'countries' }
});
treeObj.appendTo('#tree');
// Render the TreeView with list data source
var listTreeObj = new ej.navigations.TreeView({
fields: { dataSource: window.localData, id: 'id', parentID: 'pid', text: 'name', hasChildren: 'hasChild' }
});
listTreeObj.appendTo('#listtree');
}; |
ecds/otb-api-server | spec/models/tour_spec.rb | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe Tour, type: :model do
# it { should validate_presence_of(:title) }
# it { expect(subject).to validate_presence_of :title }
it { expect(subject).to have_many(:stops) }
it { expect(subject).to have_many(:tour_stops) }
it { expect(Tour.reflect_on_association(:theme).macro).to eq(:belongs_to) }
it { expect(Tour.reflect_on_association(:mode).macro).to eq(:belongs_to) }
end
|
junwei-wang/com.hotfixs.books | thinking-in-java/interfaces/src/main/java/com/hotfixs/thinkinginjava/interfaces/filter/Waveform.java | package com.hotfixs.thinkinginjava.interfaces.filter;
/**
* @author wang
*/
public class Waveform {
private static long counter;
private final long id = counter++;
public String toString() {
return "Waveform " + id;
}
}
|
runtest007/dpdk_surcata_4.1.1 | suricata-4.1.4/src/output-json-http.c | /* Copyright (C) 2007-2013 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author <NAME> <<EMAIL>>
*
* Implements HTTP JSON logging portion of the engine.
*/
#include "suricata-common.h"
#include "debug.h"
#include "detect.h"
#include "pkt-var.h"
#include "conf.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-print.h"
#include "util-unittest.h"
#include "util-debug.h"
#include "output.h"
#include "app-layer-htp.h"
#include "app-layer-htp-xff.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "util-privs.h"
#include "util-buffer.h"
#include "util-proto-name.h"
#include "util-logopenfile.h"
#include "util-time.h"
#include "util-crypt.h"
#include "output-json.h"
#include "output-json-alert.h"
#include "output-json-http.h"
#ifdef HAVE_LIBJANSSON
typedef struct LogHttpFileCtx_ {
LogFileCtx *file_ctx;
uint32_t flags; /** Store mode */
uint64_t fields;/** Store fields */
HttpXFFCfg *xff_cfg;
HttpXFFCfg *parent_xff_cfg;
OutputJsonCommonSettings cfg;
} LogHttpFileCtx;
typedef struct JsonHttpLogThread_ {
LogHttpFileCtx *httplog_ctx;
/** LogFileCtx has the pointer to the file and a mutex to allow multithreading */
uint32_t uri_cnt;
MemBuffer *buffer;
} JsonHttpLogThread;
#define LOG_HTTP_DEFAULT 0
#define LOG_HTTP_EXTENDED 1
#define LOG_HTTP_REQUEST 2 /* request field */
#define LOG_HTTP_ARRAY 4 /* require array handling */
typedef enum {
HTTP_FIELD_ACCEPT = 0,
HTTP_FIELD_ACCEPT_CHARSET,
HTTP_FIELD_ACCEPT_ENCODING,
HTTP_FIELD_ACCEPT_LANGUAGE,
HTTP_FIELD_ACCEPT_DATETIME,
HTTP_FIELD_AUTHORIZATION,
HTTP_FIELD_CACHE_CONTROL,
HTTP_FIELD_COOKIE,
HTTP_FIELD_FROM,
HTTP_FIELD_MAX_FORWARDS,
HTTP_FIELD_ORIGIN,
HTTP_FIELD_PRAGMA,
HTTP_FIELD_PROXY_AUTHORIZATION,
HTTP_FIELD_RANGE,
HTTP_FIELD_TE,
HTTP_FIELD_VIA,
HTTP_FIELD_X_REQUESTED_WITH,
HTTP_FIELD_DNT,
HTTP_FIELD_X_FORWARDED_PROTO,
HTTP_FIELD_X_AUTHENTICATED_USER,
HTTP_FIELD_X_FLASH_VERSION,
HTTP_FIELD_ACCEPT_RANGES,
HTTP_FIELD_AGE,
HTTP_FIELD_ALLOW,
HTTP_FIELD_CONNECTION,
HTTP_FIELD_CONTENT_ENCODING,
HTTP_FIELD_CONTENT_LANGUAGE,
HTTP_FIELD_CONTENT_LENGTH,
HTTP_FIELD_CONTENT_LOCATION,
HTTP_FIELD_CONTENT_MD5,
HTTP_FIELD_CONTENT_RANGE,
HTTP_FIELD_CONTENT_TYPE,
HTTP_FIELD_DATE,
HTTP_FIELD_ETAG,
HTTP_FIELD_EXPIRES,
HTTP_FIELD_LAST_MODIFIED,
HTTP_FIELD_LINK,
HTTP_FIELD_LOCATION,
HTTP_FIELD_PROXY_AUTHENTICATE,
HTTP_FIELD_REFERRER,
HTTP_FIELD_REFRESH,
HTTP_FIELD_RETRY_AFTER,
HTTP_FIELD_SERVER,
HTTP_FIELD_SET_COOKIE,
HTTP_FIELD_TRAILER,
HTTP_FIELD_TRANSFER_ENCODING,
HTTP_FIELD_UPGRADE,
HTTP_FIELD_VARY,
HTTP_FIELD_WARNING,
HTTP_FIELD_WWW_AUTHENTICATE,
HTTP_FIELD_TRUE_CLIENT_IP,
HTTP_FIELD_ORG_SRC_IP,
HTTP_FIELD_X_BLUECOAT_VIA,
HTTP_FIELD_SIZE
} HttpField;
struct {
const char *config_field;
const char *htp_field;
uint32_t flags;
} http_fields[] = {
{ "accept", "accept", LOG_HTTP_REQUEST },
{ "accept_charset", "accept-charset", LOG_HTTP_REQUEST },
{ "accept_encoding", "accept-encoding", LOG_HTTP_REQUEST },
{ "accept_language", "accept-language", LOG_HTTP_REQUEST },
{ "accept_datetime", "accept-datetime", LOG_HTTP_REQUEST },
{ "authorization", "authorization", LOG_HTTP_REQUEST },
{ "cache_control", "cache-control", LOG_HTTP_REQUEST },
{ "cookie", "cookie", LOG_HTTP_REQUEST|LOG_HTTP_ARRAY },
{ "from", "from", LOG_HTTP_REQUEST },
{ "max_forwards", "max-forwards", LOG_HTTP_REQUEST },
{ "origin", "origin", LOG_HTTP_REQUEST },
{ "pragma", "pragma", LOG_HTTP_REQUEST },
{ "proxy_authorization", "proxy-authorization", LOG_HTTP_REQUEST },
{ "range", "range", LOG_HTTP_REQUEST },
{ "te", "te", LOG_HTTP_REQUEST },
{ "via", "via", LOG_HTTP_REQUEST },
{ "x_requested_with", "x-requested-with", LOG_HTTP_REQUEST },
{ "dnt", "dnt", LOG_HTTP_REQUEST },
{ "x_forwarded_proto", "x-forwarded-proto", LOG_HTTP_REQUEST },
{ "x_authenticated_user", "x-authenticated-user", LOG_HTTP_REQUEST },
{ "x_flash_version", "x-flash-version", LOG_HTTP_REQUEST },
{ "accept_range", "accept-range", 0 },
{ "age", "age", 0 },
{ "allow", "allow", 0 },
{ "connection", "connection", 0 },
{ "content_encoding", "content-encoding", 0 },
{ "content_language", "content-language", 0 },
{ "content_length", "content-length", 0 },
{ "content_location", "content-location", 0 },
{ "content_md5", "content-md5", 0 },
{ "content_range", "content-range", 0 },
{ "content_type", "content-type", 0 },
{ "date", "date", 0 },
{ "etag", "etags", 0 },
{ "expires", "expires" , 0 },
{ "last_modified", "last-modified", 0 },
{ "link", "link", 0 },
{ "location", "location", 0 },
{ "proxy_authenticate", "proxy-authenticate", 0 },
{ "referrer", "referrer", LOG_HTTP_EXTENDED },
{ "refresh", "refresh", 0 },
{ "retry_after", "retry-after", 0 },
{ "server", "server", 0 },
{ "set_cookie", "set-cookie", 0 },
{ "trailer", "trailer", 0 },
{ "transfer_encoding", "transfer-encoding", 0 },
{ "upgrade", "upgrade", 0 },
{ "vary", "vary", 0 },
{ "warning", "warning", 0 },
{ "www_authenticate", "www-authenticate", 0 },
{ "true_client_ip", "true-client-ip", LOG_HTTP_REQUEST },
{ "org_src_ip", "org-src-ip", LOG_HTTP_REQUEST },
{ "x_bluecoat_via", "x-bluecoat-via", LOG_HTTP_REQUEST },
};
static void JsonHttpLogJSONBasic(json_t *js, htp_tx_t *tx)
{
char *c;
/* hostname */
if (tx->request_hostname != NULL)
{
c = bstr_util_strdup_to_c(tx->request_hostname);
if (c != NULL) {
json_object_set_new(js, "hostname", SCJsonString(c));
SCFree(c);
}
}
/* port */
/* NOTE: this field will be set ONLY if the port is present in the
* hostname. It may be present in the header "Host" or in the URL.
* There is no connection (from the suricata point of view) between this
* port and the TCP destination port of the flow.
*/
if (tx->request_port_number >= 0)
{
json_object_set_new(js, "http_port",
json_integer(tx->request_port_number));
}
/* uri */
if (tx->request_uri != NULL)
{
c = bstr_util_strdup_to_c(tx->request_uri);
if (c != NULL) {
json_object_set_new(js, "url", SCJsonString(c));
SCFree(c);
}
}
/* user agent */
htp_header_t *h_user_agent = NULL;
if (tx->request_headers != NULL) {
h_user_agent = htp_table_get_c(tx->request_headers, "user-agent");
}
if (h_user_agent != NULL) {
c = bstr_util_strdup_to_c(h_user_agent->value);
if (c != NULL) {
json_object_set_new(js, "http_user_agent", SCJsonString(c));
SCFree(c);
}
}
/* x-forwarded-for */
htp_header_t *h_x_forwarded_for = NULL;
if (tx->request_headers != NULL) {
h_x_forwarded_for = htp_table_get_c(tx->request_headers, "x-forwarded-for");
}
if (h_x_forwarded_for != NULL) {
c = bstr_util_strdup_to_c(h_x_forwarded_for->value);
if (c != NULL) {
json_object_set_new(js, "xff", json_string(c));
SCFree(c);
}
}
/* content-type */
htp_header_t *h_content_type = NULL;
if (tx->response_headers != NULL) {
h_content_type = htp_table_get_c(tx->response_headers, "content-type");
}
if (h_content_type != NULL) {
char *p;
c = bstr_util_strdup_to_c(h_content_type->value);
if (c != NULL) {
p = strchr(c, ';');
if (p != NULL)
*p = '\0';
json_object_set_new(js, "http_content_type", SCJsonString(c));
SCFree(c);
}
}
}
static void JsonHttpLogJSONCustom(LogHttpFileCtx *http_ctx, json_t *js, htp_tx_t *tx)
{
char *c;
HttpField f;
for (f = HTTP_FIELD_ACCEPT; f < HTTP_FIELD_SIZE; f++)
{
if ((http_ctx->fields & (1ULL<<f)) != 0)
{
/* prevent logging a field twice if extended logging is
enabled */
if (((http_ctx->flags & LOG_HTTP_EXTENDED) == 0) ||
((http_ctx->flags & LOG_HTTP_EXTENDED) !=
(http_fields[f].flags & LOG_HTTP_EXTENDED)))
{
htp_header_t *h_field = NULL;
if ((http_fields[f].flags & LOG_HTTP_REQUEST) != 0)
{
if (tx->request_headers != NULL) {
h_field = htp_table_get_c(tx->request_headers,
http_fields[f].htp_field);
}
} else {
if (tx->response_headers != NULL) {
h_field = htp_table_get_c(tx->response_headers,
http_fields[f].htp_field);
}
}
if (h_field != NULL) {
c = bstr_util_strdup_to_c(h_field->value);
if (c != NULL) {
json_object_set_new(js,
http_fields[f].config_field,
SCJsonString(c));
SCFree(c);
}
}
}
}
}
}
static void JsonHttpLogJSONExtended(json_t *js, htp_tx_t *tx)
{
char *c;
/* referer */
htp_header_t *h_referer = NULL;
if (tx->request_headers != NULL) {
h_referer = htp_table_get_c(tx->request_headers, "referer");
}
if (h_referer != NULL) {
c = bstr_util_strdup_to_c(h_referer->value);
if (c != NULL) {
json_object_set_new(js, "http_refer", SCJsonString(c));
SCFree(c);
}
}
/* method */
if (tx->request_method != NULL) {
c = bstr_util_strdup_to_c(tx->request_method);
if (c != NULL) {
json_object_set_new(js, "http_method", SCJsonString(c));
SCFree(c);
}
}
/* protocol */
if (tx->request_protocol != NULL) {
c = bstr_util_strdup_to_c(tx->request_protocol);
if (c != NULL) {
json_object_set_new(js, "protocol", SCJsonString(c));
SCFree(c);
}
}
/* response status */
if (tx->response_status != NULL) {
c = bstr_util_strdup_to_c(tx->response_status);
if (c != NULL) {
unsigned int val = strtoul(c, NULL, 10);
json_object_set_new(js, "status", json_integer(val));
SCFree(c);
}
htp_header_t *h_location = htp_table_get_c(tx->response_headers, "location");
if (h_location != NULL) {
c = bstr_util_strdup_to_c(h_location->value);
if (c != NULL) {
json_object_set_new(js, "redirect", SCJsonString(c));
SCFree(c);
}
}
}
/* length */
json_object_set_new(js, "length", json_integer(tx->response_message_len));
}
static void BodyPrintableBuffer(json_t *js, HtpBody *body, const char *key)
{
if (body->sb != NULL && body->sb->buf != NULL) {
uint32_t offset = 0;
const uint8_t *body_data;
uint32_t body_data_len;
uint64_t body_offset;
if (StreamingBufferGetData(body->sb, &body_data,
&body_data_len, &body_offset) == 0) {
return;
}
uint8_t printable_buf[body_data_len + 1];
PrintStringsToBuffer(printable_buf, &offset,
sizeof(printable_buf),
body_data, body_data_len);
if (offset > 0) {
json_object_set_new(js, key, json_string((char *)printable_buf));
}
}
}
void JsonHttpLogJSONBodyPrintable(json_t *js, Flow *f, uint64_t tx_id)
{
HtpState *htp_state = (HtpState *)FlowGetAppState(f);
if (htp_state) {
htp_tx_t *tx = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP, htp_state, tx_id);
if (tx) {
HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx);
if (htud != NULL) {
BodyPrintableBuffer(js, &htud->request_body, "http_request_body_printable");
BodyPrintableBuffer(js, &htud->response_body, "http_response_body_printable");
}
}
}
}
static void BodyBase64Buffer(json_t *js, HtpBody *body, const char *key)
{
if (body->sb != NULL && body->sb->buf != NULL) {
const uint8_t *body_data;
uint32_t body_data_len;
uint64_t body_offset;
if (StreamingBufferGetData(body->sb, &body_data,
&body_data_len, &body_offset) == 0) {
return;
}
unsigned long len = body_data_len * 2 + 1;
uint8_t encoded[len];
if (Base64Encode(body_data, body_data_len, encoded, &len) == SC_BASE64_OK) {
json_object_set_new(js, key, json_string((char *)encoded));
}
}
}
void JsonHttpLogJSONBodyBase64(json_t *js, Flow *f, uint64_t tx_id)
{
HtpState *htp_state = (HtpState *)FlowGetAppState(f);
if (htp_state) {
htp_tx_t *tx = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP, htp_state, tx_id);
if (tx) {
HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx);
if (htud != NULL) {
BodyBase64Buffer(js, &htud->request_body, "http_request_body");
BodyBase64Buffer(js, &htud->response_body, "http_response_body");
}
}
}
}
/* JSON format logging */
static void JsonHttpLogJSON(JsonHttpLogThread *aft, json_t *js, htp_tx_t *tx, uint64_t tx_id)
{
LogHttpFileCtx *http_ctx = aft->httplog_ctx;
json_t *hjs = json_object();
if (hjs == NULL) {
return;
}
JsonHttpLogJSONBasic(hjs, tx);
/* log custom fields if configured */
if (http_ctx->fields != 0)
JsonHttpLogJSONCustom(http_ctx, hjs, tx);
if (http_ctx->flags & LOG_HTTP_EXTENDED)
JsonHttpLogJSONExtended(hjs, tx);
json_object_set_new(js, "http", hjs);
}
static int JsonHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *alstate, void *txptr, uint64_t tx_id)
{
SCEnter();
htp_tx_t *tx = txptr;
JsonHttpLogThread *jhl = (JsonHttpLogThread *)thread_data;
json_t *js = CreateJSONHeaderWithTxId(p, LOG_DIR_FLOW, "http", tx_id);
if (unlikely(js == NULL))
return TM_ECODE_OK;
JsonAddCommonOptions(&jhl->httplog_ctx->cfg, p, f, js);
SCLogDebug("got a HTTP request and now logging !!");
/* reset */
MemBufferReset(jhl->buffer);
JsonHttpLogJSON(jhl, js, tx, tx_id);
HttpXFFCfg *xff_cfg = jhl->httplog_ctx->xff_cfg != NULL ?
jhl->httplog_ctx->xff_cfg : jhl->httplog_ctx->parent_xff_cfg;
/* xff header */
if ((xff_cfg != NULL) && !(xff_cfg->flags & XFF_DISABLED) && p->flow != NULL) {
int have_xff_ip = 0;
char buffer[XFF_MAXLEN];
have_xff_ip = HttpXFFGetIPFromTx(p->flow, tx_id, xff_cfg, buffer, XFF_MAXLEN);
if (have_xff_ip) {
if (xff_cfg->flags & XFF_EXTRADATA) {
json_object_set_new(js, "xff", json_string(buffer));
}
else if (xff_cfg->flags & XFF_OVERWRITE) {
if (p->flowflags & FLOW_PKT_TOCLIENT) {
json_object_set(js, "dest_ip", json_string(buffer));
} else {
json_object_set(js, "src_ip", json_string(buffer));
}
}
}
}
OutputJSONBuffer(js, jhl->httplog_ctx->file_ctx, &jhl->buffer);
json_object_del(js, "http");
json_object_clear(js);
json_decref(js);
SCReturnInt(TM_ECODE_OK);
}
json_t *JsonHttpAddMetadata(const Flow *f, uint64_t tx_id)
{
HtpState *htp_state = (HtpState *)FlowGetAppState(f);
if (htp_state) {
htp_tx_t *tx = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP, htp_state, tx_id);
if (tx) {
json_t *hjs = json_object();
if (unlikely(hjs == NULL))
return NULL;
JsonHttpLogJSONBasic(hjs, tx);
JsonHttpLogJSONExtended(hjs, tx);
return hjs;
}
}
return NULL;
}
static void OutputHttpLogDeinit(OutputCtx *output_ctx)
{
LogHttpFileCtx *http_ctx = output_ctx->data;
LogFileCtx *logfile_ctx = http_ctx->file_ctx;
LogFileFreeCtx(logfile_ctx);
if (http_ctx->xff_cfg) {
SCFree(http_ctx->xff_cfg);
}
SCFree(http_ctx);
SCFree(output_ctx);
}
#define DEFAULT_LOG_FILENAME "http.json"
static OutputInitResult OutputHttpLogInit(ConfNode *conf)
{
OutputInitResult result = { NULL, false };
LogFileCtx *file_ctx = LogFileNewCtx();
if(file_ctx == NULL) {
SCLogError(SC_ERR_HTTP_LOG_GENERIC, "couldn't create new file_ctx");
return result;
}
if (SCConfLogOpenGeneric(conf, file_ctx, DEFAULT_LOG_FILENAME, 1) < 0) {
LogFileFreeCtx(file_ctx);
return result;
}
LogHttpFileCtx *http_ctx = SCMalloc(sizeof(LogHttpFileCtx));
if (unlikely(http_ctx == NULL)) {
LogFileFreeCtx(file_ctx);
return result;
}
OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx));
if (unlikely(output_ctx == NULL)) {
LogFileFreeCtx(file_ctx);
SCFree(http_ctx);
return result;
}
http_ctx->file_ctx = file_ctx;
http_ctx->flags = LOG_HTTP_DEFAULT;
if (conf) {
const char *extended = ConfNodeLookupChildValue(conf, "extended");
if (extended != NULL) {
if (ConfValIsTrue(extended)) {
http_ctx->flags = LOG_HTTP_EXTENDED;
}
}
}
http_ctx->xff_cfg = SCCalloc(1, sizeof(HttpXFFCfg));
if (http_ctx->xff_cfg != NULL) {
HttpXFFGetCfg(conf, http_ctx->xff_cfg);
}
output_ctx->data = http_ctx;
output_ctx->DeInit = OutputHttpLogDeinit;
/* enable the logger for the app layer */
AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_HTTP);
result.ctx = output_ctx;
result.ok = true;
return result;
}
static void OutputHttpLogDeinitSub(OutputCtx *output_ctx)
{
LogHttpFileCtx *http_ctx = output_ctx->data;
if (http_ctx->xff_cfg) {
SCFree(http_ctx->xff_cfg);
}
SCFree(http_ctx);
SCFree(output_ctx);
}
static OutputInitResult OutputHttpLogInitSub(ConfNode *conf, OutputCtx *parent_ctx)
{
OutputInitResult result = { NULL, false };
OutputJsonCtx *ojc = parent_ctx->data;
LogHttpFileCtx *http_ctx = SCCalloc(1, sizeof(LogHttpFileCtx));
if (unlikely(http_ctx == NULL))
return result;
memset(http_ctx, 0x00, sizeof(*http_ctx));
OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx));
if (unlikely(output_ctx == NULL)) {
SCFree(http_ctx);
return result;
}
http_ctx->file_ctx = ojc->file_ctx;
http_ctx->flags = LOG_HTTP_DEFAULT;
http_ctx->cfg = ojc->cfg;
if (conf) {
const char *extended = ConfNodeLookupChildValue(conf, "extended");
if (extended != NULL) {
if (ConfValIsTrue(extended)) {
http_ctx->flags = LOG_HTTP_EXTENDED;
}
}
ConfNode *custom;
if ((custom = ConfNodeLookupChild(conf, "custom")) != NULL) {
ConfNode *field;
TAILQ_FOREACH(field, &custom->head, next)
{
if (field != NULL)
{
HttpField f;
for (f = HTTP_FIELD_ACCEPT; f < HTTP_FIELD_SIZE; f++)
{
if ((strcmp(http_fields[f].config_field,
field->val) == 0) ||
(strcasecmp(http_fields[f].htp_field,
field->val) == 0))
{
http_ctx->fields |= (1ULL<<f);
break;
}
}
}
}
}
}
if (conf != NULL && ConfNodeLookupChild(conf, "xff") != NULL) {
http_ctx->xff_cfg = SCCalloc(1, sizeof(HttpXFFCfg));
if (http_ctx->xff_cfg != NULL) {
HttpXFFGetCfg(conf, http_ctx->xff_cfg);
}
} else if (ojc->xff_cfg) {
http_ctx->parent_xff_cfg = ojc->xff_cfg;
}
output_ctx->data = http_ctx;
output_ctx->DeInit = OutputHttpLogDeinitSub;
/* enable the logger for the app layer */
AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_HTTP);
result.ctx = output_ctx;
result.ok = true;
return result;
}
#define OUTPUT_BUFFER_SIZE 65535
static TmEcode JsonHttpLogThreadInit(ThreadVars *t, const void *initdata, void **data)
{
JsonHttpLogThread *aft = SCMalloc(sizeof(JsonHttpLogThread));
if (unlikely(aft == NULL))
return TM_ECODE_FAILED;
memset(aft, 0, sizeof(JsonHttpLogThread));
if(initdata == NULL)
{
SCLogDebug("Error getting context for EveLogHTTP. \"initdata\" argument NULL");
SCFree(aft);
return TM_ECODE_FAILED;
}
/* Use the Ouptut Context (file pointer and mutex) */
aft->httplog_ctx = ((OutputCtx *)initdata)->data; //TODO
aft->buffer = MemBufferCreateNew(OUTPUT_BUFFER_SIZE);
if (aft->buffer == NULL) {
SCFree(aft);
return TM_ECODE_FAILED;
}
*data = (void *)aft;
return TM_ECODE_OK;
}
static TmEcode JsonHttpLogThreadDeinit(ThreadVars *t, void *data)
{
JsonHttpLogThread *aft = (JsonHttpLogThread *)data;
if (aft == NULL) {
return TM_ECODE_OK;
}
MemBufferFree(aft->buffer);
/* clear memory */
memset(aft, 0, sizeof(JsonHttpLogThread));
SCFree(aft);
return TM_ECODE_OK;
}
void JsonHttpLogRegister (void)
{
/* register as separate module */
OutputRegisterTxModule(LOGGER_JSON_HTTP, "JsonHttpLog", "http-json-log",
OutputHttpLogInit, ALPROTO_HTTP, JsonHttpLogger, JsonHttpLogThreadInit,
JsonHttpLogThreadDeinit, NULL);
/* also register as child of eve-log */
OutputRegisterTxSubModule(LOGGER_JSON_HTTP, "eve-log", "JsonHttpLog",
"eve-log.http", OutputHttpLogInitSub, ALPROTO_HTTP, JsonHttpLogger,
JsonHttpLogThreadInit, JsonHttpLogThreadDeinit, NULL);
}
#else
void JsonHttpLogRegister (void)
{
}
#endif
|
SocialGouv/emjpm | packages/app/src/containers/AdminUserService/AdminUserServiceForm.js | <reponame>SocialGouv/emjpm
import { useFormik } from "formik";
import { Box, Flex } from "rebass";
import {
FormGrayBox,
FormGroupInput,
FormInputBox,
} from "~/components/AppForm";
import { Link } from "~/containers/Commons";
import { adminUserServiceSchema } from "~/validation-schemas";
import { Button, Heading } from "~/components";
function AdminUserServiceForm(props) {
const { cancelLink, user, handleSubmit } = props;
const { nom, prenom, email, service_members } = user;
const [serviceMember] = service_members;
const { service } = serviceMember;
const formik = useFormik({
initialValues: {
email: email || "",
nom: nom || "",
prenom: prenom || "",
},
onSubmit: handleSubmit,
validationSchema: adminUserServiceSchema,
});
return (
<form noValidate onSubmit={formik.handleSubmit}>
<Flex>
<FormGrayBox>
<Heading size={4} mb={1}>{`${service.etablissement}`}</Heading>
</FormGrayBox>
<FormInputBox>
<FormGroupInput
placeholder="Prénom"
id="prenom"
formik={formik}
validationSchema={adminUserServiceSchema}
/>
<FormGroupInput
placeholder="Nom"
id="nom"
formik={formik}
validationSchema={adminUserServiceSchema}
/>
<FormGroupInput
placeholder="Email"
id="email"
formik={formik}
validationSchema={adminUserServiceSchema}
/>
</FormInputBox>
</Flex>
<Flex p={2} alignItems="center" justifyContent="flex-end">
<Box mr="2">
<Link to={cancelLink}>
<Button variant="outline">Annuler</Button>
</Link>
</Box>
<Box>
<Button
type="submit"
disabled={formik.isSubmitting}
isLoading={formik.isSubmitting}
>
Enregistrer
</Button>
</Box>
</Flex>
</form>
);
}
export { AdminUserServiceForm };
|
AlohaChina/or-tools | docs/cpp_routing/search/related_1.js | <filename>docs/cpp_routing/search/related_1.js<gh_stars>1000+
var searchData=
[
['appenddimensioncumulfilters_0',['AppendDimensionCumulFilters',['../classoperations__research_1_1_routing_dimension.html#a0e3e4445c55d0c59ef4edbaf7acbd3a8',1,'operations_research::RoutingDimension']]]
];
|
RobinSchmidt/RS-MET-Preliminary | Libraries/RobsJuceModules/rosic/legacy/OnePoleFilter.h | #ifndef OnePoleFilter_h
#define OnePoleFilter_h
//#include "AudioModule.h"
#include "Definitions.h"
#include "MoreMath.h"
/**
This is an implementation of a simple one-pole filter unit, which mimics an
analog RC-Filter circuit. It has 2 modes: lowpass and highpass.
*/
class OnePoleFilter
{
public:
/** This is an enumeration of the available filter modes. */
enum modes
{
BYPASS = 0,
LOWPASS,
HIGHPASS
};
//---------------------------------------------------------------------------
// construction/destruction:
OnePoleFilter(); ///< Constructor.
~OnePoleFilter(); ///< Destructor.
//---------------------------------------------------------------------------
// parameter settings:
void setSampleRate(double newSampleRate);
///< Overrides the setSampleRate() method of the AudioModule base class.
void setMode(int newMode);
///< Chooses the filter mode. See the enumeration above for available modes.
void setCutoff(double newCutoff);
void setCoeffs(double newB0,
double newB1,
double newA1);
///< Sets the filter coefficients manually.
//---------------------------------------------------------------------------
// audio processing:
INLINE double getSample(double in);
//---------------------------------------------------------------------------
// others:
void resetBuffers();
//===========================================================================
protected:
// buffering:
double x_1;
double y_1;
// filter coefficients:
double b0; // feedforward coeffs
double b1;
double a1; // feedback coeff
// filter parameters:
double cutoff;
int mode;
double sampleRate;
double sampleRateRec; // reciprocal of the sampleRate
// internal functions:
void calcCoeffs(); // calculates filter coefficients from filter parameters
};
//-----------------------------------------------------------------------------
//from here: definitions of the functions to be inlined, i.e. all functions
//which are supposed to be called at audio-rate (they can't be put into
//the .cpp file):
INLINE double OnePoleFilter::getSample(double in)
{
// calculate the output sample:
y_1 = b0*in
+ b1*x_1
+ a1*y_1
+ TINY;
// update the buffer variables:
x_1 = in;
return y_1;
}
#endif // OnePoleFilter_h
|
geektcp/alpha-lab | alpha-auth/alpha-auth-oauth2/alpha-auth-oauth2-server/src/main/java/com/geektcp/alpha/sso/server/vo/SysUserVO.java | package com.geektcp.alpha.sso.server.vo;
import com.geektcp.alpha.sso.server.entity.SysUser;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* @author tanghaiyang
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class SysUserVO extends SysUser {
/**
* 权限列表
*/
private List<String> authorityList;
}
|
samirans89/wcm-io-qa-galenium | modules/core/src/main/java/io/wcm/qa/glnm/pairwise/Tupel.java | <reponame>samirans89/wcm-io-qa-galenium<filename>modules/core/src/main/java/io/wcm/qa/glnm/pairwise/Tupel.java
/*
* #%L
* wcm.io
* %%
* Copyright (C) 2019 wcm.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.
* #L%
*/
package io.wcm.qa.glnm.pairwise;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
class Tupel {
private static final int NOT_SET = -1;
private int[] indices;
Tupel(int size) {
indices = new int[size];
Arrays.fill(indices, NOT_SET);
}
/** {@inheritDoc} */
@Override
public String toString() {
return "(" + StringUtils.join(indices, ", ") + ")";
}
private boolean matches(Value value) {
return value.getValue() == getValueForDomain(value.getDomain());
}
int getValueForDomain(int domain) {
return indices[domain];
}
boolean hasValueForDomain(int domain) {
return getValueForDomain(domain) != NOT_SET;
}
boolean hasValueForDomainOf(Value value) {
return hasValueForDomain(value.getDomain());
}
int[] toArray() {
return Arrays.copyOf(indices, indices.length);
}
boolean isFinished() {
return !ArrayUtils.contains(indices, NOT_SET);
}
boolean satisfies(Requirement req) {
return matches(req.getValueA()) && matches(req.getValueB());
}
void set(Value value) {
indices[value.getDomain()] = value.getValue();
}
/**
* <p>satisfy.</p>
*
* @param requirement a {@link io.wcm.qa.glnm.pairwise.Requirement} object.
* @return a boolean.
* @since 5.0.0
*/
public boolean satisfy(Requirement requirement) {
if (satisfies(requirement)) {
return true;
}
if (isFinished()) {
return false;
}
Value valueA = requirement.getValueA();
if (hasValueForDomainOf(valueA) && !matches(valueA)) {
return false;
}
Value valueB = requirement.getValueB();
if (hasValueForDomainOf(valueB) && !matches(valueB)) {
return false;
}
set(valueA);
set(valueB);
return true;
}
void finish() {
for (int i = 0; i < indices.length; i++) {
if (!hasValueForDomain(i)) {
indices[i] = 0;
}
}
}
}
|
maxirosson/jdroid-java-webapp | jdroid-java-webapp-sample/src/main/java/com/jdroid/javaweb/sample/firebase/SampleInnerEntity.java | package com.jdroid.javaweb.sample.firebase;
public class SampleInnerEntity {
private String stringField;
private Long longField;
public Long getLongField() {
return longField;
}
public void setLongField(Long longField) {
this.longField = longField;
}
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
}
|
larrytheliquid/dataflow | examples/laziness.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
local do |x, y, z|
Thread.new { unify y, by_need { 4 } }
Thread.new { unify z, x + y }
Thread.new { unify x, by_need { 3 } }
puts z
end
|
kalen2019/sp | code/c/03-asmVm/qemu/src/qemu-0.9.1/x_keymap.c | <reponame>kalen2019/sp
/*
* QEMU SDL display driver
*
* Copyright (c) 2003 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "qemu-common.h"
#include "console.h"
static const uint8_t x_keycode_to_pc_keycode[115] = {
0xc7, /* 97 Home */
0xc8, /* 98 Up */
0xc9, /* 99 PgUp */
0xcb, /* 100 Left */
0x4c, /* 101 KP-5 */
0xcd, /* 102 Right */
0xcf, /* 103 End */
0xd0, /* 104 Down */
0xd1, /* 105 PgDn */
0xd2, /* 106 Ins */
0xd3, /* 107 Del */
0x9c, /* 108 Enter */
0x9d, /* 109 Ctrl-R */
0x0, /* 110 Pause */
0xb7, /* 111 Print */
0xb5, /* 112 Divide */
0xb8, /* 113 Alt-R */
0xc6, /* 114 Break */
0x0, /* 115 */
0x0, /* 116 */
0x0, /* 117 */
0x0, /* 118 */
0x0, /* 119 */
0x0, /* 120 */
0x0, /* 121 */
0x0, /* 122 */
0x0, /* 123 */
0x0, /* 124 */
0x0, /* 125 */
0x0, /* 126 */
0x0, /* 127 */
0x0, /* 128 */
0x79, /* 129 Henkan */
0x0, /* 130 */
0x7b, /* 131 Muhenkan */
0x0, /* 132 */
0x7d, /* 133 Yen */
0x0, /* 134 */
0x0, /* 135 */
0x47, /* 136 KP_7 */
0x48, /* 137 KP_8 */
0x49, /* 138 KP_9 */
0x4b, /* 139 KP_4 */
0x4c, /* 140 KP_5 */
0x4d, /* 141 KP_6 */
0x4f, /* 142 KP_1 */
0x50, /* 143 KP_2 */
0x51, /* 144 KP_3 */
0x52, /* 145 KP_0 */
0x53, /* 146 KP_. */
0x47, /* 147 KP_HOME */
0x48, /* 148 KP_UP */
0x49, /* 149 KP_PgUp */
0x4b, /* 150 KP_Left */
0x4c, /* 151 KP_ */
0x4d, /* 152 KP_Right */
0x4f, /* 153 KP_End */
0x50, /* 154 KP_Down */
0x51, /* 155 KP_PgDn */
0x52, /* 156 KP_Ins */
0x53, /* 157 KP_Del */
0x0, /* 158 */
0x0, /* 159 */
0x0, /* 160 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, /* 170 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, /* 180 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, /* 190 */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, /* 200 */
0x0, /* 201 */
0x0, /* 202 */
0x0, /* 203 */
0x0, /* 204 */
0x0, /* 205 */
0x0, /* 206 */
0x0, /* 207 */
0x70, /* 208 Hiragana_Katakana */
0x0, /* 209 */
0x0, /* 210 */
0x73, /* 211 backslash */
};
uint8_t _translate_keycode(const int key)
{
return x_keycode_to_pc_keycode[key];
}
|
yudanli/fast_ber | include/fast_ber/ber_types/UTF8String.hpp | #pragma once
#include "fast_ber/ber_types/StringImpl.hpp"
#include "fast_ber/ber_types/Tag.hpp"
namespace fast_ber
{
template <typename Identifier = ExplicitId<UniversalTag::utf8_string>>
using UTF8String = fast_ber::StringImpl<UniversalTag::utf8_string, Identifier>;
}
|
TecArt/servicecatalog-development | oscm-database-unittests/javasrc-it/org/oscm/database/SchemaUpgrade_02_08_06_to_02_08_07_IT.java | <filename>oscm-database-unittests/javasrc-it/org/oscm/database/SchemaUpgrade_02_08_06_to_02_08_07_IT.java
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 03.09.2012
*
*******************************************************************************/
package org.oscm.database;
import java.net.URL;
import org.oscm.setup.DatabaseVersionInfo;
public class SchemaUpgrade_02_08_06_to_02_08_07_IT extends
SchemaUpgradeTestBase {
public SchemaUpgrade_02_08_06_to_02_08_07_IT() {
super(new DatabaseVersionInfo(2, 8, 6),
new DatabaseVersionInfo(2, 8, 7));
}
@Override
protected URL getSetupDataset() {
return getClass().getResource("/setup_02_08_06_to_02_08_07.xml");
}
@Override
protected URL getExpectedDataset() {
return getClass().getResource("/expected_02_08_06_to_02_08_07.xml");
}
}
|
colemujadzic/old | oldish-dotfiles/.vscode/extensions/peterjausovec.vscode-docker-0.3.1/out/commands/utils/quick-pick-azure.js | <filename>oldish-dotfiles/.vscode/extensions/peterjausovec.vscode-docker-0.3.1/out/commands/utils/quick-pick-azure.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const opn = require("opn");
const vscode = require("vscode");
const vscode_azureextensionui_1 = require("vscode-azureextensionui");
const constants_1 = require("../../constants");
const extensionVariables_1 = require("../../extensionVariables");
const acrTools = require("../../utils/Azure/acrTools");
const common_1 = require("../../utils/Azure/common");
const azureUtilityManager_1 = require("../../utils/azureUtilityManager");
async function quickPickACRImage(repository, prompt) {
const placeHolder = prompt ? prompt : 'Select image to use';
const repoImages = await acrTools.getImagesByRepository(repository);
const imageListNames = repoImages.map(img => ({ label: img.tag, data: img }));
let desiredImage = await extensionVariables_1.ext.ui.showQuickPick(imageListNames, { 'canPickMany': false, 'placeHolder': placeHolder });
return desiredImage.data;
}
exports.quickPickACRImage = quickPickACRImage;
async function quickPickACRRepository(registry, prompt) {
const placeHolder = prompt ? prompt : 'Select repository to use';
const repositories = await acrTools.getRepositoriesByRegistry(registry);
const quickPickRepoList = repositories.map(repo => ({ label: repo.name, data: repo }));
let desiredRepo = await extensionVariables_1.ext.ui.showQuickPick(quickPickRepoList, { 'canPickMany': false, 'placeHolder': placeHolder });
return desiredRepo.data;
}
exports.quickPickACRRepository = quickPickACRRepository;
async function quickPickACRRegistry(canCreateNew = false, prompt) {
const placeHolder = prompt ? prompt : 'Select registry to use';
let registries = await azureUtilityManager_1.AzureUtilityManager.getInstance().getRegistries();
let quickPickRegList = registries.map(reg => ({ label: reg.name, data: reg }));
let createNewItem = { label: '+ Create new registry', data: undefined };
if (canCreateNew) {
quickPickRegList.unshift(createNewItem);
}
let desiredReg = await extensionVariables_1.ext.ui.showQuickPick(quickPickRegList, {
'canPickMany': false,
'placeHolder': placeHolder
});
let registry;
if (desiredReg === createNewItem) {
registry = await vscode.commands.executeCommand("vscode-docker.create-ACR-Registry");
}
else {
registry = desiredReg.data;
}
return registry;
}
exports.quickPickACRRegistry = quickPickACRRegistry;
async function quickPickSKU() {
const quickPickSkuList = constants_1.skus.map(sk => ({ label: sk, data: sk }));
let desiredSku = await extensionVariables_1.ext.ui.showQuickPick(quickPickSkuList, {
'canPickMany': false,
'placeHolder': 'Choose a SKU to use'
});
return desiredSku.data;
}
exports.quickPickSKU = quickPickSKU;
async function quickPickSubscription() {
const subscriptions = azureUtilityManager_1.AzureUtilityManager.getInstance().getFilteredSubscriptionList();
if (subscriptions.length === 0) {
vscode.window.showErrorMessage("You do not have any subscriptions. You can create one in your Azure portal", "Open Portal").then(val => {
if (val === "Open Portal") {
// tslint:disable-next-line:no-unsafe-any
opn('https://portal.azure.com/');
}
});
}
if (subscriptions.length === 1) {
return subscriptions[0];
}
let quickPickSubList = subscriptions.map(sub => ({ label: sub.displayName, data: sub }));
let desiredSub = await extensionVariables_1.ext.ui.showQuickPick(quickPickSubList, {
'canPickMany': false,
'placeHolder': 'Select a subscription to use'
});
return desiredSub.data;
}
exports.quickPickSubscription = quickPickSubscription;
async function quickPickLocation(subscription) {
let locations = await azureUtilityManager_1.AzureUtilityManager.getInstance().getLocationsBySubscription(subscription);
let quickPickLocList = locations.map(loc => ({ label: loc.displayName, data: loc }));
quickPickLocList.sort((loc1, loc2) => {
return loc1.data.displayName.localeCompare(loc2.data.displayName);
});
let desiredLocation = await extensionVariables_1.ext.ui.showQuickPick(quickPickLocList, {
'canPickMany': false,
'placeHolder': 'Select a location to use'
});
return desiredLocation.label;
}
exports.quickPickLocation = quickPickLocation;
async function quickPickResourceGroup(canCreateNew, subscription) {
let resourceGroups = await azureUtilityManager_1.AzureUtilityManager.getInstance().getResourceGroups(subscription);
let quickPickResourceGroups = resourceGroups.map(res => ({ label: res.name, data: res }));
let createNewItem = { label: '+ Create new resource group', data: undefined };
if (canCreateNew) {
quickPickResourceGroups.unshift(createNewItem);
}
let desiredResGroup = await extensionVariables_1.ext.ui.showQuickPick(quickPickResourceGroups, {
'canPickMany': false,
'placeHolder': 'Choose a resource group to use'
});
let resourceGroup;
if (desiredResGroup === createNewItem) {
if (!subscription) {
subscription = await quickPickSubscription();
}
const loc = await quickPickLocation(subscription);
resourceGroup = await createNewResourceGroup(loc, subscription);
}
else {
resourceGroup = desiredResGroup.data;
}
return resourceGroup;
}
exports.quickPickResourceGroup = quickPickResourceGroup;
/** Requests confirmation for an action and returns true only in the case that the user types in yes
* @param yesOrNoPrompt Should be a yes or no question
*/
async function confirmUserIntent(yesOrNoPrompt) {
let opt = {
ignoreFocusOut: true,
placeHolder: 'Enter "Yes"',
value: 'No',
prompt: yesOrNoPrompt + ' Enter yes to continue'
};
let answer = await extensionVariables_1.ext.ui.showInputBox(opt);
answer = answer.toLowerCase();
if (answer === 'yes') {
return answer === 'yes';
}
else {
throw new vscode_azureextensionui_1.UserCancelledError();
}
}
exports.confirmUserIntent = confirmUserIntent;
/*Creates a new resource group within the current subscription */
async function createNewResourceGroup(loc, subscription) {
const resourceGroupClient = azureUtilityManager_1.AzureUtilityManager.getInstance().getResourceManagementClient(subscription);
let opt = {
validateInput: async (value) => { return await checkForValidResourcegroupName(value, resourceGroupClient); },
ignoreFocusOut: false,
prompt: 'New resource group name?'
};
let resourceGroupName = await extensionVariables_1.ext.ui.showInputBox(opt);
let newResourceGroup = {
name: resourceGroupName,
location: loc,
};
return await resourceGroupClient.resourceGroups.createOrUpdate(resourceGroupName, newResourceGroup);
}
async function checkForValidResourcegroupName(resourceGroupName, resourceGroupClient) {
let check = common_1.isValidAzureName(resourceGroupName);
if (!check.isValid) {
return check.message;
}
let resourceGroupStatus = await resourceGroupClient.resourceGroups.checkExistence(resourceGroupName);
if (resourceGroupStatus) {
return 'This resource group is already in use';
}
return undefined;
}
//# sourceMappingURL=quick-pick-azure.js.map |
SparoJ/mathLogic | JavaPractice/src/com/sparo/thread/ABThreadTest.java | package com.sparo.thread;
/**
* description: 如何让 threadA 和 threadB 依次顺序累加打印 1->100的数字
* Created by sdh on 2019-12-01
*/
public class ABThreadTest {
public int a = 0;
private final Object monitor = new Object();
// public static final Runnable RUNNABLE = new Runnable() {
// public void run() {
// a++;
// System.out.println(a);
// }
// };
public static void main(String[] args) {
// testErrorMethod();
ABThreadTest test = new ABThreadTest();
test.testOddEven();
// test.testMultiThread(2);
// test. obtainStr();
}
public void obtainStr() {
String str = "https://pan.ba\"Hello\"idu.c\"Hello\"om/s/1Ok\"Hello\"xQ1838Cz\"Hello\"pxIev\"Hello\"QhRUlrQ";
String rs = str.replace("\"Hello\"","");
System.out.println(rs);
}
// 两个线程时能保证执行的顺序 且循环 但当大于2时不能
public void testOddEven() {
Thread threadA = new Thread(oddEvenRun, "偶数");
Thread threadB = new Thread(oddEvenRun, "奇数");
threadA.start();
threadB.start();
}
/**
* 如何唤醒指定的java 线程?
* @param count
*/
public void testMultiThread(int count) {
for (int i = 0; i < count; i++) {
Thread thread = new Thread(oddEvenRun, i+"-->>thread");
thread.start();
}
}
static String[] abcArr = {"A", "B", "C"};
static int threadCount = 4;
public Runnable oddEvenRun = new Runnable() {
public void run() {
try {
while(a<=99) {
synchronized (monitor) {
monitor.notify();
// System.out.println("thread count number::" + (abcArr[(a-1)%abcArr.length]) + "-->>thread name::" + Thread.currentThread().getName());
System.out.println("thread count number::" + (a++) + "-->>thread name::" + Thread.currentThread().getName());
monitor.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// private static void testErrorMethod() {
// Thread threadA = new Thread(RUNNABLE);
// Thread threadB = new Thread(RUNNABLE);
// try {
// while (a<=99) {
// /**
// * IllegalThreadStateException java 线程不能重复start 否则 抛出异常
// * if (threadStatus != 0)
// * throw new IllegalThreadStateException();
// *
// * 解决: 即循环处理 start在循环外层,给thread 传入runnable
// */
//
// threadA.start();
// threadA.join();
// threadB.start();
// threadB.join();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
|
apache/tuscany-sca-2.x | modules/common-http/src/main/java/org/apache/tuscany/sca/common/http/HTTPUtils.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.tuscany.sca.common.http;
import java.math.BigInteger;
import java.security.MessageDigest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @tuscany.spi.extension.asclient
*
*/
public class HTTPUtils {
/**
* Utility method to set common http headers and other stuff in a
* default http response. Applications / Extensions can then override and
* tweak as they see fit.
*
* @param response
*/
public static void prepareHTTPResponse(HttpServletResponse response) {
response.setDateHeader("Date", System.currentTimeMillis());
}
/**
* Calculate the relative request path taking in consideration if
* the application is running in a embedded webContatiner or from
* within a web application server host environment
*
* @param request The http request
* @return the relative path
*/
public static String getRequestPath(HttpServletRequest request) {
// Get the request path
String contextPath = request.getContextPath();
String servletPath = request.getServletPath();
String requestURI = request.getRequestURI();
int contextPathLength = contextPath.length();
int servletPathLenght = servletPath.contains(contextPath) ? servletPath.length() - contextPath.length() : servletPath.length();
String requestPath = requestURI.substring(contextPathLength + servletPathLenght);
return requestPath;
}
/**
* Calculate the context root for an application taking in consideration if
* the application is running in a embedded webContatiner or from
* within a web application server host environment.
*
* In the case of webContainer the contextRoot will always be a empty string.
*
* @param request The http request
* @return the contextRoot
*/
public static String getContextRoot(HttpServletRequest request) {
// Get the request path
String contextPath = request.getContextPath();
String requestURI = request.getRequestURI();
int contextPathLength = contextPath.length();
String contextRoot = requestURI.substring(0, contextPathLength);
return contextRoot;
}
/**
* Calculate the ETag using MD5 Hash Algorithm
* @param content the content to hash
* @return
*/
public static String calculateHashETag(byte[] content) {
String eTag = "invalid";
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] digest = messageDigest.digest(content);
BigInteger number = new BigInteger(1, digest);
StringBuffer sb = new StringBuffer('0');
sb.append(number.toString(16));
eTag = sb.toString();
} catch(Exception e) {
//ignore, we will return random etag
eTag = Integer.toString((new java.util.Random()).nextInt(Integer.MAX_VALUE));
}
return eTag;
}
}
|
tizenorg/platform.framework.web.wrt-commons | modules/utils/include/dpl/utils/warp_iri.h | <reponame>tizenorg/platform.framework.web.wrt-commons<gh_stars>0
/*
* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _WARPIRI_H_
#define _WARPIRI_H_
#include <vector>
#include <dpl/string.h>
#include <dpl/log/log.h>
class WarpIRI
{
static const unsigned int UNKNOWN_PORT = 0;
public:
WarpIRI();
void set(const char *iri,
bool domain);
void set(const DPL::String &iristring,
bool domain);
/* It also checks port and schema */
bool isSubDomain(const WarpIRI &second) const;
bool isAccessDefinition() const;
// KW bool isIRIValid() const;
bool getSubDomain() const;
/* This is debug function */
// KW void print() const {
// KW LogInfo("P:" << m_port << " S:" << m_schema);
// KW for (size_t i = 0; i < m_host.size(); ++i)
// KW LogInfo(" " << m_host[i]);
// KW }
static bool isIRISchemaIgnored(const char *iri);
bool operator ==(const WarpIRI &other) const
{
return m_domain == other.m_domain &&
m_host == other.m_host &&
m_schema == other.m_schema &&
m_port == other.m_port &&
m_isAccessDefinition == other.m_isAccessDefinition &&
m_isIRIValid == other.m_isIRIValid;
}
private:
unsigned int getPort(const DPL::String &schema) const;
bool m_domain;
std::vector<DPL::String> m_host;
DPL::String m_schema;
unsigned int m_port;
bool m_isAccessDefinition;
bool m_isIRIValid;
};
#endif // _WarpIRI_H_
|
kklein/icontract | tests_3_6/__init__.py | <filename>tests_3_6/__init__.py
"""
Test Python 3.6-specific features.
For example, one such feature is literal string interpolation.
"""
import sys
if sys.version_info < (3, 6):
def load_tests(loader, suite, pattern): # pylint: disable=unused-argument
"""Ignore all the tests for lower Python versions."""
return suite
|
brandonbraun653/Apollo | lib/am335x_sdk/ti/drv/pm/include/pmic/pmhal_tps659037.h | <filename>lib/am335x_sdk/ti/drv/pm/include/pmic/pmhal_tps659037.h
/* =============================================================================
* Copyright (c) Texas Instruments Incorporated 2016
*
* 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.
*
* Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE COPYRIGHT
* OWNER 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.
*
*/
/**
* \file pmhal_tps659037.h
*
* \brief The Power Management IC (PMIC) tps659037 specific API definition.
*
* The APIs defined here are to control the voltage of the
* PMIC rails and to query the status.
*/
#ifndef PM_TPS659037_H_
#define PM_TPS659037_H_
/* ========================================================================== */
/* Include Files */
/* ========================================================================== */
/* None */
#ifdef __cplusplus
extern "C" {
#endif
/* ========================================================================== */
/* Macros & Typedefs */
/* ========================================================================== */
/** \brief Maximum Number of PMIC Revisions available */
#define PMHAL_PMIC_MAX_REV (4U)
/**
* \brief PMHAL_TPS659037_SMPS Regulator Register Fields Mask Field
* PMHAL_TPS659037_SMPSxx_CTRL.MODE_ACTIVE
* 1:0 MODE_ACTIVE: PMHAL_TPS659037_SMPS Active Mode
* 0x00: OFF (Default)
* 0x01: Forced PWM
* 0x10: ECO
* 0x11: Forced PWM
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_MODE_ACTIVE_MASK (0x03U)
/**
* \brief PMHAL_TPS659037_SMPS Regulator Register Fields Shift Field
* PMHAL_TPS659037_SMPSxx_CTRL.MODE_ACTIVE
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_MODE_ACTIVE_SHIFT (0x0U)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.MODE_SLEEP Mask.
* 3:2 MODE_SLEEP: PMHAL_TPS659037_SMPS Sleep Mode, values/meaning
* same as above
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_MODE_SLEEP_MASK (0x0CU)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.MODE_SLEEP Shift.
* 3:2 MODE_SLEEP: PMHAL_TPS659037_SMPS Sleep Mode, values/meaning
* same as above
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_MODE_SLEEP_SHIFT (2U)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.STATUS Mask.
* 4:5 STATUS: PMHAL_TPS659037_SMPS Status, values/meaning
* same as above.
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_STATUS_MASK (0x30U)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.STATUS Shift.
* 4:5 STATUS: PMHAL_TPS659037_SMPS Status, values/meaning
* same as above.
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_STATUS_SHIFT (4U)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.ROOF_FLOOR_EN Mask.
* 6 ROOF_FLOOR_EN:
* 0x0: Voltage selection controlled by FORCE.CMD bit
* 0x1: Voltage selection controlled by device resource pins.
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_ROOF_FLOOR_EN_MASK (0x40U)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.ROOF_FLOOR_EN Shift.
* 6 ROOF_FLOOR_EN:
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_ROOF_FLOOR_EN_SHIFT (6U)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.WR_S Mask.
* 7 WR_S: Warm reset sensitivity
* 0x0: Reload the default vlaue from OTP (VSEL, CMD etc).
* 0x1: Maintain the current voltage during warm reset.
* (Registers remain unchanged and no voltage change)
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_WR_S_MASK (0x80U)
/**
* \brief PMHAL_TPS659037_SMPSxx_CTRL.WR_S Shift.
* 7 WR_S: Warm reset sensitivity
*/
#define PMHAL_TPS659037_SMPSxx_CTRL_WR_S_SHIFT (7U)
/**
* \brief PMHAL_TPS659037_SMPSxx_FORCE.VSEL Mask
* 6:0 VSEL
*/
#define PMHAL_TPS659037_SMPSxx_FORCE_VSEL_MASK (0x7FU)
/**
* \brief PMHAL_TPS659037_SMPSxx_FORCE.VSEL Shift
* 6:0 VSEL
*/
#define PMHAL_TPS659037_SMPSxx_FORCE_VSEL_SHIFT (0U)
/**
* \brief PMHAL_TPS659037_SMPSxx_FORCE.CMD Mask
* 7 CMD (RW but the PMIC HAL will only use the
* default value of 1.)
* CMD is effective only if
* PMHAL_TPS659037_SMPSxx_CTRL.ROOF_FLOOR_EN = 0.
* 0x0: FORCE.VSEL is applied.
* 0x1: VOLTAGE.VSEL is applied.
*/
#define PMHAL_TPS659037_SMPSxx_FORCE_CMD_MASK (0x80U)
/**
* \brief PMHAL_TPS659037_SMPSxx_FORCE.CMD Shift.
*/
#define PMHAL_TPS659037_SMPSxx_FORCE_CMD_SHIFT (7U)
/**
* \brief PMHAL_TPS659037_SMPSxx_VOLTAGE.VSEL Mask.
* 6:0 VSEL
* 0x0000000 => 0V (OFF)
* 0x0000001 - 0x0000110 => 0.7V
* Step voltage is 0.01V (10mv)
* 0x1111001 - 1.65V (max)
*/
#define PMHAL_TPS659037_SMPSxx_VOLTAGE_VSEL_MASK (0x7FU)
/**
* \brief PMHAL_TPS659037_SMPSxx_VOLTAGE.VSEL Shift.
*/
#define PMHAL_TPS659037_SMPSxx_VOLTAGE_VSEL_SHIFT (0U)
/**
* \brief PMHAL_TPS659037_SMPSxx_VOLTAGE.RANGE Mask.
* 7 RANGE (RW but the PMIC HAL will only support RO)
*/
#define PMHAL_TPS659037_SMPSxx_VOLTAGE_RANGE_MASK (0x80U)
/**
* \brief PMHAL_TPS659037_SMPSxx_VOLTAGE.RANGE Shift.
*/
#define PMHAL_TPS659037_SMPSxx_VOLTAGE_RANGE_SHIFT (7U)
/** \brief Control Status Macro for Off */
#define CTRL_STATUS_OFF (0U)
/**
* \brief PMHAL_TPS659037_LDO Regulator Register Fields:
*
* PMHAL_TPS659037_LDOxx_CTRL.MODE_ACTIVE Mask
* 0 MODE_ACTIVE: PMHAL_TPS659037_LDO Active Mode
* 0x00: OFF (Default)
* 0x01: ON
* 1 Reserved
*/
#define PMHAL_TPS659037_LDOxx_CTRL_MODE_ACTIVE_MASK (0x01U)
/**
* \brief PMHAL_TPS659037_LDO Regulator Register
* PMHAL_TPS659037_LDOxx_CTRL.MODE_ACTIVE Shift
*/
#define PMHAL_TPS659037_LDOxx_CTRL_MODE_ACTIVE_SHIFT (0U)
/**
* \brief PMHAL_TPS659037_LDOxx_CTRL.MODE_SLEEP Mask
* 2 MODE_SLEEP: PMHAL_TPS659037_LDO Sleep Mode, values/meaning
* same as above
* 3 Reserved
*/
#define PMHAL_TPS659037_LDOxx_CTRL_MODE_SLEEP_MASK (0x04U)
/** \brief PMHAL_TPS659037_LDOxx_CTRL.MODE_SLEEP Shift */
#define PMHAL_TPS659037_LDOxx_CTRL_MODE_SLEEP_SHIFT (2U)
/**
* \brief PMHAL_TPS659037_LDOxx_CTRL.STATUS Mask
* 4 STATUS: PMHAL_TPS659037_LDO Status, values/meaning
* same as above.
* 6:5 Reserved
*/
#define PMHAL_TPS659037_LDOxx_CTRL_STATUS_MASK (0x10U)
/** \brief PMHAL_TPS659037_LDOxx_CTRL.STATUS Shift */
#define PMHAL_TPS659037_LDOxx_CTRL_STATUS_SHIFT (4U)
/**
* \brief PMHAL_TPS659037_LDOxx_CTRL.WR_S Mask
* 7 WR_S: Warm reset sensitivity
* 0x0: Reload the default vlaue from OTP (VSEL, CMD etc).
* 0x1: Maintain the current voltage during warm reset.
* (Registers remain unchanged and no voltage change)
*/
#define PMHAL_TPS659037_LDOxx_CTRL_WR_S_MASK (0x80U)
/** \brief PMHAL_TPS659037_LDOxx_CTRL.WR_S Mask */
#define PMHAL_TPS659037_LDOxx_CTRL_WR_S_SHIFT (7U)
/**
* \brief PMHAL_TPS659037_LDOxx_VOLTAGE Mask.
* 5:0 VSEL
* 0x000000 => 0V (OFF)
* 0x000001 => 0.9V (min)
* Step voltage is 0.05V
* 0x110001 => 3.3V (max)
*
* 7:6 Reserved
*
*/
#define PMHAL_TPS659037_LDOxx_VOLTAGE_VSEL_MASK (0x3FU)
/** \brief PMHAL_TPS659037_LDOxx_VOLTAGE Mask. */
#define PMHAL_TPS659037_LDOxx_VOLTAGE_VSEL_SHIFT (0U)
/**
* \brief Slave Address:
*
* The TPS659037 PMIC uses the standard 7-bit slave I2C address to access
* the register address space. This PMIC has 5 internal pages each of 256
* bytes. The register address is 8-bits and can address one page. Multiple
* pages are addressed using different slave addresses. The table below
* gives the slave address for the register pages as programmed in the
* TDA2xx device EVMs.
*/
#define PMHAL_TPS659037_SLAVE_ADDR_COUNT (5U)
/**
* \brief SLAVE Address Page 0
*
* Page Phy Addr Range Slave Address OTP choice Register
* ------------------------------------------------------------------------
* 0 0x000 - 0x0FF 0x12 0x12 DVS
*/
#define PMHAL_TPS659037_SLAVE_ADDR_PAGE0 (0x12U)
/**
* \brief SLAVE Address Page 1
*
* Page Phy Addr Range Slave Address OTP choice Register
* ------------------------------------------------------------------------
* 1 0x100 - 0x1FF 0x48 or 0x58 0x58 Power
*/
#define PMHAL_TPS659037_SLAVE_ADDR_PAGE1 (0x58U)
/**
* \brief SLAVE Address Page 2
*
* Page Phy Addr Range Slave Address OTP choice Register
* ------------------------------------------------------------------------
* 2 0x200 - 0x2FF 0x49 or 0x59 0x59 Interfaces
* & Auxiliaries
*/
#define PMHAL_TPS659037_SLAVE_ADDR_PAGE2 (0x59U)
/**
* \brief SLAVE Address Page 3
*
* Page Phy Addr Range Slave Address OTP choice Register
* ------------------------------------------------------------------------
* 3 0x300 - 0x3FF 0x4A or 0x5A 0x5A Trimming
* & Test
*/
#define PMHAL_TPS659037_SLAVE_ADDR_PAGE3 (0x5AU)
/**
* \brief SLAVE Address Page 4
*
* Page Phy Addr Range Slave Address OTP choice Register
* ------------------------------------------------------------------------
* 4 0x400 - 0x4FF 0x4B or 0x5B 0x5B OTP
*/
#define PMHAL_TPS659037_SLAVE_ADDR_PAGE4 (0x5BU)
/** \brief Invalid Page Address */
#define PMHAL_TPS659037_SLAVE_ADDR_INVALID (0xFFU)
/** Regulator SMPS12_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS12_CTRL (0x120U)
/** Regulator SMPS12_FORCE Physical Address */
#define PMHAL_TPS659037_SMPS12_FORCE (0x122U)
/** Regulator SMPS12_VOLTAGE Physical Address */
#define PMHAL_TPS659037_SMPS12_VOLTAGE (0x123U)
/** Regulator SMPS3_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS3_CTRL (0x124U)
/** Regulator SMPS3_VOLTAGE Physical Address */
#define PMHAL_TPS659037_SMPS3_VOLTAGE (0x127U)
/** Regulator SMPS45_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS45_CTRL (0x128U)
/** Regulator SMPS45_FORCE Physical Address */
#define PMHAL_TPS659037_SMPS45_FORCE (0x12AU)
/** Regulator SMPS45_VOLTAGE Physical Address */
#define PMHAL_TPS659037_SMPS45_VOLTAGE (0x12BU)
/** Regulator SMPS6_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS6_CTRL (0x12CU)
/** Regulator SMPS6_FORCE Physical Address */
#define PMHAL_TPS659037_SMPS6_FORCE (0x12EU)
/** Regulator SMPS6_VOLTAGE Physical Address */
#define PMHAL_TPS659037_SMPS6_VOLTAGE (0x12FU)
/** Regulator SMPS7_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS7_CTRL (0x130U)
/** Regulator SMPS7_VOLTAGE Physical Address */
#define PMHAL_TPS659037_SMPS7_VOLTAGE (0x133U)
/** Regulator SMPS8_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS8_CTRL (0x134U)
/** Regulator SMPS8_FORCE Physical Address */
#define PMHAL_TPS659037_SMPS8_FORCE (0x136U)
/** Regulator SMPS8_VOLTAGE Physical Address */
#define PMHAL_TPS659037_SMPS8_VOLTAGE (0x137U)
/** Regulator SMPS9_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS9_CTRL (0x138U)
/** Regulator SMPS9_VOLTAGE Physical Address */
#define PMHAL_TPS659037_SMPS9_VOLTAGE (0x13BU)
/** Regulator SMPS_CTRL Physical Address */
#define PMHAL_TPS659037_SMPS_CTRL (0x144U)
/** Regulator LDO1_CTRL Physical Address */
#define PMHAL_TPS659037_LDO1_CTRL (0x150U)
/** Regulator LDO1_VOLTAGE Physical Address */
#define PMHAL_TPS659037_LDO1_VOLTAGE (0x151U)
/** Regulator LDO2_CTRL Physical Address */
#define PMHAL_TPS659037_LDO2_CTRL (0x152U)
/** Regulator LDO2_VOLTAGE Physical Address */
#define PMHAL_TPS659037_LDO2_VOLTAGE (0x153U)
/** Regulator LDO3_CTRL Physical Address */
#define PMHAL_TPS659037_LDO3_CTRL (0x154U)
/** Regulator LDO3_VOLTAGE Physical Address */
#define PMHAL_TPS659037_LDO3_VOLTAGE (0x155U)
/** Regulator LDO4_CTRL Physical Address */
#define PMHAL_TPS659037_LDO4_CTRL (0x156U)
/** Regulator LDO4_VOLTAGE Physical Address */
#define PMHAL_TPS659037_LDO4_VOLTAGE (0x157U)
/** Regulator LDO9_CTRL Physical Address */
#define PMHAL_TPS659037_LDO9_CTRL (0x160U)
/** Regulator LDO9_VOLTAGE Physical Address */
#define PMHAL_TPS659037_LDO9_VOLTAGE (0x161U)
/** Regulator LDOLN_CTRL Physical Address */
#define PMHAL_TPS659037_LDOLN_CTRL (0x162U)
/** Regulator LDOLN_VOLTAGE Physical Address */
#define PMHAL_TPS659037_LDOLN_VOLTAGE (0x163U)
/** Regulator LDOUSB_CTRL Physical Address */
#define PMHAL_TPS659037_LDOUSB_CTRL (0x164U)
/** Regulator LDOUSB_VOLTAGE Physical Address */
#define PMHAL_TPS659037_LDOUSB_VOLTAGE (0x165U)
/** \brief TPS659037 vendor ID LSB. */
#define PMHAL_TPS659037_PHYADDR_VENDOR_ID_LSB (0x24FU)
/** \brief TPS659037 vendor ID MSB. */
#define PMHAL_TPS659037_PHYADDR_VENDOR_ID_MSB (0x250U)
/** \brief TPS659037 Product ID LSB. */
#define PMHAL_TPS659037_PHYADDR_PRODUCT_ID_LSB (0x251U)
/** \brief TPS659037 Product ID MSB. */
#define PMHAL_TPS659037_PHYADDR_PRODUCT_ID_MSB (0x252U)
/** \brief Expected vendor ID values for TPS659037. */
#define PMHAL_TPS659037_VENDOR_ID (0x0451U)
/** \brief Expected product ID values for TPS659037 1.0. */
#define PMHAL_TPS659037_1_0_PRODUCT_ID (0x9039U)
/**
* \brief TPS659037 device revision register physical address and the
* field definitions.
*/
#define PMHAL_TPS659037_PHYADDR_CHIP_REVISION_ID (0x357U)
/** \brief Chip Revision ID mask */
#define PMHAL_TPS659037_CHIP_REVISION_ID_MASK (0x0FU)
/** \brief Chip Revision ID Shift */
#define PMHAL_TPS659037_CHIP_REVISION_ID_SHIFT (0x0U)
/** \brief Regulator Type for SMPS */
#define PMHAL_TPS659037_RTYPE_SMPS (1U)
/** \brief Regulator Type for LDO */
#define PMHAL_TPS659037_RTYPE_LDO (2U)
/** \brief The I2C number to which the voltage rail is connected */
#define PMHAL_TPS659037_I2C_NUM_1 (0x0U)
/* ========================================================================== */
/* Structures and Enums */
/* ========================================================================== */
/**
* \brief Abstract Enumeration for the Regulators.
*/
typedef enum pmhalTps659037RegulatorId
{
PMHAL_TPS659037_REGULATOR_INVALID = (-(int32_t)1),
/**< Invalid PMIC regulator ID */
PMHAL_TPS659037_REGULATOR_MIN = 0,
/**< Minimum Abstracted PMIC Regulator ID */
PMHAL_TPS659037_REGULATOR_SMPS12 = PMHAL_PRCM_PMIC_REGULATOR_MIN,
/**< Abstracted PMIC Regulator ID for SMPS12 */
PMHAL_TPS659037_REGULATOR_SMPS3 = 1,
/**< Abstracted PMIC Regulator ID for SMPS3 */
PMHAL_TPS659037_REGULATOR_SMPS45 = 2,
/**< Abstracted PMIC Regulator ID for SMPS45 */
PMHAL_TPS659037_REGULATOR_SMPS6 = 3,
/**< Abstracted PMIC Regulator ID for SMPS6 */
PMHAL_TPS659037_REGULATOR_SMPS7 = 4,
/**< Abstracted PMIC Regulator ID for SMPS7 */
PMHAL_TPS659037_REGULATOR_SMPS8 = 5,
/**< Abstracted PMIC Regulator ID for SMPS8 */
PMHAL_TPS659037_REGULATOR_SMPS9 = 6,
/**< Abstracted PMIC Regulator ID for SMPS9 */
PMHAL_TPS659037_REGULATOR_LDO1 = 7,
/**< Abstracted PMIC Regulator ID for LDO1 */
PMHAL_TPS659037_REGULATOR_LDO2 = 8,
/**< Abstracted PMIC Regulator ID for LDO2 */
PMHAL_TPS659037_REGULATOR_LDO3 = 9,
/**< Abstracted PMIC Regulator ID for LDO3 */
PMHAL_TPS659037_REGULATOR_LDO4 = 10,
/**< Abstracted PMIC Regulator ID for LDO4 */
PMHAL_TPS659037_REGULATOR_LDO9 = 11,
/**< Abstracted PMIC Regulator ID for LDO9 */
PMHAL_TPS659037_REGULATOR_LDOLN = 12,
/**< Abstracted PMIC Regulator ID for LDOLN */
PMHAL_TPS659037_REGULATOR_LDOUSB = 13,
/**< Abstracted PMIC Regulator ID for LDOUSB */
PMHAL_TPS659037_REGULATOR_MAX = (PMHAL_TPS659037_REGULATOR_LDOUSB + 1)
/**< Maximum Abstracted PMIC Regulator ID */
} pmhalTps659037RegulatorId_t;
/**
* \brief TPS659037 Regulator description structure
*/
typedef struct pmhalTps659037RegulatorProp
{
uint16_t minVolt;
/**< Minimum voltage supported by the regulator in mV. */
uint16_t maxVolt;
/**< Maximum voltage supported by the regulator in mV. */
uint8_t stepVolt;
/**< Step voltage in mV. */
uint8_t type;
/**< The regulator type namely PMHAL_TPS659037_RTYPE_SMPS or
* PMHAL_TPS659037_RTYPE_LDO.
*/
uint16_t slewRate;
/**< The voltage ramp delay in uV/us */
uint16_t minVoltVsel;
/**< VSEL value corresponding to the minVolt.*/
uint16_t maxVoltVsel;
/**< VSEL value corresponding to the maxVolt.*/
uint32_t ctrlRegAddr;
/**< The regulator control register address.*/
uint32_t voltRegAddr;
/**< The regulator voltage register address.*/
uint32_t forceRegAddr;
/**< The regulator force command voltage register address. Not all
* regulators have the force register; if not present the value
* of this field is expected to be NULL. */
} pmhalTps659037RegulatorProp_t;
/** \brief Pointer to pmhalTps659037RegulatorProp_t structure.
*/
typedef const pmhalTps659037RegulatorProp_t *pmhalTps659037RegulatorPtr_t;
typedef struct pmhalTps659037RegulatorMap
{
pmhalTps659037RegulatorPtr_t regulatorMap;
/**< Pointer to the regulator properties */
uint8_t i2cInstanceNum;
/**< SoC I2C instance number to which the regulator of the PMIC will be
* connected to.
*/
} pmhalTps659037RegulatorMap_t;
/** \brief Pointer to the structure pmhalTps659037RegulatorMap_t */
typedef pmhalTps659037RegulatorMap_t *const pmhalTps659037RegulatorMapPtr_t;
/* ========================================================================== */
/* Global Variables Declarations */
/* ========================================================================== */
/** Array of the properties of all the SMPS and LDO PMIC regulators */
extern const pmhalTps659037RegulatorProp_t gPmhalTps659037Regulator[
PMHAL_TPS659037_REGULATOR_MAX];
/* ========================================================================== */
/* Function Declarations */
/* ========================================================================== */
/**
* \brief Get PMIC ops structure. All the other functions are accessed via
* function pointers whose array is exported by this function.
*
* \return Return pointer to the PMIC ops structure.
*/
const pmhalPmicOperations_t *PMHALTps659037GetPMICOps(void);
/**
* \brief The PMIC regulator output to the device input mapping can be
* different on different boards. This API can be used to provide
* a different mapping to the PMIC driver if the mapping does not
* match the default. Example table is shown below:
* ---------------------------------------------------------------------
* | Device voltage Rail | Ptr to Regulator |
* ---------------------------------------------------------------------
* | PMHAL_PRCM_PMIC_REGULATOR_MPU | PMHAL_TPS65037_REGULATOR_SMPS12 |
* | PMHAL_PRCM_PMIC_REGULATOR_CORE | PMHAL_TPS65037_REGULATOR_SMPS7 |
* | .... |
* | index (Refer | For index of the |
* | #pmhalPrcmPmicRegulatorId_t) | gPmhalTps659037Regulator |
* | | refer |
* | | #pmhalTps659037RegulatorId_t |
* ---------------------------------------------------------------------
* This table when translated to code is as below:
* pmhalTps659037RegulatorMap_t regulatorMap[
* PMHAL_PRCM_PMIC_REGULATOR_COUNT] = {
* {
* &gPmhalTps659037Regulator[PMHAL_TPS659037_REGULATOR_SMPS12],
* I2C_INSTANCE,
* PMIC_I2C_SLAVE_ADDRESS
* },
* {
* &gPmhalTps659037Regulator[PMHAL_TPS659037_REGULATOR_SMPS7],
* I2C_INSTANCE,
* PMIC_I2C_SLAVE_ADDRESS
* },
* ......
* };
*
* \param regulatorMap Pointer to the array of pointers which gives the
* mapping. The array is defined as above.
*
* \return None
*/
void PMHALTps659037ConfigureRegulatorMap(
pmhalTps659037RegulatorMapPtr_t regulatorMap);
#ifdef __cplusplus
}
#endif
#endif
|
mathieuravaux/nutchbase | src/java/org/apache/nutch/crawl/Injector.java | <reponame>mathieuravaux/nutchbase<filename>src/java/org/apache/nutch/crawl/Injector.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.nutch.crawl;
import java.io.*;
import java.util.*;
// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
import org.apache.nutch.net.*;
import org.apache.nutch.scoring.ScoringFilterException;
import org.apache.nutch.scoring.ScoringFilters;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
/** This class takes a flat file of URLs and adds them to the of pages to be
* crawled. Useful for bootstrapping the system. */
public class Injector extends Configured implements Tool {
public static final Log LOG = LogFactory.getLog(Injector.class);
/** Normalize and filter injected urls. */
public static class InjectMapper implements Mapper<WritableComparable, Text, Text, CrawlDatum> {
private URLNormalizers urlNormalizers;
private int interval;
private float scoreInjected;
private JobConf jobConf;
private URLFilters filters;
private ScoringFilters scfilters;
private long curTime;
public void configure(JobConf job) {
this.jobConf = job;
urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_INJECT);
interval = jobConf.getInt("db.fetch.interval.default", 2592000);
filters = new URLFilters(jobConf);
scfilters = new ScoringFilters(jobConf);
scoreInjected = jobConf.getFloat("db.score.injected", 1.0f);
curTime = job.getLong("injector.current.time", System.currentTimeMillis());
}
public void close() {}
public void map(WritableComparable key, Text value,
OutputCollector<Text, CrawlDatum> output, Reporter reporter)
throws IOException {
String url = value.toString(); // value is line of text
try {
url = urlNormalizers.normalize(url, URLNormalizers.SCOPE_INJECT);
url = filters.filter(url); // filter the url
} catch (Exception e) {
if (LOG.isWarnEnabled()) { LOG.warn("Skipping " +url+":"+e); }
url = null;
}
if (url != null) { // if it passes
value.set(url); // collect it
CrawlDatum datum = new CrawlDatum(CrawlDatum.STATUS_INJECTED, interval);
datum.setFetchTime(curTime);
datum.setScore(scoreInjected);
try {
scfilters.injectedScore(value, datum);
} catch (ScoringFilterException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Cannot filter injected score for url " + url +
", using default (" + e.getMessage() + ")");
}
datum.setScore(scoreInjected);
}
output.collect(value, datum);
}
}
}
/** Combine multiple new entries for a url. */
public static class InjectReducer implements Reducer<Text, CrawlDatum, Text, CrawlDatum> {
public void configure(JobConf job) {}
public void close() {}
private CrawlDatum old = new CrawlDatum();
private CrawlDatum injected = new CrawlDatum();
public void reduce(Text key, Iterator<CrawlDatum> values,
OutputCollector<Text, CrawlDatum> output, Reporter reporter)
throws IOException {
boolean oldSet = false;
while (values.hasNext()) {
CrawlDatum val = values.next();
if (val.getStatus() == CrawlDatum.STATUS_INJECTED) {
injected.set(val);
injected.setStatus(CrawlDatum.STATUS_DB_UNFETCHED);
} else {
old.set(val);
oldSet = true;
}
}
CrawlDatum res = null;
if (oldSet) res = old; // don't overwrite existing value
else res = injected;
output.collect(key, res);
}
}
public Injector() {}
public Injector(Configuration conf) {
setConf(conf);
}
public void inject(Path crawlDb, Path urlDir) throws IOException {
if (LOG.isInfoEnabled()) {
LOG.info("Injector: starting");
LOG.info("Injector: crawlDb: " + crawlDb);
LOG.info("Injector: urlDir: " + urlDir);
}
Path tempDir =
new Path(getConf().get("mapred.temp.dir", ".") +
"/inject-temp-"+
Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
// map text input file to a <url,CrawlDatum> file
if (LOG.isInfoEnabled()) {
LOG.info("Injector: Converting injected urls to crawl db entries.");
}
JobConf sortJob = new NutchJob(getConf());
sortJob.setJobName("inject " + urlDir);
FileInputFormat.addInputPath(sortJob, urlDir);
sortJob.setMapperClass(InjectMapper.class);
FileOutputFormat.setOutputPath(sortJob, tempDir);
sortJob.setOutputFormat(SequenceFileOutputFormat.class);
sortJob.setOutputKeyClass(Text.class);
sortJob.setOutputValueClass(CrawlDatum.class);
sortJob.setLong("injector.current.time", System.currentTimeMillis());
JobClient.runJob(sortJob);
// merge with existing crawl db
if (LOG.isInfoEnabled()) {
LOG.info("Injector: Merging injected urls into crawl db.");
}
JobConf mergeJob = CrawlDb.createJob(getConf(), crawlDb);
FileInputFormat.addInputPath(mergeJob, tempDir);
mergeJob.setReducerClass(InjectReducer.class);
JobClient.runJob(mergeJob);
CrawlDb.install(mergeJob, crawlDb);
// clean up
FileSystem fs = FileSystem.get(getConf());
fs.delete(tempDir, true);
if (LOG.isInfoEnabled()) { LOG.info("Injector: done"); }
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(NutchConfiguration.create(), new Injector(), args);
System.exit(res);
}
public int run(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: Injector <crawldb> <url_dir>");
return -1;
}
try {
inject(new Path(args[0]), new Path(args[1]));
return 0;
} catch (Exception e) {
LOG.fatal("Injector: " + StringUtils.stringifyException(e));
return -1;
}
}
}
|
Watch-Later/Eureka | crack-data-structures-and-algorithms/leetcode/find_peak_element_q162.py | # -*- coding: utf-8 -*-
# 0xCCCCCCCC
def find_peak_element(nums):
"""
:type nums: List[int]
:rtype: int
"""
# Turn to find local maximum within the array.
l, r = 0, len(nums) - 1
while l < r:
m = (l + r) // 2
if nums[m] < nums[m+1]:
# Becase we want local maximum, m is excluded.
l = m + 1
else:
# Included because m might be the local maximum
r = m
# l == r => target index
return l
# Another solution with more intuition: https://leetcode.com/submissions/detail/287986266/
nums = [1,2,3,1]
print(find_peak_element(nums) == 2)
nums = [1,2,1,3,5,6,4]
ret = find_peak_element(nums)
print(ret == 5 or ret == 1) |
htjia/vueYrProject | src/views/extensionManage/wyBasicInfoManage/portalfilm/acceptanceCriteria/siteManage.js | <reponame>htjia/vueYrProject
import PageHeaderLayout from '@/components/PageHeaderLayout'
import HeaderSearchAdd from '@/components/HeaderSearchAdd'
import { findColorList, findModelList, query, queryHv, enableDisabled, produceName, normUpdate, normAdd, remove } from '@/api/acceptanceCriteria'
export default {
components: { PageHeaderLayout, HeaderSearchAdd },
data() {
return {
listLoading: false,
addDialogVisible: false,
editDialogVisible: false,
configDialogVisible: false,
configDialogVisible1: false,
historyDialogVisible: false,
list: [],
defaultFormThead: [],
siteType: '',
siteName: '',
siteStatus: '',
pageSize: 12,
pageNum: 1,
totalPage: 0,
beginDate: '',
endDate: '',
isTrue: false,
pickerOptionsStart: {
disabledDate: (time) => {
const endDateVal = this.endDate
if (endDateVal) {
return time.getTime() > endDateVal
}
}
},
pickerOptionsEnd: {
disabledDate: (time) => {
const beginDateVal = this.beginDate
if (beginDateVal) {
return time.getTime() < beginDateVal
}
}
},
userOptions: [],
isActive: 0,
siteForm: {
siteType: '',
siteName: '',
siteStatus: ''
},
currentId: '',
color: '',
modelType: '',
status: '',
statusOptions: [
{ id: 1, name: '弃用' },
{ id: 0, name: '启用' }
],
rowInfo: null,
showCheckList: [
{ grade: 'R', key: {}},
{ grade: 'S', key: {}},
{ grade: 'F', key: {}},
{ grade: 'T8', key: {}},
{ grade: 'T7', key: {}},
{ grade: 'T6', key: {}},
{ grade: 'T5', key: {}},
{ grade: 'T4', key: {}},
{ grade: 'T3', key: {}},
{ grade: 'T2', key: {}},
{ grade: 'T1', key: {}}
],
oldList: [],
modelOptions: [],
colorOptions: [],
selectList: [],
plBaseList: [
{
thName: 'Wp',
thKey: 'wp'
},
{
thName: 'Wp_Std',
thKey: 'wpStd'
},
{
thName: 'Wd',
thKey: 'wd'
},
{
thName: 'Wd_Std',
thKey: 'wd_std'
},
{
thName: 'FWHM',
thKey: 'fwhm'
},
{
thName: 'FWHW Std',
thKey: 'fwhm_std'
},
{
thName: 'PL Int.',
thKey: 'pl_int'
},
{
thName: 'PL Int. Std',
thKey: 'pl_int_std'
},
{
thName: 'I.I.',
thKey: 'ii'
},
{
thName: 'I.I. Std',
thKey: 'ii_std'
},
{
thName: 'PDavr',
thKey: 'pdavr'
},
{
thName: 'PD Std',
thKey: 'pdstd'
},
{
thName: 'TH',
thKey: 'th'
},
{
thName: 'TH Std',
thKey: 'th_std'
},
{
thName: 'Ref.',
thKey: 'ref'
},
{
thName: 'Ref. Std',
thKey: 'ref_std'
},
{
thName: 'Bow',
thKey: 'bow'
},
{
thName: '测试机台PL',
thKey: 'machinePl'
}
],
elBaseList: [
{
thName: 'VF1',
thKey: 'vf1'
},
{
thName: 'VF2',
thKey: 'vf2'
},
{
thName: 'VF3',
thKey: 'vf3'
},
{
thName: 'VF4',
thKey: 'vf4'
},
{
thName: 'VZ1',
thKey: 'vz1'
},
{
thName: 'VZ2',
thKey: 'vz2'
},
{
thName: 'IR',
thKey: 'ir'
},
{
thName: 'LOP1',
thKey: 'lop1'
},
{
thName: 'WLP1',
thKey: 'wlp1'
},
{
thName: 'WLD1',
thKey: 'wld1'
},
// {
// thName: 'WLC1',
// thKey: 'wlc1'
// },
{
thName: 'LOP(460)',
thKey: 'lop460'
},
{
thName: 'HW',
thKey: 'hw'
},
{
thName: '测试机台El',
thKey: 'machineEl'
}
],
XRDBaseList: [
{
thName: '002',
thKey: 'c_002'
},
{
thName: '102',
thKey: 'c_102'
},
{
thName: 'QB Th.',
thKey: 'qb_th'
},
{
thName: 'QW Th.',
thKey: 'qw_th'
},
{
thName: 'Period',
thKey: 'period'
},
{
thName: 'In %',
thKey: 'cin'
},
{
thName: 'AlGaN Th.',
thKey: 'algan_th'
},
{
thName: 'Al %',
thKey: 'al'
},
{
thName: '测试机台XRD',
thKey: 'machineXrd'
}
],
cowBaseList: [
{
thName: '批次号',
thKey: 'lot_no'
},
{
thName: 'WaferID',
thKey: 'wafer_no'
},
{
thName: '测试时间',
thKey: 'test_time'
},
{
thName: 'IV均值',
thKey: 'avg_iv'
},
{
thName: 'VF1均值',
thKey: 'avg_vf1'
},
{
thName: 'VF1_ESD_A均值',
thKey: 'vf1EsdAvg'
},
{
thName: 'VF1_ESD_A差值',
thKey: 'vf1EsdDiffer'
},
{
thName: 'VZ均值',
thKey: 'avg_vz'
},
{
thName: '蓝移',
thKey: 'blue_shift'
},
{
thName: 'K值',
thKey: 'valk'
},
{
thName: 'ESD去坏(200V)',
thKey: 'esd_200'
},
{
thName: 'ESD去坏(400V)',
thKey: 'esd_400'
},
{
thName: 'ESD去坏(50V)',
thKey: 'esd_50'
},
{
thName: 'ESD去坏(500V)',
thKey: 'esd_500'
},
{
thName: 'ESD去坏(300V)',
thKey: 'esd_300'
},
{
thName: 'ESD去坏(人体1000)',
thKey: 'esd_1000'
},
{
thName: 'ESD去坏(人体2000)',
thKey: 'esd_2000'
},
{
thName: 'ESD去坏(人体4000)',
thKey: 'esd_4000'
},
{
thName: 'Thyristor良率',
thKey: 'yield_thyristor'
},
{
thName: 'Thyristor坏点数',
thKey: 'num_thyristor'
},
{
thName: 'DVF均值',
thKey: 'avg_dvf'
},
{
thName: '综合良率',
thKey: 'yield_zh'
},
{
thName: 'VF1良率',
thKey: 'yield_vf1'
},
{
thName: 'VF3良率',
thKey: 'yield_vf3'
},
{
thName: 'WLD1良率',
thKey: 'yield_wld1'
},
{
thName: 'IR良率',
thKey: 'yield_ir'
},
{
thName: 'IR_ESD_A良率',
thKey: 'irEsdYield'
},
{
thName: 'VZ良率',
thKey: 'yield_vz'
},
{
thName: 'IV良率',
thKey: 'yield_iv'
},
{
thName: 'VF4良率',
thKey: 'yield_vf4'
},
{
thName: 'VF2均值',
thKey: 'avg_vf2'
},
{
thName: 'VF3均值',
thKey: 'avg_vf3'
},
{
thName: 'VF4均值',
thKey: 'avg_vf4'
},
{
thName: 'WLD1均值',
thKey: 'avg_wld1'
},
{
thName: 'WLD1_STD',
thKey: 'wld1_std'
},
{
thName: 'WLP1均值',
thKey: 'avg_wlp1'
},
{
thName: 'HW1',
thKey: 'hw1'
},
{
thName: 'WLD2均值',
thKey: 'avg_wld2'
},
{
thName: 'WLD2_STD',
thKey: 'wld2_std'
},
{
thName: 'HW2',
thKey: 'hw2'
},
{
thName: 'wlp2均值',
thKey: 'avg_wlp2'
},
{
thName: 'IR均值',
thKey: 'avg_ir'
},
{
thName: 'PL_WP',
thKey: 'pl_wp'
},
{
thName: 'PL_WD',
thKey: 'pl_wd'
},
{
thName: 'PL_WD_STD',
thKey: 'pl_wd_std'
},
{
thName: 'PL.I.I',
thKey: 'pl_ii'
},
{
thName: '总数',
thKey: 'total'
},
{
thName: '坏点数',
thKey: 'bad'
},
{
thName: '导入时间',
thKey: 'import_time'
},
{
thName: '机台',
thKey: 'machine'
},
{
thName: '预估波长',
thKey: 'ygbc'
}
],
mjBaseList: [
{
thName: '目检',
thKey: 'eyes_exam'
}
],
leftTree: [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
],
rightTree: [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
],
leftTree1: [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
],
rightTree1: [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
],
checkOptions: [],
allready: '',
newmodel: '',
newcolor: '',
newname: '',
defaultProps: {
children: 'children',
label: 'label'
},
rowKey: [],
historyList: [],
hisVisible: false,
selectLists: []
}
},
mounted() {
this.fetchData()
this.findColorList()
this.findModelList()
},
methods: {
findColorList() {
findColorList().then(res => {
this.colorOptions = res.data.list
})
},
findModelList() {
findModelList().then(res => {
this.modelOptions = res.data.list
})
},
// 修改衬底
editSubstrate() {
this.editDialogVisible = true
},
// 每页数量改变
sizeChange(pageSize) {
this.pageSize = pageSize
this.fetchData()
},
// 当前页数改变
currentChange(pageNum) {
this.pageNum = pageNum
this.fetchData()
},
handleSearch() {
this.pageNum = 1
this.fetchData()
},
formatDate(timeStamp) {
var date = new Date(timeStamp)
var y = 1900 + date.getYear()
var m = '0' + (date.getMonth() + 1)
var d = '0' + date.getDate()
return y + '-' + m.substring(m.length - 2, m.length) + '-' + d.substring(d.length - 2, d.length)
},
clearCondition() {
this.pageSize = 12
this.modelType = ''
this.status = ''
this.color = ''
this.beginDate = ''
this.endDate = ''
this.handleSearch()
},
// 查询
fetchData() {
this.listLoading = true
const requestParams = {
pageSize: this.pageSize,
pageNum: this.pageNum,
model: this.modelType,
status: this.status,
color: this.color,
startTime: this.formatDate(this.beginDate),
endTime: this.formatDate(this.endDate)
}
if (this.beginDate === '') {
requestParams.startTime = ''
}
if (this.endDate === '') {
requestParams.endTime = ''
}
query(requestParams).then(res => {
this.list = []
for (let i = 0; i < res.data.list.length; i++) {
if (res.data.list[i].status === '0') {
res.data.list[i].isChecked = true
} else {
res.data.list[i].isChecked = false
}
this.list.push(res.data.list[i])
}
this.totalPage = parseInt(res.data.total)
this.listLoading = false
})
},
setStatus(row) {
if (row.isChecked) {
this.$confirm('确定启用标准' + row.name + '的最新版本?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
row.status = '0'
const requestParams = {
id: row.id,
status: row.status,
type: 1
}
enableDisabled(requestParams).then(res => {
this.$message({
type: 'success',
message: '修改成功!'
})
this.fetchData()
})
}, () => {
row.isChecked = false
})
} else {
this.$confirm('确定弃用标准' + row.name + '?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
row.status = '1'
const requestParams = {
id: row.id,
status: row.status,
type: 1
}
enableDisabled(requestParams).then(res => {
this.$message({
type: 'success',
message: '修改成功!'
})
this.fetchData()
})
}, () => {
row.isChecked = true
})
}
},
// 关闭
handleClose() {
if (!this.isTrue) {
this.setFirst()
}
},
// 关闭
handleClose1() {
if (!this.isTrue) {
this.setTree()
}
},
// 历史版本
handleHistory(row) {
this.rowInfo = row
this.historyDialogVisible = true
const requestParams = {
pageSize: 1000000,
pageNum: 1,
newId: row.newId
}
queryHv(requestParams).then(res => {
this.historyList = []
var datas = {}
for (let i = 0; i < res.data.list.length; i++) {
if (res.data.list[i].status === '0') {
datas = res.data.list[i]
res.data.list[i].isChecked = true
} else {
res.data.list[i].isChecked = false
}
this.historyList.push(res.data.list[i])
}
this.$refs.historys.setCurrentRow(datas)
})
},
getTitle1(row) {
this.showCheckList = []
this.oldList = [
{ grade: 'R', key: {}},
{ grade: 'S', key: {}},
{ grade: 'F', key: {}},
{ grade: 'T8', key: {}},
{ grade: 'T7', key: {}},
{ grade: 'T6', key: {}},
{ grade: 'T5', key: {}},
{ grade: 'T4', key: {}},
{ grade: 'T3', key: {}},
{ grade: 'T2', key: {}},
{ grade: 'T1', key: {}}
]
var r = { grade: 'R', key: {}}
var s = { grade: 'S', key: {}}
var f = { grade: 'F', key: {}}
var t1 = { grade: 'T1', key: {}}
var t2 = { grade: 'T2', key: {}}
var t3 = { grade: 'T3', key: {}}
var t4 = { grade: 'T4', key: {}}
var t5 = { grade: 'T5', key: {}}
var t6 = { grade: 'T6', key: {}}
var t7 = { grade: 'T7', key: {}}
var t8 = { grade: 'T8', key: {}}
if (row !== null && row.wyNormRules !== null) {
for (const item of row.wyNormRules) {
const field = this.findKeyToValue(item.field)
r.key[field] = ''
s.key[field] = ''
f.key[field] = ''
t1.key[field] = ''
t2.key[field] = ''
t3.key[field] = ''
t4.key[field] = ''
t5.key[field] = ''
t6.key[field] = ''
t7.key[field] = ''
t8.key[field] = ''
if (item.grade.toLowerCase() === 's') {
s[field] = item.val
this.oldList[1][field] = item.val
} else if (item.grade.toLowerCase() === 'r') {
r[field] = item.val
this.oldList[0][field] = item.val
} else if (item.grade.toLowerCase() === 'f') {
f[field] = item.val
this.oldList[2][field] = item.val
} else if (item.grade.toLowerCase() === 't1') {
t1[field] = item.val
this.oldList[3][field] = item.val
} else if (item.grade.toLowerCase() === 't2') {
t2[field] = item.val
this.oldList[4][field] = item.val
} else if (item.grade.toLowerCase() === 't3') {
t3[field] = item.val
this.oldList[5][field] = item.val
} else if (item.grade.toLowerCase() === 't4') {
t4[field] = item.val
this.oldList[6][field] = item.val
} else if (item.grade.toLowerCase() === 't5') {
t5[field] = item.val
this.oldList[7][field] = item.val
} else if (item.grade.toLowerCase() === 't6') {
t6[field] = item.val
this.oldList[8][field] = item.val
} else if (item.grade.toLowerCase() === 't7') {
t7[field] = item.val
this.oldList[9][field] = item.val
} else if (item.grade.toLowerCase() === 't8') {
t8[field] = item.val
this.oldList[10][field] = item.val
}
if (r[field] === undefined) {
r[field] = ''
}
if (s[field] === undefined) {
s[field] = ''
}
if (f[field] === undefined) {
f[field] = ''
}
if (t1[field] === undefined) {
t1[field] = ''
}
if (t2[field] === undefined) {
t2[field] = ''
}
if (t3[field] === undefined) {
t3[field] = ''
}
if (t4[field] === undefined) {
t4[field] = ''
}
if (t5[field] === undefined) {
t5[field] = ''
}
if (t6[field] === undefined) {
t6[field] = ''
}
if (t7[field] === undefined) {
t7[field] = ''
}
if (t8[field] === undefined) {
t8[field] = ''
}
}
}
this.showCheckList.push(r)
this.showCheckList.push(s)
this.showCheckList.push(f)
this.showCheckList.push(t8)
this.showCheckList.push(t7)
this.showCheckList.push(t6)
this.showCheckList.push(t5)
this.showCheckList.push(t4)
this.showCheckList.push(t3)
this.showCheckList.push(t2)
this.showCheckList.push(t1)
},
getList(row) {
this.showCheckList = []
this.oldList = [
{ grade: 'R' },
{ grade: 'S' },
{ grade: 'F' },
{ grade: 'T8' },
{ grade: 'T7' },
{ grade: 'T6' },
{ grade: 'T5' },
{ grade: 'T4' },
{ grade: 'T3' },
{ grade: 'T2' },
{ grade: 'T1' }
]
var keyse = {}
var r = { grade: 'R', list: [] }
var s = { grade: 'S' }
var f = { grade: 'F' }
var t1 = { grade: 'T1' }
var t2 = { grade: 'T2' }
var t3 = { grade: 'T3' }
var t4 = { grade: 'T4' }
var t5 = { grade: 'T5' }
var t6 = { grade: 'T6' }
var t7 = { grade: 'T7' }
var t8 = { grade: 'T8' }
if (row !== null && row.wyNormRules !== null) {
for (const item of row.wyNormRules) {
const field = this.findKeyToValue(item.field)
if (keyse[field] === undefined) {
r.list.push(field)
}
keyse[field] = ''
if (item.grade.toLowerCase() === 's') {
s[field] = item.val
this.oldList[1][field] = item.val
} else if (item.grade.toLowerCase() === 'r') {
r[field] = item.val
this.oldList[0][field] = item.val
} else if (item.grade.toLowerCase() === 'f') {
f[field] = item.val
this.oldList[2][field] = item.val
} else if (item.grade.toLowerCase() === 't1') {
t1[field] = item.val
this.oldList[3][field] = item.val
} else if (item.grade.toLowerCase() === 't2') {
t2[field] = item.val
this.oldList[4][field] = item.val
} else if (item.grade.toLowerCase() === 't3') {
t3[field] = item.val
this.oldList[5][field] = item.val
} else if (item.grade.toLowerCase() === 't4') {
t4[field] = item.val
this.oldList[6][field] = item.val
} else if (item.grade.toLowerCase() === 't5') {
t5[field] = item.val
this.oldList[7][field] = item.val
} else if (item.grade.toLowerCase() === 't6') {
t6[field] = item.val
this.oldList[8][field] = item.val
} else if (item.grade.toLowerCase() === 't7') {
t7[field] = item.val
this.oldList[9][field] = item.val
} else if (item.grade.toLowerCase() === 't8') {
t8[field] = item.val
this.oldList[10][field] = item.val
}
if (keyse[field] === undefined) {
keyse[field] = ''
}
}
}
this.showCheckList.push(r)
this.showCheckList.push(s)
this.showCheckList.push(f)
this.showCheckList.push(t8)
this.showCheckList.push(t7)
this.showCheckList.push(t6)
this.showCheckList.push(t5)
this.showCheckList.push(t4)
this.showCheckList.push(t3)
this.showCheckList.push(t2)
this.showCheckList.push(t1)
},
findKeyToValue(items) {
let field = items
if (items === 'eyes_exam') {
field = '目检'
} else {
let flag = false
for (let i = 0; i < this.plBaseList.length; i++) {
if (this.plBaseList[i].thKey === items) {
field = this.plBaseList[i].thName
flag = true
break
}
}
if (!flag) {
for (let i = 0; i < this.elBaseList.length; i++) {
if (this.elBaseList[i].thKey === items) {
field = this.elBaseList[i].thName
flag = true
break
}
}
}
if (!flag) {
for (let i = 0; i < this.XRDBaseList.length; i++) {
if (this.XRDBaseList[i].thKey === items) {
field = this.XRDBaseList[i].thName
flag = true
break
}
}
}
if (!flag) {
for (let i = 0; i < this.cowBaseList.length; i++) {
if (this.cowBaseList[i].thKey === items) {
field = this.cowBaseList[i].thName
flag = true
break
}
}
}
}
return field
},
tableDbEdit(row, column, cell, event) {
if (column.label !== '等级') {
if (row[column.label] !== undefined) {
row[column.label][1] = true
}
}
},
toLeft() {
const selected = this.$refs.righttree.getCheckedNodes()
this.plBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree[0].children.length; i++) {
if (this.rightTree[0].children[i].id === items.id) {
this.rightTree[0].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree[0].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.elBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree[1].children.length; i++) {
if (this.rightTree[1].children[i].id === items.id) {
this.rightTree[1].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree[1].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.XRDBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree[2].children.length; i++) {
if (this.rightTree[2].children[i].id === items.id) {
this.rightTree[2].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree[2].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.cowBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree[3].children.length; i++) {
if (this.rightTree[3].children[i].id === items.id) {
this.rightTree[3].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree[3].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.selectList = []
for (const items of this.leftTree[0].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[1].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[2].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[3].children) {
this.selectList.push(items.label)
}
for (const items of selected) {
if (items.id === 5) {
this.rightTree.splice(4, 1)
this.leftTree.push({
id: 5,
label: '目检'
})
this.selectList.push('目检')
break
}
}
if (this.leftTree.length > 4 && this.selectList.join().indexOf('目检') < 0) {
this.selectList.push('目检')
}
this.$refs.righttree.setCheckedKeys([])
},
toRight() {
const selected = this.$refs.lefttree.getCheckedNodes()
this.plBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree[0].children.length; i++) {
if (this.leftTree[0].children[i].id === items.id) {
this.leftTree[0].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree[0].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.elBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree[1].children.length; i++) {
if (this.leftTree[1].children[i].id === items.id) {
this.leftTree[1].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree[1].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.XRDBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree[2].children.length; i++) {
if (this.leftTree[2].children[i].id === items.id) {
this.leftTree[2].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree[2].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.cowBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree[3].children.length; i++) {
if (this.leftTree[3].children[i].id === items.id) {
this.leftTree[3].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree[3].children.push({
id: items.id,
label: items.label
})
break
}
}
})
for (const items of selected) {
if (items.id === 5) {
this.leftTree.splice(4, 1)
this.rightTree.push({
id: 5,
label: '目检'
})
break
}
}
this.selectList = []
for (const items of this.leftTree[0].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[1].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[2].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[3].children) {
this.selectList.push(items.label)
}
if (this.leftTree.length > 4) {
this.selectList.push('目检')
}
this.$refs.lefttree.setCheckedKeys([])
},
toLeft1() {
const selected = this.$refs.righttree1.getCheckedNodes()
this.plBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree1[0].children.length; i++) {
if (this.rightTree1[0].children[i].id === items.id) {
this.rightTree1[0].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree1[0].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.elBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree1[1].children.length; i++) {
if (this.rightTree1[1].children[i].id === items.id) {
this.rightTree1[1].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree1[1].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.XRDBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree1[2].children.length; i++) {
if (this.rightTree1[2].children[i].id === items.id) {
this.rightTree1[2].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree1[2].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.cowBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.rightTree1[3].children.length; i++) {
if (this.rightTree1[3].children[i].id === items.id) {
this.rightTree1[3].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.leftTree1[3].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.selectList = []
for (const items of this.leftTree1[0].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[1].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[2].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[3].children) {
this.selectList.push(items.label)
}
for (const items of selected) {
if (items.id === 5) {
this.rightTree1.splice(4, 1)
this.leftTree1.push({
id: 5,
label: '目检'
})
this.selectList.push('目检')
break
}
}
if (this.leftTree1.length > 4 && this.selectList.join().indexOf('目检') < 0) {
this.selectList.push('目检')
}
this.$refs.righttree1.setCheckedKeys([])
},
toRight1() {
const selected = this.$refs.lefttree1.getCheckedNodes()
this.plBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree1[0].children.length; i++) {
if (this.leftTree1[0].children[i].id === items.id) {
this.leftTree1[0].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree1[0].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.elBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree1[1].children.length; i++) {
if (this.leftTree1[1].children[i].id === items.id) {
this.leftTree1[1].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree1[1].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.XRDBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree1[2].children.length; i++) {
if (this.leftTree1[2].children[i].id === items.id) {
this.leftTree1[2].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree1[2].children.push({
id: items.id,
label: items.label
})
break
}
}
})
this.cowBaseList.map((item) => {
for (const items of selected) {
for (let i = 0; i < this.leftTree1[3].children.length; i++) {
if (this.leftTree1[3].children[i].id === items.id) {
this.leftTree1[3].children.splice(i, 1)
break
}
}
if (item.thName === items.label) {
this.rightTree1[3].children.push({
id: items.id,
label: items.label
})
break
}
}
})
for (const items of selected) {
if (items.id === 5) {
this.leftTree1.splice(4, 1)
this.rightTree1.push({
id: 5,
label: '目检'
})
break
}
}
this.selectList = []
for (const items of this.leftTree1[0].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[1].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[2].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[3].children) {
this.selectList.push(items.label)
}
if (this.leftTree1.length > 4) {
this.selectList.push('目检')
}
this.$refs.lefttree1.setCheckedKeys([])
},
getTitle() {
var data = [
{ grade: 'R', key: {}},
{ grade: 'S', key: {}},
{ grade: 'F', key: {}},
{ grade: 'T8', key: {}},
{ grade: 'T7', key: {}},
{ grade: 'T6', key: {}},
{ grade: 'T5', key: {}},
{ grade: 'T4', key: {}},
{ grade: 'T3', key: {}},
{ grade: 'T2', key: {}},
{ grade: 'T1', key: {}}
]
for (const item of this.selectList) {
for (let i = 0; i < 11; i++) {
data[i].key[item] = ''
if (this.showCheckList.length > 0 && this.showCheckList[i][item] !== undefined) {
data[i][item] = this.showCheckList[i][item]
} else {
data[i].key[item] = ''
}
}
}
this.showCheckList = data
this.isTrue = true
this.configDialogVisible = false
},
getTitles() {
var data = [
{ grade: 'R', key: {}},
{ grade: 'S', key: {}},
{ grade: 'F', key: {}},
{ grade: 'T8', key: {}},
{ grade: 'T7', key: {}},
{ grade: 'T6', key: {}},
{ grade: 'T5', key: {}},
{ grade: 'T4', key: {}},
{ grade: 'T3', key: {}},
{ grade: 'T2', key: {}},
{ grade: 'T1', key: {}}
]
for (const item of this.selectList) {
for (let i = 0; i < 11; i++) {
data[i].key[item] = ''
if (this.showCheckList[i][item] !== undefined) {
data[i][item] = this.showCheckList[i][item]
} else {
data[i].key[item] = ''
}
}
}
this.showCheckList = data
this.showCheckList[0].list = this.selectList
this.isTrue = true
this.configDialogVisible1 = false
},
setHasBZ() {
for (const item of this.checkOptions) {
if (item.id === this.allready) {
for (const colors of this.colorOptions) {
if (colors.code === item.color) {
this.newcolor = colors.code
break
}
}
for (const models of this.modelOptions) {
if (models.code === item.model) {
this.newmodel = models.code
break
}
}
this.produceName()
if (item.wyNormRules.length === 0) {
this.setFirst()
this.getTitle()
break
} else {
this.leftTree = [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
]
this.getTitle1(item)
for (const ist in this.showCheckList[0].key) {
if (ist === '目检') {
this.leftTree.push({
id: 5,
label: '目检'
})
} else {
for (let i = 0; i < this.plBaseList.length; i++) {
if (ist === this.plBaseList[i].thName) {
this.leftTree[0].children.push({
id: 1 + '' + i,
label: this.plBaseList[i].thName
})
break
}
}
for (let i = 0; i < this.elBaseList.length; i++) {
if (ist === this.elBaseList[i].thName) {
this.leftTree[1].children.push({
id: 2 + '' + i,
label: this.elBaseList[i].thName
})
break
}
}
for (let i = 0; i < this.XRDBaseList.length; i++) {
if (ist === this.XRDBaseList[i].thName) {
this.leftTree[2].children.push({
id: 3 + '' + i,
label: this.XRDBaseList[i].thName
})
break
}
}
for (let i = 0; i < this.cowBaseList.length; i++) {
if (ist === this.cowBaseList[i].thName) {
this.leftTree[3].children.push({
id: 4 + '' + i,
label: this.cowBaseList[i].thName
})
break
}
}
}
}
break
}
}
}
},
// 添加
handleAdd() {
this.isTrue = false
this.addDialogVisible = true
this.allready = ''
this.newmodel = ''
this.newcolor = ''
this.newname = ''
this.showCheckList = []
this.setFirst()
this.getTitle()
const requestParams = {
pageSize: 10000,
pageNum: 1
}
query(requestParams).then(res => {
this.checkOptions = res.data.list
})
},
setFirst() {
this.leftTree = [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
},
{
id: 5,
label: '目检'
}
]
for (let i = 0; i < this.plBaseList.length; i++) {
if (this.plBaseList[i].thName === 'Wp_Std' || this.plBaseList[i].thName === 'Wd_Std') {
this.leftTree[0].children.push({
id: 1 + '' + i,
label: this.plBaseList[i].thName
})
}
}
for (let i = 0; i < this.cowBaseList.length; i++) {
if (this.cowBaseList[i].thName === '预估波长' ||
this.cowBaseList[i].thName === 'VF1均值' ||
this.cowBaseList[i].thName === 'VF4均值' ||
this.cowBaseList[i].thName === 'VZ均值' ||
this.cowBaseList[i].thName === 'ESD去坏(200V)' ||
this.cowBaseList[i].thName === 'ESD去坏(400V)' ||
this.cowBaseList[i].thName === 'ESD去坏(300V)' ||
this.cowBaseList[i].thName === 'ESD去坏(50V)' ||
this.cowBaseList[i].thName === 'IV均值' ||
this.cowBaseList[i].thName === 'IR良率' ||
this.cowBaseList[i].thName === 'Thyristor良率' ||
this.cowBaseList[i].thName === 'VZ良率' ||
this.cowBaseList[i].thName === 'VF1良率') {
this.leftTree[3].children.push({
id: 4 + '' + i,
label: this.cowBaseList[i].thName
})
}
}
this.selectList = []
for (const items of this.leftTree[0].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[1].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[2].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree[3].children) {
this.selectList.push(items.label)
}
if (this.leftTree.length > 4) {
this.selectList.push('目检')
}
},
addConfig() {
this.isTrue = false
this.configDialogVisible = true
this.rightTree = [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
]
for (let i = 0; i < this.plBaseList.length; i++) {
let flag = true
for (const item of this.leftTree[0].children) {
if (this.plBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree[0].children.push({
id: 1 + '' + i,
label: this.plBaseList[i].thName
})
}
}
for (let i = 0; i < this.elBaseList.length; i++) {
let flag = true
for (const item of this.leftTree[1].children) {
if (this.elBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree[1].children.push({
id: 2 + '' + i,
label: this.elBaseList[i].thName
})
}
}
for (let i = 0; i < this.XRDBaseList.length; i++) {
let flag = true
for (const item of this.leftTree[2].children) {
if (this.XRDBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree[2].children.push({
id: 3 + '' + i,
label: this.XRDBaseList[i].thName
})
}
}
for (let i = 0; i < this.cowBaseList.length; i++) {
let flag = true
for (const item of this.leftTree[3].children) {
if (this.cowBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree[3].children.push({
id: 4 + '' + i,
label: this.cowBaseList[i].thName
})
}
}
if (this.leftTree.length <= 4) {
this.rightTree.push({
id: 5,
label: '目检'
})
}
},
addConfig1() {
this.isTrue = false
this.configDialogVisible1 = true
this.rightTree1 = [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
]
for (let i = 0; i < this.plBaseList.length; i++) {
let flag = true
for (const item of this.leftTree1[0].children) {
if (this.plBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree1[0].children.push({
id: 1 + '' + i,
label: this.plBaseList[i].thName
})
}
}
for (let i = 0; i < this.elBaseList.length; i++) {
let flag = true
for (const item of this.leftTree1[1].children) {
if (this.elBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree1[1].children.push({
id: 2 + '' + i,
label: this.elBaseList[i].thName
})
}
}
for (let i = 0; i < this.XRDBaseList.length; i++) {
let flag = true
for (const item of this.leftTree1[2].children) {
if (this.XRDBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree1[2].children.push({
id: 3 + '' + i,
label: this.XRDBaseList[i].thName
})
}
}
for (let i = 0; i < this.cowBaseList.length; i++) {
let flag = true
for (const item of this.leftTree1[3].children) {
if (this.cowBaseList[i].thName === item.label) {
flag = false
break
}
}
if (flag) {
this.rightTree1[3].children.push({
id: 4 + '' + i,
label: this.cowBaseList[i].thName
})
}
}
if (this.leftTree1.length <= 4) {
this.rightTree1.push({
id: 5,
label: '目检'
})
}
},
// 取消
resetForm() {
this.addDialogVisible = false
this.editDialogVisible = false
this.configDialogVisible = false
this.historyDialogVisible = false
this.fetchData()
},
// 编辑
handleEdit(row) {
this.listLoading = true
this.rowInfo = row
this.getList(row)
this.setTree()
var _this = this
setTimeout(() => {
_this.editDialogVisible = true
_this.listLoading = false
}, 800)
},
setTree() {
this.leftTree1 = [
{
id: 1,
label: 'PL',
children: []
},
{
id: 2,
label: 'EL',
children: []
},
{
id: 3,
label: 'XRD',
children: []
},
{
id: 4,
label: 'COW',
children: []
}
]
for (const key of this.showCheckList[0].list) {
if (key === '目检') {
this.leftTree1.push({
id: 5,
label: '目检'
})
} else {
for (let i = 0; i < this.plBaseList.length; i++) {
if (this.plBaseList[i].thName === key) {
this.leftTree1[0].children.push({
id: 1 + '' + i,
label: this.plBaseList[i].thName
})
}
}
for (let i = 0; i < this.elBaseList.length; i++) {
if (this.elBaseList[i].thName === key) {
this.leftTree1[1].children.push({
id: 1 + '' + i,
label: this.elBaseList[i].thName
})
}
}
for (let i = 0; i < this.XRDBaseList.length; i++) {
if (this.XRDBaseList[i].thName === key) {
this.leftTree1[2].children.push({
id: 1 + '' + i,
label: this.XRDBaseList[i].thName
})
}
}
for (let i = 0; i < this.cowBaseList.length; i++) {
if (this.cowBaseList[i].thName === key) {
this.leftTree1[3].children.push({
id: 1 + '' + i,
label: this.cowBaseList[i].thName
})
}
}
}
}
this.selectList = []
for (const items of this.leftTree1[0].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[1].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[2].children) {
this.selectList.push(items.label)
}
for (const items of this.leftTree1[3].children) {
this.selectList.push(items.label)
}
if (this.leftTree1.length > 4) {
this.selectList.push('目检')
}
},
handleDelete(row, location) {
this.$confirm('是否确认删除?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
const param = {
id: row.id,
type: location === 'out' ? 1 : 0
}
remove(param).then(res => {
this.$message({
type: 'success',
message: '操作成功!'
})
if (location !== 'out') {
this.handleHistory(this.rowInfo)
} else {
this.fetchData()
}
})
})
},
// 编辑提交
submitEditForm() {
const updateList = []
let flag1 = false
for (let i = 0; i < this.showCheckList.length; i++) {
for (const items in this.showCheckList[i]) {
if (items !== 'grade' && items !== 'list' && items !== 'key') {
if (this.showCheckList[i][items] !== this.oldList[i][items]) {
if (this.showCheckList[i][items] === '' && this.oldList[i][items] === undefined) {
console.log(1)
} else {
flag1 = true
}
}
let field = ''
if (items === '目检') {
field = 'eyes_exam'
} else {
let flag = false
for (let i = 0; i < this.plBaseList.length; i++) {
if (this.plBaseList[i].thName === items) {
field = this.plBaseList[i].thKey
flag = true
break
}
}
if (!flag) {
for (let i = 0; i < this.elBaseList.length; i++) {
if (this.elBaseList[i].thName === items) {
field = this.elBaseList[i].thKey
flag = true
break
}
}
}
if (!flag) {
for (let i = 0; i < this.XRDBaseList.length; i++) {
if (this.XRDBaseList[i].thName === items) {
field = this.XRDBaseList[i].thKey
flag = true
break
}
}
}
if (!flag) {
for (let i = 0; i < this.cowBaseList.length; i++) {
if (this.cowBaseList[i].thName === items) {
field = this.cowBaseList[i].thKey
flag = true
break
}
}
}
}
if (this.showCheckList[i][items] !== '' && field !== '') {
updateList.push({
grade: this.showCheckList[i].grade,
field: field,
val: this.showCheckList[i][items]
})
}
}
}
}
const object = Object.keys(this.oldList[0])
if (this.showCheckList[0].list.length !== object.length - 1) {
flag1 = true
}
if (flag1) {
const up = {
standard: {
id: this.rowInfo.id,
name: this.rowInfo.name,
model: this.rowInfo.model,
color: this.rowInfo.color,
status: this.rowInfo.status,
creator: sessionStorage.getItem('User-Id')
},
rules: updateList
}
if (updateList.length === 0) {
this.$message({
type: 'error',
message: '判定标准不能为空!'
})
return
}
normUpdate(up).then(res => {
if (res.code === 0) {
this.$message({
type: 'success',
message: '修改成功!'
})
this.editDialogVisible = false
this.fetchData()
}
})
} else {
this.editDialogVisible = false
}
},
produceName() {
if (this.newmodel === '' || this.newcolor === '') {
return
}
const requestParams = {
model: this.newmodel,
color: this.newcolor
}
produceName(requestParams).then(res => {
this.newname = res.data
})
},
submitAddForm() {
const updateList = []
for (const item of this.showCheckList) {
for (const items in item) {
if (items !== 'grade' && items !== 'key') {
let field = ''
if (items === '目检') {
field = 'eyes_exam'
} else {
let flag = false
for (let i = 0; i < this.plBaseList.length; i++) {
if (this.plBaseList[i].thName === items) {
field = this.plBaseList[i].thKey
flag = true
break
}
}
if (!flag) {
for (let i = 0; i < this.elBaseList.length; i++) {
if (this.elBaseList[i].thName === items) {
field = this.elBaseList[i].thKey
flag = true
break
}
}
}
if (!flag) {
for (let i = 0; i < this.XRDBaseList.length; i++) {
if (this.XRDBaseList[i].thName === items) {
field = this.XRDBaseList[i].thKey
flag = true
break
}
}
}
if (!flag) {
for (let i = 0; i < this.cowBaseList.length; i++) {
if (this.cowBaseList[i].thName === items) {
field = this.cowBaseList[i].thKey
flag = true
break
}
}
}
}
let val = item[items].replace(/and/gi, ' and ')
val = val.replace(/or/gi, ' or ')
if (field !== '') {
updateList.push({
grade: item.grade,
field: field,
val: val
})
}
}
}
}
if (this.newname === '') {
this.$message({
type: 'error',
message: '请选择标准名称!'
})
return
}
if (updateList.length === 0) {
this.$message({
type: 'error',
message: '新增判定标准不能为空!'
})
return
}
const up = {
standard: {
name: this.newname,
model: this.newmodel,
color: this.newcolor,
status: 0,
creator: sessionStorage.getItem('User-Id')
},
rules: updateList
}
normAdd(up).then(res => {
if (res.code === 0) {
this.$message({
type: 'success',
message: '添加成功!'
})
this.fetchData()
this.addDialogVisible = false
}
})
},
exportAll(row) {
var columnCn = '等级'
var columnEn = 'grade'
var setnumb = {}
console.log(row.wyNormRules)
console.log(row.id)
for (const item of row.wyNormRules) {
const field = this.findKeyToValue(item.field)
setnumb[item.field] = field
}
for (const item in setnumb) {
columnCn = columnCn + ',' + setnumb[item]
columnEn = columnEn + ',' + item
}
window.open(process.env.BASE_API + `/wy-accept-norm/export-data?normId=${row.id}&headerCn=${columnCn}&headerEn=${columnEn}`, '_blank')
},
handleCurrentChange(row) {
if (row !== null) {
this.getList(row)
}
},
handleSelectionChange(data) {
this.selectLists = data
},
tableRowClassColor({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
return {
background: '#fff'
}
}
},
isQiYong(row) {
if (!row.isChecked) {
row.isChecked = true
return
}
if (row.isChecked) {
row.status = '0'
for (let i = 0; i < this.historyList.length; i++) {
if (row.id !== this.historyList[i].id) {
this.historyList[i].status = '1'
this.historyList[i].isChecked = false
const requestParams = {
id: this.historyList[i].id,
status: this.historyList[i].status,
type: 0
}
enableDisabled(requestParams).then(res => {
console.log(res)
})
}
}
} else {
row.status = '1'
}
const requestParams = {
id: row.id,
status: row.status,
type: 0
}
enableDisabled(requestParams).then(res => {
console.log(res)
})
}
}
}
|
ruhulaminparvez/FreeCodeCamp-Container | 002_JavaScript Algorithms-and-Data-Structures/05_Basic-Data-Structures/12_create-complex-multi-dimensional-arrays.js | <filename>002_JavaScript Algorithms-and-Data-Structures/05_Basic-Data-Structures/12_create-complex-multi-dimensional-arrays.js
let myNestedArray = [
// Only change code below this line
'level 1', /* myNestedArray[0] */
['level 2'], /* myNestedArray[1][0] */
[['level 3','deep']], /* myNestedArray[2][0][0] */
[[['level 4','deeper']]], /* myNestedArray[3][0][0][0] */
[[[['level 5','deepest']]]] /* myNestedArray[4][0][0][0][0] */
// Only change code above this line
]; |
Quicr/qmedia | test/metrics.cc | <filename>test/metrics.cc<gh_stars>0
#include <doctest/doctest.h>
#include <cstring>
#include <string>
#include <iostream>
#include "metrics.hh"
using namespace neo_media;
TEST_CASE("createSetAndVerify")
{
Metrics metrics("", "", "", "");
Metrics::MeasurementPtr measurement = metrics.createMeasurement(
"jitter", {{"streamId", 1}, {"clientId", 10}});
CHECK_EQ(measurement->tags.size(), 2);
auto clock = std::chrono::system_clock::now();
for (int i = 0; i < 100; i++)
{
measurement->set(clock, {"queue_depth", i});
clock += std::chrono::milliseconds(10);
}
CHECK_EQ(measurement->time_series.size(), 100);
int index = 0;
for (auto entry : measurement->time_series)
{
for (auto field : entry.second)
{
CHECK_EQ("queue_depth", field.first);
CHECK_EQ(field.second, index);
++index;
}
}
}
TEST_CASE("nameAndTags")
{
Metrics metrics("", "", "", "");
Metrics::MeasurementPtr measurement = metrics.createMeasurement(
"jitter", {{"streamId", 1}, {"clientId", 10}, {"sw_version", 1456}});
CHECK_FALSE(measurement->name.empty());
CHECK_EQ(measurement->tags.size(), 3);
CHECK_EQ("jitter,streamId=1,clientId=10,sw_version=1456",
measurement->lineProtocol_nameAndTags());
}
TEST_CASE("lineProtocol-single-field")
{
Metrics metrics("", "", "", "");
Metrics::MeasurementPtr measurement = metrics.createMeasurement(
"jitter", {{"streamId", 1}, {"clientId", 10}, {"sw_version", 1456}});
auto clock = std::chrono::system_clock::now();
std::list<std::chrono::system_clock::time_point> clocks;
for (int i = 0; i < 10; i++)
{
clocks.push_back(clock);
measurement->set(clock, {"queue_depth", i});
clock += std::chrono::milliseconds(10);
}
auto lines = measurement->lineProtocol();
int qd = 0;
for (auto line : lines)
{
long long time = std::chrono::duration_cast<std::chrono::nanoseconds>(
clocks.front().time_since_epoch())
.count();
std::string base_line = "jitter,streamId=1,clientId=10,sw_version=1456 "
"queue_depth=";
std::string verify_line = base_line + std::to_string(qd) + " " +
std::to_string(time) + "\n";
CHECK_EQ(verify_line, line);
++qd;
clocks.pop_front();
}
}
TEST_CASE("lineProtocol-multi-fields")
{
Metrics metrics("", "", "", "");
Metrics::MeasurementPtr measurement = metrics.createMeasurement(
"jitter", {{"streamId", 1}, {"clientId", 10}, {"sw_version", 1456}});
auto clock = std::chrono::system_clock::now();
std::list<std::chrono::system_clock::time_point> clocks;
for (int i = 0; i < 10; i++)
{
clocks.push_back(clock);
measurement->set(
clock,
{{"queue_depth", i}, {"jitter", i + 100}, {"total", i + 1000}});
clock += std::chrono::milliseconds(10);
}
auto lines = measurement->lineProtocol();
int qd = 0;
for (auto line : lines)
{
long long time = std::chrono::duration_cast<std::chrono::nanoseconds>(
clocks.front().time_since_epoch())
.count();
std::string base_line = "jitter,streamId=1,clientId=10,sw_version="
"1456 ";
std::string q_string = "queue_depth=" + std::to_string(qd);
std::string jit_string = "jitter=" + std::to_string(qd + 100);
std::string total_string = "total=" + std::to_string(qd + 1000);
std::string verify_line = base_line + q_string + "," + jit_string +
"," + total_string + " " +
std::to_string(time) + "\n";
CHECK_EQ(verify_line, line);
++qd;
clocks.pop_front();
}
}
// not really a unit test - but nice to test against influx instance
#if 0 // don't want this for jenkins .. enable for local testing
TEST_CASE("salt-n-peppa-push-it")
{
std::clog << "test start" << std::endl;
Metrics metrics(MetricsConfig::URL,
MetricsConfig::ORG,
MetricsConfig::BUCKET,
MetricsConfig::AUTH_TOKEN);
Metrics::MeasurementPtr measurement = metrics.createMeasurement("jitter", {
{ "streamId", 1},
{ "clientId" ,10},
{ "sw_version", 1456}});
auto clock = std::chrono::system_clock::now();
for (int i=0; i < 25; i++)
{
measurement->set(clock, {{"queue_depth", i}, { "jitter_val", i+100} , { "total", i+1000}});
clock += std::chrono::milliseconds(10);
}
std::clog << "push start" << std::endl;
metrics.push();
std::this_thread::sleep_for(std::chrono::seconds(5));
std::clog << "push stop" << std::endl;
}
#endif
|
MeiVinEight/ReflectionFX | src/main/java/org/mve/asm/file/attribute/module/ModuleRequire.java | <reponame>MeiVinEight/ReflectionFX
package org.mve.asm.file.attribute.module;
public class ModuleRequire
{
public int require;
public int flag;
public int version;
public byte[] toByteArray()
{
byte[] b = new byte[6];
b[0] = (byte) ((this.require >>> 8) & 0XFF);
b[1] = (byte) (this.require & 0XFF);
b[2] = (byte) ((this.flag >>> 8) & 0XFF);
b[3] = (byte) (this.flag & 0XFF);
b[4] = (byte) ((this.version >>> 8) & 0XFF);
b[5] = (byte) (this.version & 0XFF);
return b;
}
}
|
openn2o/jitredis | tests/pico-examples-master/multitask/s_task/src/s_list.c | /* Copyright xhawk, MIT license */
#include "s_list.h"
/*******************************************************************/
/* list */
/*******************************************************************/
s_list_t *s_list_get_prev (s_list_t *list) {
return list->prev;
}
s_list_t *s_list_get_next (s_list_t *list) {
return list->next;
}
void s_list_set_prev (s_list_t *list, s_list_t *other) {
list->prev = other;
}
void s_list_set_next (s_list_t *list, s_list_t *other) {
list->next = other;
}
/* Initilization a list */
void s_list_init(s_list_t *list) {
s_list_set_prev(list, list);
s_list_set_next(list, list);
}
/* Connect or disconnect two lists. */
void s_list_toggle_connect(s_list_t *list1, s_list_t *list2) {
s_list_t *prev1 = s_list_get_prev(list1);
s_list_t *prev2 = s_list_get_prev(list2);
s_list_set_next(prev1, list2);
s_list_set_next(prev2, list1);
s_list_set_prev(list1, prev2);
s_list_set_prev(list2, prev1);
}
/* Connect two lists. */
void s_list_connect (s_list_t *list1, s_list_t *list2) {
s_list_toggle_connect (list1, list2);
}
/* Disconnect tow lists. */
void s_list_disconnect (s_list_t *list1, s_list_t *list2) {
s_list_toggle_connect (list1, list2);
}
/* Same as s_list_connect */
void s_list_attach (s_list_t *node1, s_list_t *node2) {
s_list_connect (node1, node2);
}
/* Make node in detach mode */
void s_list_detach (s_list_t *node) {
s_list_disconnect (node, s_list_get_next(node));
}
/* Check if list is empty */
int s_list_is_empty (s_list_t *list) {
return (s_list_get_next(list) == list);
}
int s_list_size(s_list_t *list) {
int n = 0;
s_list_t *next;
for(next = s_list_get_next(list); next != list; next = s_list_get_next(next))
++n;
return n;
}
|
zhangkn/iOS14Header | System/Library/Frameworks/MediaPlayer.framework/MPChangeQueueEndActionCommandEvent.h | <filename>System/Library/Frameworks/MediaPlayer.framework/MPChangeQueueEndActionCommandEvent.h
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:39:49 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <MediaPlayer/MPRemoteCommandEvent.h>
@interface MPChangeQueueEndActionCommandEvent : MPRemoteCommandEvent {
BOOL _preservesQueueEndAction;
long long _queueEndAction;
}
@property (nonatomic,readonly) long long queueEndAction; //@synthesize queueEndAction=_queueEndAction - In the implementation block
@property (nonatomic,readonly) BOOL preservesQueueEndAction; //@synthesize preservesQueueEndAction=_preservesQueueEndAction - In the implementation block
-(id)initWithCommand:(id)arg1 mediaRemoteType:(unsigned)arg2 options:(id)arg3 ;
-(long long)queueEndAction;
-(BOOL)preservesQueueEndAction;
@end
|
maciej-consdata/sonarqube-companion | sonarqube-companion-rest/src/main/java/pl/consdata/ico/sqcompanion/violation/project/GroupViolationsHistoryDiff.java | package pl.consdata.ico.sqcompanion.violation.project;
import lombok.Builder;
import lombok.Data;
import pl.consdata.ico.sqcompanion.violation.Violations;
import pl.consdata.ico.sqcompanion.violation.project.ProjectViolationsHistoryDiff;
import java.util.List;
@Data
@Builder
public class GroupViolationsHistoryDiff {
private final Violations groupDiff;
private final Violations addedViolations;
private final Violations removedViolations;
private final List<ProjectViolationsHistoryDiff> projectDiffs;
}
|
FionaWong/operation | src/actions/index.js | import * as types from '../constants/actionTypes'
/*
添加组件
*/
export function addElement(element) {
return {
type: types.ADD_ELEMENT,
data: element
}
}
/*
设置组件属性
*/
export function setProp(prop) {
return {
type: types.SET_PROP,
data: prop
}
}
|
chzyer/fsmq | go/fs/volume_test.go | package fs
import (
"os"
"testing"
"time"
"github.com/allmad/madq/go/bio"
"github.com/chzyer/flow"
"github.com/chzyer/test"
)
func TestVolume(t *testing.T) {
defer test.New(t)
delegate := bio.NewHybrid(test.NewMemDisk(), BlockBit)
vol, err := NewVolume(flow.New(), &VolumeConfig{
Delegate: delegate,
FlushInterval: time.Second,
FlushSize: 16 << 20,
})
defer vol.Close()
test.Nil(err)
{ // open without create
fd, err := vol.Open("hello", 0)
test.Nil(fd)
test.Equal(ErrFileNotExist, err)
}
{
fd, err := vol.Open("hello", os.O_CREATE)
test.Nil(err)
test.Equal(fd.Ino(), int32(1))
fd.Write([]byte("hello"))
fd.Sync()
fd.Close()
test.Nil(vol.FlushInodeMap())
vol.CleanCache()
fd, err = vol.Open("hello", 0)
test.Nil(err)
test.ReadStringAt(fd, 0, "hello")
}
_ = vol
}
|
philanderson888/java-playground | Projects/202009 Kotlin API/20200929-api-stock-ui/src/main/java/uk/co/philanderson/stockui/ChartController.java | <reponame>philanderson888/java-playground
package uk.co.philanderson.stockui;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.XYChart;
import org.springframework.stereotype.Component;
import uk.co.philanderson.stockclient.StockPrice;
import uk.co.philanderson.stockclient.WebClientStockClient;
import java.util.function.Consumer;
@Component
public class ChartController {
@FXML
public LineChart<String,Double> chart;
private uk.co.philanderson.stockclient.WebClientStockClient webClientStockClient;
/* public ChartController(WebClientStockClient webClientStockClient) {
this.webClientStockClient = webClientStockClient;
}*/
@FXML
public void initialize(){
ObservableList<XYChart.Series<String,Double>> data = FXCollections.observableArrayList();
// data.add(new XYChart.Series<>(seriesData));
chart.setData(data);
// webClientStockClient.pricesFor("SYMBOL").subscribe(this);
}
/* @Override
public void accept(StockPrice stockPrice) {
Platform.runLater(()->
seriesData.add(new XYChart.Data<>(String.valueOf(stockPrice.getTime().getSecond()),stockPrice.getPrice()))
);
}*/
}
|
copslock/broadcom_cpri | sdk-6.5.20/libs/sdklt/bcmlta/bcmltx/bcm56996_a0/bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler.c | /*******************************************************************************
*
* DO NOT EDIT THIS FILE!
* This file is auto-generated by fltg from Logical Table mapping files.
*
* Tool: $SDK/INTERNAL/fltg/bin/fltg
*
* Edits to this file will be lost when it is regenerated.
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
/* Logical Table Adaptor for component bcmltx */
/* Handler: bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler */
#include <bcmlrd/bcmlrd_types.h>
#include <bcmltd/chip/bcmltd_id.h>
#include <bcmltx/bcmmirror/bcmltx_mirror_encap_ipv6.h>
#include <bcmdrd/chip/bcm56996_a0_enum.h>
#include <bcmlrd/chip/bcm56996_a0/bcm56996_a0_lrd_xfrm_field_desc.h>
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s0[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s1[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s2[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s3[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s4[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s5[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_dst_field_desc_d0[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_dst_field_desc_d1[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_dst_field_desc_d1[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_dst_field_desc_d1[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_dst_field_desc_d2[];
extern const bcmltd_field_desc_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_dst_field_desc_d2[];
static const
bcmltd_field_list_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s0 = {
.field_num = 8,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s0
};
static const
bcmltd_field_list_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s1 = {
.field_num = 8,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s1
};
static const
bcmltd_field_list_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s2 = {
.field_num = 8,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s2
};
static const
bcmltd_field_list_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s3 = {
.field_num = 8,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s3
};
static const
bcmltd_field_list_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s4 = {
.field_num = 8,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s4
};
static const
bcmltd_field_list_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s5 = {
.field_num = 8,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_src_field_desc_s5
};
static const bcmltd_field_list_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_dst_list_d0 = {
.field_num = 1,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_dst_field_desc_d0
};
static const bcmltd_field_list_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_dst_list_d1 = {
.field_num = 1,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_dst_field_desc_d1
};
static const bcmltd_field_list_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_dst_list_d1 = {
.field_num = 1,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_dst_field_desc_d1
};
static const bcmltd_field_list_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_dst_list_d1 = {
.field_num = 1,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_dst_field_desc_d1
};
static const bcmltd_field_list_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_dst_list_d2 = {
.field_num = 1,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_dst_field_desc_d2
};
static const bcmltd_field_list_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_dst_list_d2 = {
.field_num = 1,
.field_array = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_dst_field_desc_d2
};
static const uint32_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s0[8] = {
MIRROR_ENCAP_ERSPAN_IPV6t_DST_IPV6u_LOWERf,
MIRROR_ENCAP_ERSPAN_IPV6t_DST_IPV6u_UPPERf,
MIRROR_ENCAP_ERSPAN_IPV6t_SRC_IPV6u_LOWERf,
MIRROR_ENCAP_ERSPAN_IPV6t_SRC_IPV6u_UPPERf,
MIRROR_ENCAP_ERSPAN_IPV6t_HOP_LIMITf,
MIRROR_ENCAP_ERSPAN_IPV6t_NEXT_HEADERf,
MIRROR_ENCAP_ERSPAN_IPV6t_FLOW_LABELf,
MIRROR_ENCAP_ERSPAN_IPV6t_TRAFFIC_CLASSf,
};
static const uint32_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s1[8] = {
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_DST_IPV6u_LOWERf,
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_DST_IPV6u_UPPERf,
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_SRC_IPV6u_LOWERf,
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_SRC_IPV6u_UPPERf,
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_HOP_LIMITf,
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_NEXT_HEADERf,
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_FLOW_LABELf,
MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t_TRAFFIC_CLASSf,
};
static const uint32_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s2[8] = {
MIRROR_ENCAP_PSAMP_IPV6t_DST_IPV6u_LOWERf,
MIRROR_ENCAP_PSAMP_IPV6t_DST_IPV6u_UPPERf,
MIRROR_ENCAP_PSAMP_IPV6t_SRC_IPV6u_LOWERf,
MIRROR_ENCAP_PSAMP_IPV6t_SRC_IPV6u_UPPERf,
MIRROR_ENCAP_PSAMP_IPV6t_HOP_LIMITf,
MIRROR_ENCAP_PSAMP_IPV6t_NEXT_HEADERf,
MIRROR_ENCAP_PSAMP_IPV6t_FLOW_LABELf,
MIRROR_ENCAP_PSAMP_IPV6t_TRAFFIC_CLASSf,
};
static const uint32_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s3[8] = {
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_DST_IPV6u_LOWERf,
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_DST_IPV6u_UPPERf,
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_SRC_IPV6u_LOWERf,
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_SRC_IPV6u_UPPERf,
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_HOP_LIMITf,
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_NEXT_HEADERf,
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_FLOW_LABELf,
MIRROR_ENCAP_PSAMP_METADATA_IPV6t_TRAFFIC_CLASSf,
};
static const uint32_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s4[8] = {
MIRROR_ENCAP_SFLOW_IPV6t_DST_IPV6u_LOWERf,
MIRROR_ENCAP_SFLOW_IPV6t_DST_IPV6u_UPPERf,
MIRROR_ENCAP_SFLOW_IPV6t_SRC_IPV6u_LOWERf,
MIRROR_ENCAP_SFLOW_IPV6t_SRC_IPV6u_UPPERf,
MIRROR_ENCAP_SFLOW_IPV6t_HOP_LIMITf,
MIRROR_ENCAP_SFLOW_IPV6t_NEXT_HEADERf,
MIRROR_ENCAP_SFLOW_IPV6t_FLOW_LABELf,
MIRROR_ENCAP_SFLOW_IPV6t_TRAFFIC_CLASSf,
};
static const uint32_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s5[8] = {
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_DST_IPV6u_LOWERf,
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_DST_IPV6u_UPPERf,
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_SRC_IPV6u_LOWERf,
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_SRC_IPV6u_UPPERf,
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_HOP_LIMITf,
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_NEXT_HEADERf,
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_FLOW_LABELf,
MIRROR_ENCAP_SFLOW_SEQ_IPV6t_TRAFFIC_CLASSf,
};
static const uint32_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_transform_dst_d0[1] = {
ERSPAN_V6v_ERSPAN_HEADER_V6f,
};
static const uint32_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_transform_dst_d1[1] = {
PSAMP_V6v_PSAMP_HEADER_V6f,
};
static const uint32_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_transform_dst_d1[1] = {
PSAMP_V6v_PSAMP_HEADER_V6f,
};
static const uint32_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_transform_dst_d1[1] = {
PSAMP_V6v_PSAMP_HEADER_V6f,
};
static const uint32_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_transform_dst_d2[1] = {
SFLOW_V6v_SFLOW_HEADER_V6f,
};
static const uint32_t
bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_transform_dst_d2[1] = {
SFLOW_V6v_SFLOW_HEADER_V6f,
};
static const bcmltd_generic_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data = {
.sid = MIRROR_ENCAP_ERSPAN_IPV6t,
.values = 0,
.value = NULL,
.user_data = NULL
};
static const bcmltd_generic_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data1 = {
.sid = MIRROR_ENCAP_MIRROR_ON_DROP_IPV6t,
.values = 0,
.value = NULL,
.user_data = NULL
};
static const bcmltd_generic_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data2 = {
.sid = MIRROR_ENCAP_PSAMP_IPV6t,
.values = 0,
.value = NULL,
.user_data = NULL
};
static const bcmltd_generic_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data3 = {
.sid = MIRROR_ENCAP_PSAMP_METADATA_IPV6t,
.values = 0,
.value = NULL,
.user_data = NULL
};
static const bcmltd_generic_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data4 = {
.sid = MIRROR_ENCAP_SFLOW_IPV6t,
.values = 0,
.value = NULL,
.user_data = NULL
};
static const bcmltd_generic_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data5 = {
.sid = MIRROR_ENCAP_SFLOW_SEQ_IPV6t,
.values = 0,
.value = NULL,
.user_data = NULL
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s0_d0 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 8,
.field = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s0,
.field_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s0,
.rfields = 1,
.rfield = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_transform_dst_d0,
.rfield_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_dst_list_d0,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s0_d0 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 1,
.field = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_transform_dst_d0,
.field_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_erspan_ipv6_dst_list_d0,
.rfields = 8,
.rfield = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s0,
.rfield_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s0,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s1_d1 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 8,
.field = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s1,
.field_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s1,
.rfields = 1,
.rfield = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_transform_dst_d1,
.rfield_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_dst_list_d1,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data1
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s1_d1 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 1,
.field = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_transform_dst_d1,
.field_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_mirror_on_drop_ipv6_dst_list_d1,
.rfields = 8,
.rfield = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s1,
.rfield_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s1,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data1
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s2_d1 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 8,
.field = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s2,
.field_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s2,
.rfields = 1,
.rfield = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_transform_dst_d1,
.rfield_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_dst_list_d1,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data2
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s2_d1 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 1,
.field = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_transform_dst_d1,
.field_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_ipv6_dst_list_d1,
.rfields = 8,
.rfield = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s2,
.rfield_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s2,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data2
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s3_d1 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 8,
.field = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s3,
.field_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s3,
.rfields = 1,
.rfield = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_transform_dst_d1,
.rfield_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_dst_list_d1,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data3
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s3_d1 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 1,
.field = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_transform_dst_d1,
.field_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_psamp_metadata_ipv6_dst_list_d1,
.rfields = 8,
.rfield = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s3,
.rfield_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s3,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data3
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s4_d2 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 8,
.field = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s4,
.field_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s4,
.rfields = 1,
.rfield = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_transform_dst_d2,
.rfield_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_dst_list_d2,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data4
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s4_d2 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 1,
.field = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_transform_dst_d2,
.field_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_ipv6_dst_list_d2,
.rfields = 8,
.rfield = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s4,
.rfield_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s4,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data4
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s5_d2 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 8,
.field = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s5,
.field_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s5,
.rfields = 1,
.rfield = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_transform_dst_d2,
.rfield_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_dst_list_d2,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data5
};
static const bcmltd_transform_arg_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s5_d2 = {
.values = 0,
.value = NULL,
.tables = 0,
.table = NULL,
.fields = 1,
.field = bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_transform_dst_d2,
.field_list = &bcm56996_a0_lrd_bcmltx_mirror_encap_ipv6_mirror_encap_sflow_seq_ipv6_dst_list_d2,
.rfields = 8,
.rfield = bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_transform_src_s5,
.rfield_list = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_src_list_s5,
.comp_data = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_comp_data5
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_s0_d0 = {
.transform = bcmltx_mirror_encap_ipv6_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s0_d0
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_s1_d1 = {
.transform = bcmltx_mirror_encap_ipv6_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s1_d1
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_s2_d1 = {
.transform = bcmltx_mirror_encap_ipv6_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s2_d1
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_s3_d1 = {
.transform = bcmltx_mirror_encap_ipv6_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s3_d1
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_s4_d2 = {
.transform = bcmltx_mirror_encap_ipv6_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s4_d2
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_s5_d2 = {
.transform = bcmltx_mirror_encap_ipv6_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_fwd_arg_s5_d2
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_s0_d0 = {
.transform = bcmltx_mirror_encap_ipv6_rev_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s0_d0
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_s1_d1 = {
.transform = bcmltx_mirror_encap_ipv6_rev_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s1_d1
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_s2_d1 = {
.transform = bcmltx_mirror_encap_ipv6_rev_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s2_d1
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_s3_d1 = {
.transform = bcmltx_mirror_encap_ipv6_rev_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s3_d1
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_s4_d2 = {
.transform = bcmltx_mirror_encap_ipv6_rev_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s4_d2
};
const bcmltd_xfrm_handler_t
bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_s5_d2 = {
.transform = bcmltx_mirror_encap_ipv6_rev_transform,
.arg = &bcm56996_a0_lta_bcmltx_mirror_encap_ipv6_xfrm_handler_rev_arg_s5_d2
};
|
tbwiss/CoAP_PubSub | coap_pubsub_plain_client/src/main/java/com/wiss/thom/main/Main.java | <gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.wiss.thom.main;
import com.wiss.thom.output.MeasurementWriter;
/**
*
* @author thomas
*/
public class Main {
//
// sudo service rabbitmq-server start
//
//
// sudo tcpdump -w amqpt_nosec_responsetime_??_1.pcap -i wlan0 tcp 'port ????'
//
// sudo tc qdisc add dev wlan0 root netem loss 25%
private static final String FILEPATH = "/home/thomas/demoOutput/";
private static final String FILENAME = "amqp_nosec_responsetime_1.txt";
private static String hostIP = "127.0.0.1";
public static void main(String[] args) {
MeasurementWriter writer = new MeasurementWriter(FILEPATH + FILENAME);
//Publisher pub = new Publisher(writer, hostIP);
//Subscriber sub = new Subscriber(writer, hostIP);
//pub.setupBaseTopic();
//pub.createTopic();
PubSub pubSub = new PubSub(writer, hostIP);
pubSub.setupBaseTopic();
pubSub.createTopic();
for(int k = 0; k < 200; k++){
writer.writeContent(String.valueOf(k) + "," + System.currentTimeMillis());
pubSub.subscribeWithCoapHandler();
pubSub.publishNbrOfData(5);
writer.writeContent(String.valueOf(k) + "," + System.currentTimeMillis());
}
}
}
|
sureshmangs/Code | competitive programming/codeforces/1406A - Subset Mex.cpp | /*
A. Subset Mex
time limit per test1 second
memory limit per test512 megabytes
inputstandard input
outputstandard output
Given a set of integers (it can contain equal elements).
You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B).
Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:
mex({1,4,0,2,2,1})=3
mex({3,3,2,1,3,0,0})=4
mex(∅)=0 (mex for empty set)
The set is splitted into two subsets A and B if for any integer number x the number of occurrences of x into this set is equal to the sum of the number of occurrences of x into A and the number of occurrences of x into B.
Input
The input consists of multiple test cases. The first line contains an integer t (1≤t≤100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer n (1≤n≤100) — the size of the set.
The second line of each testcase contains n integers a1,a2,…an (0≤ai≤100) — the numbers in the set.
Output
For each test case, print the maximum value of mex(A)+mex(B).
Example
inputCopy
4
6
0 2 1 5 0 1
3
0 1 2
4
0 2 0 1
6
1 2 3 4 5 6
outputCopy
5
3
4
0
Note
In the first test case, A={0,1,2},B={0,1,5} is a possible choice.
In the second test case, A={0,1,2},B=∅ is a possible choice.
In the third test case, A={0,1,2},B={0} is a possible choice.
In the fourth test case, A={1,3,5},B={2,4,6} is a possible choice.
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++){
int ch;
cin>>ch;
v.push_back(ch);
}
set<int> a, b;
for(auto &x: v){
if(a.find(x)==a.end()){
a.insert(x);
} else b.insert(x);
}
int i, res=0;
for(i=0;i<101;i++){
if(a.find(i)==a.end())
break;
}
res+=i;
for(i=0;i<101;i++){
if(b.find(i)==b.end())
break;
}
res+=i;
cout<<res<<endl;
}
return 0;
}
|
enowmbi/lazarus | db/migrate/20190720150237_create_observations.rb | <filename>db/migrate/20190720150237_create_observations.rb
class CreateObservations < ActiveRecord::Migration[5.2]
def change
create_table :observations do |t|
t.string :name
t.string :desc
t.boolean :is_active
t.integer :observation_group_id
t.timestamps
end
end
end
|
huhumt/programming_pearls_practice | column003_data_structure/usa_tax/usa_tax.c | /****************************************************************************************
* This source file is an implementation to calculate tax based on your monthly income
* Author: huhao
* Date: 2017.07.31
* Modification record:
*
*
*
*****************************************************************************************/
#include "usa_tax.h"
/**********************************************************************************
* Description: find index for element in ascending sorted array data
* Parameters:
* array: array to store data
* array_size: element numbers in array
* element: elment need to find index
* Return: index for element in array
**********************************************************************************/
static uint8_t find_index(uint32_t array[], uint8_t array_size, uint32_t element)
{
uint8_t i;
for (i = 0; i < array_size; i += 1) {
if (element <= array[i]) {
return i;
}
}
return (array_size - 1);
}
float usa_tax_calculator(uint32_t income)
{
const uint8_t kARRAY_SIZE = 57;
uint8_t i, index, tax_rate[kARRAY_SIZE];
uint16_t inc, tax_base[kARRAY_SIZE];
uint32_t tax_level[kARRAY_SIZE];
tax_rate[0] = 0;
tax_base[0] = 0;
tax_level[0] = 2200;
for (i = 1; i < kARRAY_SIZE; i += 1) {
tax_rate[i] = 14 + (i - 1);
if (i > 1) {
inc += 5;
} else {
inc = 70;
}
tax_base[i] = tax_base[i - 1] + inc;
tax_level[i] = tax_level[i - 1] + 500;
}
LOG("tax = %u + .%u * (income - %lu)\n", tax_base[56], tax_rate[56], tax_level[56]);
index = find_index(tax_level, kARRAY_SIZE, income);
if (index == 0) {
return 0.0f;
} else {
return (tax_base[index] + tax_rate[index] * 0.01f * (income - tax_level[index - 1]));
}
}
|
wolforest/wolf | business/org/org-api/src/main/java/study/daydayup/wolf/business/org/api/task/dto/TaskId.java | package study.daydayup.wolf.business.org.api.task.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import study.daydayup.wolf.framework.layer.api.DTO;
/**
* study.daydayup.wolf.business.org.api.task.dto
*
* @author Wingle
* @since 2020/3/16 10:39 上午
**/
@EqualsAndHashCode(callSuper = false)
@Data
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
public class TaskId extends TaskOwner implements DTO {
private Long taskId;
}
|
ZZHGit/rDSN | src/rep_tests/simple_kv/simple_kv.main.cpp | <reponame>ZZHGit/rDSN
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Description:
* Replication testing framework.
*
* Revision history:
* Nov., 2015, @qinzuoyan (<NAME>), first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include "checker.h"
# include "injector.h"
# include "case.h"
# include "client.h"
# include "simple_kv.server.impl.h"
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "simple_kv.main"
void dsn_app_registration()
{
// register services
dsn::register_app<dsn::replication::replication_service_app>("replica");
dsn::register_app<dsn::service::meta_service_app>("meta");
dsn::register_app<dsn::replication::test::simple_kv_client_app>("client");
dsn::replication::register_replica_provider<dsn::replication::test::simple_kv_service_impl>("simple_kv");
dsn::tools::register_toollet<dsn::replication::test::test_injector>("test_injector");
dsn::replication::test::install_checkers();
}
extern void dsn_core_init();
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cerr << "USGAE: " << argv[0] << " <config-file> <case-input>" << std::endl;
std::cerr << " e.g.: " << argv[0] << " case-000.ini case-000.act" << std::endl;
return -1;
}
dsn::replication::test::g_case_input = argv[2];
dsn_app_registration();
dsn_core_init();
// specify what services and tools will run in config file, then run
dsn_run(argc - 1, argv, false);
while (!dsn::replication::test::g_done)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ddebug("=== exiting ...");
dsn::replication::test::test_checker::instance().exit();
if (dsn::replication::test::g_fail)
{
#ifndef ENABLE_GCOV
dsn_exit(-1);
#endif
return -1;
}
#ifndef ENABLE_GCOV
dsn_exit(0);
#endif
return 0;
}
|
zachhardy/chi-tech | ChiTech/ChiMath/Quadratures/product_quadrature.h | <filename>ChiTech/ChiMath/Quadratures/product_quadrature.h<gh_stars>1-10
#ifndef _product_quadrature_h
#define _product_quadrature_h
#include <map>
#include <vector>
#include "angular_quadrature_base.h"
namespace chi_math
{
enum class ProductQuadratureType
{
UNKNOWN = 0,
GAUSS_LEGENDRE = 1,
GAUSS_CHEBYSHEV = 2,
GAUSS_LEGENDRE_LEGENDRE = 3,
GAUSS_LEGENDRE_CHEBYSHEV = 4,
CUSTOM_QUADRATURE = 5,
};
class ProductQuadrature;
}
//######################################################### Class def
/** Class for product quadratures*/
class chi_math::ProductQuadrature : public chi_math::AngularQuadrature
{
public:
std::vector<double> polar_ang;
std::vector<double> azimu_ang;
protected:
/** Linear indices of ordered directions mapped to polar level. */
std::map<unsigned int, std::vector<unsigned int>> map_directions;
public:
ProductQuadrature() :
AngularQuadrature(chi_math::AngularQuadratureType::ProductQuadrature)
{}
virtual ~ProductQuadrature()
{}
void InitializeWithGL(int Np, bool verbose=false);
void InitializeWithGLL(int Na, int Np, bool verbose=false);
void InitializeWithGLC(int Na, int Np, bool verbose=false);
void InitializeWithCustom(std::vector<double>& azimuthal,
std::vector<double>& polar,
std::vector<double>& in_weights,
bool verbose=false) override;
/**Obtains the abscissae index given the indices of the
* polar angle index and the azimuthal angle index.*/
unsigned int GetAngleNum(const unsigned int polar_angle_index,
const unsigned int azimu_angle_index) const
{ return map_directions.at(polar_angle_index)[azimu_angle_index]; }
/** Return constant reference to map_directions. */
const std::map<unsigned int,
std::vector<unsigned int>>& GetDirectionMap() const
{ return map_directions; }
};
#endif
|
health-connector/enroll | db/migrate/20180516222459_benefit_application_migration.rb | class BenefitApplicationMigration < Mongoid::Migration
def self.up
if Settings.site.key.to_s == "cca"
Dir.mkdir("hbx_report") unless File.exists?("hbx_report")
file_name = "#{Rails.root}/hbx_report/benefit_application_status_#{TimeKeeper.datetime_of_record.strftime("%m_%d_%Y_%H_%M_%S")}.csv"
field_names = %w(organization_name organization_fein plan_year_id plan_year_start_on status)
logger = Logger.new("#{Rails.root}/log/benefit_application_migration.log")
logger.info "Script Start - #{TimeKeeper.datetime_of_record}" unless Rails.env.test?
CSV.open(file_name, 'w') do |csv|
csv << field_names
migrate_plan_years_to_benefit_applications(csv, logger)
puts "" unless Rails.env.test?
puts "Check the report and logs for futher information" unless Rails.env.test?
end
logger.info "End of the script" unless Rails.env.test?
else
say "Skipping for non-CCA site"
end
end
def self.down
end
private
def self.migrate_plan_years_to_benefit_applications(csv, logger)
old_organizations = Organization.unscoped.exists(:"employer_profile.plan_years" => true)
success = 0
failed = 0
total_plan_years = 0
limit = 100
say_with_time("Time take to migrate plan years") do
old_organizations.batch_size(limit).no_timeout.each do |old_org|
unless new_org(old_org).present?
print 'F' unless Rails.env.test?
csv << [old_org.legal_name, old_org.fein, '', '', "New organization not found for fein: #{old_org.fein}"]
next
end
new_organization = new_org(old_org)
benefit_sponsorship = new_organization.first.active_benefit_sponsorship
self.set_benefit_sponsorship_state(old_org, benefit_sponsorship)
benefit_sponsorship.registered_on = old_org.employer_profile.registered_on
benefit_sponsorship.effective_begin_on = self.get_benefit_sponsorship_effective_on(old_org)
construct_workflow_state_for_benefit_sponsorship(benefit_sponsorship, old_org)
BenefitSponsors::BenefitSponsorships::BenefitSponsorship.skip_callback(:save, :after, :notify_on_save)
benefit_sponsorship.save
old_org.employer_profile.plan_years.asc(:start_on).each do |plan_year|
total_plan_years += 1
@benefit_package_map = {}
begin
benefit_application = convert_plan_year_to_benefit_application(benefit_sponsorship, plan_year,csv)
next unless benefit_application
plan_year_plan_hios_ids = self.get_plan_hios_ids_of_plan_year(plan_year)
benfit_application_product_hios_ids = self.get_plan_hios_ids_of_benefit_application(benefit_application)
unless self.new_benfit_application_product_valid(plan_year_plan_hios_ids, benfit_application_product_hios_ids)
if self.tufts_case(plan_year_plan_hios_ids, benfit_application_product_hios_ids, plan_year.start_on.year)
self.update_sponsor_catalog_product_package(@benefit_sponsor_catalog, plan_year)
@benefit_sponsor_catalog.save
else
print 'F' unless Rails.env.test?
csv << [old_org.legal_name, old_org.fein, plan_year.id, plan_year.start_on, "benefit application products mismatch with old model plan year products"]
next
end
end
if benefit_application.valid? && self.new_benfit_application_product_valid(self.get_plan_hios_ids_of_plan_year(plan_year), self.get_plan_hios_ids_of_benefit_application(benefit_application))
BenefitSponsors::BenefitApplications::BenefitApplication.skip_callback(:save, :after, :notify_on_save)
benefit_application.save!
assign_employee_benefits(benefit_sponsorship)
print '.' unless Rails.env.test?
csv << [old_org.legal_name, old_org.fein, plan_year.id, plan_year.start_on, 'Success']
success += 1
else
raise StandardError, benefit_application.errors.to_s
end
rescue Exception => e
print 'F' unless Rails.env.test?
csv << [old_org.legal_name, old_org.fein, plan_year.id, plan_year.start_on, 'Failed', e.to_s]
failed += 1
end
end
end
logger.info " Total #{old_organizations.count} old organizations with plan years" unless Rails.env.test?
logger.info " Total #{total_plan_years} plan years" unless Rails.env.test?
logger.info " #{failed} plan years failed to migrate into new DB at this point." unless Rails.env.test?
logger.info " #{success} plan years successfully migrated into new DB at this point." unless Rails.env.test?
end
end
# TODO: Verify updated by field on plan year
# "updated_by_id"=>BSON::ObjectId('5909e07d082e766d68000078'),
def self.convert_plan_year_to_benefit_application(benefit_sponsorship, plan_year, csv)
py_attrs = plan_year.attributes.except(:benefit_groups, :workflow_state_transitions)
application_attrs = py_attrs.slice(:fte_count, :pte_count, :msp_count, :created_at, :updated_at, :terminated_on)
benefit_application = benefit_sponsorship.benefit_applications.new(application_attrs)
benefit_application.effective_period = (plan_year.start_on..plan_year.end_on)
benefit_application.write_attribute(:effective_period, (plan_year.start_on..plan_year.end_on)) if plan_year.start_on == plan_year.end_on # benefit_application.effective_period setter method setting value to nil if plan_year.start_on == plan_year.end_on for those cases uses below
benefit_application.open_enrollment_period = (plan_year.open_enrollment_start_on..plan_year.open_enrollment_end_on)
benefit_application.pull_benefit_sponsorship_attributes
predecessor_application = benefit_sponsorship.benefit_applications.where(:"effective_period.max" => benefit_application.effective_period.min.to_date.prev_day, :aasm_state.in=> [:active, :terminated, :expired, :imported])
if predecessor_application.present?
if predecessor_application.count < 2
benefit_application.predecessor_id = predecessor_application.first.id
elsif predecessor_application.where(:"effective_period.max" => Date.new(2018,7,31)).count == 2 # exception case for 8/1 conversion
benefit_application.predecessor_id = predecessor_application.where(aasm_state: :imported).first.id
else
benefit_application.predecessor_id = predecessor_application.first.id
end
end
@benefit_sponsor_catalog = benefit_sponsorship.benefit_sponsor_catalog_for(benefit_application.effective_period.min)
catalog_product_hios_id = self.benefit_sponsor_catalog_products(@benefit_sponsor_catalog, plan_year)
plan_year_plan_hios_ids = self.get_plan_hios_ids_of_plan_year(plan_year)
unless self.new_benefit_sponsor_catalog_product_valid(catalog_product_hios_id, plan_year_plan_hios_ids)
self.update_sponsor_catalog_product_package(@benefit_sponsor_catalog, plan_year)
end
@benefit_sponsor_catalog.benefit_application = benefit_application
@benefit_sponsor_catalog.save
benefit_application.benefit_sponsor_catalog = @benefit_sponsor_catalog
# TODO: do unscoped...to pick all the benefit groups
plan_year.benefit_groups.unscoped.each do |benefit_group|
params = sanitize_benefit_group_attrs(benefit_group)
importer = BenefitSponsors::Importers::BenefitPackageImporter.call(benefit_application, params)
if importer.benefit_package.blank?
raise Standard, "Benefit Package creation failed"
end
@benefit_package_map[benefit_group] = importer.benefit_package
self.set_predecessor_for_benefit_package(benefit_application, importer.benefit_package)
end
benefit_application.aasm_state = benefit_application.matching_state_for(plan_year)
if plan_year.is_conversion
benefit_application.aasm_state = :imported
end
construct_workflow_state_transitions(benefit_application, plan_year)
benefit_application
end
def self.is_plan_year_effectuated?(plan_year)
%w(published enrolling enrolled active suspended expired terminated termination_pending renewing_draft renewing_published renewing_enrolling renewing_enrolled renewing_publish_pending).include?(plan_year.aasm_state)
end
def self.continuous_coverage?(old_org)
return true if old_org.employer_profile.plan_years.count < 2
return true unless old_org.employer_profile.plan_years.any?{|py| py.expired? || py.terminated? || py.active?}
plan_years = old_org.employer_profile.plan_years.select {|plan_year| is_plan_year_effectuated?(plan_year)}.sort_by(&:start_on)
if plan_years.each_cons(2).any? {|plan_year| plan_year[0].end_on.next_day != plan_year[1].start_on }
return false
else
return true
end
end
def self.get_benefit_sponsorship_effective_on(old_org)
plan_years = old_org.employer_profile.plan_years.asc(:start_on).where(:aasm_state.in=> [:active, :terminated, :expired])
if plan_years.present?
plan_years.first.start_on
else
return nil
end
end
def self.get_plan_hios_ids_of_plan_year(plan_year)
plan_year.benefit_groups.inject([]) do |plan_hios_ids, benefit_group|
plan_hios_ids += benefit_group.elected_plans.map(&:hios_id)
plan_hios_ids += [benefit_group.reference_plan.hios_id]
plan_hios_ids.uniq
end
end
def self.get_plan_hios_ids_of_benefit_application(benefit_application)
benefit_application.benefit_packages.inject([]) do |product_hios_ids, benefit_package|
product_hios_ids += benefit_package.health_sponsored_benefit.products(benefit_application.effective_period.min).map(&:hios_id)
product_hios_ids += [benefit_package.health_sponsored_benefit.reference_product.hios_id]
product_hios_ids.uniq
end
end
def self.new_benfit_application_product_valid(plan_year_plan_hios_ids, benfit_application_product_hios_ids)
return false unless (benfit_application_product_hios_ids.size == plan_year_plan_hios_ids.size)
(benfit_application_product_hios_ids & plan_year_plan_hios_ids).size == benfit_application_product_hios_ids.size
end
def self.benefit_sponsor_catalog_products(benefit_sponsor_catalog, plan_year)
@package_kind = plan_year.benefit_groups.map{|benfit_group| self.map_product_package_kind(benfit_group.plan_option_kind)}
benefit_sponsor_catalog.product_packages.select{|product_package| @package_kind.include?(product_package.package_kind)}.inject([]) do |catalog_product, product_package|
catalog_product += product_package.products.map(&:hios_id)
end
end
def self.new_benefit_sponsor_catalog_product_valid(catalog_product_hios_id, plan_year_plan_hios_ids)
plan_year_plan_hios_ids.all? {|hios_id| catalog_product_hios_id.include?(hios_id)}
end
def self.update_sponsor_catalog_product_package(benefit_sponsor_catalog, plan_year)
plan_year.benefit_groups.each do |benefit_group|
plans = benefit_group.elected_plans
products = plans.inject([]) do |product, plan|
product += BenefitMarkets::Products::Product.where(hios_id: plan.hios_id).select {|product| product.active_year == plan.active_year }
end
package_kind = self.map_product_package_kind(benefit_group.plan_option_kind)
product_package = benefit_sponsor_catalog.product_packages.where(package_kind: package_kind).first
product_package.products = products
end
end
def self.tufts_case(plan_hios, product_hios, year)
tufts_exists_in_plan_year = Plan.where(:"hios_id".in=>plan_hios, active_year: year).select{|product| product.carrier_profile.legal_name == "Tufts Health Direct"}
tufts_exists_in_benefit_application = BenefitMarkets::Products::Product.where(:'hios_id'.in=>product_hios).select{|product| ((product.issuer_profile.legal_name == "Tufts Health Direct") && (product.active_year == year))}
if tufts_exists_in_plan_year.blank? && tufts_exists_in_benefit_application.present?
return true
else
return false
end
end
def self.set_predecessor_for_benefit_package(benefit_application, benefit_package)
return unless benefit_application.predecessor_id.present?
predecessor_application = benefit_application.predecessor
predecessor_benefit_packages = benefit_application.predecessor.benefit_packages
if predecessor_benefit_packages.count < 2
benefit_package.predecessor_id = benefit_application.predecessor.benefit_packages.first.id
return
end
new_package_hios_id = benefit_package.health_sponsored_benefit.products(benefit_application.effective_period.min).map(&:hios_id)
predecessor_benefit_packages.each do |predecessor_package|
predecessor_package_hios_id = predecessor_package.health_sponsored_benefit.products(predecessor_application.effective_period.min).map(&:hios_id)
if ((new_package_hios_id.size == predecessor_package_hios_id.size) && ((new_package_hios_id && predecessor_package_hios_id).size == new_package_hios_id.size))
benefit_package.predecessor_id = predecessor_package.id
end
end
end
def self.map_product_package_kind(plan_option_kind)
package_kind_mapping = {
sole_source: :single_product,
single_plan: :single_product,
single_carrier: :single_issuer,
metal_level: :metal_level
}
package_kind_mapping[plan_option_kind.to_sym]
end
def self.sanitize_benefit_group_attrs(benefit_group)
attributes = benefit_group.attributes.slice(
:title, :description, :created_at, :updated_at, :is_active, :effective_on_kind, :effective_on_offset,
:plan_option_kind, :relationship_benefits, :dental_relationship_benefits
)
attributes[:is_default] = benefit_group.default
attributes[:reference_plan_hios_id] = benefit_group.reference_plan.hios_id
attributes[:dental_reference_plan_hios_id] = benefit_group.dental_reference_plan.hios_id if benefit_group.is_offering_dental?
attributes[:composite_tier_contributions] = benefit_group.composite_tier_contributions.inject([]) do |contributions, tier|
contributions << {
relationship: tier.composite_rating_tier,
offered: tier.offered,
premium_pct: tier.employer_contribution_percent,
estimated_tier_premium: tier.estimated_tier_premium,
final_tier_premium: tier.final_tier_premium
}
end
attributes
end
def self.construct_workflow_state_transitions(benefit_application, plan_year)
plan_year.workflow_state_transitions.unscoped.asc(:transition_at).each do |wst|
attributes = wst.attributes.except(:_id)
attributes[:from_state] = benefit_application.send(:plan_year_to_benefit_application_states_map)[wst.from_state.to_sym]
attributes[:to_state] = benefit_application.send(:plan_year_to_benefit_application_states_map)[wst.to_state.to_sym]
benefit_application.workflow_state_transitions.build(attributes)
end
end
def self.set_benefit_sponsorship_state(old_org, benefit_sponsorship)
if ["conversion", "mid_plan_year_conversion"].include?(benefit_sponsorship.source_kind.to_s)
benefit_sponsorship.aasm_state = :active
return
end
if benefit_sponsorship.source_kind.to_s == "self_serve"
if old_org.employer_profile.active_plan_year.present?
benefit_sponsorship.aasm_state = :active
return
end
if old_org.employer_profile.published_plan_year.present? && old_org.employer_profile.published_plan_year.enrolling?
benefit_sponsorship.aasm_state = :applicant
else
benefit_sponsorship.aasm_state = benefit_sponsorship.send(:employer_profile_to_benefit_sponsor_states_map)[old_org.employer_profile.aasm_state.to_sym]
end
end
end
def self.construct_workflow_state_for_benefit_sponsorship(benefit_sponsorship, old_org)
old_org.employer_profile.workflow_state_transitions.unscoped.asc(:transition_at).each do |wst|
attributes = wst.attributes.except(:_id)
attributes[:from_state] = benefit_sponsorship.send(:employer_profile_to_benefit_sponsor_states_map)[wst.from_state.to_sym]
attributes[:to_state] = benefit_sponsorship.send(:employer_profile_to_benefit_sponsor_states_map)[wst.to_state.to_sym]
benefit_sponsorship.workflow_state_transitions.build(attributes)
end
end
def self.assign_employee_benefits(benefit_sponsorship)
@benefit_package_map.each do |benefit_group, benefit_package|
benefit_group.census_employees.unscoped.each do |census_employee|
if census_employee.benefit_sponsorship_id.blank?
census_employee.employee_role.update_attributes(benefit_sponsors_employer_profile_id: benefit_sponsorship.organization.employer_profile.id) if census_employee.employee_role && census_employee.employee_role.benefit_sponsors_employer_profile_id.blank?
census_employee.benefit_sponsors_employer_profile_id = benefit_sponsorship.organization.employer_profile.id if census_employee.benefit_sponsors_employer_profile_id.blank?
census_employee.benefit_sponsorship = benefit_sponsorship
end
census_employee.benefit_group_assignments.unscoped.each do |benefit_group_assignment|
if benefit_group_assignment.benefit_group_id.to_s == benefit_group.id.to_s
benefit_group_assignment.benefit_package_id = benefit_package.id
end
end
CensusEmployee.skip_callback(:save, :after, :assign_default_benefit_package)
CensusEmployee.skip_callback(:save, :after, :assign_benefit_packages)
CensusEmployee.skip_callback(:save, :after, :construct_employee_role)
CensusEmployee.skip_callback(:update, :after, :update_hbx_enrollment_effective_on_by_hired_on)
census_employee.save(:validate => false)
end
end
end
def self.new_org(old_org)
BenefitSponsors::Organizations::Organization.where(fein: old_org.fein)
end
end |
kalyankondapally/chromiumos-platform2 | iioservice/libiioservice_ipc/sensor_dbus.cc | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "iioservice/libiioservice_ipc/sensor_dbus.h"
#include <utility>
#include <base/bind.h>
#include <base/files/file_util.h>
#include <base/files/scoped_file.h>
#include <base/threading/thread_task_runner_handle.h>
#include <chromeos/dbus/service_constants.h>
namespace iioservice {
namespace {
constexpr int kDelayBootstrapInMilliseconds = 1000;
}
void SensorDbus::SetBus(dbus::Bus* sensor_bus) {
sensor_bus_ = sensor_bus;
}
void SensorDbus::OnBootstrapMojoResponse(dbus::Response* response) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sensor_sequence_checker_);
if (!response) {
LOG(ERROR) << ::mojo_connection_service::kMojoConnectionServiceServiceName
<< " D-Bus call failed";
ReconnectMojoWithDelay();
return;
}
base::ScopedFD file_handle;
dbus::MessageReader reader(response);
if (!reader.PopFileDescriptor(&file_handle)) {
LOG(ERROR) << "Couldn't extract file descriptor from D-Bus call";
ReconnectMojoWithDelay();
return;
}
if (!file_handle.is_valid()) {
LOG(ERROR) << "ScopedFD extracted from D-Bus call was invalid (i.e. empty)";
ReconnectMojoWithDelay();
return;
}
if (!base::SetCloseOnExec(file_handle.get())) {
PLOG(ERROR) << "Failed setting FD_CLOEXEC on file descriptor";
ReconnectMojoWithDelay();
return;
}
// Connect to mojo in the requesting process.
OnInvitationReceived(
mojo::IncomingInvitation::Accept(mojo::PlatformChannelEndpoint(
mojo::PlatformHandle(std::move(file_handle)))));
}
void SensorDbus::ReconnectMojoWithDelay() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sensor_sequence_checker_);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&SensorDbus::BootstrapMojoConnection,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kDelayBootstrapInMilliseconds));
}
} // namespace iioservice
|
manyong-Han/MilitaryScheduleManagement | app/src/main/java/com/teamproject/aaaaan_2/ui/menu/BlankFragment.java | package com.teamproject.aaaaan_2.ui.menu;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.teamproject.aaaaan_2.R;
/**
* Created by hanman-yong on 2020-01-15.
*/
public class BlankFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
|
lechium/tvOS144Headers | System/Library/PrivateFrameworks/UIKitCore.framework/_UIProgressView.h | <reponame>lechium/tvOS144Headers
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 14, 2021 at 2:37:17 PM Mountain Standard Time
* Operating System: Version 14.4 (Build 18K802)
* Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <UIKitCore/UIKitCore-Structs.h>
#import <UIKitCore/UIView.h>
@class _UICircleProgressView, NSProgress;
@interface _UIProgressView : UIView {
_UICircleProgressView* _progressView;
NSProgress* _trackedProgress;
}
@property (nonatomic,retain) NSProgress * trackedProgress; //@synthesize trackedProgress=_trackedProgress - In the implementation block
-(id)init;
-(void)dealloc;
-(void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void*)arg4 ;
-(id)initWithFrame:(CGRect)arg1 ;
-(CGSize)intrinsicContentSize;
-(void)setTrackedProgress:(NSProgress *)arg1 ;
-(void)_updateProgressValue;
-(NSProgress *)trackedProgress;
@end
|
fciubotaru/z-pec | ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/ajax/ui/PageMain.java | /**
*
*/
package com.zimbra.qa.selenium.projects.ajax.ui;
import org.openqa.selenium.JavascriptExecutor;
import com.zimbra.qa.selenium.framework.core.ClientSessionFactory;
import com.zimbra.qa.selenium.framework.ui.*;
import com.zimbra.qa.selenium.framework.util.*;
import com.zimbra.qa.selenium.projects.ajax.ui.DialogError.DialogErrorID;
import com.zimbra.qa.selenium.projects.ajax.ui.DialogWarning.DialogWarningID;
/**
* @author <NAME>
*
*/
public class PageMain extends AbsTab {
public static class Locators {
public static final String zLogoffPulldown = "css=td[id='skin_dropMenu'] td[id$='_dropdown']";
public static final String zLogoffOption = "css=tr[id='POPUP_logOff'] td[id$='_title']";
public static final String zAppbarMail = "id=zb__App__Mail_title";
public static final String zAppbarContact = "id=zb__App__Contacts_title";
public static final String zAppbarCal = "id=zb__App__Calendar_title";
public static final String zAppbarTasks = "id=zb__App__Tasks_title";
public static final String zAppbarBriefcase = "css=td[id=zb__App__Briefcase_title]";
public static final String zAppbarPreferences = "id=zb__App__Options_title";
public static final String zAppbarSocialLocator = "css=div[id^='zb__App__com_zimbra_social_'] td[id$='_title']";
// 8.0 D1: public static final String ButtonRefreshLocatorCSS = "css=div[id='CHECK_MAIL'] td[id='CHECK_MAIL_left_icon'] div[class='ImgRefresh']";
// 8.0 D2: public static final String ButtonRefreshLocatorCSS = "css=div[id='CHECK_MAIL'] td[id='CHECK_MAIL_left_icon'] div[class='ImgRefreshAll']";
public static final String ButtonRefreshLocatorCSS = "css=div[id='CHECK_MAIL'] td[id='CHECK_MAIL_left_icon']>div";
}
public PageMain(AbsApplication application) {
super(application);
logger.info("new " + PageMain.class.getCanonicalName());
}
public Toaster zGetToaster() throws HarnessException {
this.zWaitForBusyOverlay();
Toaster toaster = new Toaster(this.MyApplication);
logger.info("toaster is active: "+ toaster.zIsActive());
return (toaster);
}
public DialogWarning zGetWarningDialog(DialogWarningID zimbra) {
return (new DialogWarning(zimbra, this.MyApplication, this));
}
public DialogError zGetErrorDialog(DialogErrorID zimbra) {
return (new DialogError(zimbra, this.MyApplication, this));
}
public boolean zIsZimletLoaded() throws HarnessException {
if (ZimbraSeleniumProperties.isWebDriver())
return ("true".equals(sGetEval("return top.appCtxt.getZimletMgr().loaded")));
else if (ZimbraSeleniumProperties.isWebDriverBackedSelenium())
return ("true".equals(sGetEval("selenium.browserbot.getCurrentWindow().top.appCtxt.getZimletMgr().loaded")));
else
return ("true".equals(sGetEval("this.browserbot.getUserWindow().top.appCtxt.getZimletMgr().loaded")));
}
public boolean zIsMinicalLoaded() throws HarnessException {
return ("true".equals(sGetEval("this.browserbot.getUserWindow().top.appCtxt.getAppViewMgr().getCurrentViewComponent(this.browserbot.getUserWindow().top.ZmAppViewMgr.C_TREE_FOOTER) != null")));
}
/* (non-Javadoc)
* @see projects.admin.ui.AbsPage#isActive()
*/
@Override
public boolean zIsActive() throws HarnessException {
// Look for the Logout button
// check if zimlet + minical loaded
boolean present = sIsElementPresent(Locators.zLogoffPulldown);
if ( !present ) {
logger.debug("Logoff button present = "+ present);
return (false);
}
boolean loaded = zIsZimletLoaded();
if ( !loaded) {
logger.debug("zIsZimletLoaded() = "+ loaded);
return (false);
}
// boolean minical = zIsMinicalLoaded();
// if ( !minical ) {
// logger.debug("zIsMinicalLoaded() = "+ minical);
// return (false);
// }
logger.debug("isActive() = "+ true);
return (true);
}
/* (non-Javadoc)
* @see projects.admin.ui.AbsPage#myPageName()
*/
@Override
public String myPageName() {
return (this.getClass().getName());
}
/* (non-Javadoc)
* @see projects.admin.ui.AbsPage#navigateTo()
*/
@Override
public void zNavigateTo() throws HarnessException {
if ( zIsActive() ) {
// This page is already active
return;
}
// 1. Logout
// 2. Login as the default account
if ( !((AppAjaxClient)MyApplication).zPageLogin.zIsActive() ) {
((AppAjaxClient)MyApplication).zPageLogin.zNavigateTo();
}
((AppAjaxClient)MyApplication).zPageLogin.zLogin(ZimbraAccount.AccountZWC());
zWaitForActive();
}
/**
* Click the logout button
* @throws HarnessException
*/
public void zLogout() throws HarnessException {
logger.debug("logout()");
tracer.trace("Logout of the "+ MyApplication.myApplicationName());
zNavigateTo();
if (ZimbraSeleniumProperties.isWebDriver()) {
// Click on logout pulldown
getElement("css=div[class=DwtLinkButtonDropDownArrow]").click();
}else{
if ( !sIsElementPresent(Locators.zLogoffPulldown) ) {
throw new HarnessException("The logoff button is not present " + Locators.zLogoffPulldown);
}
// Click on logout pulldown
zClickAt(Locators.zLogoffPulldown, "0,0");
}
this.zWaitForBusyOverlay();
if (ZimbraSeleniumProperties.isWebDriver()) {
// Click on logout pulldown
getElement("css=tr[id=POPUP_logOff]>td[id=logOff_title]").click();
}else{
if ( !sIsElementPresent(Locators.zLogoffOption) ) {
throw new HarnessException("The logoff button is not present " + Locators.zLogoffOption);
}
// Click on logout pulldown
zClick(Locators.zLogoffOption);
}
this.zWaitForBusyOverlay();
/* TODO: ... debugging to be removed */
//sWaitForPageToLoad();
((AppAjaxClient)MyApplication).zPageLogin.zWaitForActive();
((AppAjaxClient)MyApplication).zSetActiveAcount(null);
}
@Override
public AbsPage zToolbarPressButton(Button button) throws HarnessException {
logger.info(myPageName() + " zToolbarPressButton(" + button + ")");
// Q. Should the tabs or help or logout be processed here?
// A. I don't think those are considered "toolbars", so don't handle here for now (Matt)
if (button == null)
throw new HarnessException("Button cannot be null!");
// Default behavior variables
//
String locator = null; // If set, this will be clicked
AbsPage page = null; // If set, this page will be returned
if (button == Button.B_REFRESH) {
locator = Locators.ButtonRefreshLocatorCSS;
page = null;
} else {
throw new HarnessException("no logic defined for button " + button);
}
if (locator == null) {
throw new HarnessException("locator was null for button " + button);
}
// Default behavior, process the locator by clicking on it
//
this.zClick(locator);
SleepUtil.sleepSmall();
// If the app is busy, wait for it to become active
this.zWaitForBusyOverlay();
// If page was specified, make sure it is active
if (page != null) {
// This function (default) throws an exception if never active
page.zWaitForActive();
}
return (page);
}
@Override
public AbsPage zToolbarPressPulldown(Button pulldown, Button option) throws HarnessException {
throw new HarnessException("Main page does not have a Toolbar");
}
@Override
public AbsPage zListItem(Action action, String item) throws HarnessException {
throw new HarnessException("Main page does not have lists");
}
@Override
public AbsPage zListItem(Action action, Button option, String item) throws HarnessException {
throw new HarnessException("Main page does not have lists");
}
@Override
public AbsPage zListItem(Action action, Button option, Button subOption ,String item)
throws HarnessException {
throw new HarnessException("Main page does not have lists");
}
/**
* Close any extra compose tabs
*/
public void zCloseComposeTabs() throws HarnessException {
String locator = "css=td[id^='ztb_appChooser_item_'] div[id^='zb__App__tab_COMPOSE']";
if ( sIsElementPresent(locator) ) {
logger.debug("Found compose tabs");
int count = this.sGetCssCount(locator);
for (int i = 1; i <= count; i++) {
final String composeLocator = locator + ":nth-child("+i+") td[id$='_left_icon']";
if ( !sIsElementPresent(composeLocator) )
throw new HarnessException("Unable to find compose tab close icon "+ composeLocator);
this.zClick(composeLocator);
this.zWaitForBusyOverlay();
}
}
}
}
|
gridgentoo/ServiceFabricAzure | src/prod/src/Hosting2/SetupContainerGroupRequest.h | <gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Hosting2
{
class SetupContainerGroupRequest : public Serialization::FabricSerializable
{
public:
SetupContainerGroupRequest();
SetupContainerGroupRequest(
std::wstring const & servicePackageId,
std::wstring const & appId,
std::wstring const & appName,
std::wstring const & appfolder,
std::wstring const & nodeId,
std::wstring const & partitionId,
std::wstring const & servicePackageActivationId,
ServiceModel::NetworkType::Enum networkType,
std::wstring const & openNetworkAssignedIp,
std::map<std::wstring, std::wstring> const & overlayNetworkResources,
std::vector<std::wstring> const & dnsServers,
int64 timeoutTicks,
#if defined(PLATFORM_UNIX)
ContainerPodDescription const & podDesc,
#endif
ServiceModel::ServicePackageResourceGovernanceDescription const & spRg);
__declspec(property(get = get_ServicePackageId)) std::wstring const & ServicePackageId;
std::wstring const & get_ServicePackageId() const { return servicePackageId_; }
__declspec(property(get = get_AppId)) std::wstring const & AppId;
std::wstring const & get_AppId() const { return appId_; }
__declspec(property(get = get_AppName)) std::wstring const & AppName;
std::wstring const & get_AppName() const { return appName_; }
__declspec(property(get = get_NodeId)) std::wstring const & NodeId;
std::wstring const & get_NodeId() const { return nodeId_; }
__declspec(property(get = get_PartitionId)) std::wstring const & PartitionId;
std::wstring const & get_PartitionId() const { return partitionId_; }
__declspec(property(get = get_ServicePackageActivationId)) std::wstring const & ServicePackageActivationId;
std::wstring const & get_ServicePackageActivationId() const { return servicePackageActivationId_; }
__declspec(property(get = get_AppFolder)) std::wstring const & AppFolder;
std::wstring const & get_AppFolder() const { return appfolder_; }
__declspec(property(get = get_NetworkType)) ServiceModel::NetworkType::Enum const & NetworkType;
ServiceModel::NetworkType::Enum const & get_NetworkType() const { return networkType_; }
__declspec(property(get = get_OpenNetworkAssignedIp)) std::wstring const & OpenNetworkAssignedIp;
std::wstring const & get_OpenNetworkAssignedIp() const { return openNetworkAssignedIp_; }
__declspec(property(get = get_OverlayNetworkResources)) std::map<std::wstring, std::wstring> const & OverlayNetworkResources;
std::map<std::wstring, std::wstring> const & get_OverlayNetworkResources() const { return overlayNetworkResources_; }
__declspec(property(get = get_DnsServers)) std::vector<std::wstring> const & DnsServers;
inline std::vector<std::wstring> const & get_DnsServers() const { return dnsServers_; };
__declspec(property(get = get_TimeoutTicks)) int64 TimeoutInTicks;
int64 get_TimeoutTicks() const { return ticks_; }
__declspec(property(get = get_ServicePackageRG)) ServiceModel::ServicePackageResourceGovernanceDescription const & ServicePackageRG;
ServiceModel::ServicePackageResourceGovernanceDescription const & get_ServicePackageRG() const { return spRg_; }
#if defined(PLATFORM_UNIX)
__declspec(property(get = get_PodDescription)) ContainerPodDescription const & PodDescription;
ContainerPodDescription const & get_PodDescription() const { return podDescription_; }
#endif
void WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const;
#if !defined(PLATFORM_UNIX)
FABRIC_FIELDS_14(servicePackageId_, appId_, appfolder_, nodeId_, assignedIp_, ticks_,
spRg_, appName_, partitionId_, servicePackageActivationId_, networkType_,
openNetworkAssignedIp_, overlayNetworkResources_, dnsServers_);
#else
FABRIC_FIELDS_15(servicePackageId_, appId_, appfolder_, nodeId_, assignedIp_, ticks_,
spRg_, podDescription_, appName_, partitionId_, servicePackageActivationId_,
networkType_, openNetworkAssignedIp_, overlayNetworkResources_, dnsServers_);
#endif
private:
std::wstring servicePackageId_;
std::wstring assignedIp_;
ServiceModel::NetworkType::Enum networkType_;
std::wstring openNetworkAssignedIp_;
std::map<std::wstring, std::wstring> overlayNetworkResources_;
std::vector<std::wstring> dnsServers_;
std::wstring appId_;
std::wstring appName_;
std::wstring appfolder_;
std::wstring nodeId_;
std::wstring partitionId_;
std::wstring servicePackageActivationId_;
int64 ticks_;
ServiceModel::ServicePackageResourceGovernanceDescription spRg_;
#if defined(PLATFORM_UNIX)
ContainerPodDescription podDescription_;
#endif
};
} |
chris-kruining/game | js/rasher.js | 'use strict';
import Game from './engine/game.js';
import Scene from './engine/scene.js';
import Entity from './engine/entity.js';
import Sprite from './engine/graphics/elements/sprite.js';
import Background from './engine/graphics/elements/background.js';
import Texture from './engine/graphics/elements/texture.js';
import * as Audio from './engine/audio/exports.js';
import * as UI from './engine/ui/exports.js';
import Animation from './engine/graphics/animation.js';
import Resources from './engine/network/resources.js';
export {
Game, Scene, Entity,
Sprite, Background,
Texture, Audio, UI,
Animation, Resources,
}; |
ddr95070/RMIsaac | engine/engine/gems/math/tests/exponential_moving_average.cpp | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include "engine/gems/math/exponential_moving_average.hpp"
#include <random>
#include "gtest/gtest.h"
#include "engine/gems/math/pose_utils.hpp"
namespace isaac {
namespace math {
TEST(ExponentialMovingAverage, Scalar) {
std::mt19937 rng;
ExponentialMovingAverage<double> ema(2.0);
std::uniform_real_distribution<double> obs_dis(4.0, 6.0);
std::uniform_real_distribution<double> time_dis(0.001, 0.01);
// Initialize with some value (the beginning is expected to be noisy)
double time = 0.0;
while (time < 4.0) {
time += time_dis(rng);
ema.add(obs_dis(rng), time);
}
while (time < 50.0) {
time += time_dis(rng);
EXPECT_NEAR(ema.add(obs_dis(rng), time), 5.0, 0.3);
}
}
TEST(ExponentialMovingAverage, Pose2) {
std::mt19937 rng;
ExponentialMovingAverage<Pose2d> ema(1.0);
std::uniform_real_distribution<double> xy_dist(2.0, 4.0);
std::uniform_real_distribution<double> angle_dist(0.5, 1.5);
std::uniform_real_distribution<double> time_dis(0.001, 0.01);
// Initialize with some value (the beginning is expected to be noisy)
double time = 0.0;
while (time < 4.0) {
time += time_dis(rng);
const Pose2d observation = Pose2d::FromXYA(xy_dist(rng), xy_dist(rng), angle_dist(rng));
ema.add(observation, time);
}
while (time < 50.0) {
time += time_dis(rng);
const Pose2d observation = Pose2d::FromXYA(xy_dist(rng), xy_dist(rng), angle_dist(rng));
const Pose2d smoothed = ema.add(observation, time);
ASSERT_NEAR(smoothed.translation.x(), 3.0, 0.3);
ASSERT_NEAR(smoothed.translation.y(), 3.0, 0.3);
ASSERT_NEAR(smoothed.rotation.angle(), 1.0, 0.2);
}
}
TEST(ExponentialMovingAverage, Pose3) {
std::mt19937 rng;
Vector4d sigma;
sigma[0] = 1.0;
sigma[1] = 1.0;
sigma[2] = 1.0;
sigma[3] = 0.5;
ExponentialMovingAverage<Pose3d> ema(1.0);
std::uniform_real_distribution<double> time_dis(0.001, 0.01);
// Initialize with some value (the beginning is expected to be noisy)
double time = 0.0;
while (time < 4.0) {
time += time_dis(rng);
const Pose3d observation = PoseNormalDistribution(sigma, rng);
ema.add(observation, time);
}
while (time < 50.0) {
time += time_dis(rng);
const Pose3d observation = PoseNormalDistribution(sigma, rng);
const Pose3d smoothed = ema.add(observation, time);
ASSERT_NEAR(smoothed.translation.x(), 0.0, 0.7);
ASSERT_NEAR(smoothed.translation.y(), 0.0, 0.7);
ASSERT_NEAR(smoothed.translation.z(), 0.0, 0.7);
ASSERT_NEAR(smoothed.rotation.angle(), 0.0, 0.35);
}
}
TEST(ExponentialMovingAverageRate, normal_usage) {
std::mt19937 rng;
ExponentialMovingAverageRate<double> ema(2.0);
std::normal_distribution<double> flow_dis(100.0, 10.0);
std::uniform_real_distribution<double> time_dis(0.0, 0.1);
// Initialize with some value (the beginning is expected to be noisy)
double time = 0.0;
while (time < 10.0) {
const double dt = time_dis(rng);
time += dt;
ema.add(flow_dis(rng) * dt, time);
}
while (time < 50.0) {
const double dt = time_dis(rng);
time += dt;
EXPECT_NEAR(ema.add(flow_dis(rng) * dt, time), 100.0, 10.0);
}
while (time < 120.0) {
const double dt = time_dis(rng);
time += dt;
ema.updateTime(time);
}
EXPECT_NEAR(ema.rate(), 0.0, 1e-2);
}
TEST(ExponentialMovingAverageRate, low_frequency) {
std::mt19937 rng;
ExponentialMovingAverageRate<double> ema(2.0);
std::normal_distribution<double> flow_dis(100.0, 5.0);
std::uniform_real_distribution<double> time_dis(0.5, 1.5);
// Initialize with some value (the beginning is expected to be noisy)
double time = 0.0;
while (time < 20.0) {
const double dt = time_dis(rng);
time += dt;
ema.add(flow_dis(rng) * dt, time);
}
while (time < 100.0) {
const double dt = time_dis(rng);
time += dt;
EXPECT_NEAR(ema.add(flow_dis(rng) * dt, time), 100.0, 20.0);
}
while (time < 120.0) {
const double dt = time_dis(rng);
time += dt;
ema.updateTime(time);
}
EXPECT_NEAR(ema.rate(), 0.0, 1e-2);
}
} // namespace math
} // namespace isaac
|
centresource/aws-sdk-for-ruby | spec/aws/sns/topic_subscription_collection_spec.rb | <reponame>centresource/aws-sdk-for-ruby
# Copyright 2011 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.
require 'spec_helper'
module AWS
class SNS
describe TopicSubscriptionCollection do
let(:config) { stub_config }
let(:client) { config.sns_client }
let(:topic_arn) { 'arn:aws:sns:us-east-1:123456789012:topicname' }
let(:topic) { Topic.new(topic_arn, :config => config) }
let(:collection) { described_class.new(topic) }
it_should_behave_like "collection object" do
let(:constructor_args) { [topic] }
let(:client_method) { :list_subscriptions_by_topic }
let(:member_class) { Subscription }
def stub_two_members(resp)
resp.stub(:subscriptions).
and_return([double("sub 1",
:subscription_arn => "arn1",
:endpoint => "e1",
:protocol => "p-1",
:owner => "o1",
:topic_arn => "t1"),
double("sub 2",
:subscription_arn => "arn2",
:endpoint => "e2",
:protocol => "p-2",
:owner => "o2",
:topic_arn => "t2")])
end
it_should_behave_like "paginated collection"
it 'should pass the topic ARN' do
client.should_receive(:list_subscriptions_by_topic).
with(hash_including(:topic_arn => topic_arn))
collection.to_a
end
context 'yielded objects' do
it 'should have the correct arns' do
collection.map(&:arn).should == ["arn1", "arn2"]
end
it 'should have the correct endpoints' do
collection.map(&:endpoint).should == %w(e1 e2)
end
it 'should have the correct protocols' do
collection.map(&:protocol).should == [:p_1, :p_2]
end
it 'should have the correct owner IDs' do
collection.map(&:owner_id).should == %w(o1 o2)
end
it 'should have the correct topic ARNs' do
collection.map { |s| s.topic.arn }.should == %w(t1 t2)
end
it 'should have topics with the correct config' do
collection.each { |s| s.topic.config.should be(config) }
end
end
end
context '#[]' do
it 'should return a subscription object' do
sub = collection["arn"]
sub.should be_a(Subscription)
sub.arn.should == "arn"
sub.config.should be(config)
end
end
context '#initialize' do
it 'should store the topic' do
collection.topic.should be(topic)
end
end
end
end
end
|
popoviciandreea/CTS_Laboratory | Test - 15-05-2021/src/cts/popovici/andreea/AS/pattern/builder/SingleBed.java | <filename>Test - 15-05-2021/src/cts/popovici/andreea/AS/pattern/builder/SingleBed.java
package cts.popovici.andreea.AS.pattern.builder;
public class SingleBed implements BedInterface{
@Override
public void typeOfBed() {
System.out.println("You've got the Single Bed Bedroom!");
}
}
|
sandcast/bayes-scala | src/test/scala/dk/bayes/clustergraph/testutil/test/TennisDBNTest.scala | package dk.bayes.clustergraph.testutil.test
import org.junit._
import Assert._
import dk.bayes.clustergraph.infer.LoopyBP
import dk.bayes.clustergraph.factor.Var
import dk.bayes.clustergraph.factor.Factor
import dk.bayes.clustergraph.testutil.TennisDBN._
import dk.bayes.clustergraph.testutil.AssertUtil._
class TennisDBNTest {
val tennisGraph = createTennisClusterGraph()
val loopyBP = LoopyBP(tennisGraph)
@Test def marginal_for_grade_given_sat_is_high:Unit = {
loopyBP.setEvidence(match1v2Time0Var.id, 0)
loopyBP.setEvidence(match1v2Time1Var.id, 0)
loopyBP.setEvidence(match2v3Time1Var.id, 1)
loopyBP.setEvidence(match1v3Time2Var.id, 1)
loopyBP.setEvidence(match2v3Time2Var.id, 0)
loopyBP.calibrate()
val match1v2Time2Marginal = loopyBP.marginal(match1v2Time2Var.id)
assertFactor(Factor(Var(12, 2), Array(0.5407, 0.4592)), match1v2Time2Marginal, 0.0001)
}
} |
Labs-Weedmaps-Team-2/xelp-FE | src/pages/NotFound/index.js | <reponame>Labs-Weedmaps-Team-2/xelp-FE
import React, { useState } from 'react'
import { Stage, Display, StartButton } from 'components'
import { createStage, checkCollision } from 'utils'
import styled from 'styled-components'
import { usePlayer, useStage, useGameStatus, useInterval } from 'hooks'
import tetris from 'assets/audio/tetris.ogg'
import bgImage from 'assets/img/bg.png'
const audio = new Audio(tetris)
const Tetris = () => {
const [dropTime, setDropTime] = useState(null)
const [isOn, setOn] = useState(false)
const [gameOver, setGameOver] = useState(false)
const [gameAudio, setAudio] = useState(false)
const [isPaused, setPaused] = useState(false)
const [player, updatePlayerPos, resetPlayer, playerRotate] = usePlayer()
const [stage, setStage, rowsCleared] = useStage(player, resetPlayer)
const [score, setScore, rows, setRows, level, setLevel] = useGameStatus(
rowsCleared
)
const handleAudio = () => {
if (!gameAudio) {
audio.play()
setAudio(true)
} else {
audio.pause()
setAudio(false)
}
}
const handlePause = () => {
if (isPaused) {
setDropTime(1000)
handleAudio()
} else {
handleAudio()
setDropTime(null)
}
setPaused(prev => !prev)
}
const startGame = () => {
// reset everything
setStage(createStage())
setDropTime(1000)
setOn(true)
resetPlayer()
setGameOver(false)
setScore(0)
setRows(0)
setLevel(0)
handleAudio()
}
const movePlayer = dir => {
if (isPaused) {
return
}
if (!checkCollision(player, stage, { x: dir, y: 0 })) {
updatePlayerPos({ x: dir, y: 0 })
}
}
const drop = () => {
if (isPaused) {
return
}
// increase level when player has cleared 10 rows
if (rows > (level + 1) * 10) {
setLevel(prev => prev + 1)
// also increase speed
setDropTime(1000 / (level + 1) + 200)
}
if (!checkCollision(player, stage, { x: 0, y: 1 })) {
updatePlayerPos({ x: 0, y: 1, collided: false })
} else {
// game over
if (player.pos.y < 1) {
setGameOver(true)
handleAudio()
setOn(false)
setDropTime(null)
}
updatePlayerPos({ x: 0, y: 0, collided: true })
}
}
const keyUp = ({ keyCode }) => {
if (isPaused) {
return
}
if (!gameOver) {
if (keyCode === 40) {
setDropTime(1000 / (level + 1) + 200)
}
}
}
const dropPlayer = () => {
setDropTime(null)
drop()
}
const move = ({ keyCode }) => {
if (isPaused) {
return
}
if (!gameOver) {
if (keyCode === 37) {
movePlayer(-1)
} else if (keyCode === 39) {
movePlayer(1)
} else if (keyCode === 40) {
dropPlayer()
} else if (keyCode === 38) {
playerRotate(stage, 1)
}
}
}
useInterval(() => {
drop()
}, dropTime)
return (
<StyledTetrisWrapper
role='button'
tabIndex='0'
onKeyDown={move}
onKeyUp={keyUp}
>
<StyledTetris>
<Stage stage={stage} />
<aside>
{gameOver ? (
<Display gameOver={gameOver} text='Game Over' />
) : (
<div>
<Display text={`Score: ${score}`} />
<Display text={`Rows: ${rows}`} />
<Display text={`Level: ${level}`} />
</div>
)}
<StartButton
callback={startGame}
text={isOn ? 'Reset Game' : 'Start Game'}
/>
<StartButton
callback={handlePause}
text={isPaused ? 'Unpause Game' : 'Pause Game'}
/>
</aside>
</StyledTetris>
</StyledTetrisWrapper>
)
}
const StyledTetrisWrapper = styled.div`
width: 100vw;
height: 100vh;
background: url(${bgImage}) #000;
background-size: cover;
overflow: hidden;
`
const StyledTetris = styled.div`
display: flex;
align-items: flex-start;
padding: 40px;
margin: 0 auto;
max-width: 900px;
aside {
width: 100%;
max-width: 200px;
display: block;
padding: 0 20px;
}
`
export default Tetris
|
lechium/tvOS10Headers | System/Library/Frameworks/Metal.framework/MTLLibrary.h | /*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:01:32 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/Frameworks/Metal.framework/Metal
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@class NSString, NSArray;
@protocol MTLLibrary <NSObject>
@property (copy) NSString * label;
@property (readonly) id<MTLDevice> device;
@property (readonly) NSArray * functionNames;
@required
-(void)newFunctionWithName:(id)arg1 constantValues:(id)arg2 completionHandler:(/*^block*/id)arg3;
-(NSString *)label;
-(void)setLabel:(id)arg1;
-(id)newFunctionWithName:(id)arg1;
-(NSArray *)functionNames;
-(id)newFunctionWithName:(id)arg1 constantValues:(id)arg2 error:(id*)arg3;
-(id<MTLDevice>)device;
@end
|
whitefancy/designPatternApplication | commandpattern/prototype/Client.java | <gh_stars>0
package designpattern.commandpattern.prototype;
/**
* 客户负责创建一个ConcreteCommand,并设置其接收者
*/
public class Client {
{
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
}
}
|
theumang100/tutorials-1 | core-python/Core_Python/exception/FileNotFound_Ex.py |
try:
# trying to open a file in read mode
fo = open("foobar.txt","rt")
except FileNotFoundError as e:
print("File not found : ",e) |
bantudb/kv | src/oracle/kv/impl/admin/plan/task/WriteNewSNParams.java | <gh_stars>0
/*-
* Copyright (C) 2011, 2017 Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle NoSQL
* Database made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle NoSQL Database for a copy of the license and
* additional information.
*/
package oracle.kv.impl.admin.plan.task;
import static oracle.kv.impl.param.ParameterState.BOOTSTRAP_MOUNT_POINTS;
import static oracle.kv.impl.param.ParameterState.COMMON_SN_ID;
import oracle.kv.impl.admin.Admin;
import oracle.kv.impl.admin.param.StorageNodeParams;
import oracle.kv.impl.admin.plan.AbstractPlan;
import oracle.kv.impl.param.ParameterMap;
import oracle.kv.impl.security.login.LoginManager;
import oracle.kv.impl.sna.StorageNodeAgentAPI;
import oracle.kv.impl.topo.StorageNodeId;
import oracle.kv.impl.topo.Topology;
import oracle.kv.impl.util.registry.RegistryUtils;
import com.sleepycat.persist.model.Persistent;
import java.util.logging.Level;
/**
* A task for asking a storage node to write a new configuration file.
*
* version 0: original.
* version 1: Changed inheritance chain.
*/
@Persistent(version=1)
public class WriteNewSNParams extends SingleJobTask {
private static final long serialVersionUID = 1L;
private AbstractPlan plan;
private ParameterMap newParams;
private StorageNodeId targetSNId;
public WriteNewSNParams(AbstractPlan plan,
StorageNodeId targetSNId,
ParameterMap newParams) {
super();
this.plan = plan;
this.newParams = newParams;
this.targetSNId = targetSNId;
}
/*
* No-arg ctor for use by DPL.
*/
@SuppressWarnings("unused")
private WriteNewSNParams() {
}
/**
*/
@Override
public State doWork()
throws Exception {
/*
* Store the changed params in the admin db before sending them to the
* SNA. Merge rather than replace in this path. If nothing is changed
* return.
*/
final Admin admin = plan.getAdmin();
final StorageNodeParams snp = admin.getStorageNodeParams(targetSNId);
ParameterMap snMap = snp.getMap();
boolean updateAdminDB = true;
final ParameterMap storageDirMap =
newParams.getName().equals(BOOTSTRAP_MOUNT_POINTS) ? newParams :
null;
if (storageDirMap != null) {
plan.getLogger().log(Level.INFO,
"Changing storage directories for {0}: {1}",
new Object[]{targetSNId, storageDirMap});
/*
* Snid may have been stored, remove it
*/
storageDirMap.remove(COMMON_SN_ID);
snp.setStorageDirMap(storageDirMap);
snMap = null;
} else {
final ParameterMap diff = snMap.diff(newParams, true);
updateAdminDB = snMap.merge(newParams, true) > 0;
plan.getLogger().log(Level.INFO,
"Changing these params for {0}: {1}",
new Object[]{targetSNId, diff});
}
final Topology topology = admin.getCurrentTopology();
final LoginManager loginMgr = admin.getLoginManager();
final RegistryUtils registryUtils =
new RegistryUtils(topology, loginMgr);
final StorageNodeAgentAPI sna =
registryUtils.getStorageNodeAgent(targetSNId);
/* Only one or the other map will be non-null */
final ParameterMap newMap = snMap != null ? snMap : storageDirMap;
if (updateAdminDB) {
try {
/* Check the parameters prior to writing them to the DB. */
sna.checkParameters(newMap, targetSNId);
} catch (UnsupportedOperationException ignore) {
/*
* If UOE, the SN is not yet upgraded to a version that
* supports this check, so just ignore
*/
}
/* Update the admin DB */
admin.updateParams(snp, null);
}
sna.newStorageNodeParameters(newMap);
return State.SUCCEEDED;
}
@Override
public boolean continuePastError() {
return false;
}
@Override
public String toString() {
return super.toString() +
" write new " + targetSNId +
" parameters into the Admin database: " + newParams.showContents();
}
}
|
RuthDevlaeminck/NFVO | common/src/main/java/org/openbaton/nfvo/common/configuration/NfvoGsonDeserializerNFVMessage.java | <filename>common/src/main/java/org/openbaton/nfvo/common/configuration/NfvoGsonDeserializerNFVMessage.java
/*
* Copyright (c) 2016 Open Baton (http://www.openbaton.org)
*
* 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.openbaton.nfvo.common.configuration;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import org.openbaton.catalogue.nfvo.Action;
import org.openbaton.catalogue.nfvo.messages.Interfaces.NFVMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrAllocateResourcesMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrErrorMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrGenericMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrHealedMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrInstantiateMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrLogMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrScaledMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrScalingMessage;
import org.openbaton.catalogue.nfvo.messages.VnfmOrStartStopMessage;
import org.openbaton.catalogue.nfvo.viminstances.BaseVimInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class NfvoGsonDeserializerNFVMessage implements JsonDeserializer<NFVMessage> {
private Gson gson =
new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(BaseVimInstance.class, new NfvoGsonDeserializerVimInstance())
.registerTypeAdapter(BaseVimInstance.class, new NfvoGsonSerializerVimInstance())
.create();
private Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public NFVMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String action = json.getAsJsonObject().get("action").getAsString();
NFVMessage result;
switch (action) {
case "ALLOCATE_RESOURCES":
result = gson.fromJson(json, VnfmOrAllocateResourcesMessage.class);
break;
case "ERROR":
result = gson.fromJson(json, VnfmOrErrorMessage.class);
break;
case "INSTANTIATE":
log.trace("gson is: " + gson);
result = gson.fromJson(json, VnfmOrInstantiateMessage.class);
break;
case "SCALED":
result = gson.fromJson(json, VnfmOrScaledMessage.class);
break;
case "SCALING":
result = gson.fromJson(json, VnfmOrScalingMessage.class);
break;
case "HEAL":
result = gson.fromJson(json, VnfmOrHealedMessage.class);
break;
case "START":
result = gson.fromJson(json, VnfmOrStartStopMessage.class);
break;
case "STOP":
result = gson.fromJson(json, VnfmOrStartStopMessage.class);
break;
case "LOG_REQUEST":
result = gson.fromJson(json, VnfmOrLogMessage.class);
break;
default:
result = gson.fromJson(json, VnfmOrGenericMessage.class);
break;
}
result.setAction(Action.valueOf(action));
log.trace("Deserialized message is " + result);
return result;
}
}
|
jmswen/eden | eden/fs/utils/ProcUtil.cpp | /*
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "eden/fs/utils/ProcUtil.h"
#include <array>
#include <fstream>
#include <vector>
#include <folly/Conv.h>
#include <folly/FileUtil.h>
#include <folly/logging/xlog.h>
#include <folly/portability/Unistd.h>
using folly::StringPiece;
using std::optional;
namespace facebook {
namespace eden {
namespace proc_util {
optional<MemoryStats> readMemoryStats() {
return readStatmFile("/proc/self/statm");
}
optional<MemoryStats> readStatmFile(const char* filename) {
std::string contents;
if (!folly::readFile(filename, contents)) {
return std::nullopt;
}
auto pageSize = sysconf(_SC_PAGESIZE);
if (pageSize == -1) {
return std::nullopt;
}
return parseStatmFile(contents, pageSize);
}
optional<MemoryStats> parseStatmFile(StringPiece data, size_t pageSize) {
std::array<size_t, 7> values;
for (size_t& value : values) {
auto parseResult = folly::parseTo(data, value);
if (parseResult.hasError()) {
return std::nullopt;
}
data = parseResult.value();
}
MemoryStats stats{};
stats.size = pageSize * values[0];
stats.resident = pageSize * values[1];
stats.shared = pageSize * values[2];
stats.text = pageSize * values[3];
// values[4] is always 0 since Linux 2.6
stats.data = pageSize * values[5];
// values[6] is always 0 since Linux 2.6
return stats;
}
std::string& trim(std::string& str, const std::string& delim) {
str.erase(0, str.find_first_not_of(delim));
str.erase(str.find_last_not_of(delim) + 1);
return str;
}
std::pair<std::string, std::string> getKeyValuePair(
const std::string& line,
const std::string& delim) {
std::vector<std::string> v;
std::pair<std::string, std::string> result;
folly::split(delim, line, v);
if (v.size() == 2) {
result.first = trim(v.front());
result.second = trim(v.back());
}
return result;
}
std::vector<std::unordered_map<std::string, std::string>> parseProcSmaps(
std::istream& input) {
std::vector<std::unordered_map<std::string, std::string>> entryList;
bool headerFound{false};
std::unordered_map<std::string, std::string> currentMap;
for (std::string line; getline(input, line);) {
if (line.find("-") != std::string::npos) {
if (!currentMap.empty()) {
entryList.push_back(currentMap);
currentMap.clear();
}
headerFound = true;
} else {
if (!headerFound) {
XLOG(WARN) << "Failed to parse smaps file ";
continue;
}
auto keyValue = getKeyValuePair(line, ":");
if (!keyValue.first.empty()) {
currentMap[keyValue.first] = keyValue.second;
} else {
XLOG(WARN) << "Failed to parse smaps field in smaps file ";
}
}
}
if (!currentMap.empty()) {
entryList.push_back(currentMap);
}
return entryList;
}
std::vector<std::unordered_map<std::string, std::string>> loadProcSmaps() {
return loadProcSmaps(kLinuxProcSmapsPath);
}
std::vector<std::unordered_map<std::string, std::string>> loadProcSmaps(
folly::StringPiece procSmapsPath) {
try {
std::ifstream input(procSmapsPath.data());
return parseProcSmaps(input);
} catch (const std::exception& ex) {
XLOG(WARN) << "Failed to parse memory usage: " << ex.what();
}
return std::vector<std::unordered_map<std::string, std::string>>();
}
std::optional<uint64_t> calculatePrivateBytes(
std::vector<std::unordered_map<std::string, std::string>> smapsListOfMaps) {
uint64_t count{0};
for (auto currentMap : smapsListOfMaps) {
auto iter = currentMap.find("Private_Dirty");
if (iter != currentMap.end()) {
auto& entry = iter->second;
if (entry.rfind(" kB") != std::string::npos) {
auto countString = entry.substr(0, entry.size() - 3);
try {
count += std::stoull(countString) * 1024;
} catch (const std::invalid_argument& ex) {
XLOG(WARN) << "Failed to extract long from /proc/smaps value ''"
<< countString << "' error: " << ex.what();
return std::nullopt;
} catch (const std::out_of_range& ex) {
XLOG(WARN) << "Failed to extract long from proc/status value ''"
<< countString << "' error: " << ex.what();
return std::nullopt;
}
} else {
XLOG(WARN) << "Failed to find Private_Dirty units in: "
<< kLinuxProcSmapsPath;
return std::nullopt;
}
}
}
return count;
}
std::optional<uint64_t> calculatePrivateBytes() {
try {
std::ifstream input(kLinuxProcSmapsPath.data());
return calculatePrivateBytes(parseProcSmaps(input));
} catch (const std::exception& ex) {
XLOG(WARN) << "Failed to parse file " << kLinuxProcSmapsPath << ex.what();
return std::nullopt;
}
}
} // namespace proc_util
} // namespace eden
} // namespace facebook
|
jingcao80/Elastos | Sources/Elastos/Frameworks/Droid/JavaProxy/src/elastos/droid/javaproxy/CIIntentSenderNative.cpp | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/javaproxy/CIIntentSenderNative.h"
#include <elastos/utility/logging/Logger.h>
#include "elastos/droid/javaproxy/Util.h"
using Elastos::Droid::Content::EIID_IIIntentSender;
using Elastos::Droid::Os::EIID_IBinder;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace JavaProxy {
const String CIIntentSenderNative::TAG("CIIntentSenderNative");
CAR_INTERFACE_IMPL_2(CIIntentSenderNative, Object, IIIntentSender, IBinder)
CAR_OBJECT_IMPL(CIIntentSenderNative)
CIIntentSenderNative::~CIIntentSenderNative()
{
JNIEnv* env;
mJVM->AttachCurrentThread(&env, NULL);
env->DeleteGlobalRef(mJInstance);
}
ECode CIIntentSenderNative::constructor(
/* [in] */ Handle64 jVM,
/* [in] */ Handle64 jInstance)
{
mJVM = (JavaVM*)jVM;
mJInstance = (jobject)jInstance;
return NOERROR;
}
ECode CIIntentSenderNative::Send(
/* [in] */ Int32 code,
/* [in] */ IIntent* intent,
/* [in] */ const String& resolvedType,
/* [in] */ IIntentReceiver* finishedReceiver,
/* [in] */ const String& requiredPermission,
/* [out] */ Int32* result)
{
// LOGGERD(TAG, "+ CIIntentSenderNative::Send()");
JNIEnv* env;
mJVM->AttachCurrentThread(&env, NULL);
jobject jintent = NULL;
if (intent != NULL) {
jintent = Util::ToJavaIntent(env, intent);
}
jstring jresolvedType = Util::ToJavaString(env, resolvedType);
jobject jfinishedReceiver = NULL;
if (finishedReceiver != NULL) {
jfinishedReceiver = Util::ToJavaIntentReceiver(env, finishedReceiver);
}
jstring jrequiredPermission = Util::ToJavaString(env, requiredPermission);
jclass c = env->FindClass("android/content/IIntentSender");
Util::CheckErrorAndLog(env, TAG, "Fail FindClass: IIntentSender %d", __LINE__);
jmethodID m = env->GetMethodID(c, "send", "(ILandroid/content/Intent;Ljava/lang/String;Landroid/content/IIntentReceiver;Ljava/lang/String;)I");
Util::CheckErrorAndLog(env, TAG, "GetMethodID: send %d", __LINE__);
*result = env->CallIntMethod(mJInstance, m, (jint)code, jintent, jresolvedType, jfinishedReceiver, jrequiredPermission);
Util::CheckErrorAndLog(env, TAG, "CallVoidMethod: send %d", __LINE__);
env->DeleteLocalRef(c);
if(jintent){
env->DeleteLocalRef(jintent);
}
env->DeleteLocalRef(jresolvedType);
if(jfinishedReceiver){
env->DeleteLocalRef(jfinishedReceiver);
}
env->DeleteLocalRef(jrequiredPermission);
// LOGGERD(TAG, "- CIIntentSenderNative::Send()");
return NOERROR;
}
ECode CIIntentSenderNative::ToString(
/* [out] */ String* str)
{
// LOGGERD(TAG, "+ CIIntentSenderNative::ToString()");
JNIEnv* env;
mJVM->AttachCurrentThread(&env, NULL);
jclass c = env->FindClass("java/lang/Object");
Util::CheckErrorAndLog(env, TAG, "FindClass: Object %d", __LINE__);
jmethodID m = env->GetMethodID(c, "toString", "()Ljava/lang/String;");
Util::CheckErrorAndLog(env, TAG, "GetMethodID: toString %d", __LINE__);
jstring jstr = (jstring)env->CallObjectMethod(mJInstance, m);
Util::CheckErrorAndLog(env, TAG, "CallVoidMethod: toString %d", __LINE__);
*str = Util::GetElString(env, jstr);
env->DeleteLocalRef(c);
env->DeleteLocalRef(jstr);
// LOGGERD(TAG, "- CIIntentSenderNative::ToString()");
return NOERROR;
}
}
}
}
|
rkh/nii | nii-core/lib/nii/parser/fluent.rb | # frozen_string_literal: true
module Nii::Parser
module Fluent
autoload :Arguments, 'nii/parser/fluent/arguments'
autoload :Attribute, 'nii/parser/fluent/attribute'
autoload :Blank, 'nii/parser/fluent/blank'
autoload :Comment, 'nii/parser/fluent/comment'
autoload :Expression, 'nii/parser/fluent/expression'
autoload :Function, 'nii/parser/fluent/function'
autoload :Generic, 'nii/parser/fluent/generic'
autoload :Junk, 'nii/parser/fluent/junk'
autoload :MessageEntry, 'nii/parser/fluent/message_entry'
autoload :Message, 'nii/parser/fluent/message'
autoload :Named, 'nii/parser/fluent/named'
autoload :Number, 'nii/parser/fluent/number'
autoload :Pattern, 'nii/parser/fluent/pattern'
autoload :Placeable, 'nii/parser/fluent/placeable'
autoload :Reference, 'nii/parser/fluent/reference'
autoload :Resource, 'nii/parser/fluent/resource'
autoload :Select, 'nii/parser/fluent/select'
autoload :Scanner, 'nii/parser/fluent/scanner'
autoload :String, 'nii/parser/fluent/string'
autoload :Term, 'nii/parser/fluent/term'
autoload :Text, 'nii/parser/fluent/text'
autoload :Variant, 'nii/parser/fluent/variant'
def self.parse(source, **options)
Scanner.new(source, **options).to_ast
end
def self.[](key)
const_get(key.capitalize)
end
end
end
|
tomra-digital/gopass | pkg/agent/client/client_others.go | // +build !windows
package client
import (
"context"
"os"
"os/exec"
"syscall"
"github.com/justwatchcom/gopass/pkg/out"
"github.com/pkg/errors"
)
func (c *Client) startAgent(ctx context.Context) error {
path, err := os.Executable()
if err != nil {
return errors.Wrapf(err, "unable to determine executable: %s", err)
}
out.Debug(ctx, "Starting agent ...")
cmd := exec.Command(path, "agent")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
return cmd.Start()
}
|
pierredup/sentry | src/sentry/api/serializers/models/organization_access_request.py | from __future__ import absolute_import
import six
from sentry.api.serializers import Serializer, register, serialize
from sentry.models import OrganizationAccessRequest
@register(OrganizationAccessRequest)
class OrganizationAccessRequestSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
"id": six.text_type(obj.id),
"member": serialize(obj.member),
"team": serialize(obj.team),
"requester": serialize(obj.requester),
}
return d
|
dwightspectrum/cms | asset/src/purchase_order/display_details.js | <gh_stars>0
$(document).ready(function(){
(function() {
[].slice.call(document.querySelectorAll('.sttabs')).forEach(function(el) {
new CBPFWTabs(el);
});
})();
get();
$('#search').on('keyup', function(){
get();
});
function get(page = 1){
var search = $('#search').val();
$.ajax({
type: 'POST',
url: CONFIG.BASE_URL + 'purchaseorder/get_technician_list/' + CONFIG.purchase_order_id,
dataType: 'json',
data: {
page : page,
search : search
},
success: function(result){
loadData(result.list);
$('#pagination').html(result.pagination);
setPaginationClicks();
}
});
}
function loadData(list){
if(list.length > 0){
list.forEach(function(obj){
obj.technician_name = obj.employee_last_name.toUpperCase() + ", " + obj.employee_first_name.toUpperCase() + " " + obj.employee_middle_name.toUpperCase();
obj.po_operations_set_as_pm = (obj.po_operations_set_as_pm == 0) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_accomodation_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_accomodation_file = isEmpty(obj.po_operations_accomodation_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_transporation_file = isEmpty(obj.po_operations_transporation_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_transporation_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_airfares_file = isEmpty(obj.po_operations_airfares_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_airfares_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_wifi_file = isEmpty(obj.po_operations_wifi_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_wifi_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_visa_file = isEmpty(obj.po_operations_visa_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_visa_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_bosh_file = isEmpty(obj.po_operations_bosh_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_bosh_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_confined_spaces_file = isEmpty(obj.po_operations_confined_spaces_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_confined_spaces_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_work_at_heights_file = isEmpty(obj.po_operations_work_at_heights_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_work_at_heights_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_nbi_file = isEmpty(obj.po_operations_nbi_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_nbi_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_dfa_file = isEmpty(obj.po_operations_dfa_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_dfa_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_medical_file = isEmpty(obj.po_operations_medical_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_medical_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_drug_test_file = isEmpty(obj.po_operations_drug_test_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_drug_test_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_urinalysis_file = isEmpty(obj.po_operations_urinalysis_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_urinalysis_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_xray_file = isEmpty(obj.po_operations_xray_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_xray_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_fecalysis_file = isEmpty(obj.po_operations_fecalysis_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_fecalysis_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
obj.po_operations_ecg_file = isEmpty(obj.po_operations_ecg_file) ? "<a style='color:#df0000;'><span class='fa fa-times'></span></a>" : "<a href='" + CONFIG.BASE_URL + 'asset/projects/' + obj.po_operations_ecg_file + "' target='_blank' style='color:#7ace4c;'><span class='fa fa-check'></span></a>";
});
$('#technician-lists').loadTemplate($('#technician-list-row-template'), list);
}
else{
$('#technician-lists').html('<tr><td class="text-center" colspan="18">No records found.</td></tr>');
}
}
function setPaginationClicks(){
$('.pagination a[href]').on("click", function(e){
e.preventDefault();
get($(this).attr('data-ci-pagination-page'));
});
}
}); |
shaojiankui/iOS10-Runtime-Headers | protocols/PSSearchIndexOperationDelegate.h | /* Generated by RuntimeBrowser.
*/
@protocol PSSearchIndexOperationDelegate <PSSpecifierObserver>
@required
- (void)searchIndexOperation:(PSSearchIndexOperation *)arg1 didFindSpecifierDataSource:(id <PSSpecifierDataSource>)arg2;
- (void)searchIndexOperationDidFinish:(PSSearchIndexOperation *)arg1 searchEntries:(NSArray *)arg2;
@optional
- (void)searchIndexOperationDidCancel:(PSSearchIndexOperation *)arg1;
@end
|
joyrun/ActivityRouter | grouter/src/test/java/com/grouter/hybrid/GRouterJavascriptInterfaceTest.java | package com.grouter.hybrid;
import android.net.Uri;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
public class GRouterJavascriptInterfaceTest {
@Test
public void getTask() {
}
@Test
public void startPage() {
}
@Test
public void addAccessDomain() {
List<String> accessDomains = new ArrayList<>();
accessDomains.add("*.grouter.com");
String currentUrl = "https://wap.grouter.com";
if (currentUrl == null || currentUrl.length() == 0) {
System.out.println("匹配失败");
return ;
}
try {
Uri uri = Uri.parse(currentUrl);
String host = uri.getHost();
for (String reg : accessDomains) {
if (host.equals(reg)) {
System.out.println("匹配成功");
return ;
}
if (reg.startsWith("*") && currentUrl.contains(reg.substring(2))) {
System.out.println("匹配成功");
return ;
}
}
}catch (Exception e){
e.printStackTrace();
}
System.out.println("匹配失败");
return ;
}
} |
xiaoashuo/relaxed | relaxed-starters/relaxed-spring-boot-starter-oss/relaxed-spring-boot-starter-s3/src/main/java/com/relaxed/common/oss/s3/OssClient.java | <filename>relaxed-starters/relaxed-spring-boot-starter-oss/relaxed-spring-boot-starter-s3/src/main/java/com/relaxed/common/oss/s3/OssClient.java
package com.relaxed.common.oss.s3;
import com.relaxed.common.oss.s3.exception.OssException;
import com.relaxed.common.oss.s3.modifier.PathModifier;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.utils.IoUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author Yakir
* @Topic OssClient
* @Description
* @date 2021/11/25 17:49
* @Version 1.0
*/
@Slf4j
@Setter
public class OssClient implements DisposableBean {
private final String endpoint;
private final String region;
private final String accessKey;
private final String accessSecret;
private final String bucket;
private final String domain;
private final boolean pathStyleAccess;
private final String downloadPrefix;
private final ObjectCannedACL acl;
private final PathModifier pathModifier;
private final S3Client s3Client;
public OssClient(OssClientBuilder ossClientBuilder) {
// 同步OssClientBuilder信息
this.endpoint = ossClientBuilder.getEndpoint();
this.region = ossClientBuilder.getRegion();
this.accessKey = ossClientBuilder.getAccessKey();
this.accessSecret = ossClientBuilder.getAccessSecret();
this.bucket = ossClientBuilder.getBucket();
this.domain = ossClientBuilder.getDomain();
this.pathStyleAccess = ossClientBuilder.getPathStyleAccess();
this.downloadPrefix = ossClientBuilder.getProxyUrl();
this.acl = ossClientBuilder.getAcl();
this.pathModifier = ossClientBuilder.getPathModifier();
this.s3Client = ossClientBuilder.getS3Client();
}
public String upload(InputStream inputStream, Long size, String relativePath) {
return upload(inputStream, size, relativePath, acl);
}
/**
* 上传文件
* @author yakir
* @date 2021/11/26 15:34
* @param inputStream 输入流
* @param size 流大小
* @param relativePath 文件路径 未关联根路径的
* @return java.lang.String
*/
public String upload(InputStream inputStream, Long size, String relativePath, ObjectCannedACL acl) {
PutObjectRequest.Builder builder = PutObjectRequest.builder().bucket(bucket).key(relativePath);
if (acl != null) {
builder.acl(acl);
}
// 返回eTag
getS3Client().putObject(builder.build(), RequestBody.fromInputStream(inputStream, size));
return getDownloadUrl(relativePath);
}
public List<String> list(String prefix) {
return list(prefix, null, null);
}
/**
* 查询列表
* @author yakir
* @date 2021/12/1 18:19
* @param prefix 前缀匹配 oss 里面 文件物理层路径默认都为字符串 不存在目录
* @param marker
* @param maxKeys
*/
public List<String> list(String prefix, String marker, Integer maxKeys) {
ListObjectsRequest listObjects = ListObjectsRequest.builder().bucket(bucket).prefix(prefix).marker(marker)
.maxKeys(maxKeys).build();
ListObjectsResponse res = getS3Client().listObjects(listObjects);
List<S3Object> contents = res.contents();
List<String> paths = new ArrayList<>();
for (S3Object content : contents) {
String key = content.key();
String downloadUrl = getDownloadUrl(key);
paths.add(downloadUrl);
}
return paths;
}
/**
* 下载字节文件
* @author yakir
* @date 2022/1/14 13:03
* @param relativePath 相对路径 test/img.png
* @return byte[]
*/
public byte[] download(String relativePath) {
try {
GetObjectRequest getObjectRequest = GetObjectRequest.builder().bucket(bucket).key(relativePath).build();
try (ResponseInputStream<GetObjectResponse> responseInputStream = s3Client.getObject(getObjectRequest)) {
return IoUtils.toByteArray(responseInputStream);
}
}
catch (IOException e) {
throw new OssException("download file error bucket:" + this.bucket + "path:" + relativePath, e);
}
}
/**
* 删除单个文件
* @author yakir
* @date 2021/12/1 18:19
* @param path
*/
public void delete(String path) {
if (!StringUtils.hasText(path)) {
return;
}
getS3Client().deleteObject(builder -> builder.bucket(bucket).key(path));
}
/**
* 批量删除
* @author yakir
* @date 2021/12/2 13:58
* @param paths 相对于bucket命名空间下的完整路径
* <p>
* eg: bucket test-oss 文件 img/test.jpg path: img/test.jpg
* </p>
* @param paths
*/
public void batchDelete(Set<String> paths) {
if (CollectionUtils.isEmpty(paths)) {
return;
}
ArrayList<ObjectIdentifier> keys = new ArrayList<>();
for (String path : paths) {
ObjectIdentifier objectId = ObjectIdentifier.builder().key(path).build();
keys.add(objectId);
}
// Delete multiple objects in one request.
Delete del = Delete.builder().objects(keys).build();
DeleteObjectsRequest multiObjectDeleteRequest = DeleteObjectsRequest.builder()
// 指定命名空间
.bucket(bucket).delete(del).build();
getS3Client().deleteObjects(multiObjectDeleteRequest);
}
/**
* copy 对象
* @author yakir
* @date 2021/12/3 15:53
* @param sourcePath img/6.jpg 相对于bucket下面的路径
* @param toPath img/5.jpg 相对于bucket下面的路径
* @return java.lang.String 目标下载地址
*/
public String copy(String sourcePath, String toPath) {
CopyObjectRequest copyObjRequest = CopyObjectRequest.builder()
// 此处一定要指定原始命名空间
.sourceBucket(bucket).sourceKey(sourcePath).destinationBucket(bucket).destinationKey(toPath).build();
getS3Client().copyObject(copyObjRequest);
return getDownloadUrl(toPath);
}
/**
* 获取 绝对路径 的下载url
* @author lingting 2021-05-12 18:50
*/
public String getDownloadUrl(String relativePath) {
return pathModifier.getDownloadUrl(domain, bucket, downloadPrefix, relativePath);
}
public S3Client getS3Client() {
return s3Client;
}
@Override
public void destroy() throws Exception {
if (s3Client != null) {
s3Client.close();
}
}
}
|
evertrue/Singularity | SingularityBase/src/main/java/com/hubspot/singularity/WebhookType.java | package com.hubspot.singularity;
public enum WebhookType {
TASK, REQUEST, DEPLOY;
}
|
VersiraSec/epsilon-cfw | ion/src/device/n0100/shared/regs/config/flash.h | #ifndef ION_DEVICE_N0100_SHARED_REGS_CONFIG_FLASH_H
#define ION_DEVICE_N0100_SHARED_REGS_CONFIG_FLASH_H
#define REGS_FLASH_CONFIG_ART 0
#define REGS_FLASH_CONFIG_OPTCR1 0
#endif
|
inOmOney/NQ-SERVER | src/main/java/top/theanything/web/controller/url/ShortUrlController.java | <reponame>inOmOney/NQ-SERVER
package top.theanything.web.controller.url;
import top.theanything.core.anno.Controller;
import top.theanything.core.anno.RequestMapping;
import top.theanything.config.BasicConfig;
import top.theanything.core.action.AbstractAction;
import top.theanything.core.error.ShortPathNotFoundException;
import top.theanything.core.http.Request;
import top.theanything.core.http.Response;
import top.theanything.web.service.ShortUrlService;
import java.io.IOException;
/**
* @author zhou
* @Description
* @createTime 2020-05-21
*/
@Controller
public class ShortUrlController extends AbstractAction {
private static ShortUrlService service = null;
static {
service = new ShortUrlService();
}
@RequestMapping(value = "/shortUrl")
public void shortUrl(Request request , Response response) throws IOException {
response.sendFile(response.PREFIX_PATH + BasicConfig.shortUrlPath);
return;
}
/**
* 生成短链接
* @param req
* @param response
* @return
*/
@RequestMapping(value = "/getUrl") // Http请求默认设置为GET
public String generatorUrl(Request req , Response response){
String url = (String) req.getParams().get("shortUrl");
String shortUrl = service.genShortUrl(url);
return shortUrl;
}
/**
* 从短链接跳转到长链接网页
* @param request
* @param response
* @return
* @throws ShortPathNotFoundException 没有该短链接
*/
@RequestMapping(value = "/s") // Http请求默认设置为GET
public String redirectReal(Request request , Response response) throws ShortPathNotFoundException {
String KeyID = (String) request.getParams().get("p");
String realPath ;
if( (realPath = service.getRealPath(KeyID) ) == null){
throw new ShortPathNotFoundException();
}
return "redirect:"+realPath;
}
}
|
mallrat208/UnWIRED | src/main/java/com/mr208/unwired/libs/FieldsLib.java | package com.mr208.unwired.libs;
public class FieldsLib
{
public static final int FIELD_COUNT = 6;
public static final int ENERGY_LOWER = 0;
public static final int ENERGY_UPPER = 1;
public static final int ENERGY_MAX_LOWER = 2;
public static final int ENERGY_MAX_UPPER = 3;
public static final int PROGRESS = 4;
public static final int PROGRESS_MAX = 5;
}
|
RedRock-2017-Summer/freshmanspecial | app/src/main/java/com/mredrock/freshmanspecial/CQUPTElegant/Interface/IOrganizationFrg.java | package com.mredrock.freshmanspecial.CQUPTElegant.Interface;
import android.support.v4.app.FragmentManager;
/**
* Created by Anriku on 2017/8/10.
*/
public interface IOrganizationFrg {
FragmentManager getTheFragmentManager();
}
|
CiscoDevNet/ydk-cpp | cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_IP_URPF_MIB.cpp | <reponame>CiscoDevNet/ydk-cpp
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "CISCO_IP_URPF_MIB.hpp"
using namespace ydk;
namespace cisco_ios_xe {
namespace CISCO_IP_URPF_MIB {
CISCOIPURPFMIB::CISCOIPURPFMIB()
:
cipurpfscalar(std::make_shared<CISCOIPURPFMIB::CipUrpfScalar>())
, cipurpftable(std::make_shared<CISCOIPURPFMIB::CipUrpfTable>())
, cipurpfifmontable(std::make_shared<CISCOIPURPFMIB::CipUrpfIfMonTable>())
, cipurpfvrfiftable(std::make_shared<CISCOIPURPFMIB::CipUrpfVrfIfTable>())
, cipurpfvrftable(std::make_shared<CISCOIPURPFMIB::CipUrpfVrfTable>())
{
cipurpfscalar->parent = this;
cipurpftable->parent = this;
cipurpfifmontable->parent = this;
cipurpfvrfiftable->parent = this;
cipurpfvrftable->parent = this;
yang_name = "CISCO-IP-URPF-MIB"; yang_parent_name = "CISCO-IP-URPF-MIB"; is_top_level_class = true; has_list_ancestor = false;
}
CISCOIPURPFMIB::~CISCOIPURPFMIB()
{
}
bool CISCOIPURPFMIB::has_data() const
{
if (is_presence_container) return true;
return (cipurpfscalar != nullptr && cipurpfscalar->has_data())
|| (cipurpftable != nullptr && cipurpftable->has_data())
|| (cipurpfifmontable != nullptr && cipurpfifmontable->has_data())
|| (cipurpfvrfiftable != nullptr && cipurpfvrfiftable->has_data())
|| (cipurpfvrftable != nullptr && cipurpfvrftable->has_data());
}
bool CISCOIPURPFMIB::has_operation() const
{
return is_set(yfilter)
|| (cipurpfscalar != nullptr && cipurpfscalar->has_operation())
|| (cipurpftable != nullptr && cipurpftable->has_operation())
|| (cipurpfifmontable != nullptr && cipurpfifmontable->has_operation())
|| (cipurpfvrfiftable != nullptr && cipurpfvrfiftable->has_operation())
|| (cipurpfvrftable != nullptr && cipurpfvrftable->has_operation());
}
std::string CISCOIPURPFMIB::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cipUrpfScalar")
{
if(cipurpfscalar == nullptr)
{
cipurpfscalar = std::make_shared<CISCOIPURPFMIB::CipUrpfScalar>();
}
return cipurpfscalar;
}
if(child_yang_name == "cipUrpfTable")
{
if(cipurpftable == nullptr)
{
cipurpftable = std::make_shared<CISCOIPURPFMIB::CipUrpfTable>();
}
return cipurpftable;
}
if(child_yang_name == "cipUrpfIfMonTable")
{
if(cipurpfifmontable == nullptr)
{
cipurpfifmontable = std::make_shared<CISCOIPURPFMIB::CipUrpfIfMonTable>();
}
return cipurpfifmontable;
}
if(child_yang_name == "cipUrpfVrfIfTable")
{
if(cipurpfvrfiftable == nullptr)
{
cipurpfvrfiftable = std::make_shared<CISCOIPURPFMIB::CipUrpfVrfIfTable>();
}
return cipurpfvrfiftable;
}
if(child_yang_name == "cipUrpfVrfTable")
{
if(cipurpfvrftable == nullptr)
{
cipurpfvrftable = std::make_shared<CISCOIPURPFMIB::CipUrpfVrfTable>();
}
return cipurpfvrftable;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(cipurpfscalar != nullptr)
{
_children["cipUrpfScalar"] = cipurpfscalar;
}
if(cipurpftable != nullptr)
{
_children["cipUrpfTable"] = cipurpftable;
}
if(cipurpfifmontable != nullptr)
{
_children["cipUrpfIfMonTable"] = cipurpfifmontable;
}
if(cipurpfvrfiftable != nullptr)
{
_children["cipUrpfVrfIfTable"] = cipurpfvrfiftable;
}
if(cipurpfvrftable != nullptr)
{
_children["cipUrpfVrfTable"] = cipurpfvrftable;
}
return _children;
}
void CISCOIPURPFMIB::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void CISCOIPURPFMIB::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::clone_ptr() const
{
return std::make_shared<CISCOIPURPFMIB>();
}
std::string CISCOIPURPFMIB::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xe_models_path;
}
std::string CISCOIPURPFMIB::get_bundle_name() const
{
return "cisco_ios_xe";
}
augment_capabilities_function CISCOIPURPFMIB::get_augment_capabilities_function() const
{
return cisco_ios_xe_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> CISCOIPURPFMIB::get_namespace_identity_lookup() const
{
return cisco_ios_xe_namespace_identity_lookup;
}
bool CISCOIPURPFMIB::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfScalar" || name == "cipUrpfTable" || name == "cipUrpfIfMonTable" || name == "cipUrpfVrfIfTable" || name == "cipUrpfVrfTable")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfScalar::CipUrpfScalar()
:
cipurpfdropratewindow{YType::int32, "cipUrpfDropRateWindow"},
cipurpfcomputeinterval{YType::int32, "cipUrpfComputeInterval"},
cipurpfdropnotifyholddowntime{YType::int32, "cipUrpfDropNotifyHoldDownTime"}
{
yang_name = "cipUrpfScalar"; yang_parent_name = "CISCO-IP-URPF-MIB"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfScalar::~CipUrpfScalar()
{
}
bool CISCOIPURPFMIB::CipUrpfScalar::has_data() const
{
if (is_presence_container) return true;
return cipurpfdropratewindow.is_set
|| cipurpfcomputeinterval.is_set
|| cipurpfdropnotifyholddowntime.is_set;
}
bool CISCOIPURPFMIB::CipUrpfScalar::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cipurpfdropratewindow.yfilter)
|| ydk::is_set(cipurpfcomputeinterval.yfilter)
|| ydk::is_set(cipurpfdropnotifyholddowntime.yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfScalar::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfScalar::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfScalar";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfScalar::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cipurpfdropratewindow.is_set || is_set(cipurpfdropratewindow.yfilter)) leaf_name_data.push_back(cipurpfdropratewindow.get_name_leafdata());
if (cipurpfcomputeinterval.is_set || is_set(cipurpfcomputeinterval.yfilter)) leaf_name_data.push_back(cipurpfcomputeinterval.get_name_leafdata());
if (cipurpfdropnotifyholddowntime.is_set || is_set(cipurpfdropnotifyholddowntime.yfilter)) leaf_name_data.push_back(cipurpfdropnotifyholddowntime.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfScalar::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfScalar::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void CISCOIPURPFMIB::CipUrpfScalar::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cipUrpfDropRateWindow")
{
cipurpfdropratewindow = value;
cipurpfdropratewindow.value_namespace = name_space;
cipurpfdropratewindow.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfComputeInterval")
{
cipurpfcomputeinterval = value;
cipurpfcomputeinterval.value_namespace = name_space;
cipurpfcomputeinterval.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfDropNotifyHoldDownTime")
{
cipurpfdropnotifyholddowntime = value;
cipurpfdropnotifyholddowntime.value_namespace = name_space;
cipurpfdropnotifyholddowntime.value_namespace_prefix = name_space_prefix;
}
}
void CISCOIPURPFMIB::CipUrpfScalar::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cipUrpfDropRateWindow")
{
cipurpfdropratewindow.yfilter = yfilter;
}
if(value_path == "cipUrpfComputeInterval")
{
cipurpfcomputeinterval.yfilter = yfilter;
}
if(value_path == "cipUrpfDropNotifyHoldDownTime")
{
cipurpfdropnotifyholddowntime.yfilter = yfilter;
}
}
bool CISCOIPURPFMIB::CipUrpfScalar::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfDropRateWindow" || name == "cipUrpfComputeInterval" || name == "cipUrpfDropNotifyHoldDownTime")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfTable::CipUrpfTable()
:
cipurpfentry(this, {"cipurpfipversion"})
{
yang_name = "cipUrpfTable"; yang_parent_name = "CISCO-IP-URPF-MIB"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfTable::~CipUrpfTable()
{
}
bool CISCOIPURPFMIB::CipUrpfTable::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<cipurpfentry.len(); index++)
{
if(cipurpfentry[index]->has_data())
return true;
}
return false;
}
bool CISCOIPURPFMIB::CipUrpfTable::has_operation() const
{
for (std::size_t index=0; index<cipurpfentry.len(); index++)
{
if(cipurpfentry[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfTable::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfTable::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfTable";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfTable::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cipUrpfEntry")
{
auto ent_ = std::make_shared<CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry>();
ent_->parent = this;
cipurpfentry.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfTable::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : cipurpfentry.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void CISCOIPURPFMIB::CipUrpfTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void CISCOIPURPFMIB::CipUrpfTable::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool CISCOIPURPFMIB::CipUrpfTable::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfEntry")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::CipUrpfEntry()
:
cipurpfipversion{YType::enumeration, "cipUrpfIpVersion"},
cipurpfdrops{YType::uint32, "cipUrpfDrops"},
cipurpfdroprate{YType::uint32, "cipUrpfDropRate"}
{
yang_name = "cipUrpfEntry"; yang_parent_name = "cipUrpfTable"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::~CipUrpfEntry()
{
}
bool CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::has_data() const
{
if (is_presence_container) return true;
return cipurpfipversion.is_set
|| cipurpfdrops.is_set
|| cipurpfdroprate.is_set;
}
bool CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cipurpfipversion.yfilter)
|| ydk::is_set(cipurpfdrops.yfilter)
|| ydk::is_set(cipurpfdroprate.yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/cipUrpfTable/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfEntry";
ADD_KEY_TOKEN(cipurpfipversion, "cipUrpfIpVersion");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cipurpfipversion.is_set || is_set(cipurpfipversion.yfilter)) leaf_name_data.push_back(cipurpfipversion.get_name_leafdata());
if (cipurpfdrops.is_set || is_set(cipurpfdrops.yfilter)) leaf_name_data.push_back(cipurpfdrops.get_name_leafdata());
if (cipurpfdroprate.is_set || is_set(cipurpfdroprate.yfilter)) leaf_name_data.push_back(cipurpfdroprate.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cipUrpfIpVersion")
{
cipurpfipversion = value;
cipurpfipversion.value_namespace = name_space;
cipurpfipversion.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfDrops")
{
cipurpfdrops = value;
cipurpfdrops.value_namespace = name_space;
cipurpfdrops.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfDropRate")
{
cipurpfdroprate = value;
cipurpfdroprate.value_namespace = name_space;
cipurpfdroprate.value_namespace_prefix = name_space_prefix;
}
}
void CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cipUrpfIpVersion")
{
cipurpfipversion.yfilter = yfilter;
}
if(value_path == "cipUrpfDrops")
{
cipurpfdrops.yfilter = yfilter;
}
if(value_path == "cipUrpfDropRate")
{
cipurpfdroprate.yfilter = yfilter;
}
}
bool CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfIpVersion" || name == "cipUrpfDrops" || name == "cipUrpfDropRate")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonTable()
:
cipurpfifmonentry(this, {"ifindex", "cipurpfifipversion"})
{
yang_name = "cipUrpfIfMonTable"; yang_parent_name = "CISCO-IP-URPF-MIB"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfIfMonTable::~CipUrpfIfMonTable()
{
}
bool CISCOIPURPFMIB::CipUrpfIfMonTable::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<cipurpfifmonentry.len(); index++)
{
if(cipurpfifmonentry[index]->has_data())
return true;
}
return false;
}
bool CISCOIPURPFMIB::CipUrpfIfMonTable::has_operation() const
{
for (std::size_t index=0; index<cipurpfifmonentry.len(); index++)
{
if(cipurpfifmonentry[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfIfMonTable::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfIfMonTable::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfIfMonTable";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfIfMonTable::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfIfMonTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cipUrpfIfMonEntry")
{
auto ent_ = std::make_shared<CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry>();
ent_->parent = this;
cipurpfifmonentry.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfIfMonTable::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : cipurpfifmonentry.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void CISCOIPURPFMIB::CipUrpfIfMonTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void CISCOIPURPFMIB::CipUrpfIfMonTable::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool CISCOIPURPFMIB::CipUrpfIfMonTable::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfIfMonEntry")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::CipUrpfIfMonEntry()
:
ifindex{YType::str, "ifIndex"},
cipurpfifipversion{YType::enumeration, "cipUrpfIfIpVersion"},
cipurpfifdrops{YType::uint32, "cipUrpfIfDrops"},
cipurpfifsuppresseddrops{YType::uint32, "cipUrpfIfSuppressedDrops"},
cipurpfifdroprate{YType::uint32, "cipUrpfIfDropRate"},
cipurpfifdiscontinuitytime{YType::uint32, "cipUrpfIfDiscontinuityTime"},
cipurpfifdropratenotifyenable{YType::boolean, "cipUrpfIfDropRateNotifyEnable"},
cipurpfifnotifydropratethreshold{YType::uint32, "cipUrpfIfNotifyDropRateThreshold"},
cipurpfifnotifydrholddownreset{YType::boolean, "cipUrpfIfNotifyDrHoldDownReset"},
cipurpfifcheckstrict{YType::enumeration, "cipUrpfIfCheckStrict"},
cipurpfifwhichroutetableid{YType::enumeration, "cipUrpfIfWhichRouteTableID"},
cipurpfifvrfname{YType::str, "cipUrpfIfVrfName"}
{
yang_name = "cipUrpfIfMonEntry"; yang_parent_name = "cipUrpfIfMonTable"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::~CipUrpfIfMonEntry()
{
}
bool CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::has_data() const
{
if (is_presence_container) return true;
return ifindex.is_set
|| cipurpfifipversion.is_set
|| cipurpfifdrops.is_set
|| cipurpfifsuppresseddrops.is_set
|| cipurpfifdroprate.is_set
|| cipurpfifdiscontinuitytime.is_set
|| cipurpfifdropratenotifyenable.is_set
|| cipurpfifnotifydropratethreshold.is_set
|| cipurpfifnotifydrholddownreset.is_set
|| cipurpfifcheckstrict.is_set
|| cipurpfifwhichroutetableid.is_set
|| cipurpfifvrfname.is_set;
}
bool CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(ifindex.yfilter)
|| ydk::is_set(cipurpfifipversion.yfilter)
|| ydk::is_set(cipurpfifdrops.yfilter)
|| ydk::is_set(cipurpfifsuppresseddrops.yfilter)
|| ydk::is_set(cipurpfifdroprate.yfilter)
|| ydk::is_set(cipurpfifdiscontinuitytime.yfilter)
|| ydk::is_set(cipurpfifdropratenotifyenable.yfilter)
|| ydk::is_set(cipurpfifnotifydropratethreshold.yfilter)
|| ydk::is_set(cipurpfifnotifydrholddownreset.yfilter)
|| ydk::is_set(cipurpfifcheckstrict.yfilter)
|| ydk::is_set(cipurpfifwhichroutetableid.yfilter)
|| ydk::is_set(cipurpfifvrfname.yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/cipUrpfIfMonTable/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfIfMonEntry";
ADD_KEY_TOKEN(ifindex, "ifIndex");
ADD_KEY_TOKEN(cipurpfifipversion, "cipUrpfIfIpVersion");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata());
if (cipurpfifipversion.is_set || is_set(cipurpfifipversion.yfilter)) leaf_name_data.push_back(cipurpfifipversion.get_name_leafdata());
if (cipurpfifdrops.is_set || is_set(cipurpfifdrops.yfilter)) leaf_name_data.push_back(cipurpfifdrops.get_name_leafdata());
if (cipurpfifsuppresseddrops.is_set || is_set(cipurpfifsuppresseddrops.yfilter)) leaf_name_data.push_back(cipurpfifsuppresseddrops.get_name_leafdata());
if (cipurpfifdroprate.is_set || is_set(cipurpfifdroprate.yfilter)) leaf_name_data.push_back(cipurpfifdroprate.get_name_leafdata());
if (cipurpfifdiscontinuitytime.is_set || is_set(cipurpfifdiscontinuitytime.yfilter)) leaf_name_data.push_back(cipurpfifdiscontinuitytime.get_name_leafdata());
if (cipurpfifdropratenotifyenable.is_set || is_set(cipurpfifdropratenotifyenable.yfilter)) leaf_name_data.push_back(cipurpfifdropratenotifyenable.get_name_leafdata());
if (cipurpfifnotifydropratethreshold.is_set || is_set(cipurpfifnotifydropratethreshold.yfilter)) leaf_name_data.push_back(cipurpfifnotifydropratethreshold.get_name_leafdata());
if (cipurpfifnotifydrholddownreset.is_set || is_set(cipurpfifnotifydrholddownreset.yfilter)) leaf_name_data.push_back(cipurpfifnotifydrholddownreset.get_name_leafdata());
if (cipurpfifcheckstrict.is_set || is_set(cipurpfifcheckstrict.yfilter)) leaf_name_data.push_back(cipurpfifcheckstrict.get_name_leafdata());
if (cipurpfifwhichroutetableid.is_set || is_set(cipurpfifwhichroutetableid.yfilter)) leaf_name_data.push_back(cipurpfifwhichroutetableid.get_name_leafdata());
if (cipurpfifvrfname.is_set || is_set(cipurpfifvrfname.yfilter)) leaf_name_data.push_back(cipurpfifvrfname.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "ifIndex")
{
ifindex = value;
ifindex.value_namespace = name_space;
ifindex.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfIpVersion")
{
cipurpfifipversion = value;
cipurpfifipversion.value_namespace = name_space;
cipurpfifipversion.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfDrops")
{
cipurpfifdrops = value;
cipurpfifdrops.value_namespace = name_space;
cipurpfifdrops.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfSuppressedDrops")
{
cipurpfifsuppresseddrops = value;
cipurpfifsuppresseddrops.value_namespace = name_space;
cipurpfifsuppresseddrops.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfDropRate")
{
cipurpfifdroprate = value;
cipurpfifdroprate.value_namespace = name_space;
cipurpfifdroprate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfDiscontinuityTime")
{
cipurpfifdiscontinuitytime = value;
cipurpfifdiscontinuitytime.value_namespace = name_space;
cipurpfifdiscontinuitytime.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfDropRateNotifyEnable")
{
cipurpfifdropratenotifyenable = value;
cipurpfifdropratenotifyenable.value_namespace = name_space;
cipurpfifdropratenotifyenable.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfNotifyDropRateThreshold")
{
cipurpfifnotifydropratethreshold = value;
cipurpfifnotifydropratethreshold.value_namespace = name_space;
cipurpfifnotifydropratethreshold.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfNotifyDrHoldDownReset")
{
cipurpfifnotifydrholddownreset = value;
cipurpfifnotifydrholddownreset.value_namespace = name_space;
cipurpfifnotifydrholddownreset.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfCheckStrict")
{
cipurpfifcheckstrict = value;
cipurpfifcheckstrict.value_namespace = name_space;
cipurpfifcheckstrict.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfWhichRouteTableID")
{
cipurpfifwhichroutetableid = value;
cipurpfifwhichroutetableid.value_namespace = name_space;
cipurpfifwhichroutetableid.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfIfVrfName")
{
cipurpfifvrfname = value;
cipurpfifvrfname.value_namespace = name_space;
cipurpfifvrfname.value_namespace_prefix = name_space_prefix;
}
}
void CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "ifIndex")
{
ifindex.yfilter = yfilter;
}
if(value_path == "cipUrpfIfIpVersion")
{
cipurpfifipversion.yfilter = yfilter;
}
if(value_path == "cipUrpfIfDrops")
{
cipurpfifdrops.yfilter = yfilter;
}
if(value_path == "cipUrpfIfSuppressedDrops")
{
cipurpfifsuppresseddrops.yfilter = yfilter;
}
if(value_path == "cipUrpfIfDropRate")
{
cipurpfifdroprate.yfilter = yfilter;
}
if(value_path == "cipUrpfIfDiscontinuityTime")
{
cipurpfifdiscontinuitytime.yfilter = yfilter;
}
if(value_path == "cipUrpfIfDropRateNotifyEnable")
{
cipurpfifdropratenotifyenable.yfilter = yfilter;
}
if(value_path == "cipUrpfIfNotifyDropRateThreshold")
{
cipurpfifnotifydropratethreshold.yfilter = yfilter;
}
if(value_path == "cipUrpfIfNotifyDrHoldDownReset")
{
cipurpfifnotifydrholddownreset.yfilter = yfilter;
}
if(value_path == "cipUrpfIfCheckStrict")
{
cipurpfifcheckstrict.yfilter = yfilter;
}
if(value_path == "cipUrpfIfWhichRouteTableID")
{
cipurpfifwhichroutetableid.yfilter = yfilter;
}
if(value_path == "cipUrpfIfVrfName")
{
cipurpfifvrfname.yfilter = yfilter;
}
}
bool CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ifIndex" || name == "cipUrpfIfIpVersion" || name == "cipUrpfIfDrops" || name == "cipUrpfIfSuppressedDrops" || name == "cipUrpfIfDropRate" || name == "cipUrpfIfDiscontinuityTime" || name == "cipUrpfIfDropRateNotifyEnable" || name == "cipUrpfIfNotifyDropRateThreshold" || name == "cipUrpfIfNotifyDrHoldDownReset" || name == "cipUrpfIfCheckStrict" || name == "cipUrpfIfWhichRouteTableID" || name == "cipUrpfIfVrfName")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfTable()
:
cipurpfvrfifentry(this, {"cipurpfvrfname", "ifindex"})
{
yang_name = "cipUrpfVrfIfTable"; yang_parent_name = "CISCO-IP-URPF-MIB"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfVrfIfTable::~CipUrpfVrfIfTable()
{
}
bool CISCOIPURPFMIB::CipUrpfVrfIfTable::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<cipurpfvrfifentry.len(); index++)
{
if(cipurpfvrfifentry[index]->has_data())
return true;
}
return false;
}
bool CISCOIPURPFMIB::CipUrpfVrfIfTable::has_operation() const
{
for (std::size_t index=0; index<cipurpfvrfifentry.len(); index++)
{
if(cipurpfvrfifentry[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfVrfIfTable::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfVrfIfTable::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfVrfIfTable";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfVrfIfTable::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfVrfIfTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cipUrpfVrfIfEntry")
{
auto ent_ = std::make_shared<CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry>();
ent_->parent = this;
cipurpfvrfifentry.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfVrfIfTable::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : cipurpfvrfifentry.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void CISCOIPURPFMIB::CipUrpfVrfIfTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void CISCOIPURPFMIB::CipUrpfVrfIfTable::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool CISCOIPURPFMIB::CipUrpfVrfIfTable::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfVrfIfEntry")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::CipUrpfVrfIfEntry()
:
cipurpfvrfname{YType::str, "cipUrpfVrfName"},
ifindex{YType::str, "ifIndex"},
cipurpfvrfifdrops{YType::uint32, "cipUrpfVrfIfDrops"},
cipurpfvrfifdiscontinuitytime{YType::uint32, "cipUrpfVrfIfDiscontinuityTime"}
{
yang_name = "cipUrpfVrfIfEntry"; yang_parent_name = "cipUrpfVrfIfTable"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::~CipUrpfVrfIfEntry()
{
}
bool CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::has_data() const
{
if (is_presence_container) return true;
return cipurpfvrfname.is_set
|| ifindex.is_set
|| cipurpfvrfifdrops.is_set
|| cipurpfvrfifdiscontinuitytime.is_set;
}
bool CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cipurpfvrfname.yfilter)
|| ydk::is_set(ifindex.yfilter)
|| ydk::is_set(cipurpfvrfifdrops.yfilter)
|| ydk::is_set(cipurpfvrfifdiscontinuitytime.yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/cipUrpfVrfIfTable/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfVrfIfEntry";
ADD_KEY_TOKEN(cipurpfvrfname, "cipUrpfVrfName");
ADD_KEY_TOKEN(ifindex, "ifIndex");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cipurpfvrfname.is_set || is_set(cipurpfvrfname.yfilter)) leaf_name_data.push_back(cipurpfvrfname.get_name_leafdata());
if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata());
if (cipurpfvrfifdrops.is_set || is_set(cipurpfvrfifdrops.yfilter)) leaf_name_data.push_back(cipurpfvrfifdrops.get_name_leafdata());
if (cipurpfvrfifdiscontinuitytime.is_set || is_set(cipurpfvrfifdiscontinuitytime.yfilter)) leaf_name_data.push_back(cipurpfvrfifdiscontinuitytime.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cipUrpfVrfName")
{
cipurpfvrfname = value;
cipurpfvrfname.value_namespace = name_space;
cipurpfvrfname.value_namespace_prefix = name_space_prefix;
}
if(value_path == "ifIndex")
{
ifindex = value;
ifindex.value_namespace = name_space;
ifindex.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfVrfIfDrops")
{
cipurpfvrfifdrops = value;
cipurpfvrfifdrops.value_namespace = name_space;
cipurpfvrfifdrops.value_namespace_prefix = name_space_prefix;
}
if(value_path == "cipUrpfVrfIfDiscontinuityTime")
{
cipurpfvrfifdiscontinuitytime = value;
cipurpfvrfifdiscontinuitytime.value_namespace = name_space;
cipurpfvrfifdiscontinuitytime.value_namespace_prefix = name_space_prefix;
}
}
void CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cipUrpfVrfName")
{
cipurpfvrfname.yfilter = yfilter;
}
if(value_path == "ifIndex")
{
ifindex.yfilter = yfilter;
}
if(value_path == "cipUrpfVrfIfDrops")
{
cipurpfvrfifdrops.yfilter = yfilter;
}
if(value_path == "cipUrpfVrfIfDiscontinuityTime")
{
cipurpfvrfifdiscontinuitytime.yfilter = yfilter;
}
}
bool CISCOIPURPFMIB::CipUrpfVrfIfTable::CipUrpfVrfIfEntry::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfVrfName" || name == "ifIndex" || name == "cipUrpfVrfIfDrops" || name == "cipUrpfVrfIfDiscontinuityTime")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfTable()
:
cipurpfvrfentry(this, {"cipurpfvrfname"})
{
yang_name = "cipUrpfVrfTable"; yang_parent_name = "CISCO-IP-URPF-MIB"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfVrfTable::~CipUrpfVrfTable()
{
}
bool CISCOIPURPFMIB::CipUrpfVrfTable::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<cipurpfvrfentry.len(); index++)
{
if(cipurpfvrfentry[index]->has_data())
return true;
}
return false;
}
bool CISCOIPURPFMIB::CipUrpfVrfTable::has_operation() const
{
for (std::size_t index=0; index<cipurpfvrfentry.len(); index++)
{
if(cipurpfvrfentry[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfVrfTable::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfVrfTable::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfVrfTable";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfVrfTable::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfVrfTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "cipUrpfVrfEntry")
{
auto ent_ = std::make_shared<CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry>();
ent_->parent = this;
cipurpfvrfentry.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfVrfTable::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : cipurpfvrfentry.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void CISCOIPURPFMIB::CipUrpfVrfTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void CISCOIPURPFMIB::CipUrpfVrfTable::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool CISCOIPURPFMIB::CipUrpfVrfTable::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfVrfEntry")
return true;
return false;
}
CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::CipUrpfVrfEntry()
:
cipurpfvrfname{YType::str, "cipUrpfVrfName"}
{
yang_name = "cipUrpfVrfEntry"; yang_parent_name = "cipUrpfVrfTable"; is_top_level_class = false; has_list_ancestor = false;
}
CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::~CipUrpfVrfEntry()
{
}
bool CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::has_data() const
{
if (is_presence_container) return true;
return cipurpfvrfname.is_set;
}
bool CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(cipurpfvrfname.yfilter);
}
std::string CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "CISCO-IP-URPF-MIB:CISCO-IP-URPF-MIB/cipUrpfVrfTable/" << get_segment_path();
return path_buffer.str();
}
std::string CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "cipUrpfVrfEntry";
ADD_KEY_TOKEN(cipurpfvrfname, "cipUrpfVrfName");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (cipurpfvrfname.is_set || is_set(cipurpfvrfname.yfilter)) leaf_name_data.push_back(cipurpfvrfname.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "cipUrpfVrfName")
{
cipurpfvrfname = value;
cipurpfvrfname.value_namespace = name_space;
cipurpfvrfname.value_namespace_prefix = name_space_prefix;
}
}
void CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "cipUrpfVrfName")
{
cipurpfvrfname.yfilter = yfilter;
}
}
bool CISCOIPURPFMIB::CipUrpfVrfTable::CipUrpfVrfEntry::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "cipUrpfVrfName")
return true;
return false;
}
const Enum::YLeaf UnicastRpfType::strict {1, "strict"};
const Enum::YLeaf UnicastRpfType::loose {2, "loose"};
const Enum::YLeaf UnicastRpfType::disabled {3, "disabled"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::CipUrpfIpVersion::ipv4 {1, "ipv4"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfTable::CipUrpfEntry::CipUrpfIpVersion::ipv6 {2, "ipv6"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::CipUrpfIfIpVersion::ipv4 {1, "ipv4"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::CipUrpfIfIpVersion::ipv6 {2, "ipv6"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::CipUrpfIfCheckStrict::strict {1, "strict"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::CipUrpfIfCheckStrict::loose {2, "loose"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::CipUrpfIfWhichRouteTableID::default_ {1, "default"};
const Enum::YLeaf CISCOIPURPFMIB::CipUrpfIfMonTable::CipUrpfIfMonEntry::CipUrpfIfWhichRouteTableID::vrf {2, "vrf"};
}
}
|
sterobin/drools | kie-pmml-trusty/kie-pmml-models/kie-pmml-models-drools/kie-pmml-models-drools-common/src/main/java/org/kie/pmml/models/drools/ast/factories/KiePMMLDataDictionaryASTFactory.java | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.pmml.models.drools.ast.factories;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.dmg.pmml.DataDictionary;
import org.dmg.pmml.DataField;
import org.kie.pmml.api.enums.DATA_TYPE;
import org.kie.pmml.models.drools.ast.KiePMMLDroolsType;
import org.kie.pmml.models.drools.tuples.KiePMMLOriginalTypeGeneratedType;
import static org.kie.pmml.commons.utils.KiePMMLModelUtils.getSanitizedClassName;
/**
* Class used to generate <code>KiePMMLDroolsType</code>s out of a <code>DataDictionary</code>
*/
public class KiePMMLDataDictionaryASTFactory {
private final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap;
private KiePMMLDataDictionaryASTFactory(final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) {
this.fieldTypeMap = fieldTypeMap;
}
/**
* @param fieldTypeMap the <code>Map<String, KiePMMLOriginalTypeGeneratedType></code> to be populated with mapping between original field' name and <b>original type/generated type</b> tupla
* @return
*/
public static KiePMMLDataDictionaryASTFactory factory(final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) {
return new KiePMMLDataDictionaryASTFactory(fieldTypeMap);
}
/**
* Create a <code>List<KiePMMLDroolsType></code> out of original <code>DataField</code>s,
* and <b>populate</b> the <b>fieldNameTypeNameMap</b> with mapping between original field' name and <b>original type/generated type</b> tupla
* @param dataDictionary
*/
public List<KiePMMLDroolsType> declareTypes(final DataDictionary dataDictionary) {
return dataDictionary.getDataFields().stream().map(this::declareType).collect(Collectors.toList());
}
/**
* Create a <code>KiePMMLDroolsType</code> out of original <code>DataField</code>,
* and <b>populate</b> the <b>fieldNameTypeNameMap</b> with mapping between original field' name and <b>original type/generated type</b> tupla
* @param dataField
*/
public KiePMMLDroolsType declareType(DataField dataField) {
String generatedType = getSanitizedClassName(dataField.getName().getValue().toUpperCase());
String fieldName = dataField.getName().getValue();
String fieldType = dataField.getDataType().value();
fieldTypeMap.put(fieldName, new KiePMMLOriginalTypeGeneratedType(fieldType, generatedType));
return new KiePMMLDroolsType(generatedType, DATA_TYPE.byName(fieldType).getMappedClass().getSimpleName());
}
}
|
yffd/easy-parent | easy-framework-common/src/main/java/com/yffd/easy/framework/common/service/support/CommonServiceTreeSupport.java | <gh_stars>0
package com.yffd.easy.framework.common.service.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.yffd.easy.common.core.exception.EasyCommonException;
import com.yffd.easy.common.core.tree.sample.EasySampleTree;
import com.yffd.easy.common.core.tree.sample.EasySampleTreeBuilder;
import com.yffd.easy.common.core.tree.sample.EasySampleTreeJson;
import com.yffd.easy.common.core.util.EasyStringCheckUtils;
import com.yffd.easy.framework.common.persist.mybatis.constants.MybatisConstants;
import com.yffd.easy.framework.common.persist.mybatis.dao.MybatisDaoSupport;
import com.yffd.easy.framework.common.util.SpringBeanUtils;
import com.yffd.easy.framework.pojo.entity.CommonPartialTreeEntity;
/**
* @Description 简单描述该类的功能(可选).
* @Date 2018年5月8日 下午2:36:08 <br/>
* @author zhangST
* @version 1.0
* @since JDK 1.7+
* @see
*/
public class CommonServiceTreeSupport<E extends CommonPartialTreeEntity> {
public static final String SQL_ID_SELECT_CHILDREN_NODES = "selectChildrenNodes";
public static final String SQL_ID_SELECT_PARENT_NODES = "selectParentNodes";
public static final String SQL_ID_COUNT_LAYER = "countLayer";
public static final String SQL_ID_UPDATE_NODES = "updateNodes";
public static final String SQL_ID_DELETE_NODES = "deleteNodes";
public static final String SQL_ID_UPDATE_LEFT_FOR_ADD = "updateLeftForAdd";
public static final String UPDATE_RIGHT_FOR_ADD = "updateRightForAdd";
public static final String UPDATE_LEFT_FOR_DEL = "updateLeftForDel";
public static final String UPDATE_RIGHT_FOR_DEL = "updateRightForDel";
protected MybatisDaoSupport commonCustomDao = (MybatisDaoSupport) SpringBeanUtils.getBean("mybatisCustomDao");
// protected IMybatisCommonDao<?> bindDao;
//
// public CommonServiceTreeSupport(IMybatisCommonDao<?> bindDao) {
// this.bindDao = bindDao;
// }
//
private String getStatement(String sqlId) {
StringBuilder sb = new StringBuilder();
// sb.append(this.bindDao.getSqlNamespace()).append(".").append(sqlId);
return sb.toString();
}
// public E findNode(E node) {
// if(null==node) return null;
// Map<String, Object> params = new HashMap<String, Object>();
// params.put(MybatisConstants.PARAM_NAME_ENTITY, node);
// return this.commonCustomDao.customSelectOneBy(this.getStatement(MybatisConstants.SQL_ID_SELECT_ONE_BY), params);
// }
//
// public long countNodeLayer(E node) {
// if(null==node) return 0;
// E resultNode = this.findNode(node);
// if(null==resultNode) return 0;
// return this.commonCustomDao.customSelectOneBy(this.getStatement(SQL_ID_COUNT_LAYER), resultNode);
// }
// public boolean existTree(E node) {
// if(null==node) throw new EasyCommonException("参数为空");
// if(EasyStringCheckUtils.isEmpty(node.getTreeId())) throw new EasyCommonException("treeId、nodeCode为空");
// Map<String, Object> params = new HashMap<String, Object>();
// params.put(CommonConstants.PARAM_NAME_ENTITY, node);
// int result = this.commonCustomDao.customSelectCountBy(this.getStatement(CommonConstants.SQL_ID_SELECT_COUNT_BY), params);
// return (result > 0);
// }
// public boolean existNode(E node) {
// if(null==node) throw new EasyCommonException("参数为空");
// String nodeCode = node.getNodeCode();
// if(EasyStringCheckUtils.isEmpty(nodeCode)) throw new EasyCommonException("nodeCode为空");
// Map<String, Object> params = new HashMap<String, Object>();
// params.put(MybatisConstants.PARAM_NAME_ENTITY, node);
// int result = this.commonCustomDao.customSelectCountBy(this.getStatement(MybatisConstants.SQL_ID_SELECT_COUNT_BY), params);
// return (result > 0);
// }
//
// // root section
// public List<E> findRootNodes(E node) {
// if(null==node) return null;
// node.setParentCode("root");
// Map<String, Object> params = new HashMap<String, Object>();
// params.put(MybatisConstants.PARAM_NAME_ENTITY, node);
// return this.commonCustomDao.customSelectListBy(this.getStatement(MybatisConstants.SQL_ID_SELECT_LIST_BY), params);
// }
//
// public int addRootNode(E node) {
// if(null==node) throw new EasyCommonException("参数为空");
// String treeId = node.getTreeId();
// String nodeCode = node.getNodeCode();
// if(EasyStringCheckUtils.isEmpty(treeId) || EasyStringCheckUtils.isEmpty(nodeCode)) throw new EasyCommonException("treeId、nodeCode为空");
// node.setNodeLeft(1);
// node.setNodeRight(2);
// node.setParentCode("root");
// node.setNodeLayer(1);
// return this.commonCustomDao.customInsertBy(this.getStatement(MybatisConstants.SQL_ID_INSERT_ONE_BY), node);
// }
//
//
// // add child section
//// public E findParentNode(E node) {
//// if(null==node || EasyStringCheckUtils.isEmpty(node.getTreeId())
//// || EasyStringCheckUtils.isEmpty(node.getParentCode())) throw new EasyCommonException("查询父节点时,treeId 和 parentCode 不能为空");
//// Map<String, Object> params = new HashMap<String, Object>();
//// params.put(CommonConstants.PARAM_NAME_ENTITY, node);
//// return this.commonCustomDao.customSelectOneBy(this.getStatement(CommonConstants.SQL_ID_SELECT_ONE_BY), params);
//// }
//
// @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
// public int addChildNode(E childNode, E parentNode) {
// if(null==childNode) throw new EasyCommonException("参数为空");
// if(EasyStringCheckUtils.isEmpty(childNode.getTreeId()) || EasyStringCheckUtils.isEmpty(childNode.getNodeCode()))
// throw new EasyCommonException("添加树节点的treeId 和 nodeCode 不能为空");
// E resultParentNode = this.findNode(parentNode);
// if(null==resultParentNode) return 0;
// // 先更新节点左右偏序号,再插入节点,顺序不能变
// // 1.先更新节点左右偏序号
// this.updateLeftForAdd(resultParentNode); // 修改左编号
// this.updateRightForAdd(resultParentNode); // 修改右编号
//
// childNode.setNodeLeft(resultParentNode.getNodeRight());
// childNode.setNodeRight(resultParentNode.getNodeRight() + 1);
// childNode.setParentCode(resultParentNode.getNodeCode());
// childNode.setNodeLayer(resultParentNode.getNodeLayer() + 1);
// // 2.再插入节点
// int num = this.commonCustomDao.customInsertBy(this.getStatement(MybatisConstants.SQL_ID_INSERT_ONE_BY), childNode);
// return num;
// }
//
//
// // update node section
// /**
// * 级联更新节点,以及其子孙节点.</br>
// * 不更新的字段:treeId、nodeLeft、nodeRight、parentCode
// * @Date 2018年4月11日 上午10:18:38 <br/>
// * @author zhangST
// * @param node
// * @param nodeOld
// * @return
// */
// public int updateNodeWithChildren(E node, E nodeOld) {
// if(null==node || null==nodeOld) throw new EasyCommonException("参数为空");
// if(EasyStringCheckUtils.isEmpty(nodeOld.getTreeId()) || EasyStringCheckUtils.isEmpty(nodeOld.getNodeCode()))
// throw new EasyCommonException("treeId、 nodeCode 不能为空");
// E resultUpdateNode = this.findNode(nodeOld);
// if(null==resultUpdateNode) return 0;
// // 不进行更新属性
// node.setTreeId(null);
// node.setNodeLeft(null);
// node.setNodeRight(null);
// node.setParentCode(null);
//
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(resultUpdateNode.getTreeId());
// entity.setNodeLeft(resultUpdateNode.getNodeLeft());
// entity.setNodeRight(resultUpdateNode.getNodeRight());
//
// Map<String, Object> params = new HashMap<String, Object>();
// params.put(MybatisConstants.PARAM_NAME_ENTITY, node);
// params.put(MybatisConstants.PARAM_NAME_ENTITY_OLD, entity);
// int num = this.commonCustomDao.customUpdateBy(this.getStatement(SQL_ID_UPDATE_NODES), params);
// return num;
// }
//
//
// // delete node section
// /**
// * 级联删除节点,以及其子孙节点
// * @Date 2018年4月11日 上午10:19:32 <br/>
// * @author zhangST
// * @param node
// * @return
// */
// @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
// public int deleteNodeWithChildren(E node) {
// if(null==node) return 0;
// E resultDeleteNode = this.findNode(node);
// if(null==resultDeleteNode) return 0;
// // 先删除节点,再更新节点左右偏序号,顺序不能变
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(resultDeleteNode.getTreeId());
// entity.setNodeLeft(resultDeleteNode.getNodeLeft());
// entity.setNodeRight(resultDeleteNode.getNodeRight());
//
// // 1.先删除节点
// int delNum = this.commonCustomDao.customDeleteBy(this.getStatement(SQL_ID_DELETE_NODES), entity); // 删除节点、及子节点
//// int childrenNodes = (resultDeleteNode.getNodeRight() - resultDeleteNode.getNodeLeft() - 1) / 2; // 拥有子节点数
//// if(childrenNodes!=delNum) throw EasyBizException.newInstance("待删除节点数与已删除节点数不相等");
// // 2.再更新节点左右偏序号
// this.updateLeftForDel(resultDeleteNode); // 修改左编号
// this.updateRightForDel(resultDeleteNode); // 修改右编号
// return delNum;
// }
//
//
// private int updateLeftForAdd(E node) {
// if(null==node || EasyStringCheckUtils.isEmpty(node.getTreeId()) ||
// null==node.getNodeRight()) throw new EasyCommonException("添加树节点时,修改左偏序号错误");
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(node.getTreeId());
// entity.setNodeRight(node.getNodeRight());
// entity.setNodeStep(2);
// return this.commonCustomDao.customUpdateBy(this.getStatement(SQL_ID_UPDATE_LEFT_FOR_ADD), entity);
// }
//
// private int updateRightForAdd(E node) {
// if(null==node || EasyStringCheckUtils.isEmpty(node.getTreeId())
// || null==node.getNodeRight()) throw new EasyCommonException("添加树节点时,修改右偏序号错误");
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(node.getTreeId());
// entity.setNodeRight(node.getNodeRight());
// entity.setNodeStep(2);
// return this.commonCustomDao.customUpdateBy(this.getStatement(UPDATE_RIGHT_FOR_ADD), entity);
// }
//
// private int updateLeftForDel(E node) {
// if(null==node || EasyStringCheckUtils.isEmpty(node.getTreeId())
// || null==node.getNodeRight() || null==node.getNodeLeft()) throw new EasyCommonException("删除树节点时,修改左偏序号错误");
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(node.getTreeId());
// entity.setNodeLeft(node.getNodeLeft());
// int nodeStep = node.getNodeRight() - node.getNodeLeft() + 1;
// entity.setNodeStep(nodeStep);
// return this.commonCustomDao.customUpdateBy(this.getStatement(UPDATE_LEFT_FOR_DEL), entity);
// }
//
// private int updateRightForDel(E node) {
// if(null==node || EasyStringCheckUtils.isEmpty(node.getTreeId())
// || null==node.getNodeRight() || null==node.getNodeLeft()) throw new EasyCommonException("删除树节点时,修改右偏序号错误");
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(node.getTreeId());
// entity.setNodeRight(node.getNodeRight());
// int nodeStep = node.getNodeRight() - node.getNodeLeft() + 1;
// entity.setNodeStep(nodeStep);
// return this.commonCustomDao.customUpdateBy(this.getStatement(UPDATE_RIGHT_FOR_DEL), entity);
// }
//
// //////////////////////////// node list //////////////////////////////////////////////////////////
//
// public List<E> findNodes(E node) {
// if(null==node) return null;
// Map<String, Object> params = new HashMap<String, Object>();
// params.put(MybatisConstants.PARAM_NAME_ENTITY, node);
// return this.commonCustomDao.customSelectListBy(this.getStatement(MybatisConstants.SQL_ID_SELECT_LIST_BY), params);
// }
//
// public List<E> findNodeWithChildren(E node) {
// return this.findNodeWithChildren(node, -1, -1, true);
// }
// public List<E> findNodeWithChildren(E node, int relativeBeginLayer) {
// return this.findNodeWithChildren(node, relativeBeginLayer, -1, true);
// }
// public List<E> findNodeWithChildren(E node, int beginLayer, int endLayer, boolean relativeLayer) {
// if(null==node) return null;
// E result = this.findNode(node);
// if(null==result) return null;
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(result.getTreeId());
// entity.setNodeLeft(result.getNodeLeft());
// entity.setNodeRight(result.getNodeRight());
// if(relativeLayer) {
// if(beginLayer>0) entity.setBeginLayer(result.getNodeLayer() + beginLayer);
// if(endLayer>0) entity.setEndLayer(result.getNodeLayer() + endLayer);
// } else {
// if(beginLayer>0) entity.setBeginLayer(beginLayer);
// if(endLayer>0) entity.setEndLayer(endLayer);
// }
// return this.commonCustomDao.customSelectListBy(this.getStatement(SQL_ID_SELECT_CHILDREN_NODES), entity);
// }
//
// public List<E> findNodesWithChildren(E node) {
// return this.findNodesWithChildren(node, -1, -1, true);
// }
// public List<E> findNodesWithChildren(E node, int relativeBeginLayer) {
// return this.findNodesWithChildren(node, relativeBeginLayer, -1, true);
// }
// public List<E> findNodesWithChildren(E node, int beginLayer, int endLayer, boolean relativeLayer) {
// if(null==node) return null;
// List<E> nodes = this.findNodes(node);
// if(null==nodes || nodes.size()==0) return null;
// List<E> ret = new ArrayList<>();
// for(E tmp : nodes) {
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(tmp.getTreeId());
// entity.setNodeLeft(tmp.getNodeLeft());
// entity.setNodeRight(tmp.getNodeRight());
// if(relativeLayer) {
// if(beginLayer>0) entity.setBeginLayer(tmp.getNodeLayer() + beginLayer);
// if(endLayer>0) entity.setEndLayer(tmp.getNodeLayer() + endLayer);
// } else {
// if(beginLayer>0) entity.setBeginLayer(beginLayer);
// if(endLayer>0) entity.setEndLayer(endLayer);
// }
// List<E> list = this.commonCustomDao.customSelectListBy(this.getStatement(SQL_ID_SELECT_CHILDREN_NODES), entity);
// if(null!=list && list.size()>0) ret.addAll(list);
// }
// return ret;
// }
//
// public List<E> findNodeWithParent(E node) {
// return this.findNodeWithParent(node, -1, -1, true);
// }
// public List<E> findNodeWithParent(E node, int beginLayer, int endLayer, boolean relativeLayer) {
// if(null==node) return null;
// E resultNode = this.findNode(node);
// if(null==resultNode) return null;
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(resultNode.getTreeId());
// entity.setNodeLeft(resultNode.getNodeLeft());
// entity.setNodeRight(resultNode.getNodeRight());
// if(relativeLayer) {
// if(beginLayer>0) entity.setBeginLayer(resultNode.getNodeLayer() + beginLayer);
// if(endLayer>0) entity.setEndLayer(resultNode.getNodeLayer() + endLayer);
// } else {
// if(beginLayer>0) entity.setBeginLayer(beginLayer);
// if(endLayer>0) entity.setEndLayer(endLayer);
// }
// return this.commonCustomDao.customSelectListBy(this.getStatement(SQL_ID_SELECT_PARENT_NODES), entity);
// }
//
// public String findNodePath(E node) {
// List<E> parentNodeList = findNodeWithParent(node);
// if(null==parentNodeList || parentNodeList.size()==0) return null;
// StringBuffer sb = new StringBuffer();
// for(E tmp : parentNodeList) {
// sb.append(tmp.getNodeCode()).append(",");
// }
// return sb.length()>0?sb.substring(0, sb.length()-1) : sb.toString();
// }
//
// //////////////////////////// tree //////////////////////////////////////////////////////////
//
// EasySampleTreeBuilder<E> builder = new EasySampleTreeBuilder<E>() {
//
// @Override
// protected EasySampleTree getTreeNode(E node) {
// EasySampleTree tree = new EasySampleTree();
// tree.setNodeValue(node);
// tree.setIdValue(node.getNodeCode());
// tree.setPidValue(node.getParentCode());
// return tree;
// }
//
// @Override
// protected Object getIdValue(E node) {
// return node.getNodeCode();
// }
//
// @Override
// protected Object getPidValue(E node) {
// return node.getParentCode();
// }
//
// };
//
// public String findTreeJson(E node) {
// EasySampleTree tree = this.findTree(node);
// return EasySampleTreeJson.getTreeJson(tree);
// }
//
// public String findTreeJson(E node, int deep) {
// EasySampleTree tree = this.findTree(node, deep);
// return EasySampleTreeJson.getTreeJson(tree);
// }
//
// public EasySampleTree findTree(E node) {
// return this.findTree(node, 0);
// }
//
// public EasySampleTree findTree(E node, int deep) {
// if(null==node) return null;
// E resultNode = this.findNode(node);
// if(null==resultNode) return null;
// CommonPartialTreeEntity entity = new CommonPartialTreeEntity();
// entity.setTreeId(resultNode.getTreeId());
// entity.setNodeLeft(resultNode.getNodeLeft());
// entity.setNodeRight(resultNode.getNodeRight());
// if(deep>0) entity.setNodeLayer(resultNode.getNodeLayer() + deep);
// List<E> childrenNode = this.commonCustomDao.customSelectListBy(this.getStatement(SQL_ID_SELECT_CHILDREN_NODES), entity);
// return builder.buildTree(childrenNode, resultNode);
// }
}
|
PedroTreck/dctb-utfpr-2018-2 | programacao-web/as34a-n14/t02/gabriel-garcia/src/components/Portfolio/index.js | import React, { Component, Fragment } from 'react';
import './Portfolio.css';
const Portfolio = function () {
return <Fragment>
<section id="portfolio">
<h2>Portfólio</h2>
<div id="portfolio-container">
<div className="portfolio-proj">
<a href="https://github.com/gabriel-hg58/Dog-Control" target="_blank">
<div className="portfolio-img img-01"></div>
<h2>Sistema de controle Animal</h2>
</a>
</div>
<div className="portfolio-proj">
<a href="https://github.com/gabriel-hg58/IM" target="_blank">
<div className="portfolio-img img-02"></div>
<h2>Projeto de estágio</h2>
</a>
</div>
<div className="portfolio-proj">
<div className="portfolio-img img-03"></div>
<h2>Projeto do meu Site</h2>
</div>
</div>
</section>
</Fragment>;
}
export default Portfolio; |
javaeryang/mtool | light/light/com/easyctrl/ldy/domain/RoomBean.java | package com.easyctrl.ldy.domain;
public class RoomBean {
public int floorID;
public int id;
public int isUse;
public String name;
public int paixu;
public String sname;
public static final class Table {
public static String FLOORID = com.easyctrl.ldy.domain.UserScene.Table.FIELD_FLOOR;
public static String ID = com.easyctrl.ldy.domain.ImitateBean.Table.FIELD_ID;
public static String NAME = "name";
public static String PAIXU = "paixu";
public static String SNAME = "sname";
public static String T_NAME = "easy_room";
public static String generateTableSql() {
StringBuilder builder = new StringBuilder();
builder.append("CREATE TABLE IF NOT EXISTS ").append(T_NAME).append("(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,").append(FLOORID + " INTEGER,").append(PAIXU + " INTEGER ,").append(SNAME + " TEXT NULL ,").append(NAME + " TEXT NULL )");
return builder.toString();
}
}
public boolean equals(Object o) {
if (this.id != ((RoomBean) o).id) {
return false;
}
return true;
}
}
|
ch1huizong/learning | lang/py/cookbook/v2/source/cb2_12_5_sol_1.py | <filename>lang/py/cookbook/v2/source/cb2_12_5_sol_1.py
from xml.parsers import expat
class Element(object):
''' A parsed XML element '''
def __init__(self, name, attributes):
# Record tagname and attributes dictionary
self.name = name
self.attributes = attributes
# Initialize the element's cdata and children to empty
self.cdata = ''
self.children = []
def addChild(self, element):
self.children.append(element)
def getAttribute(self, key):
return self.attributes.get(key)
def getData(self):
return self.cdata
def getElements(self, name=''):
if name:
return [c for c in self.children if c.name == name]
else:
return list(self.children)
class Xml2Obj(object)
''' XML to Object converter '''
def __init__(self):
self.root = None
self.nodeStack = []
def StartElement(self, name, attributes):
'Expat start element event handler'
# Instantiate an Element object
element = Element(name.encode(), attributes)
# Push element onto the stack and make it a child of parent
if self.nodeStack:
parent = self.nodeStack[-1]
parent.addChild(element)
else:
self.root = element
self.nodeStack.append(element)
def EndElement(self, name):
'Expat end element event handler'
self.nodeStack[-1].pop()
def CharacterData(self, data):
'Expat character data event handler'
if data.strip():
data = data.encode()
element = self.nodeStack[-1]
element.cdata += data
def Parse(self, filename):
# Create an Expat parser
Parser = expat.ParserCreate()
# Set the Expat event handlers to our methods
Parser.StartElementHandler = self.StartElement
Parser.EndElementHandler = self.EndElement
Parser.CharacterDataHandler = self.CharacterData
# Parse the XML File
ParserStatus = Parser.Parse(open(filename).read(), 1)
return self.root
parser = Xml2Obj()
root_element = parser.Parse('sample.xml')
|
Eunoians/McMMOx | src/main/java/us/eunoians/mcrpg/abilities/sorcery/PotionAffinity.java | <reponame>Eunoians/McMMOx
package us.eunoians.mcrpg.abilities.sorcery;
import us.eunoians.mcrpg.abilities.BaseAbility;
import us.eunoians.mcrpg.types.UnlockedAbilities;
public class PotionAffinity extends BaseAbility {
public PotionAffinity(boolean isToggled, int currentTier) {
super(UnlockedAbilities.POTION_AFFINITY, isToggled, currentTier);
}
}
|
itsraina/ghidra | Ghidra/Debug/ProposedUtils/src/test/java/ghidra/pcode/exec/AnnotatedPcodeUseropLibraryTest.java | /* ###
* IP: GHIDRA
*
* 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 ghidra.pcode.exec;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.util.List;
import org.junit.Test;
import ghidra.app.plugin.processors.sleigh.SleighException;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.pcode.utils.Utils;
import ghidra.program.model.lang.LanguageID;
import ghidra.program.model.lang.Register;
import ghidra.program.model.pcode.Varnode;
import ghidra.test.AbstractGhidraHeadlessIntegrationTest;
public class AnnotatedPcodeUseropLibraryTest extends AbstractGhidraHeadlessIntegrationTest {
private class TestUseropLibrary extends AnnotatedPcodeUseropLibrary<byte[]> {
@Override
protected Lookup getMethodLookup() {
return MethodHandles.lookup();
}
}
protected PcodeExecutor<byte[]> createBytesExecutor() throws Exception {
return createBytesExecutor("Toy:BE:64:default");
}
protected PcodeExecutor<byte[]> createBytesExecutor(String languageId) throws Exception {
SleighLanguage language =
(SleighLanguage) getLanguageService().getLanguage(new LanguageID(languageId));
PcodeExecutorState<byte[]> state = new BytesPcodeExecutorState(language);
PcodeArithmetic<byte[]> arithmetic = BytesPcodeArithmetic.forLanguage(language);
return new PcodeExecutor<>(language, arithmetic, state);
}
protected <T> void executeSleigh(PcodeExecutor<T> executor, PcodeUseropLibrary<T> library,
String... lines) {
PcodeProgram program = SleighProgramCompiler.compileProgram(executor.getLanguage(), "test",
List.of(lines), library);
executor.execute(program, library);
}
protected void executeSleigh(PcodeUseropLibrary<byte[]> library, String... lines)
throws Exception {
executeSleigh(createBytesExecutor(), library, lines);
}
protected static void assertBytes(long expectedVal, int expectedSize, byte[] actual) {
assertEquals(expectedSize, actual.length);
assertEquals(expectedVal, Utils.bytesToLong(actual, expectedSize, true));
}
protected static void assertConstVarnode(long expectedVal, int expectedSize, Varnode actual) {
assertTrue(actual.getAddress().isConstantAddress());
assertEquals(expectedVal, actual.getOffset());
assertEquals(expectedSize, actual.getSize());
}
protected static void assertRegVarnode(Register expected, Varnode actual) {
assertEquals(expected.getAddress(), actual.getAddress());
assertEquals(expected.getNumBytes(), actual.getSize());
}
@Test
public void testNoParams() throws Exception {
var library = new TestUseropLibrary() {
boolean invoked = false;
@PcodeUserop
private void __testop() {
invoked = true;
}
};
executeSleigh(library, "__testop();");
assertTrue(library.invoked);
}
@Test
public void testOneInputFixedT() throws Exception {
var library = new TestUseropLibrary() {
byte[] input;
@PcodeUserop
private void __testop(byte[] input) {
this.input = input;
}
};
executeSleigh(library, "__testop(1234:4);");
assertBytes(1234, 4, library.input);
}
@Test
public void testVariadicInputT() throws Exception {
var library = new TestUseropLibrary() {
byte[][] inputs;
@PcodeUserop(variadic = true)
private void __testop(byte[][] inputs) {
this.inputs = inputs;
}
};
executeSleigh(library, "__testop(1234:4, 4567:2);");
assertBytes(1234, 4, library.inputs[0]);
assertBytes(4567, 2, library.inputs[1]);
}
@Test
public void testVariadicInputVars() throws Exception {
var library = new TestUseropLibrary() {
Varnode[] inputs;
@PcodeUserop(variadic = true)
private void __testop(Varnode[] inputs) {
this.inputs = inputs;
}
};
executeSleigh(library, "__testop(1234:4, 4567:2);");
assertConstVarnode(1234, 4, library.inputs[0]);
assertConstVarnode(4567, 2, library.inputs[1]);
}
@Test
public void testReturnedOutput() throws Exception {
var library = new TestUseropLibrary() {
@PcodeUserop
private byte[] __testop() {
return Utils.longToBytes(1234, 8, true);
}
};
PcodeExecutor<byte[]> executor = createBytesExecutor();
Register r0 = executor.getLanguage().getRegister("r0");
executeSleigh(executor, library, "r0 = __testop();");
assertBytes(1234, 8, executor.getState().getVar(r0));
}
@Test
public void testReturnedOutputBinaryFunc() throws Exception {
var library = new TestUseropLibrary() {
@PcodeUserop
private byte[] __testop(byte[] aBytes, byte[] bBytes) {
long a = Utils.bytesToLong(aBytes, 8, true);
long b = Utils.bytesToLong(bBytes, 8, true);
return Utils.longToBytes(a * a + b, 8, true);
}
};
PcodeExecutor<byte[]> executor = createBytesExecutor();
Register r0 = executor.getLanguage().getRegister("r0");
Register r1 = executor.getLanguage().getRegister("r1");
executor.getState().setVar(r0, Utils.longToBytes(10, 8, true));
executeSleigh(executor, library, "r1 = __testop(r0, 59:8);");
assertBytes(159, 8, executor.getState().getVar(r1));
}
@Test
public void testOpExecutor() throws Exception {
var library = new TestUseropLibrary() {
PcodeExecutor<byte[]> executor;
@PcodeUserop
private void __testop(@OpExecutor PcodeExecutor<byte[]> executor) {
this.executor = executor;
}
};
PcodeExecutor<byte[]> executor = createBytesExecutor();
executeSleigh(executor, library, "__testop();");
assertEquals(executor, library.executor);
}
@Test
public void testOpState() throws Exception {
var library = new TestUseropLibrary() {
PcodeExecutorStatePiece<byte[], byte[]> state;
@PcodeUserop
private void __testop(@OpState PcodeExecutorStatePiece<byte[], byte[]> state) {
this.state = state;
}
};
PcodeExecutor<byte[]> executor = createBytesExecutor();
executeSleigh(executor, library, "__testop();");
assertEquals(executor.getState(), library.state);
}
@Test
public void testOpLibrary() throws Exception {
var library = new TestUseropLibrary() {
PcodeUseropLibrary<byte[]> lib;
@PcodeUserop
private void __testop(@OpLibrary PcodeUseropLibrary<byte[]> lib) {
this.lib = lib;
}
};
PcodeExecutor<byte[]> executor = createBytesExecutor();
executeSleigh(executor, library, "__testop();");
assertEquals(library, library.lib);
}
@Test
public void testOpOutput() throws Exception {
var library = new TestUseropLibrary() {
Varnode outVar;
@PcodeUserop
private void __testop(@OpOutput Varnode outVar) {
this.outVar = outVar;
}
};
PcodeExecutor<byte[]> executor = createBytesExecutor();
Register r0 = executor.getLanguage().getRegister("r0");
executeSleigh(executor, library, "r0 = __testop();");
assertRegVarnode(r0, library.outVar);
}
@Test
public void testKitchenSink() throws Exception {
var library = new TestUseropLibrary() {
PcodeExecutor<byte[]> executor;
PcodeExecutorStatePiece<byte[], byte[]> state;
PcodeUseropLibrary<byte[]> lib;
Varnode outVar;
Varnode inVar0;
byte[] inVal1;
@PcodeUserop
private byte[] __testop(
@OpOutput Varnode outVar,
@OpLibrary PcodeUseropLibrary<byte[]> lib,
@OpExecutor PcodeExecutor<byte[]> executor,
Varnode inVar0,
@OpState PcodeExecutorStatePiece<byte[], byte[]> state,
byte[] inVal1) {
this.executor = executor;
this.state = state;
this.lib = lib;
this.outVar = outVar;
this.inVar0 = inVar0;
this.inVal1 = inVal1;
return inVal1;
}
};
PcodeExecutor<byte[]> executor = createBytesExecutor();
Register r0 = executor.getLanguage().getRegister("r0");
Register r1 = executor.getLanguage().getRegister("r1");
executeSleigh(executor, library, "r0 = __testop(r1, 1234:8);");
assertEquals(executor, library.executor);
assertEquals(executor.getState(), library.state);
assertEquals(library, library.lib);
assertRegVarnode(r0, library.outVar);
assertRegVarnode(r1, library.inVar0);
assertBytes(1234, 8, library.inVal1);
assertBytes(1234, 8, executor.getState().getVar(r0));
}
@Test(expected = SleighException.class)
public void testErrNotExported() throws Exception {
var library = new TestUseropLibrary() {
@SuppressWarnings("unused")
private void __testop() {
}
};
executeSleigh(library, "r0 = __testop();");
}
@Test(expected = PcodeExecutionException.class)
public void testErrParameterCountMismatch() throws Exception {
var library = new TestUseropLibrary() {
@PcodeUserop
private void __testop(Varnode in0) {
}
};
executeSleigh(library, "r0 = __testop();");
}
@Test(expected = IllegalArgumentException.class)
public void testErrAccess() throws Exception {
new AnnotatedPcodeUseropLibrary<byte[]>() {
@PcodeUserop
private void __testop(Varnode in0) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrReturnType() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private int __testop() {
return 0;
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrInputType() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(int in0) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrExecutorType() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(@OpExecutor int executor) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrStateType() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(@OpState int state) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrOutputType() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(@OpOutput int out) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrVariadicInputsType() throws Exception {
new TestUseropLibrary() {
@PcodeUserop(variadic = true)
private void __testop(int[] ins) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrConflictingAnnotations() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(@OpExecutor @OpState int in0) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrDuplicateExecutor() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(@OpExecutor PcodeExecutor<byte[]> executor0,
@OpExecutor PcodeExecutor<byte[]> executor1) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrDuplicateState() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(@OpState PcodeExecutorStatePiece<byte[], byte[]> state0,
@OpState PcodeExecutorStatePiece<byte[], byte[]> state1) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrDuplicateOutput() throws Exception {
new TestUseropLibrary() {
@PcodeUserop
private void __testop(@OpOutput Varnode out0, @OpOutput Varnode out1) {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrMissingVariadicInputs() throws Exception {
new TestUseropLibrary() {
@PcodeUserop(variadic = true)
private void __testop() {
}
};
}
@Test(expected = IllegalArgumentException.class)
public void testErrDuplicateVariadicInputs() throws Exception {
new TestUseropLibrary() {
@PcodeUserop(variadic = true)
private void __testop(Varnode[] ins0, Varnode[] ins1) {
}
};
}
}
|
Ubastic/lintcode | python/0138.subarray-sum.py | <gh_stars>1-10
class Solution:
"""
@param nums: A list of integers
@return: A list of integers includes the index of the first number and the index of the last number
"""
def subarraySum(self, nums):
d = {}
d[0] = -1
L = len(nums)
index = 0
count = 0
while index < L :
count += nums[index]
if count in d :
return [d[count]+1,index]
d[count] = index
index += 1 |
NickGenghar/Serv_Old | initial/reload.js | const Discord = require('discord.js');
const fs = require('fs');
const keyCompare = require('../functions/keyCompare');
const defaults = require('../configurations/defaults.json');
/**
* @param {Object} bot The Discord Client object.
* @returns {void}
*/
module.exports = (bot) => {
if(typeof bot.timeout === 'object' && bot.timeout.length > 0) bot.timeout.forEach(a => {bot.clearTimeout(a);});
if(typeof bot.immediate === 'object' && bot.immediate.length > 0) bot.immediate.forEach(a => {bot.clearImmediate(a);});
if(typeof bot.interval === 'object' && bot.interval.length > 0) bot.interval.forEach(a => {bot.clearInterval(a);});
bot.timeout = new Object;
bot.immediate = new Object;
bot.interval = new Object;
bot.commands = new Discord.Collection();
bot.sideload = new Discord.Collection();
const sideloads = fs.readdirSync('./sideload').filter(file => {if(file.indexOf('.js') > -1) return file;});
if(sideloads.length <= 0) {
console.error('\x1b[31m%s\x1b[0m','Required directory is empty! Cannot proceed without any command modules installed. Exiting...');
return process.exit(-1);
} else {
sideloads.forEach(sides => {
delete require.cache[require.resolve(`../sideload/${sides}`)];
let pull = require(`../sideload/${sides}`);
bot.sideload.set(pull.task, pull);
});
}
let componentIssue = [];
let commandFolder = fs.readdirSync('./commands').filter(folder => {if(folder.indexOf('.') < 0) return folder});
if(commandFolder.length <= 0) {
console.error('\x1b[31m%s\x1b[0m','Command modules are empty! Cannot proceed if no commands are present. Exiting...');
return process.exit(-1);
} else {
commandFolder.forEach(subFolder => {
let commandFiles = fs.readdirSync(`./commands/${subFolder}`).filter(files => {if(files.indexOf('.js') > -1) return files});
if(commandFiles.length <= 0) {
console.error('\x1b[33m%s\x1b[0m',`Folder "${subFolder}" is empty. Ignoring...`);
} else {
let command = [];
let index = 0;
commandFiles.forEach(files => {
try {
delete require.cache[require.resolve(`../commands/${subFolder}/${files}`)];
let pull = require(`../commands/${subFolder}/${files}`);
if(keyCompare(defaults.command_structure, pull) && pull.name != '' && pull.alias.length >= 1 && typeof pull.run === 'function') {
command[index] = {
name: pull.name,
alias: pull.alias,
desc: pull.desc,
usage: pull.usage,
dev: pull.dev,
mod: pull.mod,
activate: pull.activate,
run: pull.run,
type: subFolder
}
bot.commands.set(command[index].name, command[index++]);
console.log('\x1b[36m%s\x1b[0m',`Loaded command [${pull.name}] from "./commands/${subFolder}/${files}"`);
} else {
componentIssue.push(files);
console.log('\x1b[33m%s\x1b[0m',`Command module [${files}] has incomplete parameters. Ignoring...`);
}
} catch(e) {
componentIssue.push(files);
console.error('\x1b[31m%s\x1b[0m',e);
}
})
}
})
}
if(componentIssue.length > 0)
Promise.reject(`The following modules failed to load:\n${componentIssue.join('\n')}`);
return;
} |
EmergentOrder/SparkCyclone | tpcbench-run/src/main/scala/sc/RunResults.scala | <reponame>EmergentOrder/SparkCyclone<filename>tpcbench-run/src/main/scala/sc/RunResults.scala
package sc
import cats.effect.IO
import scalatags.Text
import java.nio.file.{Files, Path, Paths}
object RunResults {
val DefaultOrdering: List[String] =
List(
"id",
"timestamp",
"gitCommitSha",
"gitBranch",
"scale",
"queryNo",
"succeeded",
"wallTime",
"queryTime",
"compileTime",
"serializerOn",
"logOutput",
"appUrl",
"containerList",
"metrics",
"finalPlan"
)
}
final case class RunResults(columns: List[String], data: List[List[Option[AnyRef]]]) {
def reorder(priorities: List[String]): RunResults = {
copy(
data = data.map(dataRow =>
columns
.zip(dataRow)
.sortBy(xc => {
val p = priorities.indexOf(xc._1)
if (p == -1) Int.MaxValue
else p
})
.map(_._2)
),
columns = columns.sortBy(xc => {
val p = priorities.indexOf(xc)
if (p == -1) Int.MaxValue
else p
})
)
}
import _root_.scalatags.Text.all._
def toTable: Text.TypedTag[String] = html(
head(
tag("title")("TPC Bench results"),
raw(
"""<link rel="stylesheet" href="https://unpkg.com/purecss@2.0.6/build/pure-min.css" integrity="<KEY>" crossorigin="anonymous">"""
),
raw(
"""<script src="https://cdnjs.cloudflare.com/ajax/libs/dialog-polyfill/0.5.6/dialog-polyfill.min.js" integrity="sha512-qUIG93zKzcLBVD5RGRbx2PBmbVRu+tJIl+EPLTus0z8I1AMru9sQYdlf6cBacSzYmZVncB9rcc8rYBnazqgrxA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>"""
),
raw("""<meta name="viewport" content="width=device-width, initial-scale=1">"""),
raw("""<style>body {font-size:14pt; }
|td {vertical-align:top; }
|.failed td {
|background: rgb(255,240,240) !important;
|}
|td,th, button, a {
| white-space: nowrap;
|}
|tr:target td {
|background: rgb(255,225,190) !important;
|}
|dialog {
|width: 90vw
|}
|</style>""".stripMargin)
),
body(
table(
`class` := "pure-table pure-table-horizontal",
style := "font-size:9pt",
thead(tr(columns.map(col => th(col)))),
tbody(data.map { row =>
val theId = row(columns.indexOf("id")).get.toString
tr(
id := theId,
if (row(columns.indexOf("succeeded")).contains("false")) (`class` := "failed")
else (),
row.zip(columns).map {
case (None, _) => td()
case (Some(value), cn @ ("logOutput" | "traceResults" | "metrics" | "finalPlan"))
if value.toString.nonEmpty =>
td(
`class` := cn,
tag("dialog")(pre(code(value.toString))),
button(
`onclick` := "this.parentNode.querySelector('dialog').showModal();",
s"View log (${value.toString.count(_ == '\n')} lines)"
)
)
case (Some(value), cn @ "containerList") if value.toString.nonEmpty =>
val urls = value.toString.split("\n").toList
td(
`class` := cn,
tag("dialog")(ol(urls.map(x => li(a(target := "_blank", href := x, x))))),
button(
`onclick` := "this.parentNode.querySelector('dialog').showModal();",
s"View ${urls.size} container URLs"
)
)
case (Some(value), cn @ "timestamp") => td(`class` := cn, pre(value.toString))
case (Some(value), cn @ "gitBranch") =>
td(
`class` := cn,
pre(
a(
target := "_blank",
href := s"https://github.com/XpressAI/SparkCyclone/commits/${value}",
s"${value}"
)
)
)
case (Some(value), cn @ "gitCommitSha") =>
td(
`class` := cn,
pre(
a(
target := "_blank",
href := s"https://github.com/XpressAI/SparkCyclone/commit/${value}",
s"${value}"
)
)
)
case (Some(value), cn) if value.toString.startsWith("http") =>
td(
`class` := cn,
a(
href := value.toString,
target := "_blank",
if (cn == "appUrl") "Open"
else value.toString.replaceAllLiterally("http://", "")
)
)
case (Some(value), cn @ "id") =>
td(`class` := cn, a(href := s"#${theId}", value.toString))
case (Some(value), cn) => td(`class` := cn, value.toString)
}
)
})
),
raw(
"""<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dialog-polyfill/0.5.6/dialog-polyfill.min.css" integrity="sha512-J2+1q+RsZuJXabBfH1q/fgRr6jMy9By5SwVLk7bScEW7NFJkMUXxfeOyyxtDe6fsaJ4jsciexSlGrPYn9YbBIg==" crossorigin="anonymous" referrerpolicy="no-referrer" />"""
),
raw(
"""<script>Array.from(document.querySelectorAll('dialog')).forEach((d) => (dialogPolyfill.registerDialog(d)));</script>"""
)
)
)
def save: IO[Path] = IO
.blocking {
val absPth = Paths.get("target/tpc-html/index.html").toAbsolutePath
Files.createDirectories(absPth.getParent)
Files.write(absPth, toTable.render.getBytes("UTF-8"))
}
.flatTap(path => IO.println(s"Saved results to ${path}"))
}
|
denis-mludek/kaiju | es/observable/flatMapLatest.js |
import { Observable } from './observable';
export default function flatMapLatest(mapper, source) {
return Observable(function (add) {
var currentUnsub = void 0;
var unsubSource = source.subscribe(function (val) {
currentUnsub && currentUnsub();
var mappedObs = mapper(val);
currentUnsub = mappedObs.subscribe(add);
});
return function () {
currentUnsub && currentUnsub();
unsubSource();
};
});
} |
mikestaub/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/eval-code/non-definable-global-function.js | <filename>3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/eval-code/non-definable-global-function.js
// Copyright (C) 2015 <NAME>. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 18.2.1.2
description: Throws a TypeError if a global function cannot be defined.
info: >
Runtime Semantics: EvalDeclarationInstantiation( body, varEnv, lexEnv, strict)
...
8. For each d in varDeclarations, in reverse list order do
a. If d is neither a VariableDeclaration or a ForBinding, then
i. Assert: d is either a FunctionDeclaration or a GeneratorDeclaration.
ii. NOTE If there are multiple FunctionDeclarations for the same name, the last declaration is used.
iii. Let fn be the sole element of the BoundNames of d.
iv. If fn is not an element of declaredFunctionNames, then
1. If varEnvRec is a global Environment Record, then
a. Let fnDefinable be varEnvRec.CanDeclareGlobalFunction(fn).
b. ReturnIfAbrupt(fnDefinable).
c. If fnDefinable is false, throw TypeError exception.
...
flags: [noStrict]
---*/
var error;
try {
eval("function NaN(){}");
} catch (e) {
error = e;
}
assert(error instanceof TypeError);
|
richmit/mraster | lib/ramConfig.hpp | // -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-
/**************************************************************************************************************************************************************/
/**
@file ramConfig.hpp
@author <NAME> <https://www.mitchr.me>
@brief Header defining several compile options.@EOL
@copyright
@parblock
Copyright (c) 1988-2015, <NAME> <https://www.mitchr.me> 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.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
@endparblock
***************************************************************************************************************************************************************/
#ifndef MJR_INCLUDE_ramConfig
/** @brief Define color scheme index out of bound behaviour.@EOL
Set this to the name of the function used to precondition indexes passed into color scheme functions. Options:
- (i) -- Do nothing
- intWrap((i), (m)) -- Wrap
- intClamp((i), (m)) -- Clamp
*/
#ifndef IDXCOND
#define IDXCOND(i, m) (i)
#endif
/** @brief Set the error color@EOL
Set this define to the function call to set the error color. Generally, this will be 'setToBlack()' */
#ifndef SET_ERR_COLOR
#define SET_ERR_COLOR setToBlack()
#endif
/** @brief Keep track of dirty parts of the canvis.@EOL
A rectangle is maintained that contains the dirty region of the canvas.
@todo Add other dirty mark methods like a dirty pixels list, list of dirty rectangels, dirty bit mask.
@warning This option can impose as much as a 2x penalty on drawing operations.
- 0 none No dirty lists
- 1 one Single dirty/not dirty
- 2 box The coordinates of a single dirty box are stored */
#ifndef DIRTY_LIST
#define DIRTY_LIST 0
#endif
/** @brief The type to use for the dirty change index.@EOL */
#ifndef DIRTY_INDEX_TYPE
#define DIRTY_INDEX_TYPE unsigned int
#endif
/** @brief Float type used for fltCrdT in predefiend ramCanvasTpl types defined in ramCanvas.hpp.@EOL*/
#ifndef REAL_CORD
#define REAL_CORD double
#endif
/** @brief Float type used for fltCompT in predefiend colorTpl types defined in color.hpp.@EOL */
#ifndef REAL_CHAN
#define REAL_CHAN float
#endif
/** @brief Int type used for intCrdT in predefined ramCanvasTpl types defined in ramCanvas.hpp.@EOL */
#ifndef INT_CORD
#define INT_CORD int
#endif
/** @brief Always keep the Alpha color safe@EOL
If this non-zero, then the library will preserve the alpha color for normal draw operations.
@warning Imposes a small performance impact. */
#ifndef SUPPORT_ALWAYS_PRESERVE_ALPHA
#define SUPPORT_ALWAYS_PRESERVE_ALPHA 0
#endif
/** @brief Support drawing modes@EOL
If this non-zero, then the library will support drawMode in ramCanvas objects.
@warning Imposes a small performance impact. */
#ifndef SUPPORT_DRAWING_MODE
#define SUPPORT_DRAWING_MODE 0
#endif
// Put everything in the mjr namespace
namespace mjr {
/**@brief Class providing run time access to compile time parameters.@EOL */
class ramConfig {
public:
/** @name Run time detection of compile time options */
//@{
static int support_always_preserve_alpha() { return SUPPORT_ALWAYS_PRESERVE_ALPHA; }
static int support_drawing_mode() { return SUPPORT_DRAWING_MODE; }
static int dirty_list() { return DIRTY_LIST; }
//@}
};
} // end namespace mjr
#define MJR_INCLUDE_ramConfig
#endif
|
rjw57/tiw-computer | emulator/src/devices/cpu/tms1000/tms1400.cpp | // license:BSD-3-Clause
// copyright-holders:hap
/*
TMS1000 family - TMS1400, TMS1470, TMS1600, TMS1670
TODO:
- emulate TMS1600 L-pins
*/
#include "emu.h"
#include "tms1400.h"
#include "debugger.h"
// TMS1400 follows the TMS1100, it doubles the ROM size again (4 chapters of 16 pages), and adds a 3-level callstack
// - rotate the view and mirror the OR-mask to get the proper layout of the mpla, the default is identical to tms1100
// - the opla size is increased from 20 to 32 terms
DEFINE_DEVICE_TYPE(TMS1400, tms1400_cpu_device, "tms1400", "Texas Instruments TMS1400") // 28-pin DIP, 11 R pins (TMS1400CR is same, but with TMS1100 pinout)
DEFINE_DEVICE_TYPE(TMS1470, tms1470_cpu_device, "tms1470", "Texas Instruments TMS1470") // high voltage version, 1 R pin removed for Vdd
// TMS1600 adds more I/O to the TMS1400, input pins are doubled with added L1,2,4,8
// - rotate the view and mirror the OR-mask to get the proper layout of the mpla, the default is identical to tms1100
// - the opla size is increased from 20 to 32 terms
DEFINE_DEVICE_TYPE(TMS1600, tms1600_cpu_device, "tms1600", "Texas Instruments TMS1600") // 40-pin DIP, 16 R pins
DEFINE_DEVICE_TYPE(TMS1670, tms1670_cpu_device, "tms1670", "Texas Instruments TMS1670") // high voltage version
// internal memory maps
ADDRESS_MAP_START(tms1400_cpu_device::program_12bit_8)
AM_RANGE(0x000, 0xfff) AM_ROM
ADDRESS_MAP_END
// device definitions
tms1400_cpu_device::tms1400_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: tms1400_cpu_device(mconfig, TMS1400, tag, owner, clock, 8 /* o pins */, 11 /* r pins */, 6 /* pc bits */, 8 /* byte width */, 3 /* x width */, 12 /* prg width */, address_map_constructor(FUNC(tms1400_cpu_device::program_12bit_8), this), 7 /* data width */, address_map_constructor(FUNC(tms1400_cpu_device::data_128x4), this))
{
}
tms1400_cpu_device::tms1400_cpu_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock, u8 o_pins, u8 r_pins, u8 pc_bits, u8 byte_bits, u8 x_bits, int prgwidth, address_map_constructor program, int datawidth, address_map_constructor data)
: tms1100_cpu_device(mconfig, type, tag, owner, clock, o_pins, r_pins, pc_bits, byte_bits, x_bits, prgwidth, program, datawidth, data)
{
}
tms1470_cpu_device::tms1470_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: tms1400_cpu_device(mconfig, TMS1470, tag, owner, clock, 8, 10, 6, 8, 3, 12, address_map_constructor(FUNC(tms1470_cpu_device::program_12bit_8), this), 7, address_map_constructor(FUNC(tms1470_cpu_device::data_128x4), this))
{
}
tms1600_cpu_device::tms1600_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: tms1600_cpu_device(mconfig, TMS1600, tag, owner, clock, 8, 16, 6, 8, 3, 12, address_map_constructor(FUNC(tms1600_cpu_device::program_12bit_8), this), 7, address_map_constructor(FUNC(tms1600_cpu_device::data_128x4), this))
{
}
tms1600_cpu_device::tms1600_cpu_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock, u8 o_pins, u8 r_pins, u8 pc_bits, u8 byte_bits, u8 x_bits, int prgwidth, address_map_constructor program, int datawidth, address_map_constructor data)
: tms1400_cpu_device(mconfig, type, tag, owner, clock, o_pins, r_pins, pc_bits, byte_bits, x_bits, prgwidth, program, datawidth, data)
{
}
tms1670_cpu_device::tms1670_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock)
: tms1600_cpu_device(mconfig, TMS1670, tag, owner, clock, 8, 16, 6, 8, 3, 12, address_map_constructor(FUNC(tms1670_cpu_device::program_12bit_8), this), 7, address_map_constructor(FUNC(tms1670_cpu_device::data_128x4), this))
{
}
// machine configs
MACHINE_CONFIG_START(tms1400_cpu_device::device_add_mconfig)
// microinstructions PLA, output PLA
MCFG_PLA_ADD("mpla", 8, 16, 30)
MCFG_PLA_FILEFORMAT(BERKELEY)
MCFG_PLA_ADD("opla", 5, 8, 32)
MCFG_PLA_FILEFORMAT(BERKELEY)
MACHINE_CONFIG_END
// device_reset
void tms1400_cpu_device::device_reset()
{
tms1100_cpu_device::device_reset();
// small differences in 00-3f area
m_fixed_decode[0x0b] = F_TPC;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.