repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
helloShen/leetcode | java/src/main/java/com/ciaoshen/leetcode/plus_one_linked_list/Test.java | /**
* Leetcode - #369 - Plus One Linked List
*/
package com.ciaoshen.leetcode.plus_one_linked_list;
import java.util.*;
import com.ciaoshen.leetcode.myUtils.*;
class Test {
/** 测试用例对外开放 */
public List<ListNode> getTestcases() {
return testcases;
}
/** 测试用例对外服务接口 */
public void test(Solution s) {
for (int i = 0; i < testcases.size(); i++) {
call(s, testcases.get(i), answers.get(i));
}
}
/**========================== 【私有成员】 ============================*/
/** 注册测试用例以及答案 [注:测试用例和答案必须按顺序一一对应] */
private List<ListNode> testcases;
private List<String> answers;
/** 构造测试用例 [测试用例是测试类的核心资源] */
private Test() {
// 测试用例
ListNode case1 = null;
ListNode one = new ListNode(1);
ListNode two = new ListNode(2);
ListNode three = new ListNode(3);
one.next = two;
two.next = three;
ListNode case2 = one;
testcases = new ArrayList<ListNode>();
testcases.add(case1);
testcases.add(case2);
// 答案
String answer1 = "null";
String answer2 = "[1,2,4]";
answers = new ArrayList<String>();
answers.add(answer1);
answers.add(answer2);
}
/** 测试单个用例 */
private void call(Solution s, ListNode list, String answer) {
System.out.println("Before: \t" + list);
System.out.println("After: \t" + s.plusOne(list));
System.out.println("Answer: \t" + answer + "\n");
}
public static void main(String[] args) {
Test t = new Test();
Solution s1 = new Solution1();
t.test(s1);
}
} |
soulgoast/blog-repository | dbeaver/plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/actions/datasource/DataSourceRollbackHandler.java | <gh_stars>0
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2020 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ui.actions.datasource;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPMessageType;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.qm.QMTransactionState;
import org.jkiss.dbeaver.model.qm.QMUtils;
import org.jkiss.dbeaver.runtime.DBeaverNotifications;
import org.jkiss.dbeaver.runtime.TasksJob;
import org.jkiss.dbeaver.ui.actions.AbstractDataSourceHandler;
import org.jkiss.dbeaver.ui.controls.txn.TransactionLogDialog;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import java.lang.reflect.InvocationTargetException;
public class DataSourceRollbackHandler extends AbstractDataSourceHandler
{
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
DBCExecutionContext context = getActiveExecutionContext(event, true);
if (context != null && context.isConnected()) {
execute(context);
}
return null;
}
public static void execute(final DBCExecutionContext context) {
TasksJob.runTask("Rollback transaction", monitor -> {
DBCTransactionManager txnManager = DBUtils.getTransactionManager(context);
if (txnManager != null) {
QMTransactionState txnInfo = QMUtils.getTransactionState(context);
try (DBCSession session = context.openSession(monitor, DBCExecutionPurpose.UTIL, "Rollback transaction")) {
txnManager.rollback(session, null);
} catch (DBCException e) {
throw new InvocationTargetException(e);
}
if (context.getDataSource().getContainer().getPreferenceStore().getBoolean(ModelPreferences.TRANSACTIONS_SHOW_NOTIFICATIONS)) {
DBeaverNotifications.showNotification(
context.getDataSource(),
DBeaverNotifications.NT_ROLLBACK,
"Transaction has been rolled back\n\n" +
"Query count: " + txnInfo.getUpdateCount() + "\n" +
"Duration: " + RuntimeUtils.formatExecutionTime(System.currentTimeMillis() - txnInfo.getTransactionStartTime()) + "\n",
DBPMessageType.ERROR,
() -> TransactionLogDialog.showDialog(null, context, true));
}
}
});
}
} |
Lrteeter/OkAlpha | app/controllers/api/messages_controller.rb | <gh_stars>1-10
class Api::MessagesController < ApplicationController
def index
@messages = Message.all
render :index
end
def create
@message = Message.create!(message_params)
render :show
end
def destroy
@message = Message.find(params[:id])
@message.destroy
render :index
end
def update
@message = Message.find(params[:id])
@message.update_attributes(message_params)
render :index
end
private
def message_params
params.require(:message).permit(:sender_id, :receiver_id, :body, :read, :sender_delete, :receiver_delete)
end
end
|
myvyang/intellij-community | java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PropertyGroup.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.structureView.impl.java;
import com.intellij.ide.util.treeView.WeighedItem;
import com.intellij.ide.util.treeView.smartTree.Group;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.navigation.ColoredItemPresentation;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.IconLoader;
import com.intellij.psi.*;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
public class PropertyGroup implements Group, ColoredItemPresentation, AccessLevelProvider, WeighedItem {
private final String myPropertyName;
private final SmartTypePointer myPropertyType;
private SmartPsiElementPointer myFieldPointer;
private SmartPsiElementPointer myGetterPointer;
private SmartPsiElementPointer mySetterPointer;
private boolean myIsStatic;
public static final Icon PROPERTY_READ_ICON = loadIcon("/nodes/propertyRead.png");
public static final Icon PROPERTY_READ_STATIC_ICON = loadIcon("/nodes/propertyReadStatic.png");
public static final Icon PROPERTY_WRITE_ICON = loadIcon("/nodes/propertyWrite.png");
public static final Icon PROPERTY_WRITE_STATIC_ICON = loadIcon("/nodes/propertyWriteStatic.png");
public static final Icon PROPERTY_READ_WRITE_ICON = loadIcon("/nodes/propertyReadWrite.png");
public static final Icon PROPERTY_READ_WRITE_STATIC_ICON = loadIcon("/nodes/propertyReadWriteStatic.png");
private final Project myProject;
private final Collection<TreeElement> myChildren = new ArrayList<TreeElement>();
private PropertyGroup(String propertyName, PsiType propertyType, boolean isStatic, @NotNull Project project) {
myPropertyName = propertyName;
myPropertyType = SmartTypePointerManager.getInstance(project).createSmartTypePointer(propertyType);
myIsStatic = isStatic;
myProject = project;
}
public static PropertyGroup createOn(PsiElement object, final TreeElement treeElement) {
if (object instanceof PsiField) {
PsiField field = (PsiField)object;
PropertyGroup group = new PropertyGroup(PropertyUtil.suggestPropertyName(field), field.getType(),
field.hasModifierProperty(PsiModifier.STATIC), object.getProject());
group.setField(field);
group.myChildren.add(treeElement);
return group;
}
else if (object instanceof PsiMethod) {
PsiMethod method = (PsiMethod)object;
if (PropertyUtil.isSimplePropertyGetter(method)) {
PropertyGroup group = new PropertyGroup(PropertyUtil.getPropertyNameByGetter(method), method.getReturnType(),
method.hasModifierProperty(PsiModifier.STATIC), object.getProject());
group.setGetter(method);
group.myChildren.add(treeElement);
return group;
}
else if (PropertyUtil.isSimplePropertySetter(method)) {
PropertyGroup group =
new PropertyGroup(PropertyUtil.getPropertyNameBySetter(method), method.getParameterList().getParameters()[0].getType(),
method.hasModifierProperty(PsiModifier.STATIC), object.getProject());
group.setSetter(method);
group.myChildren.add(treeElement);
return group;
}
}
return null;
}
@Override
@NotNull
public Collection<TreeElement> getChildren() {
return myChildren;
}
@Override
@NotNull
public ItemPresentation getPresentation() {
return this;
}
@Override
public Icon getIcon(boolean open) {
if (isStatic()) {
if (getGetter() != null && getSetter() != null) {
return PROPERTY_READ_WRITE_STATIC_ICON;
}
else if (getGetter() != null) {
return PROPERTY_READ_STATIC_ICON;
}
else {
return PROPERTY_WRITE_STATIC_ICON;
}
}
else {
if (getGetter() != null && getSetter() != null) {
return PROPERTY_READ_WRITE_ICON;
}
else if (getGetter() != null) {
return PROPERTY_READ_ICON;
}
else {
return PROPERTY_WRITE_ICON;
}
}
}
private boolean isStatic() {
return myIsStatic;
}
@Override
public String getLocationString() {
return null;
}
@Override
public String getPresentableText() {
final PsiType type = getPropertyType();
return myPropertyName + (type != null ? ": " + type.getPresentableText() : "");
}
public String toString() {
return myPropertyName;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PropertyGroup)) return false;
final PropertyGroup propertyGroup = (PropertyGroup)o;
if (myPropertyName != null ? !myPropertyName.equals(propertyGroup.myPropertyName) : propertyGroup.myPropertyName != null) return false;
final PsiType propertyType = getPropertyType();
final PsiType otherPropertyType = propertyGroup.getPropertyType();
if (!Comparing.equal(propertyType, otherPropertyType)) {
return false;
}
return true;
}
public int hashCode() {
return myPropertyName != null ? myPropertyName.hashCode() : 0;
}
public String getGetterName() {
return PropertyUtil.suggestGetterName(myPropertyName, getPropertyType());
}
private PsiType getPropertyType() {
if (myPropertyType == null) {
return null;
}
return myPropertyType.getType();
}
@Override
public int getAccessLevel() {
int result = PsiUtil.ACCESS_LEVEL_PRIVATE;
if (getGetter() != null) {
result = Math.max(result, PsiUtil.getAccessLevel(getGetter().getModifierList()));
}
if (getSetter() != null) {
result = Math.max(result, PsiUtil.getAccessLevel(getSetter().getModifierList()));
}
if (getField() != null) {
result = Math.max(result, PsiUtil.getAccessLevel(getField().getModifierList()));
}
return result;
}
@Override
public int getSubLevel() {
return 0;
}
public void setField(PsiField field) {
myFieldPointer = SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(field);
myIsStatic &= field.hasModifierProperty(PsiModifier.STATIC);
}
public void setGetter(PsiMethod getter) {
myGetterPointer = SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(getter);
myIsStatic &= getter.hasModifierProperty(PsiModifier.STATIC);
}
public void setSetter(PsiMethod setter) {
mySetterPointer = SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(setter);
myIsStatic &= setter.hasModifierProperty(PsiModifier.STATIC);
}
public PsiField getField() {
return (PsiField)(myFieldPointer == null ? null : myFieldPointer.getElement());
}
public PsiMethod getGetter() {
return (PsiMethod)(myGetterPointer == null ? null : myGetterPointer.getElement());
}
public PsiMethod getSetter() {
return (PsiMethod)(mySetterPointer == null ? null : mySetterPointer.getElement());
}
void copyAccessorsFrom(PropertyGroup group) {
if (group.getGetter() != null) setGetter(group.getGetter());
if (group.getSetter() != null) setSetter(group.getSetter());
if (group.getField() != null) setField(group.getField());
myChildren.addAll(group.myChildren);
}
private static Icon loadIcon(@NonNls String resourceName) {
Icon icon = IconLoader.findIcon(resourceName);
Application application = ApplicationManager.getApplication();
if (icon == null && application != null && application.isUnitTestMode()) {
return new ImageIcon();
}
return icon;
}
@Override
public TextAttributesKey getTextAttributesKey() {
return isDeprecated() ? CodeInsightColors.DEPRECATED_ATTRIBUTES : null;
}
private boolean isDeprecated() {
return isDeprecated(getField()) && isDeprecated(getGetter()) && isDeprecated(getSetter());
}
private static boolean isDeprecated(final PsiElement element) {
if (element == null) return false;
if (!element.isValid()) return false;
if (!(element instanceof PsiDocCommentOwner)) return false;
return ((PsiDocCommentOwner)element).isDeprecated();
}
public boolean isComplete() {
return getGetter() != null || getSetter() != null;
}
public Object getValue() {
return this;
}
@Override
public int getWeight() {
return 60;
}
}
|
consected/restructure | app/controllers/reports_controller.rb | <reponame>consected/restructure
# frozen_string_literal: true
class ReportsController < UserBaseController
include MasterSearch
before_action :authenticate_user_or_admin!
before_action :index_authorized?, only: [:index]
before_action :setup_report, only: [:show]
before_action :set_editable_instance_from_id, only: %i[edit update new create]
before_action :set_instance_from_build, only: %i[new create]
before_action :set_master_and_user, only: %i[create update]
after_action :clear_results, only: %i[show run]
helper_method :filters, :filters_on, :index_path, :permitted_params, :filter_params_permitted,
:search_attrs_params_hash, :embedded_report
ResultsLimit = Master.results_limit
attr_accessor :failed
# List of available reports
def index
@no_masters = true
pm = @all_reports_for_user = Report.enabled.for_user(current_user)
pm = filtered_primary_model(pm)
@reports = pm.order auto: :desc, report_type: :asc, position: :asc
@reports = @reports.reject { |r| r.report_options.list_options.hide_in_list }
respond_to do |format|
format.html { render :index }
format.all { render json: @reports.as_json(except: %i[created_at updated_at id admin_id user_id]) }
end
end
# Run report
def show
return not_authorized unless @report.can_access?(current_user) || current_admin
@results_target = 'master_results_block'
setup_data_reference_request
return if failed
@view_context = params[:view_context].blank? ? nil : params[:view_context].to_sym
if params[:commit] == 'count'
@no_masters = true
@runner.count_only = true
end
unless (@report.searchable || show_authorized?) && (current_admin || @report.can_access?(current_user))
@no_masters = true
return
end
if params[:search_attrs] && !no_run
# Search attributes or data reference parameters have been provided
# and the query should be run
begin
@results = @runner.run(search_attrs_params_hash)
if params[:commit] == 'search'
# Based on the results for the report, the MasterHandler uses the ids returned to
# get the results as a masters search, allowing it to be viewed as a search rather
# than tabular report.
run 'REPORT'
return
end
rescue ActiveRecord::PreparedStatementInvalid => e
handle_bad_search_query(e)
return
end
return unless show_authorized? == true
respond_to do |format|
format.html do
if view_mode == 'results'
render partial: 'results'
else
@report_criteria = true
show_report
end
end
format.json do
render json: { results: @results, search_attributes: @runner.search_attr_values }
end
format.csv do
res_a = []
blank_value = nil
blank_value = '' if params[:csv_blank]
res_a << @results.fields.to_csv
@results.each_row do |row|
res_a << (row.collect { |val| val || blank_value }).to_csv
end
send_data res_a.join(''), filename: 'report.csv'
end
end
@master_ids = @results.map { |r| r['master_id'] } if @results
elsif params[:get_filter_previous]
return unless show_authorized? == true
@no_masters = true
render partial: 'filter_on'
else
@no_masters = true
@runner.search_attr_values = search_attrs_params_hash
begin
respond_to do |format|
format.html do
if view_mode == 'form'
render partial: 'form'
else
return unless show_authorized? == true
@report_criteria = true
show_report
end
end
format.json do
render json: { results: @results,
search_attributes: (@runner.search_attr_values || search_attrs_params_hash) }
end
end
rescue StandardError => e
raise e
end
end
end
def edit
render partial: 'edit_form'
end
def new
render partial: 'edit_form'
end
def update
return not_authorized unless @report.editable_data?
if @report_item.update(secure_params)
# Need to update the master_id manually, since it could have been set by a trigger
res = @report_item.class.find(@report_item.id)
@report_item.master_id = res.master_id if res.respond_to?(:master_id) && res.master_id
render json: { report_item: @report_item }
else
logger.warn "Error updating #{@report_item}: #{@report_item.errors.inspect}"
flash.now[:warning] = "Error updating #{@report_item}: #{error_message}"
edit
end
end
def create
if @report_item.save
# Need to update the master_id manually, since it could have been set by a trigger
res = @report_item.class.find(@report_item.id)
@report_item.master_id = res.master_id if res.respond_to?(:master_id) && res.master_id
render json: { report_item: @report_item }
else
logger.warn "Error creating #{@report_item}: #{@report_item.errors.inspect}"
flash.now[:warning] = "Error creating #{@report_item}: #{error_message}"
edit
end
end
def add_to_list
atl_params = params[:add_to_list]
list = Reports::ReportList.setup atl_params[:list_name], atl_params[:items], current_user, current_admin
n = list.add_items_to_list
res = { flash_message_only: "Added #{n} #{'item'.pluralize(n)} to the list" }
render json: res
end
def update_list
atl_params = params[:update_list]
list = Reports::ReportList.setup atl_params[:list_name], atl_params[:items], current_user, current_admin
n = list.update_items_in_list
res = { flash_message_only: "Updated #{n} #{'item'.pluralize(n)} in the list" }
render json: res
end
def remove_from_list
atl_params = params[:remove_from_list]
list = Reports::ReportList.setup atl_params[:list_name], atl_params[:items], current_user, current_admin
ids = list.remove_items_from_list
n = ids.length
render json: { flash_message_only: "Removed #{n} #{'item'.pluralize(n)} from the list.", removed_id: ids }
end
protected
def no_create
true
end
def set_master_and_user
return unless @report_item
if @report_item.respond_to?(:master) && !@report_item.class.no_master_association
@master = @report_item.master
@master.current_user = current_user if @master
elsif @report_item.respond_to? :current_user
@report_item.current_user = current_user
elsif @report_item.respond_to? :user_id
@report_item.user_id = current_user.id
end
@report_item.current_user = current_user if @report_item.respond_to? :current_user=
end
def set_instance_from_build
build_with = begin
secure_params
rescue StandardError
nil
end
@report_item = if report_model.respond_to?(:no_master_association) && report_model.no_master_association ||
!report_model.respond_to?(:master)
report_model.new(build_with)
else
@master.send(report_model.to_s.ns_underscore.pluralize).build(build_with)
end
end
# :id parameter can be either an integer ID, or a string, which looks up a item_type__short_name
# By default it uses the params[:id] for the id, but specifying id as the argument will use this instead
# @param id [(optional) Intger | String]
def setup_report(id = nil)
id ||= params[:id]
redirect_to :index if id.blank?
@report = Report.find_by_id_or_resource_name(id)
@report.current_user = current_user
@runner = @report.runner
end
def setup_data_reference_request
table_name = params[:table_name]
schema_name = params[:schema_name]
table_fields = '*' if params[:table_fields].blank?
return unless table_name && schema_name
unless current_user.can?(:view_data_reference) || current_admin
self.failed = true
not_authorized
return
end
@runner.data_reference.init(table_name: table_name,
schema_name: schema_name,
table_fields: table_fields)
end
def show_report
@runner.search_attr_values ||= search_attrs_params_hash
@report_page = !embedded_report
if embedded_report
@results_target = 'embed_results_block'
render partial: 'show'
else
render :show
end
end
def error_message
res = ''
@report_item.errors.full_messages.each do |message|
res += '; ' unless res.blank?
res += message.to_s
end
res
end
def filters_on
[:item_type]
end
def filters
cats = if @all_reports_for_user
@all_reports_for_user.pluck(:item_type).compact.uniq
else
Report.categories
end
r_cat = cats.map { |g| [g, g.to_s.humanize] }
{ item_type: r_cat.to_h }
end
def filter_defaults
{ item_type: app_config_text(:default_report_tab, nil) }
end
def connection
@connection ||= ActiveRecord::Base.connection
end
def clear_results
# Needed to help control memory usage, according to PG:Result documentation
@results&.clear
end
#
# Allow users to view a report if they have user access control
# read / general / view_reports or view_report_not_list
# @return [true | nil] <description>
def show_authorized?
return true if current_admin
return true if current_user.can?(:view_report_not_list) || current_user.can?(:view_reports)
self.failed = true
not_authorized
throw(:abort)
end
#
# Allow users to see index of reports if they have user access control
# read / general / view_reports
# @return [true | nil] <description>
def index_authorized?
return true if current_admin
return true if current_user.can?(:view_reports)
self.failed = true
not_authorized
throw(:abort)
end
def index_path(par)
reports_path par
end
def handle_bad_search_query(exception)
logger.info "Prepared statement invalid in reports_controller (#{search_attrs_params_hash}) show: " \
"#{exception.inspect}\n#{exception.backtrace.join("\n")}"
@results = nil
@no_masters = true
flash.now[:danger] = "Generated SQL invalid.\n#{@runner.sql}\n#{exception}"
respond_to do |format|
format.html do
if view_mode == 'results'
render plain: "Generated SQL invalid.\n#{@runner.sql}\n#{exception}", status: 400
else
show_report
end
end
format.json do
return general_error 'invalid query for report. Please check search fields or try to run the report again.'
end
end
end
def view_mode
params[:part]
end
### For editable reports
def permitted_params
@permitted_params = @report.edit_fields
end
def secure_params
params.require(report_params_holder).permit(*permitted_params)
end
def set_editable_instance_from_id
id = params[:report_id]
setup_report id
return if params[:id] == 'cancel' || params[:id].blank?
id = params[:id]
id = id.to_i
@report_item = report_model.find(id)
@id = @report_item.id
end
def report_model
@report.edit_model_class
end
def report_params_holder
report_model.to_s.ns_underscore.gsub('__', '_')
end
#
# Permit everything, since this is not used for assignment.
# If the search_attrs param is a string, just return it
def search_attrs_params_hash
@search_attrs_params_hash ||= if params[:search_attrs].nil? || params[:search_attrs] == '_use_defaults_'
@runner.using_defaults = true
{ _use_defaults_: '_use_defaults_' }
else
params.require(:search_attrs).permit!.to_h.dup
end
end
def embedded_report
@embedded_report ||= (params[:embed] == 'true')
end
def no_run
@no_run ||= search_attrs_params_hash[:no_run] == 'true'
end
end
|
NeuronEnix/library-management | api/index.js | <reponame>NeuronEnix/library-management
const router = require( "express" ).Router();
const { isAuthenticated } = require( "../handler").sessionHandler;
router.get( "/", isAuthenticated, ( req, res ) => { return res.redirect( "/user/home" ) });
router.use( "/user", require( "./user" ).UserRouter );
router.use( "/book", isAuthenticated, require( "./book" ).BookRouter );
router.use( "/book", isAuthenticated, require( "./lend" ).LendRouter );
router.use( "/book", isAuthenticated, require( "./pur" ).PurchaseRouter );
module.exports = router;
|
rawarren/MpiABI | src/group_compare.c | <filename>src/group_compare.c
/*
* This text was generated automatically
* It provides the ISC implementation of
* MPI_Group_compare
*/
#include <_mpi.h>
int
MPI_Group_compare (MPI_Group group1, MPI_Group group2, int *result)
{
static void *address=0;
int mpi_return;
if (!address) {
if ((address = dlsym(MPI_libhandle,"MPI_Group_compare")) == NULL) {
printf("%s %s %s",SYM_MISSING_PREFIX,"MPI_Group_compare",SYM_MISSING_TRAILER);
return -1;
}
}
if (active_groups->use_ptrs) { api_use_ptrs *local_a0=active_groups->api_declared;
api_use_ptrs *local_a1=active_groups->api_declared;
int (*VendorMPI_Group_compare)(void *,void *, int *result) = address;
mpi_return = (*VendorMPI_Group_compare)(local_a0[group1].mpi_const,local_a1[group2].mpi_const,result);
} else { api_use_ints *local_a0=active_groups->api_declared;
api_use_ints *local_a1=active_groups->api_declared;
int (*VendorMPI_Group_compare)(int,int, int *result) = address;
mpi_return = (*VendorMPI_Group_compare)(local_a0[group1].mpi_const,local_a1[group2].mpi_const,result);
}
return mpi_return;
}
|
olehmberg/winter-usecases | src/main/java/de/uni_mannheim/informatik/dws/winter/usecase/events/identityresolution/EventBlockingKeyByLabelsTokens.java | package de.uni_mannheim.informatik.dws.winter.usecase.events.identityresolution;
import de.uni_mannheim.informatik.dws.winter.matching.blockers.generators.BlockingKeyGenerator;
import de.uni_mannheim.informatik.dws.winter.matching.blockers.generators.RecordBlockingKeyGenerator;
import de.uni_mannheim.informatik.dws.winter.model.Correspondence;
import de.uni_mannheim.informatik.dws.winter.model.Matchable;
import de.uni_mannheim.informatik.dws.winter.model.Pair;
import de.uni_mannheim.informatik.dws.winter.model.defaultmodel.Attribute;
import de.uni_mannheim.informatik.dws.winter.processing.DataIterator;
import de.uni_mannheim.informatik.dws.winter.processing.Processable;
import de.uni_mannheim.informatik.dws.winter.usecase.events.model.Event;
/**
* {@link BlockingKeyGenerator} for {@link Event}s, which generates a blocking
* key based on all tokens of all labels
*
* @author <NAME>
*
*/
public class EventBlockingKeyByLabelsTokens extends
RecordBlockingKeyGenerator<Event, Attribute> {
private static final long serialVersionUID = 1L;
/* (non-Javadoc)
* @see de.uni_mannheim.informatik.wdi.matching.blocking.generators.BlockingKeyGenerator#generateBlockingKeys(de.uni_mannheim.informatik.wdi.model.Matchable, de.uni_mannheim.informatik.wdi.model.Result, de.uni_mannheim.informatik.wdi.processing.DatasetIterator)
*/
@Override
public void generateBlockingKeys(Event record, Processable<Correspondence<Attribute, Matchable>> correspondences,
DataIterator<Pair<String, Event>> resultCollector) {
for (String label : record.getLabels()) {
for (String token : label.split("\\s+")) {
resultCollector.next(new Pair<>(token, record));
}
}
}
} |
piscesdk/kglb | kglb/data_plane/utils.go | <gh_stars>100-1000
package data_plane
import (
"fmt"
"strings"
"dropbox/kglb/common"
kglb_pb "dropbox/proto/kglb"
)
func diffMetric(new, old uint64) float64 {
if new < old {
return float64(new)
}
return float64(new - old)
}
func getBgpRoutePrefix(route *kglb_pb.BgpRouteAttributes) string {
return fmt.Sprintf("%s/%d",
common.KglbAddrToNetIp(route.GetPrefix()),
route.GetPrefixlen())
}
func getBgpRouteName(route *kglb_pb.BgpRouteAttributes) string {
return strings.Replace(
strings.Replace(getBgpRoutePrefix(route), ":", ".", -1),
" ", "_", -1)
}
// returns either Hostname or IP address.
func getUpstreamHostname(dst *kglb_pb.UpstreamState) string {
if len(dst.Hostname) > 0 {
return dst.Hostname
}
// TODO(belyalov): it used to be reverse hostname resolution here
// however it seems to be redundant (just for stats!)
// If we found that decent amount of upstreams have no hostname
// proper fix would be to resolve hostname when creating (discovering?)
// upstream.
// if no hostname present - return IP
return fmt.Sprintf("%v", common.KglbAddrToNetIp(dst.Address))
}
|
ziyoung/Ccool | src/main/java/net/ziyoung/ccool/parser/ParseErrorListener.java | <reponame>ziyoung/Ccool
package net.ziyoung.ccool.parser;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
public class ParseErrorListener extends BaseErrorListener {
private boolean failed = false;
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
failed = true;
super.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e);
}
public boolean isFailed() {
return failed;
}
}
|
fanruan/swift-http | swift-core/swift-core-analyse/src/test/java/com/fr/swift/cloud/query/aggregator/extension/LimitRowAggregatorTest.java | <reponame>fanruan/swift-http<filename>swift-core/swift-core-analyse/src/test/java/com/fr/swift/cloud/query/aggregator/extension/LimitRowAggregatorTest.java
package com.fr.swift.cloud.query.aggregator.extension;
import com.fr.swift.cloud.bitmap.impl.AllShowBitMap;
import com.fr.swift.cloud.segment.column.Column;
import com.fr.swift.cloud.segment.column.DictionaryEncodedColumn;
import com.fr.swift.cloud.structure.iterator.RowTraversal;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @author Moira
* @date 2020/2/4
* @description
* @since swift 1.0
*/
public class LimitRowAggregatorTest {
@Test
public void testAggregate() {
LimitRowAggregator aggregator = new LimitRowAggregator(1);
RowTraversal traversal = AllShowBitMap.of(5);
IMocksControl control = EasyMock.createControl();
Column mockColumn = control.createMock(Column.class);
DictionaryEncodedColumn dictionaryEncodedColumn = control.createMock(DictionaryEncodedColumn.class);
EasyMock.expect(mockColumn.getDictionaryEncodedColumn()).andReturn(dictionaryEncodedColumn);
EasyMock.expect(dictionaryEncodedColumn.getValueByRow(EasyMock.anyInt())).andReturn("aa");
control.replay();
LimitRowAggregatorValue limitRowAggregatorValue;
limitRowAggregatorValue = aggregator.aggregate(traversal, mockColumn);
List<Object> list = new ArrayList<>();
list.add("aa");
assertEquals(limitRowAggregatorValue.calculateValue(), list);
}
@Test
public void testCombine() {
LimitRowAggregatorValue value = new LimitRowAggregatorValue();
LimitRowAggregatorValue other = new LimitRowAggregatorValue();
List<Object> list1 = new ArrayList<>();
List<Object> list2 = new ArrayList<>();
List<Object> list3 = new ArrayList<>();
list1.add("aa");
list2.add("bb");
list2.add("cc");
list3.addAll(list1);
list3.addAll(list2);
value.setValue(list1);
other.setValue(list2);
LimitRowAggregator aggregator = new LimitRowAggregator(1);
aggregator.combine(value, other);
assertEquals(list3, value.calculateValue());
}
} |
turchan/mediasphere | backEnd/src/main/java/com/turchanovskyi/mediasphere/controller/PurchaseController.java | package com.turchanovskyi.mediasphere.controller;
import com.turchanovskyi.mediasphere.model.Purchase;
import com.turchanovskyi.mediasphere.service.PurchaseService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/purchase")
public class PurchaseController {
private final PurchaseService purchaseService;
public PurchaseController(PurchaseService purchaseService) {
this.purchaseService = purchaseService;
}
@GetMapping
public Iterable<Purchase> getAll()
{
return purchaseService.findAll();
}
@GetMapping("/{purchaseId}")
public Purchase getMaterial(@PathVariable Long purchaseId)
{
return purchaseService.findById(purchaseId);
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/create")
public Purchase create(@RequestBody Purchase purchase)
{
purchase.setId_purchase(null);
purchaseService.save(purchase);
return purchase;
}
@ResponseStatus(HttpStatus.CREATED)
@PutMapping("/update")
public Purchase update(@RequestBody Purchase purchase)
{
purchaseService.save(purchase);
return purchase;
}
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/delete/{purchaseId}")
public void delete(@PathVariable Long purchaseId)
{
purchaseService.deleteById(purchaseId);
}
}
|
frenchamnesty/flixter | vendor/ruby/2.4.0/gems/youtube-embed-1.0.0/lib/youtube_embed.rb | require "youtube_embed/version"
require "youtube_embed/video"
|
ricpdc/ArchiRev | ArchiRev/src/main/java/es/alarcos/archirev/logic/shape/ArchiMateBusinessObjectShape.java | <reponame>ricpdc/ArchiRev<gh_stars>1-10
package es.alarcos.archirev.logic.shape;
public class ArchiMateBusinessObjectShape extends AbstractArchiMateRectangleShape {
@Override
public String getCornerImagePath() {
return null;
}
}
|
covrom/highloadcup2018 | groupset/grresult.go | <reponame>covrom/highloadcup2018<gh_stars>10-100
package groupset
import (
"github.com/covrom/highloadcup2018/db"
"sort"
)
type GroupStats struct {
gs *GroupSet
stats []GroupResult
}
func NewGroupStats(gs *GroupSet) *GroupStats {
return &GroupStats{
gs: gs,
stats: make([]GroupResult, 0, 60),
}
}
func (stg *GroupStats) Result() []GroupResult {
lim := len(stg.stats)
if lim > int(stg.gs.Limit) {
lim = int(stg.gs.Limit)
}
return stg.stats[:lim]
}
func (stg *GroupStats) Update(fwd, rev func(int) bool, gr GroupResult) {
var idx int
if stg.gs.Order > 0 {
idx = sort.Search(len(stg.stats), fwd)
} else {
idx = sort.Search(len(stg.stats), rev)
}
if idx < len(stg.stats) {
if len(stg.stats) < 60 {
stg.stats = append(stg.stats, GroupResult{})
}
copy(stg.stats[idx+1:], stg.stats[idx:])
stg.stats[idx] = gr
} else if len(stg.stats) < 60 {
stg.stats = append(stg.stats, gr)
}
}
func (stg *GroupStats) fwd_sex_country(sex byte, country db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count > v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_sex] < stg.gs.KeysOrder[G_country] {
if stg.stats[ii].Sex > sex {
return true
} else if stg.stats[ii].Sex == sex {
return db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country) >= 0
}
} else {
cmp := db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country)
if cmp > 0 {
return true
} else if cmp == 0 {
return stg.stats[ii].Sex >= sex
}
}
}
return false
}
}
func (stg *GroupStats) rev_sex_country(sex byte, country db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count < v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_sex] < stg.gs.KeysOrder[G_country] {
if stg.stats[ii].Sex < sex {
return true
} else if stg.stats[ii].Sex == sex {
return db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country) <= 0
}
} else {
cmp := db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country)
if cmp < 0 {
return true
} else if cmp == 0 {
return stg.stats[ii].Sex <= sex
}
}
}
return false
}
}
func (stg *GroupStats) fwd_sex_city(sex byte, city db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count > v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_sex] < stg.gs.KeysOrder[G_city] {
if stg.stats[ii].Sex > sex {
return true
} else if stg.stats[ii].Sex == sex {
return db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city) >= 0
}
} else {
cmp := db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city)
if cmp > 0 {
return true
} else if cmp == 0 {
return stg.stats[ii].Sex >= sex
}
}
}
return false
}
}
func (stg *GroupStats) rev_sex_city(sex byte, city db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count < v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_sex] < stg.gs.KeysOrder[G_city] {
if stg.stats[ii].Sex < sex {
return true
} else if stg.stats[ii].Sex == sex {
return db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city) <= 0
}
} else {
cmp := db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city)
if cmp < 0 {
return true
} else if cmp == 0 {
return stg.stats[ii].Sex <= sex
}
}
}
return false
}
}
func (stg *GroupStats) fwd_status_city(status, city db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count > v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_status] < stg.gs.KeysOrder[G_city] {
cmp := db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status)
if cmp > 0 {
return true
} else if cmp == 0 {
return db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city) >= 0
}
} else {
cmp := db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city)
if cmp > 0 {
return true
} else if cmp == 0 {
return db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status) >= 0
}
}
}
return false
}
}
func (stg *GroupStats) rev_status_city(status, city db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count < v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_status] < stg.gs.KeysOrder[G_city] {
cmp := db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status)
if cmp < 0 {
return true
} else if cmp == 0 {
return db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city) <= 0
}
} else {
cmp := db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city)
if cmp < 0 {
return true
} else if cmp == 0 {
return db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status) <= 0
}
}
}
return false
}
}
func (stg *GroupStats) fwd_status_country(status, country db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count > v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_status] < stg.gs.KeysOrder[G_country] {
cmp := db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status)
if cmp > 0 {
return true
} else if cmp == 0 {
return db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country) >= 0
}
} else {
cmp := db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country)
if cmp > 0 {
return true
} else if cmp == 0 {
return db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status) >= 0
}
}
}
return false
}
}
func (stg *GroupStats) rev_status_country(status, country db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
if stg.stats[ii].Count < v {
return true
} else if stg.stats[ii].Count == v {
if stg.gs.KeysOrder[G_status] < stg.gs.KeysOrder[G_country] {
cmp := db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status)
if cmp < 0 {
return true
} else if cmp == 0 {
return db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country) <= 0
}
} else {
cmp := db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country)
if cmp < 0 {
return true
} else if cmp == 0 {
return db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status) <= 0
}
}
}
return false
}
}
func (stg *GroupStats) fwd_sex(sex byte, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count > v || (stg.stats[ii].Count == v && stg.stats[ii].Sex >= sex)
}
}
func (stg *GroupStats) rev_sex(sex byte, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count < v || (stg.stats[ii].Count == v && stg.stats[ii].Sex <= sex)
}
}
func (stg *GroupStats) fwd_country(country db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count > v || (stg.stats[ii].Count == v &&
db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country) >= 0)
}
}
func (stg *GroupStats) rev_country(country db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count < v || (stg.stats[ii].Count == v &&
db.SmAcc.Country.DictonaryCompare(stg.stats[ii].Country, country) <= 0)
}
}
func (stg *GroupStats) fwd_city(city db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count > v || (stg.stats[ii].Count == v &&
db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city) >= 0)
}
}
func (stg *GroupStats) rev_city(city db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count < v || (stg.stats[ii].Count == v &&
db.SmAcc.City.DictonaryCompare(stg.stats[ii].City, city) <= 0)
}
}
func (stg *GroupStats) fwd_status(status db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count > v || (stg.stats[ii].Count == v &&
db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status) >= 0)
}
}
func (stg *GroupStats) rev_status(status db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count < v || (stg.stats[ii].Count == v &&
db.SmAcc.Status.DictonaryCompare(stg.stats[ii].Status, status) <= 0)
}
}
func (stg *GroupStats) fwd_interest(interest db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count > v || (stg.stats[ii].Count == v &&
db.SmAcc.Interests.DictonaryCompare(stg.stats[ii].Interests, interest) >= 0)
}
}
func (stg *GroupStats) rev_interest(interest db.DataEntry, v uint32) func(int) bool {
return func(ii int) bool {
return stg.stats[ii].Count < v || (stg.stats[ii].Count == v &&
db.SmAcc.Interests.DictonaryCompare(stg.stats[ii].Interests, interest) <= 0)
}
}
|
fishedee/redva | examples/dynamic-run/src/common/router.js | <reponame>fishedee/redva
import app from './app';
import dynamic from 'redva/dynamic';
const routers = [
{
url: '/counter',
name: '计数器',
models: ['counter'],
component: 'counter',
},
{
url: '/todo',
name: 'todo列表',
models: ['todo'],
component: 'todo',
},
];
export default routers.map(route => {
return {
url: route.url,
name: route.name,
component: dynamic({
app: app,
models: () => {
return route.models.map(model => {
return import(`../models/${model}`);
});
},
component: () => {
return import(`../routes/${route.component}`);
},
}),
};
});
|
luodeng/study | java/src/main/java/com/roden/study/java/sql/MySQLTest.java | package com.roden.study.java.sql;
import org.junit.Test;
import java.sql.*;
public class MySQLTest {
private static final String URL = "jdbc:mysql://user.sql.sys.com:3306/user?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true";
private static final String NAME = "user";
private static final String PASSWORD = "<PASSWORD>";
@Test
public void mysql5() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery("select * from fastdfs_file limit 10");
while(resultSet.next()){
System.out.println(resultSet.getString("file_path"));
}
}
@Test
public void mysql8() throws SQLException, ClassNotFoundException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Class.forName("com.mysql.cj.jdbc.Driver");
conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/spring?serverTimezone=UTC","luodeng","123456");
ps = conn.prepareStatement("select id,name,create_time from study where name=?;");
ps.setString(1,"mike");
rs = ps.executeQuery();
while(rs.next()) {
int num = rs.getInt("id");
String name = rs.getString("name");
System.out.print(num+"\t"+name);
}
}
} |
sofa-framework/issofa | SofaKernel/framework/sofa/core/objectmodel/BaseData.cpp | <reponame>sofa-framework/issofa<filename>SofaKernel/framework/sofa/core/objectmodel/BaseData.cpp
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: <EMAIL> *
******************************************************************************/
#include <sofa/core/objectmodel/BaseData.h>
#include <sofa/core/objectmodel/Base.h>
#include <sofa/helper/BackTrace.h>
#include <sofa/helper/logging/Messaging.h>
namespace sofa
{
namespace core
{
namespace objectmodel
{
//#define SOFA_DDG_TRACE
BaseData::BaseData(const char* h, DataFlags dataflags)
: help(h), ownerClass(""), group(""), widget("")
, m_counters(), m_isSets(), m_dataFlags(dataflags)
, m_owner(NULL), m_name("")
, parentBaseData(initLink("parent", "Linked Data, from which values are automatically copied"))
{
addLink(&inputs);
addLink(&outputs);
m_counters.assign(0);
m_isSets.assign(false);
//setAutoLink(true);
//if (owner) owner->addData(this);
}
BaseData::BaseData( const char* h, bool isDisplayed, bool isReadOnly)
: help(h), ownerClass(""), group(""), widget("")
, m_counters(), m_isSets(), m_dataFlags(FLAG_DEFAULT), m_owner(NULL), m_name("")
, parentBaseData(initLink("parent", "Linked Data, from which values are automatically copied"))
{
addLink(&inputs);
addLink(&outputs);
m_counters.assign(0);
m_isSets.assign(false);
setFlag(FLAG_DISPLAYED,isDisplayed);
setFlag(FLAG_READONLY,isReadOnly);
//setAutoLink(true);
//if (owner) owner->addData(this);
}
BaseData::BaseData( const BaseInitData& init)
: help(init.helpMsg), ownerClass(init.ownerClass), group(init.group), widget(init.widget)
, m_counters(), m_isSets(), m_dataFlags(init.dataFlags)
, m_owner(init.owner), m_name(init.name)
, parentBaseData(initLink("parent", "Linked Data, from which values are automatically copied"))
{
addLink(&inputs);
addLink(&outputs);
m_counters.assign(0);
m_isSets.assign(false);
if (init.data && init.data != this)
{
{
helper::logging::MessageDispatcher::LoggerStream msgerror = msg_error("BaseData");
msgerror << "initData POINTER MISMATCH: field name \"" << init.name << "\"";
if (init.owner)
msgerror << " created by class " << init.owner->getClassName();
}
sofa::helper::BackTrace::dump();
exit( EXIT_FAILURE );
}
//setAutoLink(true);
if (m_owner) m_owner->addData(this, m_name);
}
BaseData::~BaseData()
{
}
bool BaseData::validParent(BaseData* parent)
{
// Check if automatic conversion is possible
if (this->getValueTypeInfo()->ValidInfo() && parent->getValueTypeInfo()->ValidInfo())
return true;
// Check if one of the data is a simple string
if (this->getValueTypeInfo()->name() == defaulttype::DataTypeInfo<std::string>::name() || parent->getValueTypeInfo()->name() == defaulttype::DataTypeInfo<std::string>::name())
return true;
// No conversion found
return false;
}
bool BaseData::setParent(BaseData* parent, const std::string& path)
{
// First remove previous parents
while (!this->inputs.empty())
this->delInput(*this->inputs.begin());
if (parent && !validParent(parent))
{
if (m_owner)
{
m_owner->serr << "Invalid Data link from " << (parent->m_owner ? parent->m_owner->getName() : std::string("?")) << "." << parent->getName() << " to " << m_owner->getName() << "." << getName() << m_owner->sendl;
if (!this->getValueTypeInfo()->ValidInfo())
m_owner->serr << " Possible reason: destination Data " << getName() << " has an unknown type" << m_owner->sendl;
if (!parent->getValueTypeInfo()->ValidInfo())
m_owner->serr << " Possible reason: source Data " << parent->getName() << " has an unknown type" << m_owner->sendl;
}
return false;
}
doSetParent(parent);
if (!path.empty())
parentBaseData.set(parent, path);
if (parent)
{
addInput(parent);
BaseData::setDirtyValue();
if (!isCounterValid())
update();
m_counters[currentAspect()]++;
m_isSets[currentAspect()] = true;
}
return true;
}
bool BaseData::setParent(const std::string& path)
{
BaseData* parent = NULL;
if (this->findDataLinkDest(parent, path, &parentBaseData))
return setParent(parent, path);
else // simply set the path
{
if (parentBaseData.get())
this->delInput(parentBaseData.get());
parentBaseData.set(parent, path);
return false;
}
}
void BaseData::doSetParent(BaseData* parent)
{
parentBaseData.set(parent);
}
void BaseData::doDelInput(DDGNode* n)
{
if (parentBaseData == n)
doSetParent(NULL);
DDGNode::doDelInput(n);
}
SOFA_CORE_API int logDataUpdates = 0;
void BaseData::update()
{
cleanDirty();
if (logDataUpdates)
{
std::cout << "Data " << m_name;
if (m_owner)
std::cout << " in " << m_owner->getTypeName() << " " << m_owner->getName();
std::cout << " update";
if (parentBaseData)
{
std::cout << " from parent " << parentBaseData->m_name;
if (parentBaseData->m_owner)
std::cout << " in " << parentBaseData->m_owner->getTypeName() << " " << parentBaseData->m_owner->getName();
}
else
{
std::cout << " from " << inputs.size() << " inputs";
}
std::cout << std::endl;
}
for(DDGLinkIterator it=inputs.begin(); it!=inputs.end(); ++it)
{
(*it)->updateIfDirty();
}
if (parentBaseData)
{
#ifdef SOFA_DDG_TRACE
if (m_owner)
m_owner->sout << "Data " << m_name << ": update from parent " << parentBaseData->m_name<< m_owner->sendl;
#endif
updateFromParentValue(parentBaseData);
// If the value is dirty clean it
if(this->isDirty())
{
cleanDirty();
}
}
}
/// Update this Data from the value of its parent
bool BaseData::updateFromParentValue(const BaseData* parent)
{
const defaulttype::AbstractTypeInfo* dataInfo = this->getValueTypeInfo();
const defaulttype::AbstractTypeInfo* parentInfo = parent->getValueTypeInfo();
// Check if one of the data is a simple string
if (this->getValueTypeInfo()->name() == defaulttype::DataTypeInfo<std::string>::name() || parent->getValueTypeInfo()->name() == defaulttype::DataTypeInfo<std::string>::name())
{
std::string text = parent->getValueString();
return this->read(text);
}
// Check if automatic conversion is possible
if (!dataInfo->ValidInfo() || !parentInfo->ValidInfo())
return false; // No conversion found
std::ostringstream msgs;
const void* parentValue = parent->getValueVoidPtr();
void* dataValue = this->beginEditVoidPtr();
// First decide how many values will be copied
std::size_t inSize = 1;
std::size_t outSize = 1;
std::size_t copySize = 1;
std::size_t nbl = 1;
if (dataInfo->FixedSize())
{
outSize = dataInfo->size();
inSize = parentInfo->size(parentValue);
if (outSize > inSize)
{
msgs << "parent Data type " << parentInfo->name() << " contains " << inSize << " values while Data type " << dataInfo->name() << " requires " << outSize << " values.";
copySize = inSize;
}
else if (outSize < inSize)
{
msgs << "parent Data type " << parentInfo->name() << " contains " << inSize << " values while Data type " << dataInfo->name() << " only requires " << outSize << " values.";
copySize = outSize;
}
else
copySize = outSize;
}
else
{
std::size_t dataBSize = dataInfo->size();
std::size_t parentBSize = parentInfo->size();
if (dataBSize > parentBSize)
msgs << "parent Data type " << parentInfo->name() << " contains " << parentBSize << " values per element while Data type " << dataInfo->name() << " requires " << dataBSize << " values.";
else if (dataBSize < parentBSize)
msgs << "parent Data type " << parentInfo->name() << " contains " << parentBSize << " values per element while Data type " << dataInfo->name() << " only requires " << dataBSize << " values.";
std::size_t parentSize = parentInfo->size(parentValue);
inSize = parentBSize;
outSize = dataBSize;
nbl = parentSize / parentBSize;
copySize = (dataBSize < parentBSize) ? dataBSize : parentBSize;
dataInfo->setSize(dataValue, outSize * nbl);
}
// Then select the besttype for values transfer
if (dataInfo->Integer() && parentInfo->Integer())
{
// integer conversion
for (size_t l=0; l<nbl; ++l)
for (size_t c=0; c<copySize; ++c)
dataInfo->setIntegerValue(dataValue, l*outSize+c, parentInfo->getIntegerValue(parentValue, l*inSize+c));
}
else if ((dataInfo->Integer() || dataInfo->Scalar()) && (parentInfo->Integer() || parentInfo->Scalar()))
{
// scalar conversion
for (size_t l=0; l<nbl; ++l)
for (size_t c=0; c<copySize; ++c)
dataInfo->setScalarValue(dataValue, l*outSize+c, parentInfo->getScalarValue(parentValue, l*inSize+c));
}
else
{
// text conversion
for (size_t l=0; l<nbl; ++l)
for (size_t c=0; c<copySize; ++c)
dataInfo->setTextValue(dataValue, l*outSize+c, parentInfo->getTextValue(parentValue, l*inSize+c));
}
std::string m = msgs.str();
if (m_owner
//#ifdef NDEBUG
&& (!m.empty() || m_owner->f_printLog.getValue())
//#endif
)
{
m_owner->sout << "Data link from " << (parent->m_owner ? parent->m_owner->getName() : std::string("?")) << "." << parent->getName() << " to " << m_owner->getName() << "." << getName() << " : ";
if (!m.empty()) m_owner->sout << m;
else m_owner->sout << "OK, " << nbl << "*"<<copySize<<" values copied.";
m_owner->sout << m_owner->sendl;
}
return true;
}
/// Copy the value of another Data.
/// Note that this is a one-time copy and not a permanent link (otherwise see setParent)
/// @return true if copy was successfull
bool BaseData::copyValue(const BaseData* parent)
{
if (updateFromParentValue(parent))
return true;
return false;
}
bool BaseData::findDataLinkDest(DDGNode*& ptr, const std::string& path, const BaseLink* link)
{
return DDGNode::findDataLinkDest(ptr, path, link);
}
bool BaseData::findDataLinkDest(BaseData*& ptr, const std::string& path, const BaseLink* link)
{
if (m_owner)
return m_owner->findDataLinkDest(ptr, path, link);
else
{
msg_error("BaseData") << "findDataLinkDest: no owner defined for Data " << getName() << ", cannot lookup Data link " << path;
return false;
}
}
/// Add a link.
/// Note that this method should only be called if the link was not initialized with the initLink method
void BaseData::addLink(BaseLink* l)
{
m_vecLink.push_back(l);
//l->setOwner(this);
}
void BaseData::copyAspect(int destAspect, int srcAspect)
{
m_counters[destAspect] = m_counters[srcAspect];
m_isSets[destAspect] = m_isSets[srcAspect];
DDGNode::copyAspect(destAspect, srcAspect);
for(VecLink::const_iterator iLink = m_vecLink.begin(); iLink != m_vecLink.end(); ++iLink)
{
//std::cout << " " << iLink->first;
(*iLink)->copyAspect(destAspect, srcAspect);
}
}
void BaseData::releaseAspect(int aspect)
{
for(VecLink::const_iterator iLink = m_vecLink.begin(); iLink != m_vecLink.end(); ++iLink)
{
(*iLink)->releaseAspect(aspect);
}
}
std::string BaseData::decodeTypeName(const std::type_info& t)
{
return BaseClass::decodeTypeName(t);
}
} // namespace objectmodel
} // namespace core
} // namespace sofa
|
tuchg/SimpleJWManageSystem | Backend/2_11_JWCSystem/src/cn/wchihc/jwc/servlets/teacher/QueryServlet.java | package cn.wchihc.jwc.servlets.teacher;
import cn.wchihc.jwc.dao.base.BaseDao;
import cn.wchihc.jwc.model.Data;
import cn.wchihc.jwc.model.Query;
import cn.wchihc.jwc.model.custom.ClassStudentCustom;
import cn.wchihc.jwc.model.custom.MyStudentCustom;
import cn.wchihc.jwc.model.users.Student;
import cn.wchihc.jwc.servlets.teacher.base.TeacherServlet;
import cn.wchihc.jwc.utils.Constants;
import cn.wchihc.jwc.model.other.Course;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet(name = "教师-查", urlPatterns = "/api/teacher/list/*")
public class QueryServlet extends TeacherServlet {
@Override
protected void GET(String router, Query query, HttpServletRequest request, HttpServletResponse response) throws IOException {
super.GET(router, query, request, response);
//从当前会话获取用户
Object userId = request.getSession().getAttribute("user_id");
if (userId != null) {
switch (router) {
case "course":
BaseDao<Course> c = BaseDao.select(Course.class)
.where(BaseDao.eq("t_id", (Integer) userId))
.and();
switch (query.getStatus()) {
case "已满":
c.append("max_choose_num=selected_num").and();
break;
case "未满":
c.append("not max_choose_num=selected_num").and();
break;
}
c.like("cname", query.getContent())
.orderBy("id", query.getSort());
handleDataQueryWrap(query, c, Course.class);
result.setCode(Constants.SUCCESS_CODE);
result.setMessage("查询成功");
break;
case "student":
BaseDao<Course> courseBaseDao =
BaseDao.customSelect("elective.id,elective.cs_id,elective.st_id,s.sno,s.name,course.cname,s.sex,s.f_id,elective.score", Course.class)
.join("elective", "course.id = elective.cs_id")
.join("student s", "elective.st_id = s.id")
.where(BaseDao.eq("t_id", (Integer) userId))
.and();
//对查询的解析
if (query.getFaculty() != null && !query.getFaculty().isEmpty()) {
courseBaseDao.append(BaseDao.eq("f_id", query.getFaculty()))
.and();
}
//默认搜索姓名
String type = "name";
switch (query.getType()) {
case "1":
type = "sno";
break;
case "2":
type = "cname";
break;
}
courseBaseDao.like(type, query.getContent())
.orderBy("sno", query.getSort());
handleDataQueryWrap(query, courseBaseDao, MyStudentCustom.class);
result.setCode(Constants.SUCCESS_CODE);
result.setMessage("查询成功");
break;
case "courseStudents":
BaseDao<Student> dao = BaseDao.customSelect("student.id as s_id,name,sno,sex,e.id as e_id,f_id,cs_id as c_id", Student.class)
.join(" elective e", "student.id = e.st_id")
.where(BaseDao.eq("e.cs_id", query.getId()));
handleDataQueryWrap(query, dao, ClassStudentCustom.class);
break;
}
} else {
result.setCode(Constants.ILL_TOKEN_CODE);
result.setMessage("登录信息丢失");
}
}
/**
* 分页处理复合查询
* <p>
* 并打包要用来响应的数据
*
* @param query
* @param selects
* @param clazz
* @param <T>
* @param <C>
*/
private <T, C> void handleDataQueryWrap(Query query, BaseDao<T> selects, Class<C> clazz) {
Data<C> titles = new Data<>(selects.getTotalSize(),
findByPage(query, selects, clazz));
result.setData(titles);
}
/**
* 分页
*
* @param query 分页查询串
* @param selects 自定义查询语句
* @param clazz 返回类型
* @param <T> 查询的主表
* @param <C> 返回的类型
* @return 分页查询结果
*/
private <T, C> List<C> findByPage(Query query, BaseDao<T> selects, Class<C> clazz) {
return selects.byPage(query.getPage(), query.getLimit())
.executeCustomQuery(clazz);
}
}
|
hitachivantara-solution/sdk-examples-java | hitachivantara-java-example-hcp/src/com/hitachivantara/example/hcp/content/S3Example_PutGetDeleteObject.java | /*
* Copyright (C) 2019 <NAME> Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hitachivantara.example.hcp.content;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.Protocol;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.hitachivantara.common.util.DigestUtils;
import com.hitachivantara.common.util.StreamUtils;
import com.hitachivantara.example.hcp.util.Account;
/**
* S3 对象文件存、删、取示例
* @author sohan
*
*/
public class S3Example_PutGetDeleteObject {
public static void main(String[] args) throws IOException {
AmazonS3 hs3Client = null;
{
// 创建S3客户端,只需要创建一次客户端,请将endpoint及用户名密码更改为您的HCP配置
// Create s3 client
// 指定需要登录的HCP 租户 及 桶
String endpoint = Account.endpoint;
// 登录需要的用户名
// The access key encoded by Base64
String accessKey = Account.accessKey;
// 登录需要的密码
// The AWS secret access key encrypted by MD5
String secretKey = Account.secretKey;
com.amazonaws.ClientConfiguration clientConfig = new com.amazonaws.ClientConfiguration();
// Using HTTP protocol
clientConfig.setProtocol(Protocol.HTTP);
// clientConfig.setSignerOverride("AWS4SignerType");
clientConfig.setSignerOverride("S3SignerType");
// clientConfig.setProxyHost("localhost");
// clientConfig.setProxyPort(8080);
hs3Client = AmazonS3ClientBuilder.standard()
.withClientConfiguration(clientConfig)
.withEndpointConfiguration(new EndpointConfiguration(endpoint, ""))
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.build();
}
S3Object s3Object = null;
// Here is the file will be uploaded into HCP
File file = Account.localFile1;
// The location in HCP where this file will be stored.
String key = "example-hcp/subfolder1/" + file.getName();
String bucketName = Account.namespace;
{
try {
// 上传文件至HCP
// 上传前无需刻意创建目录,只需指定存储路径
// Inject file into HCP system.
hs3Client.putObject(bucketName, key, file);
// Check whether object exist.
// boolean exist = hs3Client.doesObjectExist(bucketName, key);
// assertTrue(exist == true);
// Get the object from HCP
s3Object = hs3Client.getObject(bucketName, key);
} catch (AmazonServiceException e) {
e.printStackTrace();
return;
} catch (SdkClientException e) {
e.printStackTrace();
return;
}
}
// ↓↓↓=*=*=* CODE JUST FOR DEMONSTRATE, UNNECESSARY IN PRODUCTION ENVIRONMENT *=*=*=↓↓↓
// Verify result:
S3ObjectInputStream in = s3Object.getObjectContent();
// StreamUtils.inputStreamToFile(in, filePath, true);
// StreamUtils.inputStreamToConsole(in, true);
byte[] orginalFileMd5 = DigestUtils.calcMD5(file);
byte[] objectFromHCPMd5 = DigestUtils.calcMD5(in);
in.close();
//
boolean equals = Arrays.equals(orginalFileMd5, objectFromHCPMd5);
assertTrue(equals == true);
// ↑↑↑=*=*=* CODE JUST FOR DEMONSTRATE, UNNECESSARY IN PRODUCTION ENVIRONMENT *=*=*=↑↑↑
{
hs3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys("111","222"));
// Delete object in HCP.
hs3Client.deleteObject(bucketName, key);
// Check whether object exist.
// boolean exist = hs3Client.doesObjectExist(bucketName, key);
// assertTrue(exist == false);
}
System.out.println("Well done!");
}
}
|
gawquon/Vic2ToHoI4 | Vic2ToHoI4Tests/OutHoI4Tests/Characters/OutCommanderDataTests.cpp | #include "OutHoi4/Characters/OutCommanderData.h"
#include "gmock/gmock-matchers.h"
#include "gtest/gtest.h"
#include <sstream>
TEST(OutHoI4World_Characters_OutCommanderDataTests, CommanderDataIsOutput)
{
const HoI4::CommanderData commanderData(HoI4::CommanderLevel::CorpsCommander, {}, 2, 3, 4, 5, 6);
std::stringstream output;
output << commanderData;
std::stringstream expected;
expected << "\t\tcorps_commander={\n";
expected << "\t\t\tskill=2\n";
expected << "\t\t\tattack_skill=3\n";
expected << "\t\t\tdefense_skill=4\n";
expected << "\t\t\tplanning_skill=5\n";
expected << "\t\t\tlogistics_skill=6\n";
expected << "\t\t\tlegacy_id=0\n";
expected << "\t\t}\n";
EXPECT_EQ(output.str(), expected.str());
}
TEST(OutHoI4World_Characters_OutCommanderDataTests, FieldMarshalLevelIsOutput)
{
const HoI4::CommanderData commanderData(HoI4::CommanderLevel::FieldMarshal, {}, 2, 3, 4, 5, 6);
std::stringstream output;
output << commanderData;
std::stringstream expected;
expected << "\t\tfield_marshal={\n";
expected << "\t\t\tskill=2\n";
expected << "\t\t\tattack_skill=3\n";
expected << "\t\t\tdefense_skill=4\n";
expected << "\t\t\tplanning_skill=5\n";
expected << "\t\t\tlogistics_skill=6\n";
expected << "\t\t\tlegacy_id=0\n";
expected << "\t\t}\n";
EXPECT_EQ(output.str(), expected.str());
}
TEST(OutHoI4World_Characters_OutCommanderDataTests, TraitsAreOutput)
{
const HoI4::CommanderData
commanderData(HoI4::CommanderLevel::CorpsCommander, {"test_trait_1", "test_trait_2"}, 2, 3, 4, 5, 6);
std::stringstream output;
output << commanderData;
std::stringstream expected;
expected << "\t\tcorps_commander={\n";
expected << "\t\t\ttraits={ test_trait_1 test_trait_2 }\n";
expected << "\t\t\tskill=2\n";
expected << "\t\t\tattack_skill=3\n";
expected << "\t\t\tdefense_skill=4\n";
expected << "\t\t\tplanning_skill=5\n";
expected << "\t\t\tlogistics_skill=6\n";
expected << "\t\t\tlegacy_id=0\n";
expected << "\t\t}\n";
EXPECT_EQ(output.str(), expected.str());
} |
ShoYamanishi/AppleNumericalComputing | 06_nbody/metal/nbody_metal_objc.h | #import "metal_compute_base.h"
#include "nbody_metal_cpp.h"
@interface NBodyMetalObjC : MetalComputeBase
- (instancetype) initWithNumElements:(size_t) num_elements ;
- (uint) numElements;
- (struct particle*) getRawPointerParticles;
- (void) performComputationDirectionIsP0ToP1:(bool) p0_to_p1;
@end
|
DelinWorks/adxe | core/network/HttpCookie.h | <reponame>DelinWorks/adxe
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2021 Bytedance Inc.
https://adxeproject.github.io/
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.
****************************************************************************/
#ifndef HTTP_COOKIE_H
#define HTTP_COOKIE_H
/// @cond DO_NOT_SHOW
#include "platform/CCPlatformMacros.h"
#include <string.h>
#include <string>
#include <vector>
NS_CC_BEGIN
namespace network
{
class Uri;
struct CookieInfo
{
CookieInfo() = default;
CookieInfo(const CookieInfo&) = default;
CookieInfo(CookieInfo&& rhs)
: domain(std::move(rhs.domain))
, tailmatch(rhs.tailmatch)
, path(std::move(rhs.path))
, secure(rhs.secure)
, name(std::move(rhs.name))
, value(std::move(rhs.value))
, expires(rhs.expires)
{}
CookieInfo& operator=(CookieInfo&& rhs)
{
domain = std::move(rhs.domain);
tailmatch = rhs.tailmatch;
path = std::move(rhs.path);
secure = rhs.secure;
name = std::move(rhs.name);
value = std::move(rhs.value);
expires = rhs.expires;
return *this;
}
bool isSame(const CookieInfo& rhs) { return name == rhs.name && domain == rhs.domain; }
void updateValue(const CookieInfo& rhs)
{
value = rhs.value;
expires = rhs.expires;
path = rhs.path;
}
std::string domain;
bool tailmatch = true;
std::string path;
bool secure = false;
std::string name;
std::string value;
time_t expires = 0;
};
class HttpCookie
{
public:
void readFile();
void writeFile();
void setCookieFileName(std::string_view fileName);
const std::vector<CookieInfo>* getCookies() const;
const CookieInfo* getMatchCookie(const Uri& uri) const;
void updateOrAddCookie(CookieInfo* cookie);
// Check match cookies for http request
std::string checkAndGetFormatedMatchCookies(const Uri& uri);
bool updateOrAddCookie(std::string_view cookie, const Uri& uri);
private:
std::string _cookieFileName;
std::vector<CookieInfo> _cookies;
};
} // namespace network
NS_CC_END
/// @endcond
#endif /* HTTP_COOKIE_H */
|
micaelps/orange-talents-02-template-proposta | src/main/java/br/com/zup/proposta/blockedcard/BlockedCardController.java | <reponame>micaelps/orange-talents-02-template-proposta
package br.com.zup.proposta.blockedcard;
import br.com.zup.proposta.card.AllCards;
import br.com.zup.proposta.card.Card;
import br.com.zup.proposta.common.CardVerificationClient;
import br.com.zup.proposta.common.ClientHostResolver;
import feign.FeignException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RestController
class BlockedCardController {
final CardVerificationClient cardVerificationClient;
final EntityManager entityManager;
final AllBlockedCards allBlockedCards;
final AllCards allCards;
public BlockedCardController(CardVerificationClient cardVerificationClient, EntityManager entityManager, AllBlockedCards allBlockedCards, AllCards allCards) {
this.cardVerificationClient = cardVerificationClient;
this.entityManager = entityManager;
this.allBlockedCards = allBlockedCards;
this.allCards = allCards;
}
@PostMapping("/api/lock/cards/{idCard}")
public ResponseEntity<?> LockCard(HttpServletRequest httpServletRequest, @PathVariable Long idCard,
@RequestHeader(value = "User-Agent") String userAgent, @RequestBody NewBlockedCardRequest request) {
String clientHostResolver = new ClientHostResolver(httpServletRequest).resolve();
return allCards.findById(idCard)
.map(c-> block(c, request))
.map(c-> new BlockedCard(c.getExternalCardId(), clientHostResolver, userAgent))
.map(allBlockedCards::save)
.map(x -> ResponseEntity.ok().build())
.orElseGet(() -> ResponseEntity.notFound().build());
}
private Card block(Card card, NewBlockedCardRequest request) {
try {
cardVerificationClient.lock(card.getExternalCardId(), request);
card.block();
return card;
} catch (FeignException.UnprocessableEntity feue) {
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|
trespasserw/MPS | editor/editorlang-runtime/source/jetbrains/mps/editor/runtime/cells/KeyMapImpl.java | /*
* Copyright 2003-2013 JetBrains s.r.o.
*
* 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 jetbrains.mps.editor.runtime.cells;
import jetbrains.mps.openapi.editor.cells.KeyMap;
import jetbrains.mps.openapi.editor.cells.KeyMapAction;
import jetbrains.mps.util.Pair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* User: shatalin
* Date: 2/8/13
*/
public class KeyMapImpl implements KeyMap {
private boolean myApplicableToEveryModel = false;
private List<KeyMap> myChildKeyMaps;
private HashMap<ActionKey, KeyMapAction> myActionMap = new HashMap<>();
private List<Pair<ActionKey, KeyMapAction>> myDuplicatedActionList;
@Override
public boolean isApplicableToEveryModel() {
return myApplicableToEveryModel;
}
public void setApplicableToEveryModel(boolean isApplicable) {
myApplicableToEveryModel = isApplicable;
}
@Override
public void addKeyMap(KeyMap keyMap) {
if (myChildKeyMaps == null) {
myChildKeyMaps = new LinkedList<>();
}
myChildKeyMaps.add(keyMap);
}
@Override
public void putAction(String modifiers, String keyCode, KeyMapAction action) {
boolean keyTyped = keyCode.length() == 1;
ActionKey key = new ActionKey(modifiers, keyCode, keyTyped);
if (!myActionMap.containsKey(key)) {
myActionMap.put(key, action);
} else {
if (myDuplicatedActionList == null) {
myDuplicatedActionList = new LinkedList<>();
}
myDuplicatedActionList.add(new Pair<>(key, action));
}
}
@Override
public Collection<KeyMapAction> getActions(Collection<ActionKey> keys) {
return getActions(keys, new ArrayList<>());
}
private Collection<KeyMapAction> getActions(Collection<KeyMap.ActionKey> keys, Collection<KeyMapAction> result) {
for (ActionKey actionKey : keys) {
KeyMapAction action = myActionMap.get(actionKey);
if (action != null) {
result.add(action);
if (myDuplicatedActionList != null) {
for (Pair<ActionKey, KeyMapAction> pair : myDuplicatedActionList) {
if (pair.o1.equals(actionKey)) {
result.add(pair.o2);
}
}
}
}
}
if (myChildKeyMaps != null) {
for (KeyMap childKeyMap : myChildKeyMaps) {
if (childKeyMap instanceof KeyMapImpl) {
((KeyMapImpl) childKeyMap).getActions(keys, result);
} else {
result.addAll(childKeyMap.getActions(keys));
}
}
}
return result;
}
@Override
public Collection<KeyMapAction> getAllActions() {
return getAllActions(new ArrayList<>());
}
private Collection<KeyMapAction> getAllActions(Collection<KeyMapAction> result) {
result.addAll(myActionMap.values());
if (myDuplicatedActionList != null) {
for (Pair<ActionKey, KeyMapAction> pair : myDuplicatedActionList) {
result.add(pair.o2);
}
}
if (myChildKeyMaps != null) {
for (KeyMap childKeyMap : myChildKeyMaps) {
if (childKeyMap instanceof KeyMapImpl) {
((KeyMapImpl) childKeyMap).getAllActions(result);
} else {
result.addAll(childKeyMap.getAllActions());
}
}
}
return result;
}
@Override
public Collection<ActionKey> getActionKeys() {
return getActionKeys(new HashSet<>());
}
private Collection<ActionKey> getActionKeys(Set<ActionKey> result) {
result.addAll(myActionMap.keySet());
if (myChildKeyMaps != null) {
for (KeyMap childKeyMap : myChildKeyMaps) {
if (childKeyMap instanceof KeyMapImpl) {
((KeyMapImpl) childKeyMap).getActionKeys(result);
} else {
result.addAll(childKeyMap.getActionKeys());
}
}
}
return result;
}
}
|
friedolino78/rtosc | example/modular/Effect.h | #pragma once
namespace rtosc{struct Ports;}
struct Effect
{
virtual ~Effect(void){};
};
|
augustobellinaso/Deitel-JavaHowToProgram10E-LateObjects | Chapter5/Exercise 5.31/ModifiedGuessNumber.java | /*Modify the program of Exercise 5.30 to count the num-
ber of guesses the player makes. If the number is 10 or fewer, display Either you know the secret
or you got lucky! If the player guesses the number in 10 tries, display Aha! You know the secret!
If the player makes more than 10 guesses, display You should be able to do better! Why should it
take no more than 10 guesses? Well, with each “good guess,” the player should be able to eliminate
half of the numbers, then half of the remaining numbers, and so on*/
/*
* <NAME>
*/
import java.util.Scanner;
import java.security.SecureRandom;
public class ModifiedGuessNumber {
//main method
public static void main(String[] args) {
//variables
Scanner input = new Scanner(System.in);
SecureRandom randomNumber = new SecureRandom();
int guess; //to store the guess made by user
int choice; //to store the choice made by user after guessing the number]
int count = 1; //to store the number of attempts made
boolean guessAgain = false; //to control the execution of the loop
//displaying prompt and loop
while (!guessAgain) {
System.out.print("Guess a number between 1 and 1000: ");
guess = input.nextInt();
int programNumber = 1 + randomNumber.nextInt(1000); //random number chosen by computer
while (guess != programNumber) {
if (guess > programNumber) {
System.out.println("Too high! Try again.");
count++;
} else if (guess < programNumber) {
System.out.println("Too low! Try again.");
count++;
}
guess = input.nextInt();
}//end while
System.out.print("Congratulations! You guesse the number!\n");
if (count <= 10) {
System.out.println("Aha! You know the secret!");
} else {
System.out.println("You should be able to do better!");
}
System.out.print("Enter 1 to play again or 2 to exit: ");
choice = input.nextInt();
if (choice == 1) {
guessAgain = false;
count = 1;
} else {
guessAgain = true;
}//end if
}//end while
}//end main
}
|
abhishekpradeepmishra/amazon-neptune-tools | neptune-export/src/main/java/com/amazonaws/services/neptune/profiles/neptune_ml/v2/config/ElementConfig.java | /*
Copyright 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://www.apache.org/licenses/LICENSE-2.0
or in the "license" file accompanying this file. This file is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License.
*/
package com.amazonaws.services.neptune.profiles.neptune_ml.v2.config;
import com.amazonaws.services.neptune.profiles.neptune_ml.common.config.Word2VecConfig;
import com.amazonaws.services.neptune.propertygraph.Label;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
public class ElementConfig {
public static final ElementConfig EMPTY_CONFIG = new ElementConfig(
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList());
private final Collection<LabelConfigV2> classLabels;
private final Collection<NoneFeatureConfig> noneFeatures;
private final Collection<TfIdfConfigV2> tfIdfFeatures;
private final Collection<DatetimeConfigV2> datetimeFeatures;
private final Collection<Word2VecConfig> word2VecFeatures;
private final Collection<FastTextConfig> fastTextFeatures;
private final Collection<SbertConfig> sbertFeatures;
private final Collection<NumericalBucketFeatureConfigV2> numericalBucketFeatures;
private final Collection<FeatureOverrideConfigV2> featureOverrides;
public ElementConfig(Collection<LabelConfigV2> classLabels,
Collection<NoneFeatureConfig> noneFeatures,
Collection<TfIdfConfigV2> tfIdfFeatures,
Collection<DatetimeConfigV2> datetimeFeatures,
Collection<Word2VecConfig> word2VecFeatures,
Collection<FastTextConfig> fastTextFeatures,
Collection<SbertConfig> sbertFeatures,
Collection<NumericalBucketFeatureConfigV2> numericalBucketFeatures,
Collection<FeatureOverrideConfigV2> featureOverrides) {
this.classLabels = classLabels;
this.noneFeatures = noneFeatures;
this.tfIdfFeatures = tfIdfFeatures;
this.datetimeFeatures = datetimeFeatures;
this.word2VecFeatures = word2VecFeatures;
this.fastTextFeatures = fastTextFeatures;
this.sbertFeatures = sbertFeatures;
this.numericalBucketFeatures = numericalBucketFeatures;
this.featureOverrides = featureOverrides;
}
public boolean allowAutoInferFeature(Label label, String property){
if (hasClassificationSpecificationForProperty(label, property)) {
return false;
}
if (hasNoneFeatureSpecification(label, property)){
return false;
}
if (hasTfIdfSpecification(label, property)){
return false;
}
if (hasDatetimeSpecification(label, property)){
return false;
}
if (hasWord2VecSpecification(label, property)){
return false;
}
if (hasFastTextSpecification(label, property)){
return false;
}
if (hasSbertSpecification(label, property)){
return false;
}
if (hasNumericalBucketSpecification(label, property)){
return false;
}
if (hasFeatureOverrideForProperty(label, property)){
return false;
}
return true;
}
public boolean hasClassificationSpecificationsFor(Label label) {
return !getClassificationSpecifications(label).isEmpty();
}
public Collection<LabelConfigV2> getClassificationSpecifications(Label label) {
return classLabels.stream().filter(c -> c.label().equals(label)).collect(Collectors.toList());
}
public boolean hasClassificationSpecificationForProperty(Label label, String property) {
return getClassificationSpecifications(label).stream().anyMatch(s -> s.property().equals(property));
}
public Collection<LabelConfigV2> getAllClassificationSpecifications(){
return classLabels;
}
public boolean hasNoneFeatureSpecification(Label label, String property) {
return getNoneFeatureSpecification(label, property) != null;
}
public NoneFeatureConfig getNoneFeatureSpecification(Label label, String property) {
return noneFeatures.stream()
.filter(config ->
config.label().equals(label) &&
config.property().equals(property))
.findFirst()
.orElse(null);
}
public boolean hasTfIdfSpecification(Label label, String property) {
return getTfIdfSpecification(label, property) != null;
}
public TfIdfConfigV2 getTfIdfSpecification(Label label, String property) {
return tfIdfFeatures.stream()
.filter(config ->
config.label().equals(label) &&
config.property().equals(property))
.findFirst()
.orElse(null);
}
public boolean hasDatetimeSpecification(Label label, String property) {
return getDatetimeSpecification(label, property) != null;
}
public DatetimeConfigV2 getDatetimeSpecification(Label label, String property) {
return datetimeFeatures.stream()
.filter(config ->
config.label().equals(label) &&
config.property().equals(property))
.findFirst()
.orElse(null);
}
public boolean hasWord2VecSpecification(Label label, String property) {
return getWord2VecSpecification(label, property) != null;
}
public Word2VecConfig getWord2VecSpecification(Label label, String property) {
return word2VecFeatures.stream()
.filter(config ->
config.label().equals(label) &&
config.property().equals(property))
.findFirst()
.orElse(null);
}
public boolean hasFastTextSpecification(Label label, String property) {
return getFastTextSpecification(label, property) != null;
}
public FastTextConfig getFastTextSpecification(Label label, String property) {
return fastTextFeatures.stream()
.filter(config ->
config.label().equals(label) &&
config.property().equals(property))
.findFirst()
.orElse(null);
}
public boolean hasSbertSpecification(Label label, String property) {
return getSbertSpecification(label, property) != null;
}
public SbertConfig getSbertSpecification(Label label, String property) {
return sbertFeatures.stream()
.filter(config ->
config.label().equals(label) &&
config.property().equals(property))
.findFirst()
.orElse(null);
}
public boolean hasNumericalBucketSpecification(Label label, String property) {
return getNumericalBucketSpecification(label, property) != null;
}
public NumericalBucketFeatureConfigV2 getNumericalBucketSpecification(Label label, String property) {
return numericalBucketFeatures.stream()
.filter(config ->
config.label().equals(label) &&
config.property().equals(property))
.findFirst()
.orElse(null);
}
public boolean hasFeatureOverrideForProperty(Label label, String property) {
return featureOverrides.stream()
.anyMatch(override ->
override.label().equals(label) &&
override.properties().contains(property));
}
public Collection<FeatureOverrideConfigV2> getFeatureOverrides(Label label) {
return featureOverrides.stream()
.filter(c -> c.label().equals(label))
.collect(Collectors.toList());
}
public FeatureOverrideConfigV2 getFeatureOverride(Label label, String property) {
return featureOverrides.stream()
.filter(config ->
config.label().equals(label) &&
config.properties().contains(property))
.findFirst()
.orElse(null);
}
@Override
public String toString() {
return "ElementConfig{" +
"classLabels=" + classLabels +
", tfIdfFeatures=" + tfIdfFeatures +
", datetimeFeatures=" + datetimeFeatures +
", word2VecFeatures=" + word2VecFeatures +
", numericalBucketFeatures=" + numericalBucketFeatures +
", featureOverrides=" + featureOverrides +
'}';
}
}
|
apcarrik/kaggle | duke-cs671-fall21-coupon-recommendation/outputs/rules/RF/3_features/numtrees_5/rule_3.py | <reponame>apcarrik/kaggle<filename>duke-cs671-fall21-coupon-recommendation/outputs/rules/RF/3_features/numtrees_5/rule_3.py
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation
# {"feature": "Occupation", "instances": 204, "metric_value": 0.9774, "depth": 1}
if obj[2]<=7.529411764705882:
# {"feature": "Coupon", "instances": 127, "metric_value": 0.9309, "depth": 2}
if obj[0]>0:
# {"feature": "Education", "instances": 107, "metric_value": 0.856, "depth": 3}
if obj[1]<=4:
return 'True'
elif obj[1]>4:
return 'True'
else: return 'True'
elif obj[0]<=0:
# {"feature": "Education", "instances": 20, "metric_value": 0.8813, "depth": 3}
if obj[1]<=2:
return 'False'
elif obj[1]>2:
return 'True'
else: return 'True'
else: return 'False'
elif obj[2]>7.529411764705882:
# {"feature": "Coupon", "instances": 77, "metric_value": 0.9989, "depth": 2}
if obj[0]<=3:
# {"feature": "Education", "instances": 50, "metric_value": 0.9954, "depth": 3}
if obj[1]>0:
return 'False'
elif obj[1]<=0:
return 'True'
else: return 'True'
elif obj[0]>3:
# {"feature": "Education", "instances": 27, "metric_value": 0.951, "depth": 3}
if obj[1]>0:
return 'False'
elif obj[1]<=0:
return 'False'
else: return 'False'
else: return 'False'
else: return 'False'
|
hongmomanu/webkitprj | app.nw/app/view/server/MemoryChart.js | <reponame>hongmomanu/webkitprj<gh_stars>0
/**
* The desktop login screen
*
* The login screen is in the first release not really used, because the login
* is controlled by the acl of zend framework.
* To use the login there are several things to check:
* - anonymous user must have access to webdesktop/index
* - GLOBAL_USER_CONFIG must be empty or some checks that validates the global var
* - never tested...
*
* In the current implementation it only passes the user informations from the
* backend to the main desktop controller.
* This needs more attention, because it can be very useful for session timeouts
* and direct relogins.
*
* @author <NAME> <<EMAIL>>
* @verion 0.1
* @package Webdesktop
* @subpackage Webdesktop
* @namespace Webdesktop.view.webdesktop
* @see ExtJs4 <http://www.sencha.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License version 3.0
*/
/**
* @class Webdesktop.view.webdesktop.Login
* @extends Ext.window.Window
* @alias webdesktop_login
*/
Ext.define('Webdesktop.view.server.MemoryChart', {
extend : 'Ext.chart.Chart',
alias : 'widget.appmemchart',
refreshRate: 3500,
updateCharts: function () {
var me = this;
clearTimeout(me.updateTimer);
me.updateTimer = setTimeout(function() {
testobj=me;
me.getStore().load();
me.updateCharts();
}, me.refreshRate);
},
initComponent: function() {
var me = this;
Ext.apply(me,
{
flex: 1,
xtype: 'chart',
animate: true,
listeners: {
afterrender: {
fn: me.updateCharts,
delay: 100
},
destroy: function () {
//alert(2);
clearTimeout(me.updateTimer);
me.updateTimer = null;
},
scope: me
},
store: 'server.MemoryCharts',
shadow: true,
legend: {
position: 'right'
},
insetPadding: 40,
theme: 'Memory:gradients',
series: [{
donut: 30,
type: 'pie',
field: 'memory',
showInLegend: true,
getLegendColor: function(index) {
var me = this;
var colorLength = 0;
me.colorArrayStyle = [ '#115fa6','#94ae0a'];
colorLength = me.colorArrayStyle.length;
if (me.style && me.style.fill) {
return me.style.fill;
} else {
return me.colorArrayStyle[index % colorLength];
}
},
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('memory')* 100) + '%');
}
},
highlight: {
segment: {
margin: 20
}
},
renderer: function(sprite, record, attr, index, store) {
var colormap={"未使用":'#94ae0a',"已使用":'#115fa6'};
var color = colormap[record.get('name')];
return Ext.apply(attr, {
fill: color
});
},
label: {
field: 'name',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
}
);
me.callParent();
}
}); |
DBatOWL/tutorials | spring-core-5/src/main/java/com/baeldung/component/inscope/ServiceExample.java | package com.baeldung.component.inscope;
import org.springframework.stereotype.Service;
@Service
public class ServiceExample {
}
|
robindittmar/mechanics | mechanics/src/hooks/FindMdl.h | <filename>mechanics/src/hooks/FindMdl.h
#ifndef __FINDMDL_H__
#define __FINDMDL_H__
#include "../source_sdk/IMDLCache.h"
struct FindMdlParam
{
const char* pName;
};
typedef MDLHandle_t(__thiscall *FindMdl_t)(void*, char*);
extern FindMdl_t g_pFindMdl;
MDLHandle_t __fastcall hk_FindMDL(void* ecx, void* edx, char* FilePath);
#endif // __FINDMDL_H__ |
xiewendan/algorithm | leetcode/85 maximal-rectangle.py | # -*- coding: utf-8 -*-
# __author__ = xiaobao
# __date__ = 2019/11/15 08:55:29
# desc: desc
# 给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
# 示例:
# 输入:
# [
# ["1","0","1","0","0"],
# ["1","0","1","1","1"],
# ["1","1","1","1","1"],
# ["1","0","0","1","0"]
# ]
# 输出: 6
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/maximal-rectangle
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# 思路
# 复杂度(时间/空间)
# 时间
# 空间
# 代码
class Solution:
# def maximalRectangle(self, matrix: List[List[str]]) -> int:
def maximalRectangle(self, matrix):
nRow = len(matrix)
if nRow == 0:
return 0
nCol = len(matrix[0])
if nCol == 0:
return 0
dp_heigh = [0] * nCol
dp_left_w = [0] * nCol
dp_right_w = [0] * nCol
left_w = [0] * nCol
right_w = [0] * nCol
max_area = 0
for i in range(nRow):
# update left_w
left_w[0] = int(matrix[i][0])
for j in range(1, nCol):
if matrix[i][j] == '0':
left_w[j] = 0
else:
left_w[j] = left_w[j-1] + 1
# update right_w
right_w[nCol-1] = int(matrix[i][nCol-1])
for j in range(nCol-2, -1, -1):
if matrix[i][j] == '0':
right_w[j] = 0
else:
right_w[j] = right_w[j+1] + 1
for j in range(nCol):
# 求高和面积
if matrix[i][j] == '0':
dp_heigh[j] = 0
dp_left_w[j] = left_w[j]
dp_right_w[j] = right_w[j]
else:
dp_heigh[j] = dp_heigh[j] + 1
if dp_left_w[j] == 0:
dp_left_w[j] = left_w[j]
else:
dp_left_w[j] = min(left_w[j], dp_left_w[j])
if dp_right_w[j] == 0:
dp_right_w[j] = right_w[j]
else:
dp_right_w[j] = min(right_w[j], dp_right_w[j])
max_area = max(max_area, dp_heigh[j] * (dp_left_w[j] + dp_right_w[j]-1))
return max_area
# 边界
solution = Solution()
# 0 x 0 矩阵
assert(solution.maximalRectangle([[]])==0)
# 1 x 1 矩阵
assert(solution.maximalRectangle([["0"]])==0)
assert(solution.maximalRectangle([["1"]])==1)
# 1 x 2 矩阵
assert(solution.maximalRectangle([["0", "0"]])==0)
assert(solution.maximalRectangle([["1", "0"]])==1)
assert(solution.maximalRectangle([["0", "1"]])==1)
assert(solution.maximalRectangle([["1", "1"]])==2)
# 2 x 1 矩阵
assert(solution.maximalRectangle([["0"],["0"]])==0)
assert(solution.maximalRectangle([["1"],["0"]])==1)
assert(solution.maximalRectangle([["0"],["1"]])==1)
assert(solution.maximalRectangle([["1"],["1"]])==2)
# 2 x 2 矩阵
assert(solution.maximalRectangle([["0", "0"],["0", "0"]])==0)
assert(solution.maximalRectangle([["0", "0"],["0", "1"]])==1)
assert(solution.maximalRectangle([["0", "1"],["0", "1"]])==2)
assert(solution.maximalRectangle([["1", "1"],["0", "1"]])==2)
assert(solution.maximalRectangle([["1", "1"],["1", "1"]])==4)
# 其它
assert(solution.maximalRectangle([["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]) == 6)
|
legioner9/Node_Way_source_2 | Store/myNpm/st_doc1/js_DOCS/Promise/PromiseError/TSH_19/2-then.js | <reponame>legioner9/Node_Way_source_2
'use strict';
const sum = (a, b) => new Promise((resolve, reject) => {
if (typeof a === 'number' && typeof b === 'number') {
resolve(a + b);
} else {
reject(new Error('a and b should be numbers'));
}
});
sum(7, 'A')
.then(
data => {
console.log({ data });
},
err => {
console.log({ messageThen: err.message });
throw new Error('Oh, no!');
}
)
.catch(err => {
console.log({ messageCatch1: err.message });
throw new Error('Oh, noo!');
})
.then(() => {}, err => {
console.log({ messageThen2: err.message });
throw new Error('Oh, nooo!');
})
.catch(err => {
console.log({ messageCatch2: err.message });
});
|
navikt/veilarbportefolje | src/main/java/no/nav/pto/veilarbportefolje/auth/AuthService.java | package no.nav.pto.veilarbportefolje.auth;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.vavr.Tuple;
import lombok.Data;
import lombok.experimental.Accessors;
import no.nav.common.abac.Pep;
import no.nav.common.abac.domain.request.ActionId;
import no.nav.common.types.identer.EnhetId;
import no.nav.common.types.identer.Fnr;
import no.nav.common.types.identer.NavIdent;
import no.nav.pto.veilarbportefolje.domene.Bruker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static java.util.stream.Collectors.toList;
import static no.nav.common.client.utils.CacheUtils.tryCacheFirst;
@Service
public class AuthService {
private final ModiaPep modiaPep;
private final Pep veilarbPep;
private final Cache<VeilederPaEnhet, Boolean > harVeilederTilgangTilEnhetCache;
@Autowired
public AuthService(Pep veilarbPep, ModiaPep modiaPep) {
this.modiaPep = modiaPep;
this.veilarbPep = veilarbPep;
this.harVeilederTilgangTilEnhetCache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.maximumSize(6000)
.build();
}
public void tilgangTilOppfolging() {
AuthUtils.test("oppfølgingsbruker", AuthUtils.getInnloggetVeilederIdent(), modiaPep.harVeilederTilgangTilModia(AuthUtils.getInnloggetBrukerToken()));
}
public void tilgangTilEnhet(String enhet) {
String veilederId = AuthUtils.getInnloggetVeilederIdent().toString();
AuthUtils.test("tilgang til enhet", Tuple.of(enhet, veilederId), harVeilederTilgangTilEnhet(veilederId, enhet));
}
public boolean harVeilederTilgangTilEnhet(String veilederId, String enhet) {
return tryCacheFirst(harVeilederTilgangTilEnhetCache, new VeilederPaEnhet(veilederId,enhet),
() -> veilarbPep.harVeilederTilgangTilEnhet(NavIdent.of(veilederId), EnhetId.of(enhet)));
}
public void tilgangTilBruker(String fnr) {
AuthUtils.test("tilgangTilBruker", fnr, veilarbPep.harTilgangTilPerson(AuthUtils.getInnloggetBrukerToken(), ActionId.READ, Fnr.of(fnr)));
}
public List<Bruker> sensurerBrukere(List<Bruker> brukere) {
String veilederIdent = AuthUtils.getInnloggetVeilederIdent().toString();
return brukere.stream()
.map(bruker -> fjernKonfidensiellInfoDersomIkkeTilgang(bruker, veilederIdent))
.collect(toList());
}
public Bruker fjernKonfidensiellInfoDersomIkkeTilgang(Bruker bruker, String veilederIdent) {
if(!bruker.erKonfidensiell()) {
return bruker;
}
String diskresjonskode = bruker.getDiskresjonskode();
if("6".equals(diskresjonskode) && !veilarbPep.harVeilederTilgangTilKode6(NavIdent.of(veilederIdent))) {
return AuthUtils.fjernKonfidensiellInfo(bruker);
}
if("7".equals(diskresjonskode) && !veilarbPep.harVeilederTilgangTilKode7(NavIdent.of(veilederIdent))) {
return AuthUtils.fjernKonfidensiellInfo(bruker);
}
if(bruker.isEgenAnsatt() && !veilarbPep.harVeilederTilgangTilEgenAnsatt(NavIdent.of(veilederIdent))) {
return AuthUtils.fjernKonfidensiellInfo(bruker);
}
return bruker;
}
@Data
@Accessors(chain = true)
class VeilederPaEnhet {
private final String veilederId;
private final String enhetId;
}
}
|
timboudreau/ANTLR4-Plugins-for-NetBeans | ANTLRTestProjects/antbased/CodeCompletion/build/generated-sources/antlr4/org/mypackage/CombinedGrammarParser.java | <filename>ANTLRTestProjects/antbased/CodeCompletion/build/generated-sources/antlr4/org/mypackage/CombinedGrammarParser.java<gh_stars>1-10
// Generated from D:\NetBeansProjects\ANTLRTestProjects\antbased\CodeCompletion\grammar\org\mypackage\CombinedGrammar.g4 by ANTLR 4.6
package org.mypackage;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class CombinedGrammarParser extends Parser {
static { RuntimeMetaData.checkVersion("4.6", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1, ID=2, INT=3, NEWLINE=4, IT_1_TOKEN_1=1, IT_1_TOKEN_2=2, LG_TOKEN_1=3,
LG_TOKEN_2=4, ILG_1_TOKEN_1=5, LG_TOKEN_3=6, ILG_1_TOKEN_2=7, ILG_1_TOKEN_3=8,
ILG_1_TOKEN_4=9, LG_TOKEN_5=10, TOK=11, PG_TOKEN=12, FRAGMENT=13;
public static final int
RULE_rule4 = 0, RULE_rule5 = 1, RULE_rule1 = 2, RULE_rule2 = 3, RULE_rule3 = 4;
public static final String[] ruleNames = {
"rule4", "rule5", "rule1", "rule2", "rule3"
};
private static final String[] _LITERAL_NAMES = {
null, "'azerty'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, null, "ID", "INT", "NEWLINE", "ILG_1_TOKEN_1", "LG_TOKEN_3", "ILG_1_TOKEN_2",
"ILG_1_TOKEN_3", "ILG_1_TOKEN_4", "LG_TOKEN_5", "TOK", "PG_TOKEN", "FRAGMENT"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "CombinedGrammar.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public CombinedGrammarParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class Rule4Context extends ParserRuleContext {
public Rule4Context(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_rule4; }
public Rule4Context() { }
public void copyFrom(Rule4Context ctx) {
super.copyFrom(ctx);
}
}
public static class AltLabel2Context extends Rule4Context {
public Rule2Context eltLabel1;
public Rule2Context rule2() {
return getRuleContext(Rule2Context.class,0);
}
public AltLabel2Context(Rule4Context ctx) { copyFrom(ctx); }
}
public static class AltLabel1Context extends Rule4Context {
public Rule1Context eltLabel1;
public Token eltLabel2;
public Token eltLabel3;
public TerminalNode INT() { return getToken(CombinedGrammarParser.INT, 0); }
public TerminalNode ILG_1_TOKEN_4() { return getToken(CombinedGrammarParser.ILG_1_TOKEN_4, 0); }
public Rule1Context rule1() {
return getRuleContext(Rule1Context.class,0);
}
public TerminalNode TOK() { return getToken(CombinedGrammarParser.TOK, 0); }
public List<TerminalNode> ID() { return getTokens(CombinedGrammarParser.ID); }
public TerminalNode ID(int i) {
return getToken(CombinedGrammarParser.ID, i);
}
public List<Rule2Context> rule2() {
return getRuleContexts(Rule2Context.class);
}
public Rule2Context rule2(int i) {
return getRuleContext(Rule2Context.class,i);
}
public TerminalNode FRAGMENT() { return getToken(CombinedGrammarParser.FRAGMENT, 0); }
public AltLabel1Context(Rule4Context ctx) { copyFrom(ctx); }
}
public static class AltLabel3Context extends Rule4Context {
public Rule5Context eltLabel1;
public Rule5Context rule5() {
return getRuleContext(Rule5Context.class,0);
}
public AltLabel3Context(Rule4Context ctx) { copyFrom(ctx); }
}
public final Rule4Context rule4() throws RecognitionException {
Rule4Context _localctx = new Rule4Context(_ctx, getState());
enterRule(_localctx, 0, RULE_rule4);
int _la;
try {
setState(29);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,3,_ctx) ) {
case 1:
_localctx = new AltLabel1Context(_localctx);
enterOuterAlt(_localctx, 1);
{
setState(10);
((AltLabel1Context)_localctx).eltLabel1 = rule1();
setState(12);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
{
setState(11);
match(ID);
}
}
setState(14);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( _la==ID );
setState(16);
match(INT);
setState(17);
((AltLabel1Context)_localctx).eltLabel2 = match(TOK);
setState(18);
match(ILG_1_TOKEN_4);
{
setState(20);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la==FRAGMENT) {
{
setState(19);
((AltLabel1Context)_localctx).eltLabel3 = match(FRAGMENT);
}
}
setState(23);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
{
setState(22);
rule2();
}
}
setState(25);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( _la==ILG_1_TOKEN_3 );
}
}
break;
case 2:
_localctx = new AltLabel2Context(_localctx);
enterOuterAlt(_localctx, 2);
{
setState(27);
((AltLabel2Context)_localctx).eltLabel1 = rule2();
}
break;
case 3:
_localctx = new AltLabel3Context(_localctx);
enterOuterAlt(_localctx, 3);
{
setState(28);
((AltLabel3Context)_localctx).eltLabel1 = rule5();
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class Rule5Context extends ParserRuleContext {
public Rule5Context(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_rule5; }
public Rule5Context() { }
public void copyFrom(Rule5Context ctx) {
super.copyFrom(ctx);
}
}
public static class AltLabel4Context extends Rule5Context {
public Rule2Context eltLabel1;
public Rule2Context rule2() {
return getRuleContext(Rule2Context.class,0);
}
public AltLabel4Context(Rule5Context ctx) { copyFrom(ctx); }
}
public static class AltLabel5Context extends Rule5Context {
public Rule1Context eltLabel1;
public Rule1Context rule1() {
return getRuleContext(Rule1Context.class,0);
}
public AltLabel5Context(Rule5Context ctx) { copyFrom(ctx); }
}
public final Rule5Context rule5() throws RecognitionException {
Rule5Context _localctx = new Rule5Context(_ctx, getState());
enterRule(_localctx, 2, RULE_rule5);
try {
setState(33);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,4,_ctx) ) {
case 1:
_localctx = new AltLabel4Context(_localctx);
enterOuterAlt(_localctx, 1);
{
setState(31);
((AltLabel4Context)_localctx).eltLabel1 = rule2();
}
break;
case 2:
_localctx = new AltLabel5Context(_localctx);
enterOuterAlt(_localctx, 2);
{
setState(32);
((AltLabel5Context)_localctx).eltLabel1 = rule1();
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class Rule1Context extends ParserRuleContext {
public Token gr1;
public Rule2Context gr2;
public Rule2Context rule2() {
return getRuleContext(Rule2Context.class,0);
}
public List<TerminalNode> LG_TOKEN_1() { return getTokens(CombinedGrammarParser.LG_TOKEN_1); }
public TerminalNode LG_TOKEN_1(int i) {
return getToken(CombinedGrammarParser.LG_TOKEN_1, i);
}
public Rule1Context(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_rule1; }
}
public final Rule1Context rule1() throws RecognitionException {
Rule1Context _localctx = new Rule1Context(_ctx, getState());
enterRule(_localctx, 4, RULE_rule1);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(38);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==INT) {
{
{
setState(35);
((Rule1Context)_localctx).gr1 = match(INT);
}
}
setState(40);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(41);
((Rule1Context)_localctx).gr2 = rule2();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class Rule2Context extends ParserRuleContext {
public TerminalNode PG_TOKEN() { return getToken(CombinedGrammarParser.PG_TOKEN, 0); }
public List<TerminalNode> ILG_1_TOKEN_3() { return getTokens(CombinedGrammarParser.ILG_1_TOKEN_3); }
public TerminalNode ILG_1_TOKEN_3(int i) {
return getToken(CombinedGrammarParser.ILG_1_TOKEN_3, i);
}
public Rule2Context(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_rule2; }
}
public final Rule2Context rule2() throws RecognitionException {
Rule2Context _localctx = new Rule2Context(_ctx, getState());
enterRule(_localctx, 6, RULE_rule2);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(44);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
{
setState(43);
match(ILG_1_TOKEN_3);
}
}
setState(46);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( _la==ILG_1_TOKEN_3 );
setState(48);
match(PG_TOKEN);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class Rule3Context extends ParserRuleContext {
public Rule3Context(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_rule3; }
}
public final Rule3Context rule3() throws RecognitionException {
Rule3Context _localctx = new Rule3Context(_ctx, getState());
enterRule(_localctx, 8, RULE_rule3);
try {
enterOuterAlt(_localctx, 1);
{
setState(50);
match(T__0);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\17\67\4\2\t\2\4\3"+
"\t\3\4\4\t\4\4\5\t\5\4\6\t\6\3\2\3\2\6\2\17\n\2\r\2\16\2\20\3\2\3\2\3"+
"\2\3\2\5\2\27\n\2\3\2\6\2\32\n\2\r\2\16\2\33\3\2\3\2\5\2 \n\2\3\3\3\3"+
"\5\3$\n\3\3\4\7\4\'\n\4\f\4\16\4*\13\4\3\4\3\4\3\5\6\5/\n\5\r\5\16\5\60"+
"\3\5\3\5\3\6\3\6\3\6\2\2\7\2\4\6\b\n\2\29\2\37\3\2\2\2\4#\3\2\2\2\6(\3"+
"\2\2\2\b.\3\2\2\2\n\64\3\2\2\2\f\16\5\6\4\2\r\17\7\4\2\2\16\r\3\2\2\2"+
"\17\20\3\2\2\2\20\16\3\2\2\2\20\21\3\2\2\2\21\22\3\2\2\2\22\23\7\5\2\2"+
"\23\24\7\r\2\2\24\26\7\13\2\2\25\27\7\17\2\2\26\25\3\2\2\2\26\27\3\2\2"+
"\2\27\31\3\2\2\2\30\32\5\b\5\2\31\30\3\2\2\2\32\33\3\2\2\2\33\31\3\2\2"+
"\2\33\34\3\2\2\2\34 \3\2\2\2\35 \5\b\5\2\36 \5\4\3\2\37\f\3\2\2\2\37\35"+
"\3\2\2\2\37\36\3\2\2\2 \3\3\2\2\2!$\5\b\5\2\"$\5\6\4\2#!\3\2\2\2#\"\3"+
"\2\2\2$\5\3\2\2\2%\'\7\5\2\2&%\3\2\2\2\'*\3\2\2\2(&\3\2\2\2()\3\2\2\2"+
")+\3\2\2\2*(\3\2\2\2+,\5\b\5\2,\7\3\2\2\2-/\7\n\2\2.-\3\2\2\2/\60\3\2"+
"\2\2\60.\3\2\2\2\60\61\3\2\2\2\61\62\3\2\2\2\62\63\7\16\2\2\63\t\3\2\2"+
"\2\64\65\7\3\2\2\65\13\3\2\2\2\t\20\26\33\37#(\60";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} |
pur-token/pur-core | setup.py | <reponame>pur-token/pur-core
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file was generated with PyScaffold 3.0.2.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: http://pyscaffold.org/
"""
import sys
from setuptools import setup
import versioneer
# Add here console scripts and other entry points in ini-style format
entry_points = """
[console_scripts]
start_pur = pur.main:main
pur_start = pur.main:main
pur = pur.cli:main
pur_grpc_proxy = pur.grpcProxy:main
pur_measure = pur.measure:main
pur_walletd = pur.daemon.walletd:main
pur_generate_genesis = pur.tools.generate_genesis:main
"""
def setup_package():
needs_sphinx = {'build_sphinx', 'upload_docs'}.intersection(sys.argv)
sphinx = ['sphinx'] if needs_sphinx else []
setup(setup_requires=['pyscaffold>=3.0a0,<3.1a0'] + sphinx,
entry_points=entry_points,
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
use_pyscaffold=True)
if __name__ == "__main__":
setup_package()
|
paige-ingram/nwhacks2022 | node_modules/@fluentui/react-icons/lib/cjs/components/ArrowRepeatAll24Regular.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const wrapIcon_1 = require("../utils/wrapIcon");
const rawSvg = (iconProps) => {
const { className, primaryFill } = iconProps;
return React.createElement("svg", { width: 24, height: 24, viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", className: className },
React.createElement("path", { d: "M14.61 2.47l-.08-.07a.75.75 0 00-.98.07l-.07.08c-.22.3-.2.72.07.98l1.97 1.98H8.27a6.51 6.51 0 00-4.58 10.92l.07.06a.75.75 0 001.08-1.03l-.2-.23A5 5 0 018.5 7.02h6.88l-1.83 1.84-.07.07c-.22.3-.2.72.07 1 .3.29.77.29 1.06 0l3.18-3.2.07-.08c.22-.3.2-.72-.07-.99l-3.18-3.19zm5.62 5.1a.75.75 0 00-1.05 1.07 5.01 5.01 0 01-3.68 8.41H8.56l1.9-1.9.08-.1c.2-.26.2-.63 0-.9l-.08-.07-.08-.08a.75.75 0 00-.9.01l-.08.07-3.18 3.2-.07.08c-.2.26-.2.63 0 .9l.07.08 3.18 3.19.09.07c.29.22.7.2.97-.07s.3-.7.07-.99l-.07-.07-1.9-1.91H15.73A6.51 6.51 0 0020.3 7.63l-.07-.07z", fill: primaryFill }));
};
const ArrowRepeatAll24Regular = wrapIcon_1.default(rawSvg({}), 'ArrowRepeatAll24Regular');
exports.default = ArrowRepeatAll24Regular;
|
kupl/starlab-benchmarks | Benchmarks_with_Functional_Bugs/Java/collections-39/src/src/test/org/apache/commons/collections/TestFastArrayList1.java | <reponame>kupl/starlab-benchmarks
/*
* Copyright 2001-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import junit.framework.Test;
/**
* Test FastArrayList implementation in <strong>fast</strong> mode.
*
* @version $Revision: 1.10 $ $Date: 2004/06/23 21:41:49 $
*
* @author <NAME>
*/
public class TestFastArrayList1 extends TestFastArrayList {
public TestFastArrayList1(String testName) {
super(testName);
}
public static Test suite() {
return BulkTest.makeSuite(TestFastArrayList1.class);
}
public static void main(String args[]) {
String[] testCaseName = { TestFastArrayList1.class.getName()};
junit.textui.TestRunner.main(testCaseName);
}
public void setUp() {
list = (ArrayList) makeEmptyList();
}
public List makeEmptyList() {
FastArrayList fal = new FastArrayList();
fal.setFast(true);
return (fal);
}
public void testIterateModify1() {
List list = makeEmptyList();
list.add("A");
list.add("B");
list.add("C");
assertEquals(3, list.size());
Iterator it = list.iterator();
assertEquals("A", it.next());
assertEquals(3, list.size());
list.add(1, "Z");
assertEquals(4, list.size());
assertEquals("B", it.next());
assertEquals("C", it.next());
assertEquals(false, it.hasNext());
}
public void testIterateModify2() {
List list = makeEmptyList();
list.add("A");
list.add("B");
list.add("C");
assertEquals(3, list.size());
ListIterator it = list.listIterator();
assertEquals("A", it.next());
it.add("M"); // change via Iterator interface
assertEquals(4, list.size());
list.add(2, "Z"); // change via List interface
assertEquals(5, list.size());
assertEquals("B", it.next());
try {
it.set("N"); // fails as previously changed via List interface
fail();
} catch (ConcurrentModificationException ex) {}
try {
it.remove();
fail();
} catch (ConcurrentModificationException ex) {}
try {
it.add("N");
fail();
} catch (ConcurrentModificationException ex) {}
assertEquals("C", it.next());
assertEquals(false, it.hasNext());
}
}
|
marincenusa/james-project | mailbox/plugin/quota-search-elasticsearch/src/main/java/org/apache/james/quota/search/elasticsearch/events/ElasticSearchQuotaMailboxListener.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.james.quota.search.elasticsearch.events;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.james.backends.es.ElasticSearchIndexer;
import org.apache.james.mailbox.events.Event;
import org.apache.james.mailbox.events.Group;
import org.apache.james.mailbox.events.MailboxListener;
import org.apache.james.quota.search.elasticsearch.QuotaRatioElasticSearchConstants;
import org.apache.james.quota.search.elasticsearch.json.QuotaRatioToElasticSearchJson;
public class ElasticSearchQuotaMailboxListener implements MailboxListener.GroupMailboxListener {
public static class ElasticSearchQuotaMailboxListenerGroup extends Group {
}
private static final Group GROUP = new ElasticSearchQuotaMailboxListenerGroup();
private final ElasticSearchIndexer indexer;
private final QuotaRatioToElasticSearchJson quotaRatioToElasticSearchJson;
@Inject
public ElasticSearchQuotaMailboxListener(
@Named(QuotaRatioElasticSearchConstants.InjectionNames.QUOTA_RATIO) ElasticSearchIndexer indexer,
QuotaRatioToElasticSearchJson quotaRatioToElasticSearchJson) {
this.indexer = indexer;
this.quotaRatioToElasticSearchJson = quotaRatioToElasticSearchJson;
}
@Override
public Group getDefaultGroup() {
return GROUP;
}
@Override
public boolean isHandling(Event event) {
return event instanceof QuotaUsageUpdatedEvent;
}
@Override
public void event(Event event) throws IOException {
handleEvent((QuotaUsageUpdatedEvent) event);
}
private void handleEvent(QuotaUsageUpdatedEvent event) throws IOException {
indexer.index(event.getUser().asString(),
quotaRatioToElasticSearchJson.convertToJson(event));
}
}
|
sw17ch/cauterize | lib/cauterize/base_type.rb | <gh_stars>1-10
require 'set'
require 'digest'
module Cauterize
class BaseType
attr_reader :name, :description
@@instances = {}
def initialize(name, description=nil)
if @@instances.keys.include?(name)
raise Exception.new("A type with the name #{name} already exists. [#{@@instances[name].inspect}]")
end
@name = name
@description = description
register_instance(self)
end
def type_hash(digest = nil)
digest ||= BaseType.digest_class.new
digest.update(@name.to_s)
local_hash(digest)
end
def self.all_instances; @@instances.values end
def self.model_hash
@@instances.keys.sort.map do |k|
@@instances[k]
end.inject(BaseType.digest_class.new) do |d, i|
i.type_hash(d)
end.digest
end
def self.find_type(name)
@@instances[name]
end
def self.find_type!(name)
unless t = find_type(name)
raise Exception.new("The name #{name} does not correspond to a type.")
else
return t
end
end
def self.digest_class
Digest::SHA1
end
alias :orig_method_missing :method_missing
def method_missing(sym, *args)
m = sym.to_s.match /is_([^\?]+)\?/
if m
return ("Cauterize::#{m[1].camel}" == self.class.name)
else
orig_method_missing(sym, *args)
end
end
protected
# local_hash is responsible for hashing the things in the type that
# are not known about in the BaseType parent class.
def local_hash(digest)
raise Exception.new("All instances of BaseType (including #{self.class}) must implement local_hash.")
end
def register_instance(inst)
if @@instances[inst.name]
raise Exception.new("Type with name #{inst.name} already defined.")
end
@@instances[inst.name] = inst
end
end
end
|
GrafNikola/tera-guide | guides/9970.js |
//
let player, entity, library, effect;
function applyDistance(loc, distance, degrees) {
let r = loc.w; //(loc.w / 0x8000) * Math.PI;
let rads = (degrees * Math.PI/180);
let finalrad = r - rads;
loc.x += Math.cos(finalrad) * distance;
loc.y += Math.sin(finalrad) * distance;
return loc;
}
function Spawnitem2(item,degree,distance, intervalDegrees, radius, delay,times, handlers, event, entity ) {
let shield_loc = entity['loc'].clone();
shield_loc.w = entity['loc'].w;
let degrees = 360 - degree;
applyDistance(shield_loc, distance, degrees);
for (let angle = -Math.PI; angle <= Math.PI; angle += Math.PI * intervalDegrees / 180) {
handlers['spawn']({
"id": item,
"delay": delay,
"sub_delay": times,
"distance": radius,
"offset": angle
}, {loc: shield_loc});
}
}
const FIRST_TIMER_DELAY = 40000;
const SECOND_TIMER_DELAY = 55000;
const EVENT_FOR_DEBUFFS = [
{
"type": "text",
"sub_type": "message",
"delay": FIRST_TIMER_DELAY,
"message": "Debuff swap will happen soon",
"message_TW": "Debuff交换准备"
},
{
"type": "text",
"sub_type": "message",
"delay": SECOND_TIMER_DELAY,
"message": "Debuff swap will happen soon",
"message_TW": "Debuff交换准备"
}
];
module.exports = {
load(dispatch) {
({ player, entity, library, effect } = dispatch.require.library);
},
// Start(first debuff applied)
// "ae-0-0-97000042": EVENT_FOR_DEBUFFS,
// "ae-0-0-97000043": EVENT_FOR_DEBUFFS,
// Debuff rotation happening
// "s-970-1000-1307": ,
// Meh, fill in with stop_timer id 1 below 70% hp, but cba
// Second boss
"s-970-2000-2106-0": [{"type": "text","sub_type": "message","message_TW": "晕","message": " STUN"}],
// Third boss
"s-970-3000-1102-0": [{"type": "text","sub_type": "message","message_TW": "左手","message": " Left Hand"}],
"s-970-3000-2102-0": [{"type": "text","sub_type": "message","message_TW": "左手","message": " Left Hand"}],
//Right Hand
"s-970-3000-1101-0": [{"type": "text","sub_type": "message","message_TW": "右手","message": " Right Hand"}],
"s-970-3000-2101-0": [{"type": "text","sub_type": "message","message_TW": "右手","message": " Right Hand"}],
//Tail Slam
"s-970-3000-1103-0": [{"type": "text","sub_type": "message","message_TW": "尾巴","message": " Tail Slam"}],
"s-970-3000-2103-0": [{"type": "text","sub_type": "message","message_TW": "尾巴","message": " Tail Slam"}],
//FATE Avoid Circles
"s-970-3000-1301-0": [{"type": "text","sub_type": "message","message_TW": "命运圈","message": " FATE Avoid Circles"}],
//Tail AOE (jump in front)
"s-970-3000-2110-0": [{"type": "text","sub_type": "message","message_TW": "尾部AOE(向前跳)","message": " Tail AOE (jump in front)"}],
"s-970-3000-1110-0": [{"type": "text","sub_type": "message","message_TW": "尾部AOE(向前跳)","message": " Tail AOE (jump in front)"}],
//Get Ready ! (for in out mechanic)
"s-970-3000-1304-0": [{"type": "text","sub_type": "message","message_TW": "准备","message": " Get Ready ! (for in out mechanic)"}],
"s-970-3000-1303-0": [{"type": "text","sub_type": "message","message_TW": "准备","message": " Get Ready ! (for in out mechanic)"}],
//GO OUT then come in
"s-970-3000-2113-0": [{"type": "text","sub_type": "message","message_TW": "出 -> 进","message": " OUT -> IN"},
{"type": "func","func": Spawnitem2.bind(null,912,0,0,15,300,0,5000)}],
"s-970-3000-1113-0": [{"type": "text","sub_type": "message","message_TW": "出 -> 进","message": " OUT -> IN"},
{"type": "func","func": Spawnitem2.bind(null,912,0,0,15,300,0,5000)}],
//STAY IN then go out
"s-970-3000-2116-0": [{"type": "text","sub_type": "message","message_TW": "进 -> 出","message": " IN -> OUT"},
{"type": "func","func": Spawnitem2.bind(null,912,0,0,15,300,0,5000)}],
"s-970-3000-1116-0": [{"type": "text","sub_type": "message","message_TW": "进 -> 出","message": " IN -> OUT"},
{"type": "func","func": Spawnitem2.bind(null,912,0,0,15,300,0,5000)}],
//GET RED SKULL !!
"s-970-3000-1318-0": [{"type": "text","sub_type": "message","message_TW": "吃红球","message": " GET RED SKULL !!"}],
"s-970-3000-1317-0": [{"type": "text","sub_type": "message","message_TW": "吃红球","message": " GET RED SKULL !!"}],
"s-970-3000-1319-0": [{"type": "text","sub_type": "message","message_TW": "吃红球","message": " GET RED SKULL !!"}],
//DODGE the PATTERNS !
"s-970-3000-1322-0": [{"type": "text","sub_type": "message","message_TW": "內外炸解王!","message": " DODGE the PATTERNS !"}],
//GATHER FOR CLEANSE ! !
"s-970-3000-1311-0": [{"type": "text","sub_type": "message","message_TW": "集中净化","message": " GATHER FOR CLEANSE !"}]
}; |
vglocus/github-java-client | src/main/java/com/spotify/github/v3/repos/FolderContent.java | /*-
* -\-\-
* github-api
* --
* Copyright (C) 2016 - 2020 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.github.v3.repos;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.spotify.github.GithubStyle;
import com.spotify.github.v3.git.ShaLink;
import java.net.URI;
import javax.annotation.Nullable;
import org.immutables.value.Value;
/** Repository file content resource */
@Value.Immutable
@GithubStyle
@JsonSerialize(as = ImmutableFolderContent.class)
@JsonDeserialize(as = ImmutableFolderContent.class)
public interface FolderContent extends ShaLink {
/** Content type. E.g file, dir, symlink, submodule */
@Nullable
String type();
/** Content size in bytes */
@Nullable
Integer size();
/** Content name. E.g. file name */
@Nullable
String name();
/** The content path. */
@Nullable
String path();
/** Git blob API URL */
@Nullable
URI gitUrl();
/** Content URL */
@Nullable
URI htmlUrl();
/** Content download URL */
@Nullable
URI downloadUrl();
}
|
smhanes15/CodingBat-Personal | java/Logic-1/MaxMod5.java | <filename>java/Logic-1/MaxMod5.java
/*
* Logic-1 --> maxMod5
*
* Given two int values, return whichever value is larger. However if the two values have the same
* remainder when divided by 5, then the return the smaller value. However, in all cases, if the two
* values are the same, return 0. Note: the % "mod" operator computes the remainder, e.g. 7 % 5 is 2.
*
* Tests:
* maxMod5(2, 3) ? 3
* maxMod5(6, 2) ? 6
* maxMod5(3, 2) ? 3
* maxMod5(8, 12) ? 12
* maxMod5(7, 12) ? 7
* maxMod5(11, 6) ? 6
* maxMod5(2, 7) ? 2
* maxMod5(7, 7) ? 0
* maxMod5(9, 1) ? 9
* maxMod5(9, 14) ? 9
* maxMod5(1, 2) ? 2
* other tests
*/
public class MaxMod5 {
public int maxMod5(int a, int b) {
if (a % 5 == b % 5 && a != b) return (a > b) ? b : a;
if (a != b) return (a > b) ? a : b;
return 0;
}
} // Delete the line below to have this file overwritten with current CodingBat content. //
// %FINISHED% //
|
mitre/mediawiki-vagrant | puppet/modules/thumbor/lib/puppet/parser/functions/file_exists.rb | require 'puppet'
module Puppet::Parser::Functions
newfunction(:file_exists, type: :rvalue) do |args|
return File.exists?(args[0])
end
end
|
shivanigupta71299/Gossip-Mongers-Android-SDK-master | mobicommons/src/main/java/com/gossipmongers/mobicommons/json/JsonParcelableMarker.java | <gh_stars>0
package com.gossipmongers.mobicommons.json;
import android.os.Parcelable;
/**
* Created by sunil on 2/6/16.
*/
abstract public class JsonParcelableMarker implements Parcelable {
}
|
samuelerwardi/restaurant | public/js/trx_beli.js | $(function(){
// $.showHideMenu();
// $(".datepicker").datepicker().on("changeDate", function(ev){
// $(this).datepicker("hide");
// });
// $(".datepicker").keydown(function(){return false;});
$("#namasupplier").autocomplete({
source: "/supplier/search",
open: function(){
$("#supplier_id").val("");
},
focus: function( event, ui ) {
$("#namasupplier").val(ui.item.nama);
return false;
},
select: function( event, ui ) {
$("#supplier_id").val(ui.item.id); //yg ui.item.namafield dari json
$("#namasupplier").val(ui.item.nama);
return false;
}
}).data("ui-autocomplete")._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.id + " - " + item.nama + "</a>" )
.appendTo( ul );
};
$("#namasupplier").keyup(function(){
if($(this).val()==""){
$("#supplier_id").val("");
}
});
$("#ppn").keyup(function(){
console.log($(this));
var grandtotal = parseInt($("[name=grandtotal]").val());
var ppn = parseInt($("#ppn").val());
ppn=isNaN(ppn)?0:ppn;
var afterppn = grandtotal +(grandtotal * ppn/100);
$("#afterppn").html('<input type="hidden" name="afterppn" value="'+afterppn+'">'+afterppn);
});
$("#kodebarang").autocomplete({
source: "/master_bahan/search",
open: function(){
$("#namabarang").html("");
$("#harga").html("0");
$("#subtotal").html("0");
},
focus: function( event, ui ) {
$("#kodebarang").val(ui.item.id);
return false;
},
select: function( event, ui ) {
$("#kodebarang").val(ui.item.id);
$("#namabarang").html(ui.item.nama_bahan);
$("#harga").html(ui.item.harga_beli);
$("#subtotal").html("0");
$("#harga").focus();
return false;
}
}).data("ui-autocomplete")._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.id + " - " + item.nama_bahan + "</a>" )
.appendTo( ul );
};
$("#kodebarang").keyup(function(){
if($(this).val()==""){
$("#namabarang").html("");
$("#harga").html("");
$("#subtotal").html("0");
}
});
$("#qty, #harga").keyup(function(){
var qty = getNumberValue($("#qty").val());
var harga = $("#harga").val();
if(!isNaN(qty) && qty != "" && !isNaN(harga) && harga != ""){
qty = parseInt(qty);
harga = parseInt(harga);
$("#subtotal").html(qty*harga);
}else{
$("#subtotal").html("0");
}
});
var countGrandtotal = function(){
var detail = $("#detail tbody");
if(detail.find(".empty-detail").length==0){
var grandtotal = 0;
var rows = detail.find("tr");
for(i = 0; i < rows.length; i++){
var row = $(rows[i]);
var subtotal = parseInt(row.find("td:nth-child(5) input").val());
grandtotal += subtotal;
}
$("#grandtotal").html('<input type="hidden" name="grandtotal" value="'+grandtotal+'">'+grandtotal);
}else{
$("#grandtotal").html('<input type="hidden" name="grandtotal" value="0">0');
}
}
var tambah = function(){
if( $("#kodebarang").val() != "" &&
$("#namabarang").html() != "" &&
$("#harga").html() != "0" &&
$("#qty").val() != "" &&
$("#subtotal").html() != "0" ){
var detail = $("#detail tbody");
var isAvailable = false;
if(detail.find(".empty-detail").length>0){
detail.html("");
}else{
var rows = detail.find("tr");
for(i = 0; i < rows.length; i++){
var row = $(rows[i]);
var kodebarang = row.find("td:nth-child(1) input").val();
if(kodebarang == $("#kodebarang").val()){
row.find("td:nth-child(3)").html($("#harga").html());
var qty = parseInt(row.find("td:nth-child(4) input").val())+parseInt($("#qty").val());
row.find("td:nth-child(4)").html(qty);
var subtotal = qty*parseInt($("#harga").val())
row.find("td:nth-child(5)").html('<input type="hidden" name="subtotal[]" value="'+subtotal+'">'+subtotal);
isAvailable = true;
break;
}
}
}
if(!isAvailable){
var row = $(
'<tr data-id="'+$("#kodebarang").val()+'">'+
'<td>'+
'<input type="hidden" name="kodebarang[]" value="'+$("#kodebarang").val()+'">'+
$("#kodebarang").val()+
'</td>'+
'<td>'+
'<input type="hidden" name="namabarang[]" value="'+$("#namabarang").html()+'">'+
$("#namabarang").html()+
'</td>'+
'<td>'+
'<input type="hidden" name="harga[]" value="'+$("#harga").val()+'">'+
$("#harga").val()+
'</td>'+
'<td>'+
'<input type="hidden" name="qty[]" value="'+$("#qty").val()+'">'+
$("#qty").val()+
'</td>'+
'<td>'+
'<input type="hidden" name="subtotal[]" value="'+$("#subtotal").html()+'">'+
$("#subtotal").html()+
'</td>'+
'<td>'+
'<a href="#" class="btn btn-danger input-block-level remove" data-id="'+$("#kodebarang").val()+'"><i class="icon-remove icon-white"></i>Remove</a>'+
'</td>'+
'</tr>'
);
detail.append(row);
}
countGrandtotal();
$("#kodebarang").val("");
$("#namabarang").html("");
$("#harga").val("");
$("#qty").val("");
$("#subtotal").html("0");
$("#kodebarang").focus();
}
var grandtotal = parseInt($("[name=grandtotal]").val());
var ppn = parseInt($("#ppn").val());
ppn=isNaN(ppn)?0:ppn;
var afterppn = grandtotal +(grandtotal * ppn/100);
$("#afterppn").html('<input type="hidden" name="afterppn" value="'+afterppn+'">'+afterppn);
return false;
}
$("#tambah").click(tambah);
$("#kodebarang, #qty").keyup(function(e){
if(e.keyCode == 13){
tambah();
}
return false;
});
$(document).on("click",".remove",function(){
var id = $(this).data("id");
$("tr[data-id="+id+"]").remove();
var detail = $("#detail tbody");
if(detail.find("tr").length == 0){
detail.html('<tr class="empty-detail">'+
'<td colspan="6">Detail masih kosong</td>'+
'</tr>');
}
countGrandtotal();
return false;
});
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
$("#form button[type=submit]").click(function(){
if( $("#nopenjualan").val() != "" &&
$("#tanggalpenjualan").val() != "" &&
$("#kodepelanggan").val() != "" &&
$("#detail .empty-detail").length == 0){
return true;
}
return false;
});
$("#form button[type=reset]").click(function(){
var detail = $("#detail tbody");
detail.html('<tr class="empty-detail">'+
'<td colspan="6">Detail masih kosong</td>'+
'</tr>');
countGrandtotal();
});
}); |
alexanderbock/Kameleon-Converter | ext/kameleon/src/ccmc/GeneralFileReader.cpp | /*
* FileReader.cpp
*
* Created on: Apr 22, 2009
* Author: <NAME>
*/
// #include "config.h"
#include "Kameleon-plus-Config.h"
#include "FileReader.h"
#include "CDFFileReader.h"
#include "HDF5FileReader.h"
#include "GeneralFileReader.h"
#include <string>
#include <vector>
#include <deque>
#include <iostream>
#include <fstream>
#include <queue>
namespace ccmc
{
GeneralFileReader::GeneralFileReader()
{
this->fileReader = NULL;
}
long GeneralFileReader::open(const std::string& filename)
{
//check the file
//std::cout << "First, checking if the file is a CDF file" << std::endl;
if (this->fileReader == NULL)
this->fileReader = new CDFFileReader();
else
{
this->close();
//delete this->fileReader;
this->fileReader = new CDFFileReader();
}
long status = fileReader->open(filename);
if (status == FileReader::OK)
{
// std::cerr << "Initialized a CDF file reader" << std::endl;
//this->fileReader = fileReader;
return status;
}
#ifdef HAVE_HDF5
else
{
// std::cout << "Checking if the file is an HDF5 file" << std::endl;
delete fileReader;
this->fileReader = new HDF5FileReader::HDF5FileReader();
long status = fileReader->open(filename);
// std::cerr << "opened HDF5 file. status: " << status << std::endl;
if (status == FileReader::OK)
{
// std::cerr << "Initialized an HDF5 file reader" << std::endl;
return status;
} else
return FileReader::OPEN_ERROR;
}
#endif /* HAVE_HDF5 */
return status;
}
std::vector<float>* GeneralFileReader::getVariable(const std::string& variable)
{
return fileReader->getVariable(variable);
}
std::vector<float>* GeneralFileReader::getVariable(long variable)
{
return fileReader->getVariable(variable);
}
std::vector<float>* GeneralFileReader::getVariable(const std::string& variable, long startIndex, long count)
{
return fileReader->getVariable(variable, startIndex, count);
}
std::vector<float>* GeneralFileReader::getVariable(long variable, long startIndex, long count)
{
return fileReader->getVariable(variable, startIndex, count);
}
float GeneralFileReader::getVariableAtIndex(const std::string& variable, long index)
{
return fileReader->getVariableAtIndex(variable, index);
}
float GeneralFileReader::getVariableAtIndex(long variable_id, long index)
{
return fileReader->getVariableAtIndex(variable_id, index);
}
std::vector<int>* GeneralFileReader::getVariableInt(const std::string& variable)
{
return fileReader->getVariableInt(variable);
}
int GeneralFileReader:: getVariableIntAtIndex(const std::string& variable, long index)
{
return fileReader->getVariableIntAtIndex(variable, index);
}
int GeneralFileReader:: getNumberOfGlobalAttributes()
{
return fileReader->getNumberOfGlobalAttributes();
}
int GeneralFileReader:: getNumberOfVariables()
{
return fileReader->getNumberOfVariables();
}
int GeneralFileReader:: getNumberOfVariableAttributes()
{
return fileReader->getNumberOfVariableAttributes();
}
long GeneralFileReader:: getNumberOfRecords(const std::string& variable)
{
return fileReader->getNumberOfRecords(variable);
}
long GeneralFileReader:: getNumberOfRecords(long variable_id)
{
return fileReader->getNumberOfRecords(variable_id);
}
long GeneralFileReader:: getVariableID(const std::string& variable)
{
return fileReader->getVariableID(variable);
}
std::string GeneralFileReader::getVariableName(long variable_id)
{
return fileReader->getVariableName(variable_id);
}
Attribute GeneralFileReader::getGlobalAttribute(long i)
{
return fileReader->getGlobalAttribute(i);
}
std::string GeneralFileReader::getGlobalAttributeName(long attribute_id)
{
return fileReader->getGlobalAttributeName(attribute_id);
}
std::string GeneralFileReader::getVariableAttributeName(long attribute_id)
{
return fileReader->getVariableAttributeName(attribute_id);
}
Attribute GeneralFileReader::getGlobalAttribute(const std::string& attribute)
{
return fileReader->getGlobalAttribute(attribute);
}
Attribute GeneralFileReader::getVariableAttribute(const std::string& variable, const std::string& attribute)
{
return fileReader->getVariableAttribute(variable, attribute);
}
std::vector<std::string> GeneralFileReader::getVariableAttributeNames()
{
return fileReader->getVariableAttributeNames();
}
bool GeneralFileReader::doesAttributeExist(const std::string& attribute)
{
return fileReader->doesAttributeExist(attribute);
}
bool GeneralFileReader::doesVariableExist(const std::string& variable)
{
return fileReader->doesVariableExist(variable);
}
long GeneralFileReader:: close()
{
long status = fileReader->close();
delete fileReader;
fileReader = NULL;
return status;
}
const std::string& GeneralFileReader::getCurrentFilename()
{
return fileReader->getCurrentFilename();
}
GeneralFileReader::~GeneralFileReader()
{
if (fileReader != NULL)
close();
}
void GeneralFileReader::initializeVariableIDs()
{
fileReader->initializeVariableIDs();
}
void GeneralFileReader::initializeVariableNames()
{
fileReader->initializeVariableNames();
}
}
|
zmilonas/service-ui | app/src/pages/inside/common/accordion/useAccordionTabsState.js | /*
* Copyright 2021 EPAM Systems
*
* 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.
*/
import { useState } from 'react';
export const useAccordionTabsState = (initialState) => {
const [tabsState, setTabsState] = useState(initialState);
const toggleTab = (tabId) => {
setTabsState({ ...tabsState, [tabId]: !tabsState[tabId] });
};
const collapseTabsExceptCurr = (currentTab) => {
const newTabsState = Object.keys(tabsState).reduce(
(acc, id) => ({ ...acc, [id]: currentTab === id }),
{},
);
setTabsState(newTabsState);
};
return [tabsState, toggleTab, collapseTabsExceptCurr];
};
|
jkdubr/Proj4 | Pod/Classes/Projection/MOBProjectionEPSG6469.h | #import "MOBProjection.h"
@interface MOBProjectionEPSG6469 : MOBProjection
@end
|
pingidentity/astro | src/components/AccordionGroup/AccordionGroup.js | <filename>src/components/AccordionGroup/AccordionGroup.js
import React, { forwardRef, useRef, useImperativeHandle } from 'react';
import { useAccordion } from '@react-aria/accordion';
import { useTreeState } from '@react-stately/tree';
import PropTypes from 'prop-types';
import { Box } from '../../index';
import AccordionItem from '../AccordionItem';
import { AccordionContext } from '../../context/AccordionContext';
import { isIterableProp } from '../../utils/devUtils/props/isIterable';
/**
* Component that allows for a child to be expanded and retracted.
* Built on top of [React Aria useAccordion and useAccordionItem](https://reactspectrum.blob.core.windows.net/reactspectrum/d77b35e970e5549f66b47a83f07423f5c93b7297/docs/react-aria/useAccordion.html).
*
* Console Warning: "Cannot update a component (`Unknown`)...`"
* when using controlledExpanded prop is expected
* and related to a known issue within React Stately.
*/
const AccordionGroup = forwardRef((props, ref) => {
const {
onPress,
onExpandedChange,
...others
} = props;
const state = useTreeState(props);
const accordionRef = useRef();
const { accordionProps } = useAccordion(props, state, accordionRef);
delete accordionProps.onMouseDown;
/* istanbul ignore next */
useImperativeHandle(ref, () => accordionRef.current);
return (
<AccordionContext.Provider value={state} >
<Box ref={accordionRef} {...accordionProps} {...others}>
{Array.from(state.collection).map(item => (
<AccordionItem key={item.key} item={item} data-id={item['data-id']}>
{item.props.children}
</AccordionItem>
))}
</Box>
</AccordionContext.Provider>
);
});
AccordionGroup.propTypes = {
/** Handler that is called when items are expanded or collapsed. */
onExpandedChange: PropTypes.func,
/** Handler that is called when the press is released over the target. */
onPress: PropTypes.func,
/** Item objects in the collection. */
items: isIterableProp,
/**
* The item keys that are disabled. These items cannot be selected, focused, or otherwise
* interacted with.
*/
disabledKeys: isIterableProp,
/** The currently expanded keys in the collection (controlled). */
expandedKeys: isIterableProp,
/** The initial expanded keys in the collection (uncontrolled). */
defaultExpandedKeys: isIterableProp,
/** Id of the selected element */
id: PropTypes.string,
};
AccordionGroup.displayName = 'AccordionGroup';
export default AccordionGroup;
|
AIPHES/ecml-pkdd-2019-J3R-explainable-recommender | refs/librec/core/src/main/java/net/librec/math/structure/MatrixBasedSequentialSparseVector.java | package net.librec.math.structure;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @author <NAME> (email: <EMAIL>)
*/
public class MatrixBasedSequentialSparseVector extends SequentialSparseVector {
private SequentialAccessSparseMatrix sparseMatrix;
private int column;
private int length;
private int[] indices;
private MatrixBasedSequentialSparseVector(int size) {
super(size);
}
public MatrixBasedSequentialSparseVector(SequentialAccessSparseMatrix sparseMatrix, int column) {
super(sparseMatrix.rowSize());
this.sparseMatrix = sparseMatrix;
this.column = column;
indices = sparseMatrix.columnBasedRowIndices()[column];
length = indices.length;
}
@Override
public void setAtPosition(int position, double value) {
sparseMatrix.setAtRowPosition(position, column, value);
}
@Override
public double getAtPosition(int position) {
return sparseMatrix.getAtRowPosition(position, column);
}
@Override
public int getIndexAtPosition(int position) {
return getIndices()[position];
}
@Override
protected void reshape() {
sparseMatrix.reshape();
}
@Override
public int[] getIndices() {
return sparseMatrix.columnBasedRowIndices()[column];
}
@Override
public VectorEntry getVectorEntryAtPosition(int position) {
MatrixBasedSparseVectorEntry matrixBasedSparseVectorEntry = new MatrixBasedSparseVectorEntry();
matrixBasedSparseVectorEntry.position = position;
return matrixBasedSparseVectorEntry;
}
@Override
public int getNumEntries() {
return length;
}
@Override
@Deprecated
public void set(int index, double value) {
sparseMatrix.set(index, column, value);
}
@Override
@Deprecated
public double get(int index) {
return sparseMatrix.get(index, column);
}
@Override
public Iterator<VectorEntry> iterator() {
return new MatrixBasedSequentialAccessIterator();
}
private final class MatrixBasedSequentialAccessIterator implements Iterator<VectorEntry> {
private final MatrixBasedSparseVectorEntry vectorEntry = new MatrixBasedSparseVectorEntry();
@Override
public boolean hasNext() {
return vectorEntry.getNextOffset() < getNumEntries();
}
@Override
public MatrixBasedSparseVectorEntry next() {
vectorEntry.advanceOffset();
return vectorEntry;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public final class MatrixBasedSparseVectorEntry implements VectorEntry {
private int position = -1;
void advanceOffset() {
position++;
}
int getNextOffset() {
return position + 1;
}
@Override
public double get() {
return sparseMatrix.getAtRowPosition(position, column);
}
@Override
public int index() {
return indices[position];
}
/**
* @return the position of this vector element.
* For dense vector and random sparse vector, the values of position and index are the same, i.e., index() = position()
*/
@Override
public int position() {
return position;
}
@Override
public void set(double value) {
sparseMatrix.setAtRowPosition(position, column, value);
}
}
}
|
GlaDOSik/Adele | Adele/src/main/java/adele/image/EditorImage.java | <filename>Adele/src/main/java/adele/image/EditorImage.java
/*
* 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 adele.image;
import javafx.scene.image.WritableImage;
import lombok.Getter;
import lombok.Setter;
/**
* ImageEditor container for Image which contains UID, JavaFX cache
* (WritableImage), current frame pointer and current layer pointer.
*/
public class EditorImage {
@Getter
private String uid;
@Getter
private Image image;
@Getter
private final WritableImage fxCache;
@Getter
@Setter
private int currentFrame = 0;
@Getter
@Setter
private int currentLayer = 0;
public EditorImage(String uid, Image image) {
this.uid = uid;
this.image = image;
fxCache = new WritableImage(image.getWidth(), image.getHeight());
}
}
|
cybergarage/CyberLink4CC | src/mupnp/soap/SOAP.cpp | <reponame>cybergarage/CyberLink4CC
/******************************************************************
*
* mUPnP for C++
*
* Copyright (C) <NAME> 2002
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <string>
#include <sstream>
#include <string.h>
#include <mupnp/soap/SOAP.h>
#include <uhttp/util/StringUtil.h>
////////////////////////////////////////////////
// CreateEnvelopeBodyNode
////////////////////////////////////////////////
mupnp_shared_ptr<uXML::Node> uSOAP::SOAP::CreateEnvelopeBodyNode() {
// <Envelope>
std::string envNodeName;
envNodeName += XMLNS;
envNodeName += DELIM;
envNodeName += ENVELOPE;
uXML::Node *envNode = new uXML::Node(envNodeName.c_str());
std::string xmlNs;
xmlNs += "xmlns";
xmlNs += DELIM;
xmlNs += XMLNS;
envNode->setAttribute(xmlNs.c_str(), XMLNS_URL);
std::string encStyle;
encStyle += XMLNS;
encStyle += DELIM;
encStyle += "encodingStyle";
envNode->setAttribute(encStyle.c_str(), ENCSTYLE_URL);
// <Body>
std::string bodyNodeName;
bodyNodeName += XMLNS;
bodyNodeName += DELIM;
bodyNodeName += BODY;
uXML::Node *bodyNode = new uXML::Node(bodyNodeName.c_str());
envNode->addNode(bodyNode);
return mupnp_shared_ptr<uXML::Node>(envNode);
}
////////////////////////////////////////////////
// Header
////////////////////////////////////////////////
const char *uSOAP::SOAP::GetHeader(const std::string &content, std::string &header) {
header = "";
if (content.length() <= 0)
return header.c_str();
std::string::size_type gtIdx = content.find(">");
if (gtIdx == std::string::npos)
return header.c_str();
header = content.substr(0, gtIdx+1);
return header.c_str();
}
////////////////////////////////////////////////
// Encoding
////////////////////////////////////////////////
const char *uSOAP::SOAP::GetEncording(const std::string &content, std::string &encording) {
encording = "";
std::string header;
SOAP::GetHeader(content, header);
if (header.size() <= 0)
return encording.c_str();
std::string::size_type encIdx = header.find(uSOAP::SOAP::ENCORDING);
if (encIdx == std::string::npos)
return encording.c_str();
std::string::size_type startIdx = header.find('\"', encIdx+strlen(uSOAP::SOAP::ENCORDING)+1);
if (startIdx == std::string::npos)
return encording.c_str();
std::string::size_type endIdx = header.find('\"', startIdx+1);
encording = header.substr(startIdx+1, (endIdx-startIdx-1));
return encording.c_str();
}
bool uSOAP::SOAP::IsEncording(const std::string &content, const std::string &encType) {
std::string enc;
SOAP::GetEncording(content, enc);
uHTTP::String encStr(enc);
return encStr.equalsIgnoreCase(encType);
}
|
marcomarasca/SynapseWebClient | src/main/java/org/sagebionetworks/web/client/widget/entity/tabs/DatasetsTab.java | package org.sagebionetworks.web.client.widget.entity.tabs;
import java.util.Collections;
import java.util.List;
import org.sagebionetworks.repo.model.Entity;
import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.repo.model.table.Dataset;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.place.Synapse.EntityArea;
import com.google.inject.Inject;
/**
* Tab that shows Datasets only.
*/
public class DatasetsTab extends AbstractTablesTab {
public static final String DATASETS_HELP = "Create and share a collection of File versions using a Dataset.";
public static final String DATASETS_HELP_URL = ""; // WebConstants.DOCS_URL + "Tables.2011038095.html"; // TODO
@Inject
public DatasetsTab(Tab tab, PortalGinInjector ginInjector) {
super(tab, ginInjector);
this.tab = tab;
this.ginInjector = ginInjector;
tab.configure(DisplayConstants.DATASETS, "dataset", DATASETS_HELP, "", EntityArea.DATASETS);
}
@Override
protected EntityArea getTabArea() {
return EntityArea.DATASETS;
}
@Override
protected String getTabDisplayName() {
return DisplayConstants.DATASETS;
}
@Override
protected List<EntityType> getTypesShownInList() {
return Collections.singletonList(EntityType.dataset);
}
@Override
protected boolean isEntityShownInTab(Entity entity) {
return entity instanceof Dataset;
}
}
|
sleepingkingstudios/bronze | lib/bronze/entities/associations/collection.rb | # lib/bronze/entities/associations/collection.rb
require 'sleeping_king_studios/tools/toolbox/delegator'
require 'bronze/entities/associations'
require 'bronze/entities/associations/helpers'
module Bronze::Entities::Associations
# Collection object for *_many associations.
class Collection
extend SleepingKingStudios::Tools::Toolbox::Delegator
include Enumerable
include Bronze::Entities::Associations::Helpers
# @param entity [Bronze::Entities::Entity] The entity that the collection
# belongs to; inverse of entity.(collection_name).
# @param metadata [Associations::Metadata::HasManyMetadata] The metadata for
# the association.
def initialize entity, metadata, entities = []
@entity = entity
@metadata = metadata
@entities = entities
end # constructor
# @return [Bronze::Entities::Entity] The entity that the collection belongs
# to.
attr_reader :entity
# @return [Associations::Metadata::HasManyMetadata] The metadata for the
# association.
attr_reader :metadata
# @!method count
# # @return [Integer] The number of entities in the collection.
# @!method each
# # @yield [Entity] Yields each entity to the given block.
# @!method empty?
# # @return [Integer] True if the collection has no entities, otherwise
# false.
delegate \
:count,
:each,
:empty?,
:to => :@entities
# Adds the specified entity to the collection, if it is not already part of
# the collection.
#
# @param value [Entity] The entity to add.
#
# @return [Collection] The collection.
#
# @raise ArgumentError if the object is not a valid entity for the
# association.
def << new_value
add new_value
self
end # method <<
# @return [Boolean] True if the other object is an array or collection and
# contains the same entities, otherwise false.
def == other
return true if other.is_a?(Array) && other == entities
return true if other.is_a?(self.class) && other.entities == entities
false
end # method ==
# rubocop:disable Metrics/MethodLength
# Adds the specified entity to the collection, if it is not already part of
# the collection.
#
# @param new_value [Entity] The entity to add.
#
# @return [Entity] The added entity.
#
# @raise ArgumentError if the object is not a valid entity for the
# association.
def add new_value
validate_association! metadata, new_value, :allow_nil => false
# 1. Locally cache prior values
inverse_metadata = metadata.inverse_metadata
# 2. Break if collection already includes the value.
return if @entities.include?(new_value)
# 3. Set local values
@entities << new_value
# 4. Set new inverse
if inverse_metadata
new_value.send(
:write_references_one_association,
inverse_metadata,
entity
) # end send
end # if
new_value
end # method add
# rubocop:enable Metrics/MethodLength
# Removes all entities from the collection.
#
# @return [Collection] The empty collection.
def clear
return self if empty?
entities = @entities.dup
inverse_metadata = metadata.inverse_metadata
@entities.clear
entities.each do |deleted|
if inverse_metadata
deleted.send(inverse_metadata.writer_name, nil)
end # if
end # each
self
end # method clear
# @return [Integer] The number of entities in the collection.
def count
@entities.count
end # method count
# rubocop:disable Metrics/MethodLength
# Removes the specified entity from the collection.
#
# @param prior_value [Entity, Object] The entity to remove, or the primary
# key of the entity to remove.
#
# @return [Entity] The removed entity, or nil if the entity was not in the
# collection.
#
# @raise ArgumentError if the object is not a valid entity for the
# association.
def delete prior_value
validate_association! \
metadata,
prior_value,
:allow_nil => false,
:allow_primary_key => true
# 1. Locally cache prior values
inverse_metadata = metadata.inverse_metadata
primary_key =
if prior_value.is_a?(metadata.association_class)
prior_value.id
else
prior_value
end # if-else
# 2. Break if collection already includes the value.
index = @entities.find_index { |item| item.id == primary_key }
return unless index
# 3. Set local values
deleted = @entities.delete_at index
# 4. Set new inverse
if inverse_metadata
deleted.send(inverse_metadata.writer_name, nil)
end # if
prior_value
end # method delete
# rubocop:enable Metrics/MethodLength
# Returns the collection entities as an immutable array.
#
# @return [Array<Entity>] The entities in the collection.
def to_a
@entities.dup.freeze
end # method to_a
protected
attr_reader :entities
end # class
end # module
|
cwegrzyn/records-mover | tests/unit/db/vertica/test_vertica_db_driver.py | from .base_test_vertica_db_driver import BaseTestVerticaDBDriver
from mock import Mock
from ...records.format_hints import (vertica_format_hints)
import sqlalchemy
class TestVerticaDBDriver(BaseTestVerticaDBDriver):
def test_unload(self):
mock_result = Mock(name='result')
mock_result.rows = 579
self.mock_db_engine.execute.return_value.fetchall.return_value = [mock_result]
self.mock_records_unload_plan.processing_instructions.fail_if_dont_understand = True
self.mock_records_unload_plan.processing_instructions.fail_if_cant_handle_hint = True
self.mock_records_unload_plan.records_format.hints = vertica_format_hints
self.mock_directory.scheme = 's3'
export_count = self.vertica_db_driver\
.unloader().unload(schema='myschema',
table='mytable',
unload_plan=self.mock_records_unload_plan,
directory=self.mock_directory)
self.assertEqual(579, export_count)
def test_unload_to_non_s3(self):
mock_result = Mock(name='result')
mock_result.rows = 579
self.mock_db_engine.execute.return_value.fetchall.return_value = [mock_result]
self.mock_records_unload_plan.processing_instructions.fail_if_dont_understand = True
self.mock_records_unload_plan.processing_instructions.fail_if_cant_handle_hint = True
self.mock_records_unload_plan.records_format.hints = vertica_format_hints
self.mock_directory.scheme = 'mumble'
mock_load_loc = self.mock_s3_temp_base_loc.temporary_directory().__enter__()
mock_load_creds = mock_load_loc.aws_creds()
mock_load_creds.token = None
export_count = self.vertica_db_driver\
.unloader().unload(schema='myschema',
table='mytable',
unload_plan=self.mock_records_unload_plan,
directory=self.mock_directory)
self.assertEqual(579, export_count)
def test_schema_sql(self):
mock_result = Mock(name='result')
self.mock_db_engine.execute.return_value.fetchall.return_value = [mock_result]
sql = self.vertica_db_driver.schema_sql('myschema', 'mytable')
self.assertEqual(sql, mock_result.EXPORT_OBJECTS)
def test_schema_sql_but_not_from_export_objects(self):
self.mock_db_engine.execute.return_value.fetchall.return_value = []
sql = self.vertica_db_driver.schema_sql('myschema', 'mytable')
self.assertTrue(sql is not None)
def test_has_table_true(self):
mock_schema = Mock(name='schema')
mock_table = Mock(name='table')
self.assertEqual(True,
self.vertica_db_driver.has_table(mock_schema, mock_table))
def test_has_table_false(self):
mock_schema = Mock(name='schema')
mock_table = Mock(name='table')
self.mock_db_engine.execute.side_effect = sqlalchemy.exc.ProgrammingError('statement', {},
'orig')
self.assertEqual(False,
self.vertica_db_driver.has_table(mock_schema, mock_table))
def test_can_load_this_format(self):
mock_source_records_format = Mock(name='source_records_format')
out = self.vertica_db_driver.loader().can_load_this_format(mock_source_records_format)
self.assertEqual(self.mock_vertica_loader.can_load_this_format.return_value,
out)
self.mock_vertica_loader.can_load_this_format.assert_called_with(mock_source_records_format)
def test_integer_limits(self):
int_min, int_max = self.vertica_db_driver.integer_limits(sqlalchemy.sql.sqltypes.INTEGER())
self.assertEqual(int_min, -9223372036854775808)
self.assertEqual(int_max, 9223372036854775807)
def test_fp_constraints(self):
total_bits, significand_bits =\
self.vertica_db_driver.fp_constraints(sqlalchemy.sql.sqltypes.FLOAT())
self.assertEqual(total_bits, 64)
self.assertEqual(significand_bits, 53)
def test_type_for_integer_fits(self):
out = self.vertica_db_driver.type_for_integer(-123, 123)
self.assertEqual(type(out), sqlalchemy.sql.sqltypes.INTEGER)
def test_type_for_integer_too_big(self):
out = self.vertica_db_driver.type_for_integer(-12300000000000000000, 123000000000000000000)
self.assertEqual(type(out), sqlalchemy.sql.sqltypes.Numeric)
def test_type_for_floating_point_too_big(self):
out = self.vertica_db_driver.type_for_floating_point(100, 80)
self.assertEqual(type(out), sqlalchemy.sql.sqltypes.Float)
self.assertEqual(out.precision, 53)
def test_type_for_floating_point_fits(self):
out = self.vertica_db_driver.type_for_floating_point(12, 8)
self.assertEqual(type(out), sqlalchemy.sql.sqltypes.Float)
self.assertEqual(out.precision, 8)
|
carlosrovira/flex-sdk | modules/thirdparty/batik/sources/org/apache/flex/forks/batik/bridge/SVGGlyphElementBridge.java | <filename>modules/thirdparty/batik/sources/org/apache/flex/forks/batik/bridge/SVGGlyphElementBridge.java
/*
Copyright 2001,2003 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.flex.forks.batik.bridge;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.flex.forks.batik.gvt.CompositeGraphicsNode;
import org.apache.flex.forks.batik.gvt.GraphicsNode;
import org.apache.flex.forks.batik.gvt.font.Glyph;
import org.apache.flex.forks.batik.gvt.font.GVTFontFace;
import org.apache.flex.forks.batik.gvt.text.TextPaintInfo;
import org.apache.flex.forks.batik.parser.AWTPathProducer;
import org.apache.flex.forks.batik.parser.ParseException;
import org.apache.flex.forks.batik.parser.PathParser;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Bridge class for the <glyph> element.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: SVGGlyphElementBridge.java,v 1.14 2004/09/06 00:01:58 deweese Exp $
*/
public class SVGGlyphElementBridge extends AbstractSVGBridge
implements ErrorConstants {
/**
* Constructs a new bridge for the <glyph> element.
*/
protected SVGGlyphElementBridge() {}
/**
* Returns 'glyph'.
*/
public String getLocalName() {
return SVG_GLYPH_TAG;
}
/**
* Constructs a new Glyph that represents the specified <glyph> element
* at the requested size.
*
* @param ctx The current bridge context.
* @param glyphElement The glyph element to base the glyph construction on.
* @param textElement The textElement the glyph will be used for.
* @param glyphCode The unique id to give to the new glyph.
* @param fontSize The font size used to determine the size of the glyph.
* @param fontFace The font face object that contains the font attributes.
*
* @return The new Glyph.
*/
public Glyph createGlyph(BridgeContext ctx,
Element glyphElement,
Element textElement,
int glyphCode,
float fontSize,
GVTFontFace fontFace,
TextPaintInfo tpi) {
float fontHeight = fontFace.getUnitsPerEm();
float scale = fontSize/fontHeight;
AffineTransform scaleTransform
= AffineTransform.getScaleInstance(scale, -scale);
// create a shape that represents the d attribute
String d = glyphElement.getAttributeNS(null, SVG_D_ATTRIBUTE);
Shape dShape = null;
if (d.length() != 0) {
AWTPathProducer app = new AWTPathProducer();
// Glyph is supposed to use properties from text element.
app.setWindingRule(CSSUtilities.convertFillRule(textElement));
try {
PathParser pathParser = new PathParser();
pathParser.setPathHandler(app);
pathParser.parse(d);
} catch (ParseException ex) {
throw new BridgeException(glyphElement,
ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object [] {SVG_D_ATTRIBUTE});
} finally {
// transform the shape into the correct coord system
Shape shape = app.getShape();
Shape transformedShape
= scaleTransform.createTransformedShape(shape);
dShape = transformedShape;
}
}
// process any glyph children
// first see if there are any, because don't want to do the following
// bit of code if we can avoid it
NodeList glyphChildren = glyphElement.getChildNodes();
int numChildren = glyphChildren.getLength();
int numGlyphChildren = 0;
for (int i = 0; i < numChildren; i++) {
Node childNode = glyphChildren.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
numGlyphChildren++;
}
}
CompositeGraphicsNode glyphContentNode = null;
if (numGlyphChildren > 0) { // the glyph has child elements
// build the GVT tree that represents the glyph children
GVTBuilder builder = ctx.getGVTBuilder();
glyphContentNode = new CompositeGraphicsNode();
//
// need to clone the parent font element and glyph element
// this is so that the glyph doesn't inherit anything past the font element
//
Element fontElementClone
= (Element)glyphElement.getParentNode().cloneNode(false);
// copy all font attributes over
NamedNodeMap fontAttributes
= glyphElement.getParentNode().getAttributes();
int numAttributes = fontAttributes.getLength();
for (int i = 0; i < numAttributes; i++) {
fontElementClone.setAttributeNode((Attr)fontAttributes.item(i));
}
Element clonedGlyphElement = (Element)glyphElement.cloneNode(true);
fontElementClone.appendChild(clonedGlyphElement);
textElement.appendChild(fontElementClone);
CompositeGraphicsNode glyphChildrenNode
= new CompositeGraphicsNode();
glyphChildrenNode.setTransform(scaleTransform);
NodeList clonedGlyphChildren = clonedGlyphElement.getChildNodes();
int numClonedChildren = clonedGlyphChildren.getLength();
for (int i = 0; i < numClonedChildren; i++) {
Node childNode = clonedGlyphChildren.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element)childNode;
GraphicsNode childGraphicsNode =
builder.build(ctx, childElement);
glyphChildrenNode.add(childGraphicsNode);
}
}
glyphContentNode.add(glyphChildrenNode);
textElement.removeChild(fontElementClone);
}
// set up glyph attributes
// unicode
String unicode
= glyphElement.getAttributeNS(null, SVG_UNICODE_ATTRIBUTE);
// glyph-name
String nameList
= glyphElement.getAttributeNS(null, SVG_GLYPH_NAME_ATTRIBUTE);
Vector names = new Vector();
StringTokenizer st = new StringTokenizer(nameList, " ,");
while (st.hasMoreTokens()) {
names.add(st.nextToken());
}
// orientation
String orientation
= glyphElement.getAttributeNS(null, SVG_ORIENTATION_ATTRIBUTE);
// arabicForm
String arabicForm
= glyphElement.getAttributeNS(null, SVG_ARABIC_FORM_ATTRIBUTE);
// lang
String lang = glyphElement.getAttributeNS(null, SVG_LANG_ATTRIBUTE);
Element parentFontElement = (Element)glyphElement.getParentNode();
// horz-adv-x
String s = glyphElement.getAttributeNS(null, SVG_HORIZ_ADV_X_ATTRIBUTE);
if (s.length() == 0) {
// look for attribute on parent font element
s = parentFontElement.getAttributeNS(null, SVG_HORIZ_ADV_X_ATTRIBUTE);
if (s.length() == 0) {
// throw an exception since this attribute is required on the font element
throw new BridgeException (parentFontElement, ERR_ATTRIBUTE_MISSING,
new Object[] {SVG_HORIZ_ADV_X_ATTRIBUTE});
}
}
float horizAdvX;
try {
horizAdvX = SVGUtilities.convertSVGNumber(s) * scale;
} catch (NumberFormatException ex) {
throw new BridgeException
(glyphElement, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object [] {SVG_HORIZ_ADV_X_ATTRIBUTE, s});
}
// vert-adv-y
s = glyphElement.getAttributeNS(null, SVG_VERT_ADV_Y_ATTRIBUTE);
if (s.length() == 0) {
// look for attribute on parent font element
s = parentFontElement.getAttributeNS(null, SVG_VERT_ADV_Y_ATTRIBUTE);
if (s.length() == 0) {
// not specified on parent either, use one em
s = String.valueOf(fontFace.getUnitsPerEm());
}
}
float vertAdvY;
try {
vertAdvY = SVGUtilities.convertSVGNumber(s) * scale;
} catch (NumberFormatException ex) {
throw new BridgeException
(glyphElement, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object [] {SVG_VERT_ADV_Y_ATTRIBUTE, s});
}
// vert-origin-x
s = glyphElement.getAttributeNS(null, SVG_VERT_ORIGIN_X_ATTRIBUTE);
if (s.length() == 0) {
// look for attribute on parent font element
s = parentFontElement.getAttributeNS(null, SVG_VERT_ORIGIN_X_ATTRIBUTE);
if (s.length() == 0) {
// not specified so use the default value which is horizAdvX/2
s = Float.toString(horizAdvX/2);
}
}
float vertOriginX;
try {
vertOriginX = SVGUtilities.convertSVGNumber(s) * scale;
} catch (NumberFormatException ex) {
throw new BridgeException
(glyphElement, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object [] {SVG_VERT_ORIGIN_X_ATTRIBUTE, s});
}
// vert-origin-y
s = glyphElement.getAttributeNS(null, SVG_VERT_ORIGIN_Y_ATTRIBUTE);
if (s.length() == 0) {
// look for attribute on parent font element
s = parentFontElement.getAttributeNS(null, SVG_VERT_ORIGIN_Y_ATTRIBUTE);
if (s.length() == 0) {
// not specified so use the default value which is the fonts ascent
s = String.valueOf(fontFace.getAscent());
}
}
float vertOriginY;
try {
vertOriginY = SVGUtilities.convertSVGNumber(s) * -scale;
} catch (NumberFormatException ex) {
throw new BridgeException
(glyphElement, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object [] {SVG_VERT_ORIGIN_Y_ATTRIBUTE, s});
}
Point2D vertOrigin = new Point2D.Float(vertOriginX, vertOriginY);
// get the horizontal origin from the parent font element
// horiz-origin-x
s = parentFontElement.getAttributeNS(null, SVG_HORIZ_ORIGIN_X_ATTRIBUTE);
if (s.length() == 0) {
// not specified so use the default value which is 0
s = SVG_HORIZ_ORIGIN_X_DEFAULT_VALUE;
}
float horizOriginX;
try {
horizOriginX = SVGUtilities.convertSVGNumber(s) * scale;
} catch (NumberFormatException ex) {
throw new BridgeException
(parentFontElement, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object [] {SVG_HORIZ_ORIGIN_X_ATTRIBUTE, s});
}
// horiz-origin-y
s = parentFontElement.getAttributeNS(null, SVG_HORIZ_ORIGIN_Y_ATTRIBUTE);
if (s.length() == 0) {
// not specified so use the default value which is 0
s = SVG_HORIZ_ORIGIN_Y_DEFAULT_VALUE;
}
float horizOriginY;
try {
horizOriginY = SVGUtilities.convertSVGNumber(s) * -scale;
} catch (NumberFormatException ex) {
throw new BridgeException
(glyphElement, ERR_ATTRIBUTE_VALUE_MALFORMED,
new Object [] {SVG_HORIZ_ORIGIN_Y_ATTRIBUTE, s});
}
Point2D horizOrigin = new Point2D.Float(horizOriginX, horizOriginY);
// return a new Glyph
return new Glyph(unicode, names, orientation,
arabicForm, lang, horizOrigin, vertOrigin,
horizAdvX, vertAdvY, glyphCode,
tpi, dShape, glyphContentNode);
}
}
|
abouroubi/azure-sdk-for-js | sdk/keyvault/keyvault-secrets/recordings/node/secret_client__list_secrets_in_various_ways/recording_can_retrieve_all_versions_of_a_secret_by_page.js | let nock = require('nock');
module.exports.hash = "7496025bac43cb1c8b22ee827d40e11a";
module.exports.testInfo = {"uniqueName":{},"newDate":{}}
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.put('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(401, {"error":{"code":"Unauthorized","message":"Request is missing a Bearer or PoP token."}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'87',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'WWW-Authenticate',
'Bearer authorization="https://login.windows.net/azure_tenant_id", resource="https://vault.azure.net"',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'd55eec8a-686a-4d9c-91ee-5991820c80e3',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:06 GMT'
]);
nock('https://login.microsoftonline.com:443', {"encodedQueryParams":true})
.post('/azure_tenant_id/oauth2/v2.0/token', "response_type=token&grant_type=client_credentials&client_id=azure_client_id&client_secret=azure_client_secret&scope=https%3A%2F%2Fvault.azure.net%2F.default")
.reply(200, {"token_type":"Bearer","expires_in":86399,"ext_expires_in":86399,"access_token":"access_token"}, [
'Cache-Control',
'no-cache, no-store',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'x-ms-request-id',
'bdab5f05-cd83-4feb-9578-ad1b547d7000',
'x-ms-ests-server',
'2.1.10433.14 - EUS ProdSlices',
'P3P',
'CP="DSP CUR OTPi IND OTRi ONL FIN"',
'Set-Cookie',
'fpc=AnnH6thWKDZMuFMJUm6rJdc_aSJHAQAAAK6iOdYOAAAA; expires=Thu, 28-May-2020 04:06:07 GMT; path=/; secure; HttpOnly; SameSite=None',
'Set-Cookie',
'x-ms-gateway-slice=estsfd; path=/; SameSite=None; secure; HttpOnly',
'Set-Cookie',
'stsservicecookie=estsfd; path=/; SameSite=None; secure; HttpOnly',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'1315'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.put('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-', {"value":"SECRET_VALUE0","attributes":{}})
.query(true)
.reply(200, {"value":"SECRET_VALUE0","id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/49b64f0f20e14323bb4348452aaacdee","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'd3a9ff88-1db4-46f9-97d3-7afa536a8918',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'319'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.put('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-', {"value":"SECRET_VALUE1","attributes":{}})
.query(true)
.reply(200, {"value":"SECRET_VALUE1","id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/1a17664491aa4bb7b3164a42908a1e96","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'404a4e15-fb0b-4112-90e8-bbf4bcfcd962',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'319'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.put('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-', {"value":"SECRET_VALUE2","attributes":{}})
.query(true)
.reply(200, {"value":"SECRET_VALUE2","id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/97f26ff2b5384bbe9a7df425d1952bd3","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'44ff7f52-b324-4dcd-83fe-ffaea97da8b4',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'319'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/versions')
.query(true)
.reply(200, {"value":[{"id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/1a17664491aa4bb7b3164a42908a1e96","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}},{"id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/49b64f0f20e14323bb4348452aaacdee","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}},{"id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/97f26ff2b5384bbe9a7df425d1952bd3","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}],"nextLink":null}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'7b2dcf61-154b-467a-b59a-6acfc491fd3c',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'915'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/1a17664491aa4bb7b3164a42908a1e96')
.query(true)
.reply(200, {"value":"SECRET_VALUE1","id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/1a17664491aa4bb7b3164a42908a1e96","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'e4e01dd7-c27d-448d-b71e-52e4de8768b8',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'319'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/49b64f0f20e14323bb4348452aaacdee')
.query(true)
.reply(200, {"value":"SECRET_VALUE0","id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/49b64f0f20e14323bb4348452aaacdee","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'385f1726-0738-474b-a7d2-c5aee5f60d72',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'319'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/97f26ff2b5384bbe9a7df425d1952bd3')
.query(true)
.reply(200, {"value":"SECRET_VALUE2","id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/97f26ff2b5384bbe9a7df425d1952bd3","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'9a11020e-9c8e-41fa-a5fb-7cedc37ac9ce',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'319'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.delete('/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(200, {"recoveryId":"https://keyvault_name.vault.azure.net/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-","deletedDate":1588046767,"scheduledPurgeDate":1595822767,"id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/97f26ff2b5384bbe9a7df425d1952bd3","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'30b15324-da6e-4cba-b011-3766201d23cb',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT',
'Content-Length',
'495'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'e2503dee-a370-4702-8f79-37db015777a5',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'e0cd044d-61b7-417a-ac3a-4e1556c1434b',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:07 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'5a51993b-a0bd-41a4-80f5-d1a109d0e3a0',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:09 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'd0618a45-fc66-46a1-9701-f74a81359fa1',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:11 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'6cc0f519-8c26-4d65-91ea-305e7089d0e3',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:13 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'5002a66c-67f1-4622-96af-5d9b450a9881',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:15 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'b831949f-67af-4a45-80c0-fd67f293e62e',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:17 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'74f53a4d-c291-42f0-9310-62fdd7ca0ed4',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:19 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'819db5a0-759f-4869-a9db-5cc4beb8e265',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:21 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'd918c815-b5a6-4610-bb39-f679c62f549f',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:23 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'f9e37371-9bd6-4f81-8912-883cb09e0c9d',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:26 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'02e0f598-5a0a-44d9-aade-997df8796553',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:28 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'1595e0ed-4512-40b6-b75e-b3d416cdf15a',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:30 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'4233374c-b6db-446e-94ef-38e49e82ca93',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:32 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'f9d3488e-a2cc-48a2-9f5e-2030927c757b',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:34 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'e31bb418-0592-4384-8a8f-6572e3e45546',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:36 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'e5108240-d348-41f3-832e-b2ec355ef3a0',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:38 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'39d47e44-5ecd-4afe-a931-d804e2c433a4',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:40 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'82d4e6b1-cef3-48e1-a01f-258f0c678ee6',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:42 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'70f10ad7-d465-4f00-89e3-0d2514bfe9bc',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:44 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'4a5dac9b-6063-4699-a122-a26d99e43382',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:46 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'e6f11637-dcfb-48f4-8233-d3621ac444eb',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:48 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'a23adeeb-6187-4a57-907e-0ef344c2dbde',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:50 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'00227402-b9f5-48cc-a563-73b453b37088',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:52 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'4fb1ff96-f6dc-412f-9fc9-a2b2395ba99c',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:54 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(404, {"error":{"code":"SecretNotFound","message":"Deleted Secret not found: CRUDSecretName-canretrieveallversionsofasecretbypage-"}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Length',
'143',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'05ddbf75-0f61-492e-b0b5-e73b13205463',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:56 GMT'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.get('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(200, {"recoveryId":"https://keyvault_name.vault.azure.net/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-","deletedDate":1588046767,"scheduledPurgeDate":1595822767,"id":"https://keyvault_name.vault.azure.net/secrets/CRUDSecretName-canretrieveallversionsofasecretbypage-/97f26ff2b5384bbe9a7df425d1952bd3","attributes":{"enabled":true,"created":1588046767,"updated":1588046767,"recoveryLevel":"Recoverable+Purgeable","recoverableDays":90}}, [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Content-Type',
'application/json; charset=utf-8',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'c6235ae7-80d2-4c26-af99-7e6b6f1ddeb6',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:58 GMT',
'Content-Length',
'495'
]);
nock('https://keyvault_name.vault.azure.net:443', {"encodedQueryParams":true})
.delete('/deletedsecrets/CRUDSecretName-canretrieveallversionsofasecretbypage-')
.query(true)
.reply(204, "", [
'Cache-Control',
'no-cache',
'Pragma',
'no-cache',
'Expires',
'-1',
'Server',
'Microsoft-IIS/10.0',
'x-ms-keyvault-region',
'westus',
'x-ms-request-id',
'b139c13e-c80d-4369-a234-55d776376743',
'x-ms-keyvault-service-version',
'1.1.0.898',
'x-ms-keyvault-network-info',
'addr=192.168.127.12;act_addr_fam=InterNetwork;',
'X-AspNet-Version',
'4.0.30319',
'X-Powered-By',
'ASP.NET',
'Strict-Transport-Security',
'max-age=31536000;includeSubDomains',
'X-Content-Type-Options',
'nosniff',
'Date',
'Tue, 28 Apr 2020 04:06:58 GMT'
]);
|
nnkwrik/fangxianyu | goods-service/src/main/java/io/github/nnkwrik/goodsservice/service/UserService.java | <gh_stars>100-1000
package io.github.nnkwrik.goodsservice.service;
import io.github.nnkwrik.goodsservice.model.po.Goods;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author nnkwrik
* @date 18/11/27 20:37
*/
public interface UserService {
Boolean userHasCollect(String userId, int goodsId);
void collectAddOrDelete(int goodsId, String userId, boolean hasCollect);
List<Goods> getUserCollectList(String userId, int page, int size);
List<Goods> getUserBought(String buyerId, int page, int size);
List<Goods> getUserSold(String sellerId, int page, int size);
List<Goods> getUserPosted(String userId, int page, int size);
LinkedHashMap<String, List<Goods>> getUserHistoryList(String userId, int page, int size);
void addWant(int goodsId, String userId);
}
|
guigail/medecine-de-ville | src/components/Results/DoctorsMap/doctors.map.container.js | import { connect } from 'react-redux'
import { getPosition } from 'redux/search'
import { getVisible } from 'redux/doctors'
import { select, unselect, updateMyPosition } from './doctors.map.actions'
import Component from './doctors.map'
const mapStateToProps = state => ({
doctors: getVisible(state),
position: getPosition(state),
})
const mapDispatchToProps = dispatch => ({
selectDoctor: id => dispatch(select(id)),
unselectDoctor: id => dispatch(unselect(id)),
updateMyPosition: () => dispatch(updateMyPosition),
})
export default connect(mapStateToProps, mapDispatchToProps)(Component)
|
immbudden/buddeen | node_modules/simple-get/index.js | <gh_stars>10-100
module.exports = simpleGet
const concat = require('simple-concat')
const decompressResponse = require('decompress-response') // excluded from browser build
const http = require('http')
const https = require('https')
const once = require('once')
const querystring = require('querystring')
const url = require('url')
const isStream = o => o !== null && typeof o === 'object' && typeof o.pipe === 'function'
function simpleGet (opts, cb) {
opts = Object.assign({ maxRedirects: 10 }, typeof opts === 'string' ? { url: opts } : opts)
cb = once(cb)
if (opts.url) {
const { hostname, port, protocol, auth, path } = url.parse(opts.url)
delete opts.url
if (!hostname && !port && !protocol && !auth) opts.path = path // Relative redirect
else Object.assign(opts, { hostname, port, protocol, auth, path }) // Absolute redirect
}
const headers = { 'accept-encoding': 'gzip, deflate' }
if (opts.headers) Object.keys(opts.headers).forEach(k => (headers[k.toLowerCase()] = opts.headers[k]))
opts.headers = headers
let body
if (opts.body) {
body = opts.json && !isStream(opts.body) ? JSON.stringify(opts.body) : opts.body
} else if (opts.form) {
body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form)
opts.headers['content-type'] = 'application/x-www-form-urlencoded'
}
if (body) {
if (!opts.method) opts.method = 'POST'
if (!isStream(body)) opts.headers['content-length'] = Buffer.byteLength(body)
if (opts.json && !opts.form) opts.headers['content-type'] = 'application/json'
}
delete opts.body; delete opts.form
if (opts.json) opts.headers.accept = 'application/json'
if (opts.method) opts.method = opts.method.toUpperCase()
const protocol = opts.protocol === 'https:' ? https : http // Support http/https urls
const req = protocol.request(opts, res => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
opts.url = res.headers.location // Follow 3xx redirects
delete opts.headers.host // Discard `host` header on redirect (see #32)
res.resume() // Discard response
if (opts.method === 'POST' && [301, 302].includes(res.statusCode)) {
opts.method = 'GET' // On 301/302 redirect, change POST to GET (see #35)
delete opts.headers['content-length']; delete opts.headers['content-type']
}
if (opts.maxRedirects-- === 0) return cb(new Error('too many redirects'))
else return simpleGet(opts, cb)
}
const tryUnzip = typeof decompressResponse === 'function' && opts.method !== 'HEAD'
cb(null, tryUnzip ? decompressResponse(res) : res)
})
req.on('timeout', () => {
req.abort()
cb(new Error('Request timed out'))
})
req.on('error', cb)
if (isStream(body)) body.on('error', cb).pipe(req)
else req.end(body)
return req
}
simpleGet.concat = (opts, cb) => {
return simpleGet(opts, (err, res) => {
if (err) return cb(err)
concat(res, (err, data) => {
if (err) return cb(err)
if (opts.json) {
try {
data = JSON.parse(data.toString())
} catch (err) {
return cb(err, res, data)
}
}
cb(null, res, data)
})
})
}
;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(method => {
simpleGet[method] = (opts, cb) => {
if (typeof opts === 'string') opts = {url: opts}
return simpleGet(Object.assign({ method: method.toUpperCase() }, opts), cb)
}
})
|
ArcGIS/dynamic-situational-awareness-qt | Shared/markup/MarkupBroadcast.h | <reponame>ArcGIS/dynamic-situational-awareness-qt<gh_stars>10-100
/*******************************************************************************
* Copyright 2012-2018 Esri
*
* 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 MARKUPBROADCAST_H
#define MARKUPBROADCAST_H
// toolkit headers
#include "AbstractTool.h"
class QJsonObject;
class QJsonDocument;
namespace Dsa
{
class DataSender;
class DataListener;
class MarkupBroadcast : public AbstractTool
{
Q_OBJECT
public:
explicit MarkupBroadcast(QObject* parent = nullptr);
~MarkupBroadcast();
QString toolName() const override;
void setProperties(const QVariantMap& properties) override;
void broadcastMarkup(const QString& json);
signals:
void markupReceived(const QString& filePath, const QString& sharedBy);
void markupSent(const QString& filePath);
private:
void updateDataSender();
void updateDataListener();
static const QString MARKUPCONFIG_PROPERTYNAME;
static const QString ROOTDATA_PROPERTYNAME;
static const QString UDPPORT_PROPERTYNAME;
static const QString USERNAME_PROPERTYNAME;
static const QString MARKUPKEY;
static const QString NAMEKEY;
static const QString SHAREDBYKEY;
QString m_username;
QString m_rootDataDirectory;
DataSender* m_dataSender;
DataListener* m_dataListener;
int m_udpPort = -1;
};
} // Dsa
#endif // MARKUPBROADCAST_H
|
ieg-vienna/TimeBench | src/timeBench/data/io/GraphMLTemporalDatasetWriter.java | <reponame>ieg-vienna/TimeBench<filename>src/timeBench/data/io/GraphMLTemporalDatasetWriter.java
package timeBench.data.io;
import static prefuse.data.io.GraphMLWriter.Tokens;
import static prefuse.data.io.GraphMLWriter.TYPES;
import java.io.OutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import prefuse.data.Graph;
import prefuse.data.Schema;
import prefuse.data.io.DataIOException;
import prefuse.data.io.GraphMLWriter;
import prefuse.util.collections.IntIterator;
import timeBench.data.GenericTemporalElement;
import timeBench.data.TemporalDataset;
import timeBench.data.TemporalElement;
import timeBench.data.TemporalObject;
/**
* writes a {@link TemporalDataset} to XML using the GraphML language. It is
* implemented with SAX using JAXP.
*
* TODO calendar
* TODO handle default values of data columns
*
* <p>
* GraphML only supports attributes of primitive types and string. Only
* attributes of temporal objects are stored, i.e. the attributes of edges
* between temporal objects are ignored.
*
* <p>
* The class is not thread-safe. Each thread should use its own instance.
*
* @author Rind
*
* @see {@linkplain http://graphml.graphdrawing.org/primer/graphml-primer.html}
*/
public class GraphMLTemporalDatasetWriter extends AbstractTemporalDatasetWriter {
public static final String GRAPHML_NS = "http://graphml.graphdrawing.org/xmlns";
public static final String OBJECT_PREFIX = "o";
public static final String ELEMENT_PREFIX = "t";
public static final String ROOT = "root";
public static final String EDGE_DATA_PREFIX = "edge-";
public static final String RESERVED_FIELD_PREFIX = "_";
private TransformerHandler hd = null;
@Override
public void writeData(TemporalDataset tmpds, OutputStream os)
throws DataIOException {
writeData(tmpds, new StreamResult(os));
}
/**
* Write a {@link TemporalDataset} to a JAXP {@link Result}.
*
* @param tmpds
* the {@link TemporalDataset} to write
* @param result
* the JAXP result to write the temporal dataset to
* @throws DataIOException
*/
public void writeData(TemporalDataset tmpds, Result result)
throws DataIOException {
try {
// first, check the schema to ensure GraphML compatibility
GraphMLWriter.checkGraphMLSchema(tmpds.getDataColumnSchema());
GraphMLWriter.checkGraphMLSchema(tmpds.getEdgeTable().getSchema());
// setup SAX to identity transform events to a stream; cp.
// http://www.javazoom.net/services/newsletter/xmlgeneration.html
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();
hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
hd.setResult(result);
// check XML namespace support -- did not work??
// System.err.println(tf.getFeature("http://xml.org/sax/features/namespaces"));
// System.err.println(tf.getFeature("http://xml.org/sax/features/namespace-prefixes"));
// *** prologue ***
hd.startDocument();
// <graphml ...
hd.startPrefixMapping("", GRAPHML_NS);
hd.startPrefixMapping("xsi",
"http://www.w3.org/2001/XMLSchema-instance");
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(
"http://www.w3.org/2001/XMLSchema-instance",
"schemaLocation",
"xsi:schemaLocation",
"CDATA",
GRAPHML_NS
+ " http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd");
hd.startElement(GRAPHML_NS, Tokens.GRAPHML, Tokens.GRAPHML, atts);
// <key ... elements
writeAttributeSchema(tmpds);
// <graph ...
atts.clear();
atts.addAttribute(GRAPHML_NS, Tokens.ID, Tokens.ID, "CDATA",
"temporalData");
atts.addAttribute(GRAPHML_NS, Tokens.EDGEDEF, Tokens.EDGEDEF,
"CDATA", Tokens.DIRECTED);
hd.startElement(GRAPHML_NS, Tokens.GRAPH, Tokens.GRAPH, atts);
// *** nodes ***
AttributesImpl nodeAtts = new AttributesImpl();
nodeAtts.addAttribute(GRAPHML_NS, Tokens.ID, Tokens.ID, "CDATA", "");
AttributesImpl dataAtts = new AttributesImpl();
dataAtts.addAttribute(GRAPHML_NS, Tokens.KEY, Tokens.KEY, "CDATA",
"");
writeTemporalElements(tmpds, nodeAtts, dataAtts);
writeTemporalObjects(tmpds, nodeAtts, dataAtts);
// *** edges ***
AttributesImpl edgeAtts = new AttributesImpl();
edgeAtts.addAttribute(GRAPHML_NS, Tokens.SOURCE, Tokens.SOURCE,
"CDATA", "");
edgeAtts.addAttribute(GRAPHML_NS, Tokens.TARGET, Tokens.TARGET,
"CDATA", "");
writeBipartiteEdges(tmpds, edgeAtts);
writeGraphEdgesWithData(tmpds, TemporalObject.ID,
OBJECT_PREFIX, edgeAtts, dataAtts);
writeGraphEdges(tmpds.getTemporalElements(),
TemporalElement.ID, ELEMENT_PREFIX,
edgeAtts);
// *** root objects ***
writeRoots(tmpds, nodeAtts, edgeAtts);
// *** epilogue ***
hd.endElement(GRAPHML_NS, Tokens.GRAPH, Tokens.GRAPH);
hd.endElement(GRAPHML_NS, Tokens.GRAPHML, Tokens.GRAPHML);
hd.endPrefixMapping("");
hd.endPrefixMapping("xsi");
hd.endDocument();
} catch (TransformerConfigurationException e) {
throw new DataIOException(e);
} catch (SAXException e) {
throw new DataIOException(e);
} finally {
hd = null;
}
}
// ----- middle abstraction layer: write TimeBench data structures -----
/**
* generate key elements needed for this temporal dataset.
*
* @param tmpds
* @throws SAXException
*/
private void writeAttributeSchema(TemporalDataset tmpds)
throws SAXException {
AttributesImpl keyAtts = new AttributesImpl();
keyAtts.addAttribute(GRAPHML_NS, Tokens.ID, Tokens.ID, "CDATA", "");
keyAtts.addAttribute(GRAPHML_NS, Tokens.ATTRNAME, Tokens.ATTRNAME,
"CDATA", "");
keyAtts.addAttribute(GRAPHML_NS, Tokens.ATTRTYPE, Tokens.ATTRTYPE,
"CDATA", "");
keyAtts.addAttribute(GRAPHML_NS, Tokens.FOR, Tokens.FOR, "CDATA",
"node");
// key elements for predefined field values
writeGraphMLKey(RESERVED_FIELD_PREFIX + TemporalElement.INF,
long.class, keyAtts);
writeGraphMLKey(RESERVED_FIELD_PREFIX + TemporalElement.SUP,
long.class, keyAtts);
writeGraphMLKey(RESERVED_FIELD_PREFIX + TemporalElement.GRANULARITY_ID,
int.class, keyAtts);
writeGraphMLKey(RESERVED_FIELD_PREFIX
+ TemporalElement.GRANULARITY_CONTEXT_ID, int.class, keyAtts);
writeGraphMLKey(RESERVED_FIELD_PREFIX + TemporalElement.KIND,
int.class, keyAtts);
// key elements for application-specific field values
// XXX consider getDataColumnSchema() -- Bug with depth & MuTIny
Schema dataElements = tmpds.getNodeTable().getSchema();
for (int i = 0; i < dataElements.getColumnCount(); i++) {
String name = dataElements.getColumnName(i);
// column names starting with "_" are reserved
if (! name.startsWith(RESERVED_FIELD_PREFIX)) {
writeGraphMLKey(name, dataElements.getColumnType(i), keyAtts);
}
}
Schema edgeElements = tmpds.getEdgeTable().getSchema();
keyAtts.setValue(3, "edge");
for (int i = 0; i < edgeElements.getColumnCount(); i++) {
String name = edgeElements.getColumnName(i);
if (! (name.equals(tmpds.getEdgeSourceField()) || name.equals(tmpds.getEdgeTargetField()))) {
writeGraphMLKey(EDGE_DATA_PREFIX+name, name, edgeElements.getColumnType(i), keyAtts);
}
}
}
/**
* generate node elements for all temporal elements in the temporal dataset.
*
* @param tmpds
* @param nodeAtts
* @param dataAtts
* @throws SAXException
*/
private void writeTemporalElements(TemporalDataset tmpds,
AttributesImpl nodeAtts, AttributesImpl dataAtts)
throws SAXException {
for (GenericTemporalElement te : tmpds.temporalElements()) {
nodeAtts.setValue(0, ELEMENT_PREFIX + te.getId());
hd.startElement(GRAPHML_NS, Tokens.NODE, Tokens.NODE, nodeAtts);
// data elements for predefined field values
writeGraphMLData(RESERVED_FIELD_PREFIX + TemporalElement.INF,
Long.toString(te.getInf()), dataAtts);
writeGraphMLData(RESERVED_FIELD_PREFIX + TemporalElement.SUP,
Long.toString(te.getSup()), dataAtts);
writeGraphMLData(RESERVED_FIELD_PREFIX
+ TemporalElement.GRANULARITY_ID,
Integer.toString(te.getGranularityId()), dataAtts);
writeGraphMLData(RESERVED_FIELD_PREFIX
+ TemporalElement.GRANULARITY_CONTEXT_ID,
Integer.toString(te.getGranularityContextId()), dataAtts);
writeGraphMLData(RESERVED_FIELD_PREFIX + TemporalElement.KIND,
Integer.toString(te.getKind()), dataAtts);
hd.endElement(GRAPHML_NS, Tokens.NODE, Tokens.NODE);
}
}
/**
* generate node elements for all temporal objects in the temporal dataset.
*
* @param tmpds
* @param nodeAtts
* @param dataAtts
* @throws SAXException
*/
private void writeTemporalObjects(TemporalDataset tmpds,
AttributesImpl nodeAtts, AttributesImpl dataAtts)
throws SAXException {
for (TemporalObject tObj : tmpds.temporalObjects()) {
nodeAtts.setValue(0, OBJECT_PREFIX + tObj.getId());
hd.startElement("", Tokens.NODE, Tokens.NODE, nodeAtts);
// data elements for application-specific field values
// XXX consider getDataColumnSchema() -- Bug with depth & MuTIny
for (int i = 0; i < tObj.getColumnCount(); i++) {
String name = tObj.getColumnName(i);
// predefined columns are handled differently
if (! name.startsWith(RESERVED_FIELD_PREFIX)) {
writeGraphMLData(name, tObj.getString(i), dataAtts);
}
}
hd.endElement(GRAPHML_NS, Tokens.NODE, Tokens.NODE);
}
}
/**
* generate edge elements for all temporal object – temporal element
* relationships.
*
* @param tmpds
* @param edgeAtts
* @throws SAXException
*/
private void writeBipartiteEdges(TemporalDataset tmpds,
AttributesImpl edgeAtts) throws SAXException {
for (TemporalObject tObj : tmpds.temporalObjects()) {
long objId = tObj.getId();
long elId = tObj.getTemporalElement().getId();
writeGraphMLEdge(OBJECT_PREFIX + objId, ELEMENT_PREFIX + elId,
edgeAtts);
}
}
/**
* generate edge elements for all edges in a graph.
*
* @param graph
* @param idField
* field name of the node identifier
* @param prefix
* prefix for the identifier in GraphML
* @param edgeAtts
* @throws SAXException
*/
private void writeGraphEdges(Graph graph, String idField, String prefix,
AttributesImpl edgeAtts) throws SAXException {
IntIterator edges = graph.edgeRows();
while (edges.hasNext()) {
int edgeRow = edges.nextInt();
int sRow = graph.getSourceNode(edgeRow);
long sId = graph.getNodeTable().getLong(sRow, idField);
int tRow = graph.getTargetNode(edgeRow);
long tId = graph.getNodeTable().getLong(tRow, idField);
writeGraphMLEdge(prefix + sId, prefix + tId, edgeAtts);
}
}
private void writeGraphEdgesWithData(Graph graph, String idField, String prefix,
AttributesImpl edgeAtts, AttributesImpl dataAtts) throws SAXException {
IntIterator edges = graph.edgeRows();
while (edges.hasNext()) {
int edgeRow = edges.nextInt();
int sRow = graph.getSourceNode(edgeRow);
long sId = graph.getNodeTable().getLong(sRow, idField);
int tRow = graph.getTargetNode(edgeRow);
long tId = graph.getNodeTable().getLong(tRow, idField);
edgeAtts.setValue(0, prefix + sId);
edgeAtts.setValue(1, prefix + tId);
hd.startElement(GRAPHML_NS, Tokens.EDGE, Tokens.EDGE, edgeAtts);
// data elements for application-specific field values
Schema edgeSchema = graph.getEdgeTable().getSchema();
for (int i = 0; i < edgeSchema.getColumnCount(); i++) {
String name = edgeSchema.getColumnName(i);
// columns for source and target nodes are excluded
if (! (name.equals(graph.getEdgeSourceField()) || name.equals(graph.getEdgeTargetField()))) {
writeGraphMLData(EDGE_DATA_PREFIX+name, graph.getEdgeTable().getString(edgeRow, name), dataAtts);
}
}
hd.endElement(GRAPHML_NS, Tokens.EDGE, Tokens.EDGE);
}
}
/**
* generate a fake node that has edges from all root objects.
*
* @param tmpds
* @param nodeAtts
* @param edgeAtts
* @throws SAXException
*/
private void writeRoots(TemporalDataset tmpds, AttributesImpl nodeAtts,
AttributesImpl edgeAtts) throws SAXException {
if (tmpds.getRootCount() > 0) {
nodeAtts.setValue(0, ROOT);
hd.startElement("", Tokens.NODE, Tokens.NODE, nodeAtts);
hd.endElement(GRAPHML_NS, Tokens.NODE, Tokens.NODE);
for (TemporalObject obj : tmpds.roots()) {
writeGraphMLEdge(OBJECT_PREFIX + obj.getId(), ROOT, edgeAtts);
}
}
}
// ----- lowest abstraction layer: write atomic GraphML elements -----
/**
* generate a GraphML key element.
*
* @param id
* @param type
* @param keyAtts
* @throws SAXException
*/
private void writeGraphMLKey(String id,
@SuppressWarnings("rawtypes") Class type, AttributesImpl keyAtts)
throws SAXException {
writeGraphMLKey(id, id, type, keyAtts);
}
private void writeGraphMLKey(String id, String name,
@SuppressWarnings("rawtypes") Class type, AttributesImpl keyAtts)
throws SAXException {
keyAtts.setValue(0, id);
keyAtts.setValue(1, name);
keyAtts.setValue(2, (String) TYPES.get(type));
hd.startElement(GRAPHML_NS, Tokens.KEY, Tokens.KEY, keyAtts);
hd.endElement(GRAPHML_NS, Tokens.KEY, Tokens.KEY);
}
/**
* generate a GraphML data element.
*
* @param key
* @param value
* @param dataAtts
* @throws SAXException
*/
private void writeGraphMLData(String key, String value,
AttributesImpl dataAtts) throws SAXException {
dataAtts.setValue(0, key);
hd.startElement(GRAPHML_NS, Tokens.DATA, Tokens.DATA, dataAtts);
hd.characters(value.toCharArray(), 0, value.length());
hd.endElement(GRAPHML_NS, Tokens.DATA, Tokens.DATA);
}
/**
* generate a GraphML edge element.
*
* @param source
* @param target
* @param edgeAtts
* @throws SAXException
*/
private void writeGraphMLEdge(String source, String target,
AttributesImpl edgeAtts) throws SAXException {
// we assume that attribute object has correct structure (performance)
// atts.clear();
// atts.addAttribute("", "", SOURCE, "CDATA", source);
// atts.addAttribute("", "", TARGET, "CDATA", target);
edgeAtts.setValue(0, source);
edgeAtts.setValue(1, target);
hd.startElement(GRAPHML_NS, Tokens.EDGE, Tokens.EDGE, edgeAtts);
hd.endElement(GRAPHML_NS, Tokens.EDGE, Tokens.EDGE);
}
}
|
linuxbender/react-nd | react-fundamentals/contacts/src/ListContacts.spec.js | <gh_stars>0
import React from 'react';
import ListContacts from './ListContacts'
import { shallow } from 'enzyme';
describe('<ListContacts/> component tests', () => {
it('Component is loaded without crashing', () => {
shallow(<ListContacts contacts={[]} onDeleteContact={()=> ''} />);
});
it('Contains <ol/> element and has className contact-list', () => {
const testee = shallow(<ListContacts contacts={[]} onDeleteContact={()=> ''} />);
expect(testee.find('ol')).toHaveClassName('contact-list');
});
it('When contacts is empty then should no list items <li> displayed ', () => {
const testee = shallow(<ListContacts contacts={[]} onDeleteContact={()=> ''} />);
expect(testee.find('li')).toBeEmpty();
});
it('When contacts is set with an empty list then should no list items <li> displayed ', () => {
const contacts = [];
const testee = shallow(<ListContacts contacts={contacts} onDeleteContact={()=> ''} />);
expect(testee.find('li')).toBeEmpty();
});
it('When contacts is set with one item then should one list item displayed', () => {
const contacts = [{
"id": "ryan",
"name": "<NAME>",
"email": "<EMAIL>",
"avatarURL": "http://localhost:5001/ryan.jpg"
}];
const testee = shallow(<ListContacts contacts={contacts} onDeleteContact={()=> ''} />);
expect(testee.find('li')).toHaveLength(1);
});
it('When contacts is set with one item then should props.contacts have one item', () => {
const contacts = [{
"id": "ryan",
"name": "<NAME>",
"email": "<EMAIL>",
"avatarURL": "http://localhost:5001/ryan.jpg"
}];
const testee = shallow(<ListContacts contacts={contacts} onDeleteContact={()=> ''} />);
expect(testee.contains(contacts[0].email)).toBeTruthy();
expect(testee.contains(contacts[0].name)).toBeTruthy();
});
});
|
JungyeonYoon/MicroSuite | src/Router/lookup_service/src/thread_safe_map.cpp | <reponame>JungyeonYoon/MicroSuite
#include <iostream>
#include <mutex> // For std::unique_lock
#include <shared_mutex>
#include <thread>
#include <map>
class ThreadSafeMap {
public:
ThreadSafeMap() = default;
// Multiple threads/readers can read the counter's value at the same time.
std::string Get(std::string key) {
std::shared_lock<std::shared_mutex> lock(mutex_);
try {
map_.at(key);
} catch( ... ) {
return "nack";
}
return map_[key];
}
// Only one thread/writer can increment/write the counter's value.
void Set(std::string key, std::string value) {
std::unique_lock<std::shared_mutex> lock(mutex_);
map_[key] = value;
}
private:
mutable std::shared_mutex mutex_;
std::map<std::string, std::string> map_;
};
|
Eroo36/node-social-auths | src/helpers/user-helper.js | <reponame>Eroo36/node-social-auths<filename>src/helpers/user-helper.js
import { User } from "../models/index.js";
export class UserHelper {
static async login(req, user, done) {
req.logIn(user, function (err) {
if (err) {
return done(err);
}
});
}
static async createUser(email, accountId, propertyModel) {
const newUser = await new User({
linkedEmails: [email],
linkedAccounts: [{ accountId, propertyModel }],
});
await newUser.save();
}
// create a new user model in case if this is the first time user is linking accounts
static async createLinkedUser(
modelUserOne,
modelUserTwo,
linkedEmail,
currentEmail,
currentModel,
linkModel
) {
const newUser = new User({
linkedAccounts: [
{ accountId: modelUserOne._id, propertyModel: currentModel },
{ accountId: modelUserTwo._id, propertyModel: linkModel },
],
linkedEmails: [linkedEmail, currentEmail],
});
await newUser.save();
return newUser;
}
// add the account to be linked to the user model
static async findByIdAndPush(
currentUser,
modelUserTwo,
linkedEmail,
linkModel
) {
// if this account has not been linked before update user model otherwise dont update it and just return current model
const checkLinked = await this.findIfLinked(
currentUser._id,
modelUserTwo._id
);
if (!checkLinked) {
const updatedUser = await User.findByIdAndUpdate(
currentUser._id,
{
$push: {
linkedAccounts: {
accountId: modelUserTwo._id,
propertyModel: linkModel,
},
linkedEmails: linkedEmail,
},
},
{ new: true }
);
return updatedUser;
} else {
return currentUser;
}
}
//Check if this account has been linked before
static async findIfLinked(currentUserId, linkAccountId) {
const user = await User.findById(currentUserId);
let accounts = user.linkedAccounts;
const check = accounts.some(
(account) =>
JSON.stringify(account.accountId) === JSON.stringify(linkAccountId)
);
if (check) {
return true;
} else {
return false;
}
}
static async getPopulatedUser(user) {
const currentUser = await User.findOne({
"linkedAccounts.accountId": { $in: user._id },
});
const populated = await User.populate(currentUser, {
path: "linkedAccounts.accountId",
});
return populated;
}
static async checkIfThereIsLinkedUser(populatedUser, currentUser) {
return populatedUser.linkedAccounts.some(
(account) =>
JSON.stringify(account.accountId._id) ===
JSON.stringify(currentUser._id)
);
}
}
|
patrick4444/TPShare | FCPE_JDBC/src/fr/imie/persistence/ConnexionManagement.java | package fr.imie.persistence;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnexionManagement implements IConnexionManagement {
public ConnexionManagement() {
super();
}
@Override
public void closeJDBCResources(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null && !resultSet.isClosed()) {
resultSet.close();
}
if (statement != null && !statement.isClosed()) {
statement.close();
}
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Connection initConnexion() throws SQLException {
Connection connection;
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/fcpe", "postgres", "postgres");
return connection;
}
} |
Peiiii/wpkit | test3.py | from wpkit.basic import json_load,json_dump
from wpkit.piu import BackupDB
db=BackupDB('D:\work\wpkit\data\db')
info=db.get("fund_infos")
db.set('all_funds',info)
print(info)
|
CRaFT4ik/2021-highload-dht | src/test/java/ru/mail/polis/service/TwoNodeTest.java | <gh_stars>0
/*
* Copyright 2021 (c) Odnoklassniki
*
* 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 ru.mail.polis.service;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
/**
* Unit tests for a two node replicated {@link Service} cluster.
*
* @author <NAME>
*/
class TwoNodeTest extends ClusterTestBase {
private static final Duration TIMEOUT = Duration.ofMinutes(1);
@Override
int getClusterSize() {
return 2;
}
@Test
void tooSmallRF() {
assertTimeoutPreemptively(TIMEOUT, () -> {
assertEquals(400, get(0, randomId(), 0, 2).getStatus());
assertEquals(400, upsert(0, randomId(), randomValue(), 0, 2).getStatus());
assertEquals(400, delete(0, randomId(), 0, 2).getStatus());
});
}
@Test
void tooBigRF() {
assertTimeoutPreemptively(TIMEOUT, () -> {
assertEquals(400, get(0, randomId(), 3, 2).getStatus());
assertEquals(400, upsert(0, randomId(), randomValue(), 3, 2).getStatus());
assertEquals(400, delete(0, randomId(), 3, 2).getStatus());
});
}
@Test
void unreachableRF() {
assertTimeoutPreemptively(TIMEOUT, () -> {
stop(0);
assertEquals(504, get(1, randomId(), 2, 2).getStatus());
assertEquals(504, upsert(1, randomId(), randomValue(), 2, 2).getStatus());
assertEquals(504, delete(1, randomId(), 2, 2).getStatus());
});
}
@Test
void overlapRead() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
// Insert value1
final byte[] value1 = randomValue();
assertEquals(201, upsert(0, key, value1, 1, 2).getStatus());
// Check
checkResponse(200, value1, get(0, key, 2, 2));
checkResponse(200, value1, get(1, key, 2, 2));
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
// Insert value2
final byte[] value2 = randomValue();
assertEquals(201, upsert(1, key, value2, 1, 2).getStatus());
// Check
checkResponse(200, value2, get(0, key, 2, 2));
checkResponse(200, value2, get(1, key, 2, 2));
});
}
@Test
void overlapWrite() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
// Insert value1
final byte[] value1 = randomValue();
assertEquals(201, upsert(0, key, value1, 2, 2).getStatus());
// Check
checkResponse(200, value1, get(0, key, 1, 2));
checkResponse(200, value1, get(1, key, 1, 2));
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
// Insert value2
final byte[] value2 = randomValue();
assertEquals(201, upsert(1, key, value2, 2, 2).getStatus());
// Check
checkResponse(200, value2, get(0, key, 1, 2));
checkResponse(200, value2, get(1, key, 1, 2));
});
}
@Test
void overlapDelete() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
final byte[] value = randomValue();
// Insert & delete at 0
assertEquals(201, upsert(0, key, value, 2, 2).getStatus());
waitForVersionAdvancement();
assertEquals(202, delete(0, key, 2, 2).getStatus());
// Check
assertEquals(404, get(0, key, 1, 2).getStatus());
assertEquals(404, get(1, key, 1, 2).getStatus());
// Insert & delete at 1
assertEquals(201, upsert(1, key, value, 2, 2).getStatus());
waitForVersionAdvancement();
assertEquals(202, delete(1, key, 2, 2).getStatus());
// Check
assertEquals(404, get(0, key, 1, 2).getStatus());
assertEquals(404, get(1, key, 1, 2).getStatus());
});
}
@Test
void missedWrite() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
for (int node = 0; node < getClusterSize(); node++) {
// Reinitialize
restartAllNodes();
// Stop node
stop(node);
// Insert
final byte[] value = randomValue();
assertEquals(201, upsert((node + 1) % getClusterSize(), key, value, 1, 2).getStatus());
// Start node 1
createAndStart(node);
// Check
checkResponse(200, value, get(node, key, 2, 2));
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
}
});
}
@Test
void missedDelete() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
for (int node = 0; node < getClusterSize(); node++) {
// Reinitialize
restartAllNodes();
// Insert
final byte[] value = randomValue();
assertEquals(201, upsert(node, key, value, 2, 2).getStatus());
// Stop node 0
stop(node);
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
// Delete
assertEquals(202, delete((node + 1) % getClusterSize(), key, 1, 2).getStatus());
// Start node 0
createAndStart(node);
// Check
assertEquals(404, get(node, key, 2, 2).getStatus());
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
}
});
}
@Test
void missedOverwrite() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
for (int node = 0; node < getClusterSize(); node++) {
// Reinitialize
restartAllNodes();
// Insert value1
final byte[] value1 = randomValue();
assertEquals(201, upsert(node, key, value1, 2, 2).getStatus());
// Stop node
stop(node);
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
// Insert value2
final byte[] value2 = randomValue();
assertEquals(201, upsert((node + 1) % getClusterSize(), key, value2, 1, 2).getStatus());
// Start node
createAndStart(node);
// Check value2
checkResponse(200, value2, get(node, key, 2, 2));
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
}
});
}
@Test
void missedRecreate() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
for (int node = 0; node < getClusterSize(); node++) {
// Reinitialize
restartAllNodes();
// Insert & delete value1
final byte[] value1 = randomValue();
assertEquals(201, upsert(node, key, value1, 2, 2).getStatus());
waitForVersionAdvancement();
assertEquals(202, delete(node, key, 2, 2).getStatus());
// Stop node
stop(node);
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
// Insert value2
final byte[] value2 = randomValue();
assertEquals(201, upsert((node + 1) % getClusterSize(), key, value2, 1, 2).getStatus());
// Start node
createAndStart(node);
// Check value2
checkResponse(200, value2, get(node, key, 2, 2));
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
}
});
}
@Test
void tolerateFailure() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
for (int node = 0; node < getClusterSize(); node++) {
// Reinitialize
restartAllNodes();
// Insert into node
final byte[] value = randomValue();
assertEquals(201, upsert(node, key, value, 2, 2).getStatus());
// Stop node
stop(node);
// Check
checkResponse(200, value, get((node + 1) % getClusterSize(), key, 1, 2));
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
// Delete
assertEquals(202, delete((node + 1) % getClusterSize(), key, 1, 2).getStatus());
// Check
assertEquals(404, get((node + 1) % getClusterSize(), key, 1, 2).getStatus());
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
}
});
}
@Test
void respectRF() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
final byte[] value = randomValue();
// Insert
assertEquals(201, upsert(0, key, value, 1, 1).getStatus());
// Stop all
for (int node = 0; node < getClusterSize(); node++) {
stop(node);
}
// Check each
int copies = 0;
for (int node = 0; node < getClusterSize(); node++) {
// Start node
createAndStart(node);
// Check
if (get(node, key, 1, 1).getStatus() == 200) {
copies++;
}
// Stop node
stop(node);
}
assertEquals(1, copies);
});
}
@Test
@Disabled("Not implemented functionality")
void repairCheck() {
assertTimeoutPreemptively(TIMEOUT, () -> {
final String key = randomId();
final byte[] value = randomValue();
// Stopping 1
stop(1);
// Insert at 0
assertEquals(201, upsert(0, key, value, 1, 2).getStatus());
// Stopping 0
stop(0);
// Starting 1
createAndStart(1);
// Check 1
assertEquals(404, get(1, key, 1, 2).getStatus());
// Starting 0
createAndStart(0);
// Check 0 & 1
assertEquals(200, get(0, key, 2, 2).getStatus());
// Help implementors with ms precision for conflict resolution
waitForVersionAdvancement();
// Stopping 0
stop(0);
// Check repair between 0 & 1
assertEquals(200, get(1, key, 1, 2).getStatus());
});
}
}
|
hankai17/trafficserver | mgmt/api/EventControlMain.cc | /** @file
A brief file description
@section license License
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.
*/
/*****************************************************************************
* Filename: EventControlMain.cc
* Purpose: Handles all event requests from the user.
* Created: 01/08/01
* Created by: lant
*
***************************************************************************/
#include "tscore/ink_platform.h"
#include "tscore/ink_sock.h"
#include "LocalManager.h"
#include "MgmtSocket.h"
#include "MgmtMarshall.h"
#include "MgmtUtils.h"
#include "EventControlMain.h"
#include "CoreAPI.h"
#include "NetworkUtilsLocal.h"
#include "NetworkMessage.h"
// variables that are very important
ink_mutex mgmt_events_lock;
LLQ *mgmt_events;
std::unordered_map<int, EventClientT *> accepted_clients; // list of all accepted client connections
static TSMgmtError handle_event_message(EventClientT *client, void *req, size_t reqlen);
/*********************************************************************
* new_event_client
*
* purpose: creates a new EventClientT and return pointer to it
* input: None
* output: EventClientT
* note: None
*********************************************************************/
EventClientT *
new_event_client()
{
EventClientT *ele = (EventClientT *)ats_malloc(sizeof(EventClientT));
// now set the alarms registered section
for (bool &i : ele->events_registered) {
i = false;
}
ele->adr = (struct sockaddr *)ats_malloc(sizeof(struct sockaddr));
return ele;
}
/*********************************************************************
* delete_event_client
*
* purpose: frees memory allocated for an EventClientT
* input: EventClientT
* output: None
* note: None
*********************************************************************/
void
delete_event_client(EventClientT *client)
{
if (client) {
ats_free(client->adr);
ats_free(client);
}
return;
}
/*********************************************************************
* remove_event_client
*
* purpose: removes the EventClientT from the specified hashtable; includes
* removing the binding and freeing the ClientT
* input: client - the ClientT to remove
* output:
*********************************************************************/
void
remove_event_client(EventClientT *client, std::unordered_map<int, EventClientT *> &table)
{
// close client socket
close_socket(client->fd);
// remove client binding from hash table
table.erase(client->fd);
// free ClientT
delete_event_client(client);
return;
}
/*********************************************************************
* init_mgmt_events
*
* purpose: initializes the mgmt_events queue which is intended to hold
* TM events.
* input:
* output: TS_ERR_xx
* note: None
*********************************************************************/
TSMgmtError
init_mgmt_events()
{
ink_mutex_init(&mgmt_events_lock);
// initialize queue
mgmt_events = create_queue();
if (!mgmt_events) {
ink_mutex_destroy(&mgmt_events_lock);
return TS_ERR_SYS_CALL;
}
return TS_ERR_OKAY;
}
/*********************************************************************
* delete_mgmt_events
*
* purpose: frees the mgmt_events queue.
* input:
* output: None
* note: None
*********************************************************************/
void
delete_mgmt_events()
{
// obtain lock
ink_mutex_acquire(&mgmt_events_lock);
// delete the queue associated with the queue of events
delete_event_queue(mgmt_events);
// release it
ink_mutex_release(&mgmt_events_lock);
// kill lock
ink_mutex_destroy(&mgmt_events_lock);
delete_queue(mgmt_events);
return;
}
/*********************************************************************
* delete_event_queue
*
* purpose: frees queue where the elements are of type TSMgmtEvent* 's
* input: LLQ * q - a queue with entries of TSMgmtEvent*'s
* output: None
* note: None
*********************************************************************/
void
delete_event_queue(LLQ *q)
{
if (!q) {
return;
}
// now for every element, dequeue and free
TSMgmtEvent *ele;
while (!queue_is_empty(q)) {
ele = (TSMgmtEvent *)dequeue(q);
ats_free(ele);
}
delete_queue(q);
return;
}
/*********************************************************************
* apiEventCallback
*
* purpose: callback function registered with alarm processor so that
* each time alarm is signalled, can enqueue it in the mgmt_events
* queue
* input:
* output: None
* note: None
*********************************************************************/
void
apiEventCallback(alarm_t newAlarm, const char * /* ip ATS_UNUSED */, const char *desc)
{
// create an TSMgmtEvent
// addEvent(new_alarm, ip, desc) // adds event to mgmt_events
TSMgmtEvent *newEvent;
newEvent = TSEventCreate();
newEvent->id = newAlarm;
newEvent->name = get_event_name(newEvent->id);
// newEvent->ip = ats_strdup(ip);
if (desc) {
newEvent->description = ats_strdup(desc);
} else {
newEvent->description = ats_strdup("None");
}
// add it to the mgmt_events list
ink_mutex_acquire(&mgmt_events_lock);
enqueue(mgmt_events, newEvent);
ink_mutex_release(&mgmt_events_lock);
return;
}
/*********************************************************************
* event_callback_main
*
* This function is run as a thread in WebIntrMain.cc that listens on a
* specified socket. It loops until Traffic Manager dies.
* In the loop, it just listens on a socket, ready to accept any connections,
* until receives a request from the remote API client. Parse the request
* to determine which CoreAPI call to make.
*********************************************************************/
void *
event_callback_main(void *arg)
{
int ret;
int *socket_fd;
int con_socket_fd; // main socket for listening to new connections
socket_fd = (int *)arg;
con_socket_fd = *socket_fd; // the socket for event callbacks
Debug("event", "[event_callback_main] listen on socket = %d", con_socket_fd);
// initialize queue for holding mgmt events
if ((ret = init_mgmt_events()) != TS_ERR_OKAY) {
return nullptr;
}
// register callback with alarms processor
lmgmt->alarm_keeper->registerCallback(apiEventCallback);
// now we can start listening, accepting connections and servicing requests
int new_con_fd; // new connection fd when socket accepts connection
fd_set selectFDs; // for select call
EventClientT *client_entry; // an entry of fd to alarms mapping
int fds_ready; // return value for select go here
struct timeval timeout;
while (true) {
// LINUX fix: to prevent hard-spin reset timeout on each loop
timeout.tv_sec = 1;
timeout.tv_usec = 0;
FD_ZERO(&selectFDs);
if (con_socket_fd >= 0) {
FD_SET(con_socket_fd, &selectFDs);
Debug("event", "[event_callback_main] add fd %d to select set", con_socket_fd);
}
// see if there are more fd to set
for (auto &&it : accepted_clients) {
client_entry = it.second;
if (client_entry->fd >= 0) { // add fd to select set
FD_SET(client_entry->fd, &selectFDs);
}
}
// select call - timeout is set so we can check events at regular intervals
fds_ready = mgmt_select(FD_SETSIZE, &selectFDs, (fd_set *)nullptr, (fd_set *)nullptr, &timeout);
// check return
if (fds_ready > 0) {
// we got connections or requests!
// first check for connections!
if (con_socket_fd >= 0 && FD_ISSET(con_socket_fd, &selectFDs)) {
fds_ready--;
// create a new instance of the fd to alarms registered mapping
EventClientT *new_client_con = new_event_client();
if (!new_client_con) {
// Debug ("TS_Control_Main", "can't create new EventClientT for new connection");
} else {
// accept connection
socklen_t addr_len = (sizeof(struct sockaddr));
new_con_fd = mgmt_accept(con_socket_fd, new_client_con->adr, &addr_len);
new_client_con->fd = new_con_fd;
accepted_clients.emplace(new_client_con->fd, new_client_con);
Debug("event", "[event_callback_main] Accept new connection: fd=%d", new_con_fd);
}
} // end if (new_con_fd >= 0 && FD_ISSET(new_con_fd, &selectFDs))
// some other file descriptor; for each one, service request
if (fds_ready > 0) { // RECEIVED A REQUEST from remote API client
// see if there are more fd to set - iterate through all entries in hash table
for (auto it = accepted_clients.begin(); it != accepted_clients.end();) {
client_entry = it->second;
++it; // prevent the breaking of remove_event_client
// got information check
if (client_entry->fd && FD_ISSET(client_entry->fd, &selectFDs)) {
// SERVICE REQUEST - read the op and message into a buffer
// clear the fields first
void *req;
size_t reqlen;
ret = preprocess_msg(client_entry->fd, &req, &reqlen);
if (ret == TS_ERR_NET_READ || ret == TS_ERR_NET_EOF) { // preprocess_msg FAILED!
Debug("event", "[event_callback_main] preprocess_msg FAILED; skip!");
remove_event_client(client_entry, accepted_clients);
continue;
}
ret = handle_event_message(client_entry, req, reqlen);
ats_free(req);
if (ret == TS_ERR_NET_WRITE || ret == TS_ERR_NET_EOF) {
Debug("event", "[event_callback_main] ERROR: handle_control_message");
remove_event_client(client_entry, accepted_clients);
continue;
}
} // end if(client_entry->fd && FD_ISSET(client_entry->fd, &selectFDs))
} // end for (auto it = accepted_clients.begin(); it != accepted_clients.end();)
} // end if (fds_ready > 0)
} // end if (fds_ready > 0)
// ------------ service loop is done, check for events now -------------
// for each event in the mgmt_events list, uses the event id to check the
// events_registered queue for each client connection to see if that client
// has a callback registered for that event_id
TSMgmtEvent *event;
if (!mgmt_events || queue_is_empty(mgmt_events)) { // no events to process
// fprintf(stderr, "[event_callback_main] NO EVENTS TO PROCESS\n");
Debug("event", "[event_callback_main] NO EVENTS TO PROCESS");
continue;
}
// iterate through each event in mgmt_events
while (!queue_is_empty(mgmt_events)) {
ink_mutex_acquire(&mgmt_events_lock); // acquire lock
event = (TSMgmtEvent *)dequeue(mgmt_events); // get what we want
ink_mutex_release(&mgmt_events_lock); // release lock
if (!event) {
continue;
}
// fprintf(stderr, "[event_callback_main] have an EVENT TO PROCESS\n");
// iterate through all entries in hash table, if any
for (auto &&it : accepted_clients) {
client_entry = it.second;
if (client_entry->events_registered[event->id]) {
OpType optype = OpType::EVENT_NOTIFY;
MgmtMarshallString name = event->name;
MgmtMarshallString desc = event->description;
ret = send_mgmt_request(client_entry->fd, OpType::EVENT_NOTIFY, &optype, &name, &desc);
if (ret != TS_ERR_OKAY) {
Debug("event", "sending even notification to fd [%d] failed.", client_entry->fd);
}
}
// get next client connection, if any
} // end while(con_entry)
// now we can delete the event
// fprintf(stderr, "[event_callback_main] DELETE EVENT\n");
TSEventDestroy(event);
} // end while (!queue_is_empty)
} // end while (1)
// delete tables
delete_mgmt_events();
// iterate through hash table; close client socket connections and remove entry
for (auto &&it : accepted_clients) {
client_entry = it.second;
if (client_entry->fd >= 0) {
close_socket(client_entry->fd);
}
accepted_clients.erase(client_entry->fd); // remove binding
delete_event_client(client_entry); // free ClientT
}
// all entries should be removed and freed already
accepted_clients.clear();
ink_thread_exit(nullptr);
return nullptr;
}
/*-------------------------------------------------------------------------
HANDLER FUNCTIONS
--------------------------------------------------------------------------*/
/**************************************************************************
* handle_event_reg_callback
*
* purpose: handles request to register a callback for a specific event (or all events)
* input: client - the client currently reading the msg from
* req - the event_name
* output: TS_ERR_xx
* note: the req should be the event name; does not send a reply to client
*************************************************************************/
static TSMgmtError
handle_event_reg_callback(EventClientT *client, void *req, size_t reqlen)
{
MgmtMarshallInt optype;
MgmtMarshallString name = nullptr;
TSMgmtError ret;
ret = recv_mgmt_request(req, reqlen, OpType::EVENT_REG_CALLBACK, &optype, &name);
if (ret != TS_ERR_OKAY) {
goto done;
}
// mark the specified alarm as "wanting to be notified" in the client's alarm_registered list
if (strlen(name) == 0) { // mark all alarms
for (bool &i : client->events_registered) {
i = true;
}
} else {
int id = get_event_id(name);
if (id < 0) {
ret = TS_ERR_FAIL;
goto done;
}
client->events_registered[id] = true;
}
ret = TS_ERR_OKAY;
done:
ats_free(name);
return ret;
}
/**************************************************************************
* handle_event_unreg_callback
*
* purpose: handles request to unregister a callback for a specific event (or all events)
* input: client - the client currently reading the msg from
* req - the event_name
* output: TS_ERR_xx
* note: the req should be the event name; does not send reply to client
*************************************************************************/
static TSMgmtError
handle_event_unreg_callback(EventClientT *client, void *req, size_t reqlen)
{
MgmtMarshallInt optype;
MgmtMarshallString name = nullptr;
TSMgmtError ret;
ret = recv_mgmt_request(req, reqlen, OpType::EVENT_UNREG_CALLBACK, &optype, &name);
if (ret != TS_ERR_OKAY) {
goto done;
}
// mark the specified alarm as "wanting to be notified" in the client's alarm_registered list
if (strlen(name) == 0) { // mark all alarms
for (bool &i : client->events_registered) {
i = false;
}
} else {
int id = get_event_id(name);
if (id < 0) {
ret = TS_ERR_FAIL;
goto done;
}
client->events_registered[id] = false;
}
ret = TS_ERR_OKAY;
done:
ats_free(name);
return ret;
}
using event_message_handler = TSMgmtError (*)(EventClientT *, void *, size_t);
static const event_message_handler handlers[] = {
nullptr, // RECORD_SET
nullptr, // RECORD_GET
nullptr, // PROXY_STATE_GET
nullptr, // PROXY_STATE_SET
nullptr, // RECONFIGURE
nullptr, // RESTART
nullptr, // BOUNCE
nullptr, // EVENT_RESOLVE
nullptr, // EVENT_GET_MLT
nullptr, // EVENT_ACTIVE
handle_event_reg_callback, // EVENT_REG_CALLBACK
handle_event_unreg_callback, // EVENT_UNREG_CALLBACK
nullptr, // EVENT_NOTIFY
nullptr, // DIAGS
nullptr, // STATS_RESET_NODE
nullptr, // STORAGE_DEVICE_CMD_OFFLINE
nullptr, // RECORD_MATCH_GET
nullptr, // LIFECYCLE_MESSAGE
nullptr, // HOST_STATUS_UP
nullptr, // HOST_STATUS_DOWN
};
static TSMgmtError
handle_event_message(EventClientT *client, void *req, size_t reqlen)
{
OpType optype = extract_mgmt_request_optype(req, reqlen);
if (static_cast<unsigned>(optype) >= countof(handlers)) {
goto fail;
}
if (handlers[static_cast<unsigned>(optype)] == nullptr) {
goto fail;
}
if (mgmt_has_peereid()) {
uid_t euid = -1;
gid_t egid = -1;
// For now, all event messages require privilege. This is compatible with earlier
// versions of Traffic Server that always required privilege.
if (mgmt_get_peereid(client->fd, &euid, &egid) == -1 || (euid != 0 && euid != geteuid())) {
return TS_ERR_PERMISSION_DENIED;
}
}
return handlers[static_cast<unsigned>(optype)](client, req, reqlen);
fail:
mgmt_elog(0, "%s: missing handler for type %d event message\n", __func__, (int)optype);
return TS_ERR_PARAMS;
}
|
jess22664/x3ogre | core/Node.h | <gh_stars>1-10
/*
* X3DObject.h
*
* Created on: 15.11.2013
* Author: baudenri_local
*/
#pragma once
#include <string>
#include <ciso646>
#include <reflection/Object.h>
#include <memory>
namespace X3D {
struct World;
/**
* Superclass every Node that has been parsed from the X3D-File inherits
*/
class Node : public reflection::Object {
protected:
bool _init = false;
public:
virtual void id(const std::string& id) {
}
virtual void initialise(World& world) {
}
};
}
|
AmericaGL/TrashTalk_Dapp | opencv_contrib-3.3.0/modules/ximgproc/src/disparity_filters.cpp | /*
* By downloading, copying, installing or using the software you agree to this license.
* If you do not agree to this license, do not download, install,
* copy or use the software.
*
*
* License Agreement
* For Open Source Computer Vision Library
* (3 - clause BSD License)
*
* 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 names of the copyright holders nor the names of the 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 copyright holders 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.
*/
#include "precomp.hpp"
#include "opencv2/ximgproc/disparity_filter.hpp"
#include "opencv2/imgcodecs.hpp"
#include <math.h>
#include <vector>
namespace cv {
namespace ximgproc {
using std::vector;
#define EPS 1e-43f
class DisparityWLSFilterImpl : public DisparityWLSFilter
{
protected:
int left_offset, right_offset, top_offset, bottom_offset;
Rect valid_disp_ROI;
Rect right_view_valid_disp_ROI;
int min_disp;
bool use_confidence;
Mat confidence_map;
double lambda,sigma_color;
int LRC_thresh,depth_discontinuity_radius;
float depth_discontinuity_roll_off_factor;
float resize_factor;
int num_stripes;
void init(double _lambda, double _sigma_color, bool _use_confidence, int l_offs, int r_offs, int t_offs, int b_offs, int _min_disp);
void computeDepthDiscontinuityMaps(Mat& left_disp, Mat& right_disp, Mat& left_dst, Mat& right_dst);
void computeConfidenceMap(InputArray left_disp, InputArray right_disp);
protected:
struct ComputeDiscontinuityAwareLRC_ParBody : public ParallelLoopBody
{
DisparityWLSFilterImpl* wls;
Mat *left_disp, *right_disp;
Mat *left_disc, *right_disc, *dst;
Rect left_ROI, right_ROI;
int nstripes, stripe_sz;
ComputeDiscontinuityAwareLRC_ParBody(DisparityWLSFilterImpl& _wls, Mat& _left_disp, Mat& _right_disp, Mat& _left_disc, Mat& _right_disc, Mat& _dst, Rect _left_ROI, Rect _right_ROI, int _nstripes);
void operator () (const Range& range) const;
};
struct ComputeDepthDisc_ParBody : public ParallelLoopBody
{
DisparityWLSFilterImpl* wls;
Mat *disp,*disp_squares,*dst;
int nstripes, stripe_sz;
ComputeDepthDisc_ParBody(DisparityWLSFilterImpl& _wls, Mat& _disp, Mat& _disp_squares, Mat& _dst, int _nstripes);
void operator () (const Range& range) const;
};
typedef void (DisparityWLSFilterImpl::*MatOp)(Mat& src, Mat& dst);
struct ParallelMatOp_ParBody : public ParallelLoopBody
{
DisparityWLSFilterImpl* wls;
vector<MatOp> ops;
vector<Mat*> src;
vector<Mat*> dst;
ParallelMatOp_ParBody(DisparityWLSFilterImpl& _wls, vector<MatOp> _ops, vector<Mat*>& _src, vector<Mat*>& _dst);
void operator () (const Range& range) const;
};
void boxFilterOp(Mat& src,Mat& dst)
{
int rad = depth_discontinuity_radius;
boxFilter(src,dst,CV_32F,Size(2*rad+1,2*rad+1),Point(-1,-1));
}
void sqrBoxFilterOp(Mat& src,Mat& dst)
{
int rad = depth_discontinuity_radius;
sqrBoxFilter(src,dst,CV_32F,Size(2*rad+1,2*rad+1),Point(-1,-1));
}
void copyToOp(Mat& src,Mat& dst)
{
src.copyTo(dst);
}
public:
static Ptr<DisparityWLSFilterImpl> create(bool _use_confidence, int l_offs, int r_offs, int t_offs, int b_offs, int min_disp);
void filter(InputArray disparity_map_left, InputArray left_view, OutputArray filtered_disparity_map, InputArray disparity_map_right, Rect ROI, InputArray);
double getLambda() {return lambda;}
void setLambda(double _lambda) {lambda = _lambda;}
double getSigmaColor() {return sigma_color;}
void setSigmaColor(double _sigma_color) {sigma_color = _sigma_color;}
int getLRCthresh() {return LRC_thresh;}
void setLRCthresh(int _LRC_thresh) {LRC_thresh = _LRC_thresh;}
int getDepthDiscontinuityRadius() {return depth_discontinuity_radius;}
void setDepthDiscontinuityRadius(int _disc_radius) {depth_discontinuity_radius = _disc_radius;}
Mat getConfidenceMap() {return confidence_map;}
Rect getROI() {return valid_disp_ROI;}
};
void DisparityWLSFilterImpl::init(double _lambda, double _sigma_color, bool _use_confidence, int l_offs, int r_offs, int t_offs, int b_offs, int _min_disp)
{
left_offset = l_offs; right_offset = r_offs;
top_offset = t_offs; bottom_offset = b_offs;
min_disp = _min_disp;
valid_disp_ROI = Rect();
right_view_valid_disp_ROI = Rect();
min_disp=0;
lambda = _lambda;
sigma_color = _sigma_color;
use_confidence = _use_confidence;
confidence_map = Mat();
LRC_thresh = 24;
depth_discontinuity_radius = 5;
depth_discontinuity_roll_off_factor = 0.001f;
resize_factor = 1.0;
num_stripes = getNumThreads();
}
void DisparityWLSFilterImpl::computeDepthDiscontinuityMaps(Mat& left_disp, Mat& right_disp, Mat& left_dst, Mat& right_dst)
{
Mat left_disp_ROI (left_disp, valid_disp_ROI);
Mat right_disp_ROI(right_disp,right_view_valid_disp_ROI);
Mat ldisp,rdisp,ldisp_squared,rdisp_squared;
{
vector<Mat*> _src; _src.push_back(&left_disp_ROI);_src.push_back(&right_disp_ROI);
_src.push_back(&left_disp_ROI);_src.push_back(&right_disp_ROI);
vector<Mat*> _dst; _dst.push_back(&ldisp); _dst.push_back(&rdisp);
_dst.push_back(&ldisp_squared);_dst.push_back(&rdisp_squared);
vector<MatOp> _ops; _ops.push_back(&DisparityWLSFilterImpl::copyToOp); _ops.push_back(&DisparityWLSFilterImpl::copyToOp);
_ops.push_back(&DisparityWLSFilterImpl::copyToOp); _ops.push_back(&DisparityWLSFilterImpl::copyToOp);
parallel_for_(Range(0,4),ParallelMatOp_ParBody(*this,_ops,_src,_dst));
}
{
vector<Mat*> _src; _src.push_back(&ldisp); _src.push_back(&rdisp);
_src.push_back(&ldisp_squared);_src.push_back(&rdisp_squared);
vector<Mat*> _dst; _dst.push_back(&ldisp); _dst.push_back(&rdisp);
_dst.push_back(&ldisp_squared);_dst.push_back(&rdisp_squared);
vector<MatOp> _ops; _ops.push_back(&DisparityWLSFilterImpl::boxFilterOp); _ops.push_back(&DisparityWLSFilterImpl::boxFilterOp);
_ops.push_back(&DisparityWLSFilterImpl::sqrBoxFilterOp);_ops.push_back(&DisparityWLSFilterImpl::sqrBoxFilterOp);
parallel_for_(Range(0,4),ParallelMatOp_ParBody(*this,_ops,_src,_dst));
}
left_dst = Mat::zeros(left_disp.rows,left_disp.cols,CV_32F);
right_dst = Mat::zeros(right_disp.rows,right_disp.cols,CV_32F);
Mat left_dst_ROI (left_dst,valid_disp_ROI);
Mat right_dst_ROI(right_dst,right_view_valid_disp_ROI);
parallel_for_(Range(0,num_stripes),ComputeDepthDisc_ParBody(*this,ldisp,ldisp_squared,left_dst_ROI ,num_stripes));
parallel_for_(Range(0,num_stripes),ComputeDepthDisc_ParBody(*this,rdisp,rdisp_squared,right_dst_ROI,num_stripes));
}
void DisparityWLSFilterImpl::computeConfidenceMap(InputArray left_disp, InputArray right_disp)
{
Mat ldisp = left_disp.getMat();
Mat rdisp = right_disp.getMat();
Mat depth_discontinuity_map_left,depth_discontinuity_map_right;
right_view_valid_disp_ROI = Rect(ldisp.cols-(valid_disp_ROI.x+valid_disp_ROI.width),valid_disp_ROI.y,
valid_disp_ROI.width,valid_disp_ROI.height);
computeDepthDiscontinuityMaps(ldisp,rdisp,depth_discontinuity_map_left,depth_discontinuity_map_right);
confidence_map = depth_discontinuity_map_left;
parallel_for_(Range(0,num_stripes),ComputeDiscontinuityAwareLRC_ParBody(*this,ldisp,rdisp, depth_discontinuity_map_left,depth_discontinuity_map_right,confidence_map,valid_disp_ROI,right_view_valid_disp_ROI,num_stripes));
confidence_map = 255.0f*confidence_map;
}
Ptr<DisparityWLSFilterImpl> DisparityWLSFilterImpl::create(bool _use_confidence, int l_offs=0, int r_offs=0, int t_offs=0, int b_offs=0, int min_disp=0)
{
DisparityWLSFilterImpl *wls = new DisparityWLSFilterImpl();
wls->init(8000.0,1.0,_use_confidence,l_offs, r_offs, t_offs, b_offs, min_disp);
return Ptr<DisparityWLSFilterImpl>(wls);
}
void DisparityWLSFilterImpl::filter(InputArray disparity_map_left, InputArray left_view, OutputArray filtered_disparity_map, InputArray disparity_map_right, Rect ROI, InputArray)
{
CV_Assert( !disparity_map_left.empty() && (disparity_map_left.depth() == CV_16S) && (disparity_map_left.channels() == 1) );
CV_Assert( !left_view.empty() && (left_view.depth() == CV_8U) && (left_view.channels() == 3 || left_view.channels() == 1) );
Mat disp,src,dst;
if(disparity_map_left.size()!=left_view.size())
resize_factor = disparity_map_left.cols()/(float)left_view.cols();
else
resize_factor = 1.0;
if(ROI.area()!=0) /* user provided a ROI */
valid_disp_ROI = ROI;
else
valid_disp_ROI = Rect(left_offset,top_offset,
disparity_map_left.cols()-left_offset-right_offset,
disparity_map_left.rows()-top_offset-bottom_offset);
if(!use_confidence)
{
Mat disp_full_size = disparity_map_left.getMat();
Mat src_full_size = left_view.getMat();
if(disp_full_size.size!=src_full_size.size)
{
float x_ratio = src_full_size.cols/(float)disp_full_size.cols;
float y_ratio = src_full_size.rows/(float)disp_full_size.rows;
resize(disp_full_size,disp_full_size,src_full_size.size());
disp_full_size = disp_full_size*x_ratio;
ROI = Rect((int)(valid_disp_ROI.x*x_ratio), (int)(valid_disp_ROI.y*y_ratio),
(int)(valid_disp_ROI.width*x_ratio),(int)(valid_disp_ROI.height*y_ratio));
}
else
ROI = valid_disp_ROI;
disp = Mat(disp_full_size,ROI);
src = Mat(src_full_size ,ROI);
filtered_disparity_map.create(disp_full_size.size(), disp_full_size.type());
Mat& dst_full_size = filtered_disparity_map.getMatRef();
dst_full_size = Scalar(16*(min_disp-1));
dst = Mat(dst_full_size,ROI);
Mat filtered_disp;
fastGlobalSmootherFilter(src,disp,filtered_disp,lambda,sigma_color);
filtered_disp.copyTo(dst);
}
else
{
CV_Assert( !disparity_map_right.empty() && (disparity_map_right.depth() == CV_16S) && (disparity_map_right.channels() == 1) );
CV_Assert( (disparity_map_left.cols() == disparity_map_right.cols()) );
CV_Assert( (disparity_map_left.rows() == disparity_map_right.rows()) );
computeConfidenceMap(disparity_map_left,disparity_map_right);
Mat disp_full_size = disparity_map_left.getMat();
Mat src_full_size = left_view.getMat();
if(disp_full_size.size!=src_full_size.size)
{
float x_ratio = src_full_size.cols/(float)disp_full_size.cols;
float y_ratio = src_full_size.rows/(float)disp_full_size.rows;
resize(disp_full_size,disp_full_size,src_full_size.size());
disp_full_size = disp_full_size*x_ratio;
resize(confidence_map,confidence_map,src_full_size.size());
ROI = Rect((int)(valid_disp_ROI.x*x_ratio), (int)(valid_disp_ROI.y*y_ratio),
(int)(valid_disp_ROI.width*x_ratio),(int)(valid_disp_ROI.height*y_ratio));
}
else
ROI = valid_disp_ROI;
disp = Mat(disp_full_size,ROI);
src = Mat(src_full_size ,ROI);
filtered_disparity_map.create(disp_full_size.size(), disp_full_size.type());
Mat& dst_full_size = filtered_disparity_map.getMatRef();
dst_full_size = Scalar(16*(min_disp-1));
dst = Mat(dst_full_size,ROI);
Mat conf(confidence_map,ROI);
Mat disp_mul_conf;
disp.convertTo(disp_mul_conf,CV_32F);
disp_mul_conf = conf.mul(disp_mul_conf);
Mat conf_filtered;
Ptr<FastGlobalSmootherFilter> wls = createFastGlobalSmootherFilter(src,lambda,sigma_color);
wls->filter(disp_mul_conf,disp_mul_conf);
wls->filter(conf,conf_filtered);
disp_mul_conf = disp_mul_conf.mul(1/(conf_filtered+EPS));
disp_mul_conf.convertTo(dst,CV_16S);
}
}
DisparityWLSFilterImpl::ComputeDiscontinuityAwareLRC_ParBody::ComputeDiscontinuityAwareLRC_ParBody(DisparityWLSFilterImpl& _wls, Mat& _left_disp, Mat& _right_disp, Mat& _left_disc, Mat& _right_disc, Mat& _dst, Rect _left_ROI, Rect _right_ROI, int _nstripes):
wls(&_wls),left_disp(&_left_disp),right_disp(&_right_disp),left_disc(&_left_disc),right_disc(&_right_disc),dst(&_dst),left_ROI(_left_ROI),right_ROI(_right_ROI),nstripes(_nstripes)
{
stripe_sz = (int)ceil(left_disp->rows/(double)nstripes);
}
void DisparityWLSFilterImpl::ComputeDiscontinuityAwareLRC_ParBody::operator() (const Range& range) const
{
short* row_left;
float* row_left_conf;
short* row_right;
float* row_right_conf;
float* row_dst;
int right_idx;
int h = left_disp->rows;
int start = std::min(range.start * stripe_sz, h);
int end = std::min(range.end * stripe_sz, h);
int thresh = (int)(wls->resize_factor*wls->LRC_thresh);
for(int i=start;i<end;i++)
{
row_left = (short*)left_disp->ptr(i);
row_left_conf = (float*)left_disc->ptr(i);
row_right = (short*)right_disp->ptr(i);
row_right_conf = (float*)right_disc->ptr(i);
row_dst = (float*)dst->ptr(i);
int j_start = left_ROI.x;
int j_end = left_ROI.x+left_ROI.width;
int right_end = right_ROI.x+right_ROI.width;
for(int j=j_start;j<j_end;j++)
{
right_idx = j-(row_left[j]>>4);
if( right_idx>=right_ROI.x && right_idx<right_end)
{
if(abs(row_left[j] + row_right[right_idx])< thresh)
row_dst[j] = min(row_left_conf[j],row_right_conf[right_idx]);
else
row_dst[j] = 0.0f;
}
}
}
}
DisparityWLSFilterImpl::ComputeDepthDisc_ParBody::ComputeDepthDisc_ParBody(DisparityWLSFilterImpl& _wls, Mat& _disp, Mat& _disp_squares, Mat& _dst, int _nstripes):
wls(&_wls),disp(&_disp),disp_squares(&_disp_squares),dst(&_dst),nstripes(_nstripes)
{
stripe_sz = (int)ceil(disp->rows/(double)nstripes);
}
void DisparityWLSFilterImpl::ComputeDepthDisc_ParBody::operator() (const Range& range) const
{
float* row_disp;
float* row_disp_squares;
float* row_dst;
float variance;
int h = disp->rows;
int w = disp->cols;
int start = std::min(range.start * stripe_sz, h);
int end = std::min(range.end * stripe_sz, h);
float roll_off = wls->depth_discontinuity_roll_off_factor/(wls->resize_factor*wls->resize_factor);
for(int i=start;i<end;i++)
{
row_disp = (float*)disp->ptr(i);
row_disp_squares = (float*)disp_squares->ptr(i);
row_dst = (float*)dst->ptr(i);
for(int j=0;j<w;j++)
{
variance = row_disp_squares[j] - (row_disp[j])*(row_disp[j]);
row_dst[j] = max(1.0f - roll_off*variance,0.0f);
}
}
}
DisparityWLSFilterImpl::ParallelMatOp_ParBody::ParallelMatOp_ParBody(DisparityWLSFilterImpl& _wls, vector<MatOp> _ops, vector<Mat*>& _src, vector<Mat*>& _dst):
wls(&_wls),ops(_ops),src(_src),dst(_dst)
{}
void DisparityWLSFilterImpl::ParallelMatOp_ParBody::operator() (const Range& range) const
{
for(int i=range.start;i<range.end;i++)
(wls->*ops[i])(*src[i],*dst[i]);
}
CV_EXPORTS_W
Ptr<DisparityWLSFilter> createDisparityWLSFilter(Ptr<StereoMatcher> matcher_left)
{
Ptr<DisparityWLSFilter> wls;
matcher_left->setDisp12MaxDiff(1000000);
matcher_left->setSpeckleWindowSize(0);
int min_disp = matcher_left->getMinDisparity();
int num_disp = matcher_left->getNumDisparities();
int wsize = matcher_left->getBlockSize();
int wsize2 = wsize/2;
if(Ptr<StereoBM> bm = matcher_left.dynamicCast<StereoBM>())
{
bm->setTextureThreshold(0);
bm->setUniquenessRatio(0);
wls = DisparityWLSFilterImpl::create(true,max(0,min_disp+num_disp)+wsize2,max(0,-min_disp)+wsize2,wsize2,wsize2,min_disp);
wls->setDepthDiscontinuityRadius((int)ceil(0.33*wsize));
}
else if(Ptr<StereoSGBM> sgbm = matcher_left.dynamicCast<StereoSGBM>())
{
sgbm->setUniquenessRatio(0);
wls = DisparityWLSFilterImpl::create(true,max(0,min_disp+num_disp),max(0,-min_disp),0,0,min_disp);
wls->setDepthDiscontinuityRadius((int)ceil(0.5*wsize));
}
else
CV_Error(Error::StsBadArg, "DisparityWLSFilter natively supports only StereoBM and StereoSGBM");
return wls;
}
CV_EXPORTS_W
Ptr<StereoMatcher> createRightMatcher(Ptr<StereoMatcher> matcher_left)
{
int min_disp = matcher_left->getMinDisparity();
int num_disp = matcher_left->getNumDisparities();
int wsize = matcher_left->getBlockSize();
if(Ptr<StereoBM> bm = matcher_left.dynamicCast<StereoBM>())
{
Ptr<StereoBM> right_bm = StereoBM::create(num_disp,wsize);
right_bm->setMinDisparity(-(min_disp+num_disp)+1);
right_bm->setTextureThreshold(0);
right_bm->setUniquenessRatio(0);
right_bm->setDisp12MaxDiff(1000000);
right_bm->setSpeckleWindowSize(0);
return right_bm;
}
else if(Ptr<StereoSGBM> sgbm = matcher_left.dynamicCast<StereoSGBM>())
{
Ptr<StereoSGBM> right_sgbm = StereoSGBM::create(-(min_disp+num_disp)+1,num_disp,wsize);
right_sgbm->setUniquenessRatio(0);
right_sgbm->setP1(sgbm->getP1());
right_sgbm->setP2(sgbm->getP2());
right_sgbm->setMode(sgbm->getMode());
right_sgbm->setPreFilterCap(sgbm->getPreFilterCap());
right_sgbm->setDisp12MaxDiff(1000000);
right_sgbm->setSpeckleWindowSize(0);
return right_sgbm;
}
else
{
CV_Error(Error::StsBadArg, "createRightMatcher supports only StereoBM and StereoSGBM");
return Ptr<StereoMatcher>();
}
}
CV_EXPORTS_W
Ptr<DisparityWLSFilter> createDisparityWLSFilterGeneric(bool use_confidence)
{
return Ptr<DisparityWLSFilter>(DisparityWLSFilterImpl::create(use_confidence));
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#define UNKNOWN_DISPARITY 16320
int readGT(String src_path,OutputArray dst)
{
Mat src = imread(src_path,IMREAD_UNCHANGED);
dst.create(src.rows,src.cols,CV_16S);
Mat& dstMat = dst.getMatRef();
if(!src.empty() && src.channels()==3 && src.depth()==CV_8U)
{
//MPI-Sintel format:
for(int i=0;i<src.rows;i++)
for(int j=0;j<src.cols;j++)
{
Vec3b bgrPixel = src.at<Vec3b>(i, j);
dstMat.at<short>(i,j) = 64*bgrPixel.val[2]+bgrPixel.val[1]/4; //16-multiplied disparity
}
return 0;
}
else if(!src.empty() && src.channels()==1 && src.depth()==CV_8U)
{
//Middlebury format:
for(int i=0;i<src.rows;i++)
for(int j=0;j<src.cols;j++)
{
short src_val = src.at<unsigned char>(i, j);
if(src_val==0)
dstMat.at<short>(i,j) = UNKNOWN_DISPARITY;
else
dstMat.at<short>(i,j) = 16*src_val; //16-multiplied disparity
}
return 0;
}
else
return 1;
}
double computeMSE(InputArray GT, InputArray src, Rect ROI)
{
CV_Assert( !GT.empty() && (GT.depth() == CV_16S) && (GT.channels() == 1) );
CV_Assert( !src.empty() && (src.depth() == CV_16S) && (src.channels() == 1) );
CV_Assert( src.rows() == GT.rows() && src.cols() == GT.cols() );
double res = 0;
Mat GT_ROI (GT.getMat(), ROI);
Mat src_ROI(src.getMat(),ROI);
int cnt=0;
for(int i=0;i<src_ROI.rows;i++)
for(int j=0;j<src_ROI.cols;j++)
{
if(GT_ROI.at<short>(i,j)!=UNKNOWN_DISPARITY)
{
res += (GT_ROI.at<short>(i,j) - src_ROI.at<short>(i,j))*(GT_ROI.at<short>(i,j) - src_ROI.at<short>(i,j));
cnt++;
}
}
res /= cnt*256;
return res;
}
double computeBadPixelPercent(InputArray GT, InputArray src, Rect ROI, int thresh)
{
CV_Assert( !GT.empty() && (GT.depth() == CV_16S) && (GT.channels() == 1) );
CV_Assert( !src.empty() && (src.depth() == CV_16S) && (src.channels() == 1) );
CV_Assert( src.rows() == GT.rows() && src.cols() == GT.cols() );
int bad_pixel_num = 0;
Mat GT_ROI (GT.getMat(), ROI);
Mat src_ROI(src.getMat(),ROI);
int cnt=0;
for(int i=0;i<src_ROI.rows;i++)
for(int j=0;j<src_ROI.cols;j++)
{
if(GT_ROI.at<short>(i,j)!=UNKNOWN_DISPARITY)
{
if( abs(GT_ROI.at<short>(i,j) - src_ROI.at<short>(i,j))>=thresh )
bad_pixel_num++;
cnt++;
}
}
return (100.0*bad_pixel_num)/cnt;
}
void getDisparityVis(InputArray src,OutputArray dst,double scale)
{
CV_Assert( !src.empty() && (src.depth() == CV_16S) && (src.channels() == 1) );
Mat srcMat = src.getMat();
dst.create(srcMat.rows,srcMat.cols,CV_8UC1);
Mat& dstMat = dst.getMatRef();
for(int i=0;i<dstMat.rows;i++)
for(int j=0;j<dstMat.cols;j++)
{
if(srcMat.at<short>(i,j)==UNKNOWN_DISPARITY)
dstMat.at<unsigned char>(i,j) = 0;
else
dstMat.at<unsigned char>(i,j) = saturate_cast<unsigned char>(scale*srcMat.at<short>(i,j)/16.0);
}
}
}
}
|
jppreti/OrientacaoObjetos | java/src/main/java/br/edu/ifmt/cba/java/projeto/locadora/relatorio/RelDividasCliente.java | package br.edu.ifmt.cba.java.projeto.locadora.relatorio;
public class RelDividasCliente {
}
|
edsonayllon/besu | ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthCallIntegrationTest.java | <filename>ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthCallIntegrationTest.java<gh_stars>1-10
/*
* Copyright 2018 ConsenSys AG.
*
* 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.hyperledger.besu.ethereum.api.jsonrpc.methods;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import org.hyperledger.besu.ethereum.api.jsonrpc.BlockchainImporter;
import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcTestMethodsFactory;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonCallParameter;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
import org.hyperledger.besu.ethereum.transaction.CallParameter;
import org.hyperledger.besu.testutil.BlockTestUtil;
import java.util.Map;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class EthCallIntegrationTest {
private static JsonRpcTestMethodsFactory BLOCKCHAIN;
private JsonRpcMethod method;
@BeforeClass
public static void setUpOnce() throws Exception {
final String genesisJson =
Resources.toString(BlockTestUtil.getTestGenesisUrl(), Charsets.UTF_8);
BLOCKCHAIN =
new JsonRpcTestMethodsFactory(
new BlockchainImporter(BlockTestUtil.getTestBlockchainUrl(), genesisJson));
}
@Before
public void setUp() {
final Map<String, JsonRpcMethod> methods = BLOCKCHAIN.methods();
method = methods.get("eth_call");
}
@Test
public void shouldReturnExpectedResultForCallAtLatestBlock() {
final CallParameter callParameter =
new JsonCallParameter(
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
null,
null,
null,
"0x12a7b914");
final JsonRpcRequest request = requestWithParams(callParameter, "latest");
final JsonRpcResponse expectedResponse =
new JsonRpcSuccessResponse(
null, "0x0000000000000000000000000000000000000000000000000000000000000001");
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);
}
@Test
public void shouldReturnExpectedResultForCallAtSpecificBlock() {
final CallParameter callParameter =
new JsonCallParameter(
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
null,
null,
null,
"0x12a7b914");
final JsonRpcRequest request = requestWithParams(callParameter, "0x8");
final JsonRpcResponse expectedResponse =
new JsonRpcSuccessResponse(
null, "0x0000000000000000000000000000000000000000000000000000000000000000");
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);
}
@Test
public void shouldReturnInvalidRequestWhenMissingToField() {
final CallParameter callParameter =
new JsonCallParameter(
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b", null, null, null, null, "0x12a7b914");
final JsonRpcRequest request = requestWithParams(callParameter, "latest");
final Throwable thrown = catchThrowable(() -> method.response(request));
assertThat(thrown)
.isInstanceOf(InvalidJsonRpcParameters.class)
.hasNoCause()
.hasMessage("Missing \"to\" field in call arguments");
}
@Test
public void shouldReturnErrorWithGasLimitTooLow() {
final CallParameter callParameter =
new JsonCallParameter(
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
"0x0",
null,
null,
"0x12a7b914");
final JsonRpcRequest request = requestWithParams(callParameter, "latest");
final JsonRpcResponse expectedResponse =
new JsonRpcErrorResponse(null, JsonRpcError.INTRINSIC_GAS_EXCEEDS_LIMIT);
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);
}
@Test
public void shouldReturnErrorWithGasPriceTooHigh() {
final CallParameter callParameter =
new JsonCallParameter(
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
null,
"0x10000000000000",
null,
"0x12a7b914");
final JsonRpcRequest request = requestWithParams(callParameter, "latest");
final JsonRpcResponse expectedResponse =
new JsonRpcErrorResponse(null, JsonRpcError.TRANSACTION_UPFRONT_COST_EXCEEDS_BALANCE);
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);
}
@Test
public void shouldReturnEmptyHashResultForCallWithOnlyToField() {
final CallParameter callParameter =
new JsonCallParameter(
null, "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f", null, null, null, null);
final JsonRpcRequest request = requestWithParams(callParameter, "latest");
final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(null, "0x");
final JsonRpcResponse response = method.response(request);
assertThat(response).isEqualToComparingFieldByField(expectedResponse);
}
private JsonRpcRequest requestWithParams(final Object... params) {
return new JsonRpcRequest("2.0", "eth_call", params);
}
}
|
HackerFoo/vtr-verilog-to-routing | abc/src/opt/cgt/cgtSat.c | /**CFile****************************************************************
FileName [cgtSat.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [Clock gating package.]
Synopsis [Checking implications using SAT.]
Author [<NAME>]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: cgtSat.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "cgtInt.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [Runs equivalence test for the two nodes.]
Description [Both nodes should be regular and different from each other.]
SideEffects []
SeeAlso []
***********************************************************************/
int Cgt_CheckImplication( Cgt_Man_t * p, Aig_Obj_t * pGate, Aig_Obj_t * pMiter )
{
int nBTLimit = p->pPars->nConfMax;
int pLits[2], RetValue;
abctime clk;
p->nCalls++;
// sanity checks
assert( p->pSat && p->pCnf );
assert( !Aig_IsComplement(pMiter) );
assert( Aig_Regular(pGate) != pMiter );
// solve under assumptions
// G => !M -- true G & M -- false
pLits[0] = toLitCond( p->pCnf->pVarNums[Aig_Regular(pGate)->Id], Aig_IsComplement(pGate) );
pLits[1] = toLitCond( p->pCnf->pVarNums[pMiter->Id], 0 );
clk = Abc_Clock();
RetValue = sat_solver_solve( p->pSat, pLits, pLits + 2, (ABC_INT64_T)nBTLimit, (ABC_INT64_T)0, (ABC_INT64_T)0, (ABC_INT64_T)0 );
p->timeSat += Abc_Clock() - clk;
if ( RetValue == l_False )
{
p->timeSatUnsat += Abc_Clock() - clk;
pLits[0] = lit_neg( pLits[0] );
pLits[1] = lit_neg( pLits[1] );
RetValue = sat_solver_addclause( p->pSat, pLits, pLits + 2 );
assert( RetValue );
sat_solver_compress( p->pSat );
p->nCallsUnsat++;
return 1;
}
else if ( RetValue == l_True )
{
p->timeSatSat += Abc_Clock() - clk;
p->nCallsSat++;
return 0;
}
else // if ( RetValue1 == l_Undef )
{
p->timeSatUndec += Abc_Clock() - clk;
p->nCallsUndec++;
return -1;
}
return -2;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
|
swamp/compiler | src/loader/workspace.go | package loader
import (
"log"
decorated "github.com/swamp/compiler/src/decorated/expression"
)
type Workspace struct {
rootDirectory LocalFileSystemRoot
projects map[string]Project
}
func NewWorkspace(rootDirectory LocalFileSystemRoot) *Workspace {
return &Workspace{rootDirectory: rootDirectory, projects: make(map[string]Project)}
}
func (w *Workspace) FindProjectFromRootDirectory(root LocalFileSystemRoot) Project {
foundProject := w.projects[string(root)]
return foundProject
}
func (w *Workspace) AddProject(root LocalFileSystemRoot, project Project) {
w.projects[string(root)] = project
}
func (w *Workspace) AddPackage(p *Package) {
w.AddProject(p.Root(), p)
}
func (w *Workspace) AllPackages() []*Package {
var packages []*Package
for _, project := range w.projects {
foundPackage, wasPackage := project.(*Package)
if wasPackage {
packages = append(packages, foundPackage)
}
}
return packages
}
func (w *Workspace) AddOrReplacePackage(p *Package) {
existingPackage := w.FindProject(p.root)
if existingPackage != nil {
log.Printf("remove for overwrite package %v", p.Root())
delete(w.projects, string(p.root))
}
w.AddPackage(p)
}
func (w *Workspace) FindProject(root LocalFileSystemRoot) *Package {
p := w.FindProjectFromRootDirectory(root)
if p != nil {
foundPackage, wasPackage := p.(*Package)
if wasPackage {
return foundPackage
}
}
return nil
}
func (w *Workspace) FindModuleFromSourceFile(path LocalFileSystemPath) (*decorated.Module, *Package) {
for _, foundPackage := range w.AllPackages() {
foundModule := foundPackage.FindModuleFromAbsoluteFilePath(path)
if foundModule != nil {
return foundModule, foundPackage
}
}
return nil, nil
}
|
webdevhub42/Lambda | WEEKS/CD_Sata-Structures/_RESOURCES/python-prac/python-scripts/scripts/15_check_my_environment.py | <reponame>webdevhub42/Lambda<filename>WEEKS/CD_Sata-Structures/_RESOURCES/python-prac/python-scripts/scripts/15_check_my_environment.py
"""
Pass in a config file based on your environment.
Example:
import check_my_environment
class Main:
def __init__(self, configFile):
pass
def process(self):
print("ok")
if __name__ == "__main__":
m = Main(some_script.CONFIGFILE)
m.process()
"""
import os
import sys
ENVIRONMENT = "development"
CONFIGFILE = None
def get_config_file():
directory = os.path.dirname(__file__)
return {
"development": "{}/../config/development.cfg".format(directory),
"staging": "{}/../config/staging.cfg".format(directory),
"production": "{}/../config/production.cfg".format(directory),
}.get(ENVIRONMENT, None)
CONFIGFILE = get_config_file()
if CONFIGFILE is None:
sys.exit(
"Configuration error! Unknown environment set. \
Edit config.py and set appropriate environment"
)
print("Config file: {}".format(CONFIGFILE))
if not os.path.exists(CONFIGFILE):
sys.exit("Configuration error! Config file does not exist")
print("Config ok ....")
|
atlasapi/atlas | src/main/java/org/atlasapi/remotesite/metabroadcast/similar/SimilarContentModule.java | package org.atlasapi.remotesite.metabroadcast.similar;
import javax.annotation.PostConstruct;
import org.atlasapi.application.v3.DefaultApplication;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.persistence.MongoContentPersistenceModule;
import org.atlasapi.persistence.content.ContentResolver;
import org.atlasapi.persistence.content.ContentWriter;
import org.atlasapi.persistence.content.listing.ContentLister;
import org.atlasapi.persistence.lookup.entry.LookupEntryStore;
import org.atlasapi.persistence.output.MongoAvailableItemsResolver;
import org.atlasapi.persistence.output.MongoUpcomingItemsResolver;
import org.joda.time.LocalTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import com.metabroadcast.common.persistence.mongo.DatabasedMongo;
import com.metabroadcast.common.scheduling.RepetitionRule;
import com.metabroadcast.common.scheduling.RepetitionRules;
import com.metabroadcast.common.scheduling.SimpleScheduler;
@Configuration
@Import({ MongoContentPersistenceModule.class })
public class SimilarContentModule {
private static RepetitionRule SIMILAR_CONTENT_UPDATER_REPETITION = RepetitionRules.daily(LocalTime.parse("15:00"));
@Autowired ContentLister contentLister;
@Autowired ContentWriter contentWriter;
@Autowired ContentResolver contentResolver;
@Autowired SimpleScheduler scheduler;
@Autowired LookupEntryStore lookupStore;
@Autowired DatabasedMongo mongo;
@Value("${updaters.similarcontent.enabled}")
Boolean tasksEnabled;
@PostConstruct
public void scheduleTasks() {
if (Boolean.TRUE.equals(tasksEnabled)) {
scheduler.schedule(similarContentUpdater(), SIMILAR_CONTENT_UPDATER_REPETITION);
}
}
@Bean
public SimilarContentUpdater similarContentUpdater() {
return new SimilarContentUpdater(contentLister, Publisher.PA, similarContentProvider(),
similarContentWriter());
}
SimilarContentProvider similarContentProvider() {
return new DefaultSimilarContentProvider(
contentLister,
Publisher.PA,
10,
new GenreAndPeopleTraitHashCalculator(),
availableItemsResolver(),
upcomingItemsResolver(),
DefaultApplication.createWithReads(Publisher.all().asList())
);
}
SeparateSourceSimilarContentWriter similarContentWriter() {
return new SeparateSourceSimilarContentWriter(Publisher.METABROADCAST_SIMILAR_CONTENT, contentResolver,
contentWriter);
}
MongoUpcomingItemsResolver upcomingItemsResolver() {
return new MongoUpcomingItemsResolver(mongo);
}
MongoAvailableItemsResolver availableItemsResolver() {
return new MongoAvailableItemsResolver(mongo, lookupStore);
}
}
|
mlapierre/Selenium-Grid-Extras | SeleniumGridExtras/src/main/java/com/groupon/seleniumgridextras/utilities/ResourceRetriever.java | package com.groupon.seleniumgridextras.utilities;
import com.groupon.seleniumgridextras.SeleniumGridExtras;
import java.io.IOException;
import java.io.InputStream;
public class ResourceRetriever {
public String getAsString(String resource) throws IOException {
InputStream in = SeleniumGridExtras.class.getResourceAsStream(resource);
return StreamUtility.inputStreamToString(in);
}
}
|
jimsimon/wc-framework | src/mixins/host-attributes-mixin.js | <gh_stars>0
export default (superclass) => class HostAttributesMixin extends superclass {
static get hostAttributes() {
return {}
}
constructor() {
super()
const {constructor: Type} = this
for (const [name, value] of Object.entries(Type.hostAttributes)) {
this.setAttribute(name, value)
}
}
}
|
Boom618/DigitalFarms | library/src/main/java/com/linheimx/app/library/touch/GodTouchListener.java | <reponame>Boom618/DigitalFarms<filename>library/src/main/java/com/linheimx/app/library/touch/GodTouchListener.java<gh_stars>0
package com.linheimx.app.library.touch;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewParent;
import com.linheimx.app.library.charts.LineChart;
import com.linheimx.app.library.manager.MappingManager;
import com.linheimx.app.library.utils.RectD;
/**
* Created by lijian on 2017/1/30.
*/
public class GodTouchListener implements View.OnTouchListener {
GestureDetector _GestureDetector;
ScaleGestureDetector _ScaleGestureDetector;
LineChart _LineChart;
public GodTouchListener(LineChart lineChart) {
_LineChart = lineChart;
_GestureDetector = new GestureDetector(lineChart.getContext(), new GestureListener());
_ScaleGestureDetector = new ScaleGestureDetector(lineChart.getContext(), new ScaleListener());
}
@Override
public boolean onTouch(View v, MotionEvent event) {
ViewParent parent = v.getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
boolean hit = _GestureDetector.onTouchEvent(event);
hit |= _ScaleGestureDetector.onTouchEvent(event);
if (hit) {
_LineChart.invalidate();
return true;
}
return false;
}
class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
float _lastSpanX, _lastSpanY;
public ScaleListener() {
super();
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
float spanX = detector.getCurrentSpanX();
float kx = spanX / _lastSpanX;
float spanY = detector.getCurrentSpanY();
float ky = spanY / _lastSpanY;
RectF godRect = _LineChart.get_GodRect();
RectF mainRect = _LineChart.get_MainPlotRect();
godRect.right = godRect.left + godRect.width() * kx;
godRect.bottom = godRect.top + godRect.height() * ky;
constrainRect(godRect, mainRect);
nofityViewPortChanged(godRect);
_lastSpanX = spanX;
_lastSpanY = spanY;
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
_lastSpanX = detector.getCurrentSpanX();
_lastSpanY = detector.getCurrentSpanY();
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
super.onScaleEnd(detector);
}
}
RectD _rectD_ob = new RectD();
class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent e) {
return super.onDoubleTap(e);
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return super.onFling(e1, e2, velocityX, velocityY);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
RectF godRect = _LineChart.get_GodRect();
RectF mainRect = _LineChart.get_MainPlotRect();
float w = godRect.width();
float h = godRect.height();
godRect.left += -distanceX;
godRect.right = godRect.left + w;
godRect.top += -distanceY;
godRect.bottom = godRect.top + h;
constrainRect(godRect, mainRect);
nofityViewPortChanged(godRect);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return super.onSingleTapConfirmed(e);
}
}
private void nofityViewPortChanged(RectF godRect) {
// 计算出godRect对应的viewport
MappingManager mappingManager = _LineChart.get_MappingManager();
double left = mappingManager.p2v_x(godRect.left);
double right = mappingManager.p2v_x(godRect.right);
double bottom = mappingManager.p2v_y(godRect.bottom);
double top = mappingManager.p2v_y(godRect.top);
_rectD_ob.left = left;
_rectD_ob.top = top;
_rectD_ob.right = right;
_rectD_ob.bottom = bottom;
_LineChart.notifyOB_ViewportChanged(_rectD_ob);
}
private void constrainRect(RectF godRect, RectF maxRect) {
float w = godRect.width();
float h = godRect.height();
// 1. 保持比例
if (godRect.left < maxRect.left) {
godRect.left = maxRect.left;
godRect.right = godRect.left + w;
}
if (godRect.top < maxRect.top) {
godRect.top = maxRect.top;
godRect.bottom = godRect.top + h;
}
if (godRect.right > maxRect.right) {
godRect.right = maxRect.right;
godRect.left = godRect.right - w;
}
if (godRect.bottom > maxRect.bottom) {
godRect.bottom = maxRect.bottom;
godRect.top = godRect.bottom - h;
}
// 2. 限定值的范围
if (godRect.left < maxRect.left) {
godRect.left = maxRect.left;
}
if (godRect.top < maxRect.top) {
godRect.top = maxRect.top;
}
if (godRect.right > maxRect.right) {
godRect.right = maxRect.right;
}
if (godRect.bottom > maxRect.bottom) {
godRect.bottom = maxRect.bottom;
}
}
}
|
71yuu/ssm-my-blog | yuu-blog-domain/src/main/java/com/yyh/yuu/blog/domain/Article.java | <gh_stars>0
package com.yyh.yuu.blog.domain;
import com.yyh.yuu.blog.commons.persistence.BaseEntity;
import lombok.Data;
/**
* 文章
* @Classname Article
* @Date 2018/11/13 10:56
* @Created by Yuu
*/
@Data
public class Article extends BaseEntity {
private Integer cid;
private String aname;
private String author;
private Integer click;
private String content;
private String html;
}
|
cleberecht/singa | singa-simulation/src/test/java/bio/singa/simulation/export/format/FormatReactionKineticsTest.java | package bio.singa.simulation.export.format;
import bio.singa.chemistry.features.reactions.MichaelisConstant;
import bio.singa.chemistry.features.reactions.RateConstant;
import bio.singa.chemistry.features.reactions.TurnoverNumber;
import bio.singa.features.model.Evidence;
import bio.singa.simulation.entities.ChemicalEntity;
import bio.singa.simulation.entities.SimpleEntity;
import bio.singa.simulation.model.modules.concentration.imlementations.reactions.Reaction;
import bio.singa.simulation.model.modules.concentration.imlementations.reactions.ReactionBuilder;
import bio.singa.simulation.model.simulation.Simulation;
import org.junit.jupiter.api.Test;
import tech.units.indriya.quantity.Quantities;
import tech.units.indriya.unit.ProductUnit;
import static bio.singa.features.units.UnitProvider.MOLE_PER_LITRE;
import static bio.singa.simulation.model.sections.CellTopology.MEMBRANE;
import static bio.singa.simulation.model.sections.CellTopology.OUTER;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static tech.units.indriya.AbstractUnit.ONE;
import static tech.units.indriya.unit.Units.MINUTE;
import static tech.units.indriya.unit.Units.SECOND;
/**
* @author cl
*/
class FormatReactionKineticsTest {
@Test
void testMichaelisMentenFormat() {
Simulation simulation = new Simulation();
MichaelisConstant michaelisConstant = new MichaelisConstant(Quantities.getQuantity(9.0e-3, MOLE_PER_LITRE), Evidence.NO_EVIDENCE);
TurnoverNumber turnoverNumber = new TurnoverNumber(76, new ProductUnit<>(ONE.divide(MINUTE)), Evidence.NO_EVIDENCE);
ChemicalEntity substrate = SimpleEntity.create("A").build();
ChemicalEntity product1 = SimpleEntity.create("B").build();
ChemicalEntity product2 = SimpleEntity.create("C").build();
ChemicalEntity enzyme = SimpleEntity.create("E").build();
Reaction reaction = ReactionBuilder.staticReactants(simulation)
.addSubstrate(substrate)
.addCatalyst(enzyme)
.addProduct(product1)
.addProduct(product2)
.michaelisMenten()
.michaelisConstant(michaelisConstant)
.turnover(turnoverNumber)
.build();
assertEquals("$\\frac{k_{\\text{cat}} \\cdot [\\text{E}] \\cdot [\\text{A}]}{K_m \\cdot [\\text{A}]}$", FormatReactionKinetics.formatTex(reaction).get(0));
}
@Test
void testNthOrderReactionFormat() {
Simulation simulation = new Simulation();
ChemicalEntity substrate1 = SimpleEntity.create("A").build();
ChemicalEntity substrate2 = SimpleEntity.create("B").build();
ChemicalEntity product1 = SimpleEntity.create("C").build();
ChemicalEntity product2 = SimpleEntity.create("D").build();
RateConstant k = RateConstant.create(1.0)
.forward().secondOrder()
.concentrationUnit(MOLE_PER_LITRE)
.timeUnit(SECOND)
.build();
Reaction reaction = ReactionBuilder.staticReactants(simulation)
.addSubstrate(substrate1, 2)
.addSubstrate(substrate2)
.addProduct(product1)
.addProduct(product2)
.irreversible()
.rate(k)
.build();
assertEquals("$k_{1} \\cdot [\\text{A}] \\cdot [\\text{B}]$", FormatReactionKinetics.formatTex(reaction).get(0));
}
@Test
void testReversibleReactionFormat() {
Simulation simulation = new Simulation();
ChemicalEntity substrate = SimpleEntity.create("A").build();
ChemicalEntity product = SimpleEntity.create("B").build();
RateConstant kf = RateConstant.create(2.0)
.forward().firstOrder()
.timeUnit(SECOND)
.build();
RateConstant kb = RateConstant.create(1.0)
.backward().firstOrder()
.timeUnit(SECOND)
.build();
Reaction reaction = ReactionBuilder.staticReactants(simulation)
.addSubstrate(substrate, MEMBRANE)
.addProduct(product, OUTER)
.reversible()
.forwardReactionRate(kf)
.backwardReactionRate(kb)
.build();
assertEquals("$k_{1} \\cdot [\\text{A}] - k_{-1} \\cdot [\\text{B}]$", FormatReactionKinetics.formatTex(reaction).get(0));
}
} |
HeBomou/Melon | libs/MelonFrontend/MelonFrontend/RenderMesh.h | <reponame>HeBomou/Melon
#pragma once
#include <MelonCore/SharedComponent.h>
#include <MelonFrontend/MeshBuffer.h>
#include <MelonFrontend/MeshResource.h>
#include <functional>
#include <vector>
namespace Melon {
struct RenderMesh : public SharedComponent {
bool operator==(const RenderMesh& other) const {
return vertices() == other.vertices() && indices() == other.indices();
}
const std::vector<Vertex>& vertices() const { return meshResource->vertices(); }
const std::vector<uint16_t>& indices() const { return meshResource->indices(); }
MeshResource* meshResource;
};
struct ManualRenderMesh : public ManualSharedComponent {
bool operator==(const ManualRenderMesh& other) const {
return meshBuffer == other.meshBuffer;
}
unsigned int renderMeshIndex;
MeshBuffer meshBuffer;
};
} // namespace Melon
template <>
struct std::hash<Melon::RenderMesh> {
std::size_t operator()(const Melon::RenderMesh& renderMesh) {
std::size_t hash{};
for (const Melon::Vertex& vertex : renderMesh.vertices())
hash ^= std::hash<Melon::Vertex>()(vertex);
for (const unsigned int& index : renderMesh.indices())
hash ^= std::hash<unsigned int>()(index);
return hash;
}
};
template <>
struct std::hash<Melon::ManualRenderMesh> {
std::size_t operator()(const Melon::ManualRenderMesh& manualRenderMesh) {
return std::hash<Melon::MeshBuffer>()(manualRenderMesh.meshBuffer);
}
};
|
CaioProiete/blog | src/main/java/blog/objgen/UnfilteredIterator.java | <reponame>CaioProiete/blog
/**
*
*/
package blog.objgen;
import java.util.BitSet;
import java.util.Set;
import blog.sample.EvalContext;
class UnfilteredIterator extends AbstractObjectIterator {
/**
*
*/
private final CompiledSetSpec compiledSetSpec;
UnfilteredIterator(CompiledSetSpec compiledSetSpec, EvalContext context, Set externallyDistinguished) {
this.compiledSetSpec = compiledSetSpec;
graphIters = new ObjectIterator[this.compiledSetSpec.objGenGraphs.length];
for (int i = 0; i < this.compiledSetSpec.objGenGraphs.length; ++i) {
graphIters[i] = this.compiledSetSpec.objGenGraphs[i].iterator(context,
externallyDistinguished, false);
active.set(i);
}
}
protected int skipAfterNext() {
return graphIters[nextDisjunctIndex].skipIndistinguishable();
}
protected Object findNext() {
while (active.cardinality() > 0) {
nextDisjunctIndex = (nextDisjunctIndex + 1) % graphIters.length;
if (!graphIters[nextDisjunctIndex].canDetermineNext()) {
canDetermineNext = false;
return null;
}
if (graphIters[nextDisjunctIndex].hasNext()) {
return graphIters[nextDisjunctIndex].next();
} else {
active.clear(nextDisjunctIndex);
}
}
return null;
}
private ObjectIterator[] graphIters;
private BitSet active = new BitSet();
private int nextDisjunctIndex = -1;
} |
SkyZero1228/react-GraphQL | src/components/AntComponents/Table/index.js | import React from 'react'
import ReactDOM from 'react-dom'
import SyntaxHighlighter from 'react-syntax-highlighter/prism'
import { base16AteliersulphurpoolLight } from 'react-syntax-highlighter/styles/prism'
import { Collapse, Icon } from 'antd'
import { default as renderTableAjax } from './Ajax/index.js'
import { default as renderTableBasic } from './Basic/index.js'
import { default as renderTableBordered } from './Bordered/index.js'
import { default as renderTableColspanrowspan } from './Colspanrowspan/index.js'
import { default as renderTableCustomfilterpanel } from './Customfilterpanel/index.js'
import { default as renderTableDragsorting } from './Dragsorting/index.js'
import { default as renderTableDynamicsettings } from './Dynamicsettings/index.js'
import { default as renderTableEditcell } from './Editcell/index.js'
import { default as renderTableEditrow } from './Editrow/index.js'
import { default as renderTableExpandchildren } from './Expandchildren/index.js'
import { default as renderTableExpand } from './Expand/index.js'
import { default as renderTableFixedcolumnsheader } from './Fixedcolumnsheader/index.js'
import { default as renderTableFixedcolumns } from './Fixedcolumns/index.js'
import { default as renderTableFixedheader } from './Fixedheader/index.js'
import { default as renderTableGroupingcolumns } from './Groupingcolumns/index.js'
import { default as renderTableHead } from './Head/index.js'
import { default as renderTableJsx } from './Jsx/index.js'
import { default as renderTableNestedtable } from './Nestedtable/index.js'
import { default as renderTableResetfilter } from './Resetfilter/index.js'
import { default as renderTableRowselectionandoperation } from './Rowselectionandoperation/index.js'
import { default as renderTableRowselectioncustom } from './Rowselectioncustom/index.js'
import { default as renderTableRowselection } from './Rowselection/index.js'
import { default as renderTableSize } from './Size/index.js'
const Panel = Collapse.Panel
class TableItems extends React.Component {
componentDidMount() {
renderTableAjax(ReactDOM, document.getElementById('TableAjax'))
renderTableBasic(ReactDOM, document.getElementById('TableBasic'))
renderTableBordered(ReactDOM, document.getElementById('TableBordered'))
renderTableColspanrowspan(ReactDOM, document.getElementById('TableColspanrowspan'))
renderTableCustomfilterpanel(ReactDOM, document.getElementById('TableCustomfilterpanel'))
renderTableDragsorting(ReactDOM, document.getElementById('TableDragsorting'))
renderTableDynamicsettings(ReactDOM, document.getElementById('TableDynamicsettings'))
renderTableEditcell(ReactDOM, document.getElementById('TableEditcell'))
renderTableEditrow(ReactDOM, document.getElementById('TableEditrow'))
renderTableExpandchildren(ReactDOM, document.getElementById('TableExpandchildren'))
renderTableExpand(ReactDOM, document.getElementById('TableExpand'))
renderTableFixedcolumnsheader(ReactDOM, document.getElementById('TableFixedcolumnsheader'))
renderTableFixedcolumns(ReactDOM, document.getElementById('TableFixedcolumns'))
renderTableFixedheader(ReactDOM, document.getElementById('TableFixedheader'))
renderTableGroupingcolumns(ReactDOM, document.getElementById('TableGroupingcolumns'))
renderTableHead(ReactDOM, document.getElementById('TableHead'))
renderTableJsx(ReactDOM, document.getElementById('TableJsx'))
renderTableNestedtable(ReactDOM, document.getElementById('TableNestedtable'))
renderTableResetfilter(ReactDOM, document.getElementById('TableResetfilter'))
renderTableRowselectionandoperation(
ReactDOM,
document.getElementById('TableRowselectionandoperation'),
)
renderTableRowselectioncustom(ReactDOM, document.getElementById('TableRowselectioncustom'))
renderTableRowselection(ReactDOM, document.getElementById('TableRowselection'))
renderTableSize(ReactDOM, document.getElementById('TableSize'))
}
render() {
return (
<div className="TableDemo">
<div className="row">
<div className="col-lg-12">
<div className="card">
<div className="card-header">
<div className="utils__title">
<strong>Table</strong>
<a
href="https://ant.design/components/table/"
target="_blank"
rel="noopener noreferrer"
className="btn btn-sm btn-primary ml-4"
>
Official Documentation <i className="icmn-link ml-1" />
</a>
</div>
</div>
<div className="card-body">
<div className="row">
<div className="col-xl-6 col-lg-12">
<div className="card card--example" id="components-table-demo-ajax">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Ajax</strong>
</h5>
</div>
<div className="card-body pb-0">
This example shows how to fetch and present data from remote server, and how
to implement filtering and sorting in server side by sending related
parameters to server. **Note, this example use [Mock
API](https://randomuser.me) that you can look up in Network Console.**
</div>
<div className="card-body pb-0">
<div id="TableAjax" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
import reqwest from 'reqwest';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
sorter\: true,
render\: name => \`\$\{name.first\} \$\{name.last\}\`,
width\: '20%',
\}, \{
title\: 'Gender',
dataIndex\: 'gender',
filters\: [
\{ text\: 'Male', value\: 'male' \},
\{ text\: 'Female', value\: 'female' \},
],
width\: '20%',
\}, \{
title\: 'Email',
dataIndex\: 'email',
\}];
class App extends React.Component \{
state = \{
data\: [],
pagination\: \{\},
loading\: false,
\};
handleTableChange = (pagination, filters, sorter) => \{
const pager = \{ ...this.state.pagination \};
pager.current = pagination.current;
this.setState(\{
pagination\: pager,
\});
this.fetch(\{
results\: pagination.pageSize,
page\: pagination.current,
sortField\: sorter.field,
sortOrder\: sorter.order,
...filters,
\});
\}
fetch = (params = \{\}) => \{
console.log('params\:', params);
this.setState(\{ loading\: true \});
reqwest(\{
url\: 'https\://randomuser.me/api',
method\: 'get',
data\: \{
results\: 10,
...params,
\},
type\: 'json',
\}).then((data) => \{
const pagination = \{ ...this.state.pagination \};
// Read total count from server
// pagination.total = data.totalCount;
pagination.total = 200;
this.setState(\{
loading\: false,
data\: data.results,
pagination,
\});
\});
\}
componentDidMount() \{
this.fetch();
\}
render() \{
return (
<Table columns=\{columns\}
rowKey=\{record => record.registered\}
dataSource=\{this.state.data\}
pagination=\{this.state.pagination\}
loading=\{this.state.loading\}
onChange=\{this.handleTableChange\}
/>
);
\}
\}
ReactDOM.render(<App />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-bordered">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize" />
</h5>
</div>
<div className="card-body pb-0">Add border, title and footer for table.</div>
<div className="card-body pb-0">
<div id="TableBordered" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
render\: text => <a href="#">\{text\}</a>,
\}, \{
title\: 'Cash Assets',
className\: 'column-money',
dataIndex\: 'money',
\}, \{
title\: 'Address',
dataIndex\: 'address',
\}];
const data = [\{
key\: '1',
name\: '<NAME>',
money\: '¥300,000.00',
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
money\: '¥1,256,000.00',
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
money\: '¥120,000.00',
address\: 'Sidney No. 1 Lake Park',
\}];
ReactDOM.render(
<Table
columns=\{columns\}
dataSource=\{data\}
bordered
title=\{() => 'Header'\}
footer=\{() => 'Footer'\}
/>
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div
className="card card--example"
id="components-table-demo-custom-filter-panel"
>
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Customized filter panel</strong>
</h5>
</div>
<div className="card-body pb-0">
Implement a customized column search example via{' '}
<code>{'filterDropdown'}</code>, <code>{'filterDropdownVisible'}</code> and{' '}
<code>{'filterDropdownVisibleChange'}</code>.
</div>
<div className="card-body pb-0">
<div id="TableCustomfilterpanel" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Input, Button, Icon \} from 'antd';
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}, \{
key\: '4',
name\: '<NAME>',
age\: 32,
address\: 'London No. 2 Lake Park',
\}];
class App extends React.Component \{
state = \{
filterDropdownVisible\: false,
data,
searchText\: '',
filtered\: false,
\};
onInputChange = (e) => \{
this.setState(\{ searchText\: e.target.value \});
\}
onSearch = () => \{
const \{ searchText \} = this.state;
const reg = new RegExp(searchText, 'gi');
this.setState(\{
filterDropdownVisible\: false,
filtered\: !!searchText,
data\: data.map((record) => \{
const match = record.name.match(reg);
if (!match) \{
return null;
\}
return \{
...record,
name\: (
<span>
\{record.name.split(reg).map((text, i) => (
i > 0 ? [<span className="highlight">\{match[0]\}</span>, text] \: text
))\}
</span>
),
\};
\}).filter(record => !!record),
\});
\}
render() \{
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
key\: 'name',
filterDropdown\: (
<div className="custom-filter-dropdown">
<Input
ref=\{ele => this.searchInput = ele\}
placeholder="Search name"
value=\{this.state.searchText\}
onChange=\{this.onInputChange\}
onPressEnter=\{this.onSearch\}
/>
<Button type="primary" onClick=\{this.onSearch\}>Search</Button>
</div>
),
filterIcon\: <Icon type="smile-o" style=\{\{ color\: this.state.filtered ? '#108ee9' \: '#aaa' \}\} />,
filterDropdownVisible\: this.state.filterDropdownVisible,
onFilterDropdownVisibleChange\: (visible) => \{
this.setState(\{
filterDropdownVisible\: visible,
\}, () => this.searchInput && this.searchInput.focus());
\},
\}, \{
title\: 'Age',
dataIndex\: 'age',
key\: 'age',
\}, \{
title\: 'Address',
dataIndex\: 'address',
key\: 'address',
filters\: [\{
text\: 'London',
value\: 'London',
\}, \{
text\: 'New York',
value\: 'New York',
\}],
onFilter\: (value, record) => record.address.indexOf(value) === 0,
\}];
return <Table columns=\{columns\} dataSource=\{this.state.data\} />;
\}
\}
ReactDOM.render(<App />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-dynamic-settings">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Dynamic Settings</strong>
</h5>
</div>
<div className="card-body pb-0">
Select different settings to see the result.
</div>
<div className="card-body pb-0">
<div id="TableDynamicsettings" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Icon, Switch, Radio, Form, Divider \} from 'antd';
const FormItem = Form.Item;
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
key\: 'name',
width\: 150,
render\: text => <a href="#">\{text\}</a>,
\}, \{
title\: 'Age',
dataIndex\: 'age',
key\: 'age',
width\: 70,
\}, \{
title\: 'Address',
dataIndex\: 'address',
key\: 'address',
\}, \{
title\: 'Action',
key\: 'action',
width\: 360,
render\: (text, record) => (
<span>
<a href="#">Action 一 \{record.name\}</a>
<Divider type="vertical" />
<a href="#">Delete</a>
<Divider type="vertical" />
<a href="#" className="ant-dropdown-link">
More actions <Icon type="down" />
</a>
</span>
),
\}];
const data = [];
for (let i = 1; i <= 10; i++) \{
data.push(\{
key\: i,
name\: '<NAME>',
age\: \`\$\{i\}2\`,
address\: \`New York No. \$\{i\} Lake Park\`,
description\: \`My name is <NAME>, I am \$\{i\}2 years old, living in New York No. \$\{i\} Lake Park.\`,
\});
\}
const expandedRowRender = record => <p>\{record.description\}</p>;
const title = () => 'Here is title';
const showHeader = true;
const footer = () => 'Here is footer';
const scroll = \{ y\: 240 \};
const pagination = \{ position\: 'bottom' \};
class Demo extends React.Component \{
state = \{
bordered\: false,
loading\: false,
pagination,
size\: 'default',
expandedRowRender,
title\: undefined,
showHeader,
footer,
rowSelection\: \{\},
scroll\: undefined,
\}
handleToggle = (prop) => \{
return (enable) => \{
this.setState(\{ [prop]\: enable \});
\};
\}
handleSizeChange = (e) => \{
this.setState(\{ size\: e.target.value \});
\}
handleExpandChange = (enable) => \{
this.setState(\{ expandedRowRender\: enable ? expandedRowRender \: undefined \});
\}
handleTitleChange = (enable) => \{
this.setState(\{ title\: enable ? title \: undefined \});
\}
handleHeaderChange = (enable) => \{
this.setState(\{ showHeader\: enable ? showHeader \: false \});
\}
handleFooterChange = (enable) => \{
this.setState(\{ footer\: enable ? footer \: undefined \});
\}
handleRowSelectionChange = (enable) => \{
this.setState(\{ rowSelection\: enable ? \{\} \: undefined \});
\}
handleScollChange = (enable) => \{
this.setState(\{ scroll\: enable ? scroll \: undefined \});
\}
handlePaginationChange = (e) => \{
const \{ value \} = e.target;
this.setState(\{
pagination\: value === 'none' ? false \: \{ position\: value \},
\});
\}
render() \{
const state = this.state;
return (
<div>
<div className="components-table-demo-control-bar">
<Form layout="inline">
<FormItem label="Bordered">
<Switch checked=\{state.bordered\} onChange=\{this.handleToggle('bordered')\} />
</FormItem>
<FormItem label="loading">
<Switch checked=\{state.loading\} onChange=\{this.handleToggle('loading')\} />
</FormItem>
<FormItem label="Title">
<Switch checked=\{!!state.title\} onChange=\{this.handleTitleChange\} />
</FormItem>
<FormItem label="Column Header">
<Switch checked=\{!!state.showHeader\} onChange=\{this.handleHeaderChange\} />
</FormItem>
<FormItem label="Footer">
<Switch checked=\{!!state.footer\} onChange=\{this.handleFooterChange\} />
</FormItem>
<FormItem label="Expandable">
<Switch checked=\{!!state.expandedRowRender\} onChange=\{this.handleExpandChange\} />
</FormItem>
<FormItem label="Checkbox">
<Switch checked=\{!!state.rowSelection\} onChange=\{this.handleRowSelectionChange\} />
</FormItem>
<FormItem label="Fixed Header">
<Switch checked=\{!!state.scroll\} onChange=\{this.handleScollChange\} />
</FormItem>
<FormItem label="Size">
<Radio.Group size="default" value=\{state.size\} onChange=\{this.handleSizeChange\}>
<Radio.Button value="default">Default</Radio.Button>
<Radio.Button value="middle">Middle</Radio.Button>
<Radio.Button value="small">Small</Radio.Button>
</Radio.Group>
</FormItem>
<FormItem label="Pagination">
<Radio.Group
value=\{state.pagination ? state.pagination.position \: 'none'\}
onChange=\{this.handlePaginationChange\}
>
<Radio.Button value="top">Top</Radio.Button>
<Radio.Button value="bottom">Bottom</Radio.Button>
<Radio.Button value="both">Both</Radio.Button>
<Radio.Button value="none">None</Radio.Button>
</Radio.Group>
</FormItem>
</Form>
</div>
<Table \{...this.state\} columns=\{columns\} dataSource=\{data\} />
</div>
);
\}
\}
ReactDOM.render(<Demo />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-edit-row">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Editable Rows</strong>
</h5>
</div>
<div className="card-body pb-0">Table with editable rows.</div>
<div className="card-body pb-0">
<div id="TableEditrow" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Input, Popconfirm \} from 'antd';
const data = [];
for (let i = 0; i < 100; i++) \{
data.push(\{
key\: i.toString(),
name\: \`Edrward \$\{i\}\`,
age\: 32,
address\: \`London Park no. \$\{i\}\`,
\});
\}
const EditableCell = (\{ editable, value, onChange \}) => (
<div>
\{editable
? <Input style=\{\{ margin\: '-5px 0' \}\} value=\{value\} onChange=\{e => onChange(e.target.value)\} />
\: value
\}
</div>
);
class EditableTable extends React.Component \{
constructor(props) \{
super(props);
this.columns = [\{
title\: 'name',
dataIndex\: 'name',
width\: '25%',
render\: (text, record) => this.renderColumns(text, record, 'name'),
\}, \{
title\: 'age',
dataIndex\: 'age',
width\: '15%',
render\: (text, record) => this.renderColumns(text, record, 'age'),
\}, \{
title\: 'address',
dataIndex\: 'address',
width\: '40%',
render\: (text, record) => this.renderColumns(text, record, 'address'),
\}, \{
title\: 'operation',
dataIndex\: 'operation',
render\: (text, record) => \{
const \{ editable \} = record;
return (
<div className="editable-row-operations">
\{
editable ?
<span>
<a onClick=\{() => this.save(record.key)\}>Save</a>
<Popconfirm title="Sure to cancel?" onConfirm=\{() => this.cancel(record.key)\}>
<a>Cancel</a>
</Popconfirm>
</span>
\: <a onClick=\{() => this.edit(record.key)\}>Edit</a>
\}
</div>
);
\},
\}];
this.state = \{ data \};
this.cacheData = data.map(item => (\{ ...item \}));
\}
renderColumns(text, record, column) \{
return (
<EditableCell
editable=\{record.editable\}
value=\{text\}
onChange=\{value => this.handleChange(value, record.key, column)\}
/>
);
\}
handleChange(value, key, column) \{
const newData = [...this.state.data];
const target = newData.filter(item => key === item.key)[0];
if (target) \{
target[column] = value;
this.setState(\{ data\: newData \});
\}
\}
edit(key) \{
const newData = [...this.state.data];
const target = newData.filter(item => key === item.key)[0];
if (target) \{
target.editable = true;
this.setState(\{ data\: newData \});
\}
\}
save(key) \{
const newData = [...this.state.data];
const target = newData.filter(item => key === item.key)[0];
if (target) \{
delete target.editable;
this.setState(\{ data\: newData \});
this.cacheData = newData.map(item => (\{ ...item \}));
\}
\}
cancel(key) \{
const newData = [...this.state.data];
const target = newData.filter(item => key === item.key)[0];
if (target) \{
Object.assign(target, this.cacheData.filter(item => key === item.key)[0]);
delete target.editable;
this.setState(\{ data\: newData \});
\}
\}
render() \{
return <Table bordered dataSource=\{this.state.data\} columns=\{this.columns\} />;
\}
\}
ReactDOM.render(<EditableTable />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-expand">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Expandable Row</strong>
</h5>
</div>
<div className="card-body pb-0">
When there's too much information to show and the table can't display all at
once.
</div>
<div className="card-body pb-0">
<div id="TableExpand" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [
\{ title\: 'Name', dataIndex\: 'name', key\: 'name' \},
\{ title\: 'Age', dataIndex\: 'age', key\: 'age' \},
\{ title\: 'Address', dataIndex\: 'address', key\: 'address' \},
\{ title\: 'Action', dataIndex\: '', key\: 'x', render\: () => <a href="#">Delete</a> \},
];
const data = [
\{ key\: 1, name\: '<NAME>', age\: 32, address\: 'New York No. 1 Lake Park', description\: 'My name is <NAME>, I am 32 years old, living in New York No. 1 Lake Park.' \},
\{ key\: 2, name\: '<NAME>', age\: 42, address\: 'London No. 1 Lake Park', description\: 'My name is <NAME>, I am 42 years old, living in London No. 1 Lake Park.' \},
\{ key\: 3, name\: '<NAME>', age\: 32, address\: 'Sidney No. 1 Lake Park', description\: 'My name is <NAME>, I am 32 years old, living in Sidney No. 1 Lake Park.' \},
];
ReactDOM.render(
<Table
columns=\{columns\}
expandedRowRender=\{record => <p style=\{\{ margin\: 0 \}\}>\{record.description\}</p>\}
dataSource=\{data\}
/>
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-fixed-columns">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Fixed Columns</strong>
</h5>
</div>
<div className="card-body pb-0">
To fix some columns and scroll inside other columns, and you must set{' '}
<code>{'scroll.x'}</code> meanwhile. > Specify the width of columns if
header and cell do not align properly. > A fixed value which is greater than
table width for <code>{'scroll.x'}</code> is recommended. The sum of unfixed
columns should not greater than <code>{'scroll.x'}</code>.
</div>
<div className="card-body pb-0">
<div id="TableFixedcolumns" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [
\{ title\: 'Full Name', width\: 100, dataIndex\: 'name', key\: 'name', fixed\: 'left' \},
\{ title\: 'Age', width\: 100, dataIndex\: 'age', key\: 'age', fixed\: 'left' \},
\{ title\: 'Column 1', dataIndex\: 'address', key\: '1' \},
\{ title\: 'Column 2', dataIndex\: 'address', key\: '2' \},
\{ title\: 'Column 3', dataIndex\: 'address', key\: '3' \},
\{ title\: 'Column 4', dataIndex\: 'address', key\: '4' \},
\{ title\: 'Column 5', dataIndex\: 'address', key\: '5' \},
\{ title\: 'Column 6', dataIndex\: 'address', key\: '6' \},
\{ title\: 'Column 7', dataIndex\: 'address', key\: '7' \},
\{ title\: 'Column 8', dataIndex\: 'address', key\: '8' \},
\{
title\: 'Action',
key\: 'operation',
fixed\: 'right',
width\: 100,
render\: () => <a href="#">action</a>,
\},
];
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 40,
address\: 'London Park',
\}];
ReactDOM.render(<Table columns=\{columns\} dataSource=\{data\} scroll=\{\{ x\: 1300 \}\} />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-grouping-columns">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Grouping table head</strong>
</h5>
</div>
<div className="card-body pb-0">
Group table head with <code>{'columns[n].children'}</code>.
</div>
<div className="card-body pb-0">
<div id="TableGroupingcolumns" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
key\: 'name',
width\: 100,
fixed\: 'left',
filters\: [\{
text\: 'Joe',
value\: 'Joe',
\}, \{
text\: 'John',
value\: 'John',
\}],
onFilter\: (value, record) => record.name.indexOf(value) === 0,
\}, \{
title\: 'Other',
children\: [\{
title\: 'Age',
dataIndex\: 'age',
key\: 'age',
width\: 200,
sorter\: (a, b) => a.age - b.age,
\}, \{
title\: 'Address',
children\: [\{
title\: 'Street',
dataIndex\: 'street',
key\: 'street',
width\: 200,
\}, \{
title\: 'Block',
children\: [\{
title\: 'Building',
dataIndex\: 'building',
key\: 'building',
width\: 100,
\}, \{
title\: 'Door No.',
dataIndex\: 'number',
key\: 'number',
width\: 100,
\}],
\}],
\}],
\}, \{
title\: 'Company',
children\: [\{
title\: 'Company Address',
dataIndex\: 'companyAddress',
key\: 'companyAddress',
\}, \{
title\: 'Company Name',
dataIndex\: 'companyName',
key\: 'companyName',
\}],
\}, \{
title\: 'Gender',
dataIndex\: 'gender',
key\: 'gender',
width\: 60,
fixed\: 'right',
\}];
const data = [];
for (let i = 0; i < 100; i++) \{
data.push(\{
key\: i,
name\: '<NAME>',
age\: i + 1,
street\: 'Lake Park',
building\: 'C',
number\: 2035,
companyAddress\: 'Lake Street 42',
companyName\: 'SoftLake Co',
gender\: 'M',
\});
\}
ReactDOM.render(
<Table
columns=\{columns\}
dataSource=\{data\}
bordered
size="middle"
scroll=\{\{ x\: '130%', y\: 240 \}\}
/>
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-jsx">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">JSX style API</strong>
</h5>
</div>
<div className="card-body pb-0">
Using JSX style API (introduced in 2.5.0) > Since this is just a syntax
sugar for the prop <code>{'columns'}</code>, so that you can't compose{' '}
<code>{'Column'}</code> and <code>{'ColumnGroup'}</code> with other
Components.
</div>
<div className="card-body pb-0">
<div id="TableJsx" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Icon, Divider \} from 'antd';
const \{ Column, ColumnGroup \} = Table;
const data = [\{
key\: '1',
firstName\: 'John',
lastName\: 'Brown',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
firstName\: 'Jim',
lastName\: 'Green',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
firstName\: 'Joe',
lastName\: 'Black',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}];
ReactDOM.render(
<Table dataSource=\{data\}>
<ColumnGroup title="Name">
<Column
title="First Name"
dataIndex="firstName"
key="firstName"
/>
<Column
title="Last Name"
dataIndex="lastName"
key="lastName"
/>
</ColumnGroup>
<Column
title="Age"
dataIndex="age"
key="age"
/>
<Column
title="Address"
dataIndex="address"
key="address"
/>
<Column
title="Action"
key="action"
render=\{(text, record) => (
<span>
<a href="#">Action 一 \{record.name\}</a>
<Divider type="vertical" />
<a href="#">Delete</a>
<Divider type="vertical" />
<a href="#" className="ant-dropdown-link">
More actions <Icon type="down" />
</a>
</span>
)\}
/>
</Table>
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-reset-filter">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Reset filters and sorters</strong>
</h5>
</div>
<div className="card-body pb-0">
Control filters and sorters by <code>{'filteredValue'}</code> and{' '}
<code>{'sortOrder'}</code>. > 1. Defining <code>{'filteredValue'}</code> or{' '}
<code>{'sortOrder'}</code> means that it is in the controlled mode. > 2.
Make sure <code>{'sortOrder'}</code> is assigned for only one column. > 3.{' '}
<code>{'column.key'}</code> is required.
</div>
<div className="card-body pb-0">
<div id="TableResetfilter" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Button \} from 'antd';
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}, \{
key\: '4',
name\: '<NAME>',
age\: 32,
address\: 'London No. 2 Lake Park',
\}];
class App extends React.Component \{
state = \{
filteredInfo\: null,
sortedInfo\: null,
\};
handleChange = (pagination, filters, sorter) => \{
console.log('Various parameters', pagination, filters, sorter);
this.setState(\{
filteredInfo\: filters,
sortedInfo\: sorter,
\});
\}
clearFilters = () => \{
this.setState(\{ filteredInfo\: null \});
\}
clearAll = () => \{
this.setState(\{
filteredInfo\: null,
sortedInfo\: null,
\});
\}
setAgeSort = () => \{
this.setState(\{
sortedInfo\: \{
order\: 'descend',
columnKey\: 'age',
\},
\});
\}
render() \{
let \{ sortedInfo, filteredInfo \} = this.state;
sortedInfo = sortedInfo || \{\};
filteredInfo = filteredInfo || \{\};
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
key\: 'name',
filters\: [
\{ text\: 'Joe', value\: 'Joe' \},
\{ text\: 'Jim', value\: 'Jim' \},
],
filteredValue\: filteredInfo.name || null,
onFilter\: (value, record) => record.name.includes(value),
sorter\: (a, b) => a.name.length - b.name.length,
sortOrder\: sortedInfo.columnKey === 'name' && sortedInfo.order,
\}, \{
title\: 'Age',
dataIndex\: 'age',
key\: 'age',
sorter\: (a, b) => a.age - b.age,
sortOrder\: sortedInfo.columnKey === 'age' && sortedInfo.order,
\}, \{
title\: 'Address',
dataIndex\: 'address',
key\: 'address',
filters\: [
\{ text\: 'London', value\: 'London' \},
\{ text\: 'New York', value\: 'New York' \},
],
filteredValue\: filteredInfo.address || null,
onFilter\: (value, record) => record.address.includes(value),
sorter\: (a, b) => a.address.length - b.address.length,
sortOrder\: sortedInfo.columnKey === 'address' && sortedInfo.order,
\}];
return (
<div>
<div className="table-operations">
<Button onClick=\{this.setAgeSort\}>Sort age</Button>
<Button onClick=\{this.clearFilters\}>Clear filters</Button>
<Button onClick=\{this.clearAll\}>Clear filters and sorters</Button>
</div>
<Table columns=\{columns\} dataSource=\{data\} onChange=\{this.handleChange\} />
</div>
);
\}
\}
ReactDOM.render(<App />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div
className="card card--example"
id="components-table-demo-row-selection-custom"
>
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Custom selection</strong>
</h5>
</div>
<div className="card-body pb-0">
Use <code>{'rowSelection.selections'}</code> custom selections, default no
select dropdown, show default selections via setting to{' '}
<code>{'true'}</code>.
</div>
<div className="card-body pb-0">
<div id="TableRowselectioncustom" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
\}, \{
title\: 'Age',
dataIndex\: 'age',
\}, \{
title\: 'Address',
dataIndex\: 'address',
\}];
const data = [];
for (let i = 0; i < 46; i++) \{
data.push(\{
key\: i,
name\: \`<NAME> \$\{i\}\`,
age\: 32,
address\: \`London, Park Lane no. \$\{i\}\`,
\});
\}
class App extends React.Component \{
state = \{
selectedRowKeys\: [], // Check here to configure the default column
\};
onSelectChange = (selectedRowKeys) => \{
console.log('selectedRowKeys changed\: ', selectedRowKeys);
this.setState(\{ selectedRowKeys \});
\}
render() \{
const \{ selectedRowKeys \} = this.state;
const rowSelection = \{
selectedRowKeys,
onChange\: this.onSelectChange,
hideDefaultSelections\: true,
selections\: [\{
key\: 'all-data',
text\: 'Select All Data',
onSelect\: () => \{
this.setState(\{
selectedRowKeys\: [...Array(46).keys()], // 0...45
\});
\},
\}, \{
key\: 'odd',
text\: 'Select Odd Row',
onSelect\: (changableRowKeys) => \{
let newSelectedRowKeys = [];
newSelectedRowKeys = changableRowKeys.filter((key, index) => \{
if (index % 2 !== 0) \{
return false;
\}
return true;
\});
this.setState(\{ selectedRowKeys\: newSelectedRowKeys \});
\},
\}, \{
key\: 'even',
text\: 'Select Even Row',
onSelect\: (changableRowKeys) => \{
let newSelectedRowKeys = [];
newSelectedRowKeys = changableRowKeys.filter((key, index) => \{
if (index % 2 !== 0) \{
return true;
\}
return false;
\});
this.setState(\{ selectedRowKeys\: newSelectedRowKeys \});
\},
\}],
onSelection\: this.onSelection,
\};
return (
<Table rowSelection=\{rowSelection\} columns=\{columns\} dataSource=\{data\} />
);
\}
\}
ReactDOM.render(<App />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-size">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">size</strong>
</h5>
</div>
<div className="card-body pb-0">
Two compacted table size: <code>{'middle'}</code> and <code>{'small'}</code>,{' '}
<code>{'small'}</code> size is used in Modal only.
</div>
<div className="card-body pb-0">
<div id="TableSize" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
\}, \{
title\: 'Age',
dataIndex\: 'age',
\}, \{
title\: 'Address',
dataIndex\: 'address',
\}];
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}];
ReactDOM.render(
<div>
<h4>Middle size table</h4>
<Table columns=\{columns\} dataSource=\{data\} size="middle" />
<h4>Small size table</h4>
<Table columns=\{columns\} dataSource=\{data\} size="small" />
</div>
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
</div>
<div className="col-xl-6 col-lg-12">
<div className="card card--example" id="components-table-demo-basic">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Basic Usage</strong>
</h5>
</div>
<div className="card-body pb-0">Simple table with actions.</div>
<div className="card-body pb-0">
<div id="TableBasic" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Icon, Divider \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
key\: 'name',
render\: text => <a href="#">\{text\}</a>,
\}, \{
title\: 'Age',
dataIndex\: 'age',
key\: 'age',
\}, \{
title\: 'Address',
dataIndex\: 'address',
key\: 'address',
\}, \{
title\: 'Action',
key\: 'action',
render\: (text, record) => (
<span>
<a href="#">Action 一 \{record.name\}</a>
<Divider type="vertical" />
<a href="#">Delete</a>
<Divider type="vertical" />
<a href="#" className="ant-dropdown-link">
More actions <Icon type="down" />
</a>
</span>
),
\}];
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}];
ReactDOM.render(<Table columns=\{columns\} dataSource=\{data\} />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-colspan-rowspan">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">colSpan and rowSpan</strong>
</h5>
</div>
<div className="card-body pb-0">
Table column title supports <code>{'colSpan'}</code> that set in{' '}
<code>{'column'}</code>. Table cell supports <code>{'colSpan'}</code> and{' '}
<code>{'rowSpan'}</code> that set in render return object. When each of them
is set to <code>{'0'}</code>, the cell will not be rendered.
</div>
<div className="card-body pb-0">
<div id="TableColspanrowspan" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
// In the fifth row, other columns are merged into first column
// by setting it's colSpan to be 0
const renderContent = (value, row, index) => \{
const obj = \{
children\: value,
props\: \{\},
\};
if (index === 4) \{
obj.props.colSpan = 0;
\}
return obj;
\};
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
render\: (text, row, index) => \{
if (index < 4) \{
return <a href="#">\{text\}</a>;
\}
return \{
children\: <a href="#">\{text\}</a>,
props\: \{
colSpan\: 5,
\},
\};
\},
\}, \{
title\: 'Age',
dataIndex\: 'age',
render\: renderContent,
\}, \{
title\: 'Home phone',
colSpan\: 2,
dataIndex\: 'tel',
render\: (value, row, index) => \{
const obj = \{
children\: value,
props\: \{\},
\};
if (index === 2) \{
obj.props.rowSpan = 2;
\}
// These two are merged into above cell
if (index === 3) \{
obj.props.rowSpan = 0;
\}
if (index === 4) \{
obj.props.colSpan = 0;
\}
return obj;
\},
\}, \{
title\: 'Phone',
colSpan\: 0,
dataIndex\: 'phone',
render\: renderContent,
\}, \{
title\: 'Address',
dataIndex\: 'address',
render\: renderContent,
\}];
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
tel\: '0571-22098909',
phone\: 18889898989,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
tel\: '0571-22098333',
phone\: 18889898888,
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
tel\: '0575-22098909',
phone\: 18900010002,
address\: 'Sidney No. 1 Lake Park',
\}, \{
key\: '4',
name\: '<NAME>',
age\: 18,
tel\: '0575-22098909',
phone\: 18900010002,
address\: 'London No. 2 Lake Park',
\}, \{
key\: '5',
name\: '<NAME>',
age\: 18,
tel\: '0575-22098909',
phone\: 18900010002,
address\: 'Dublin No. 2 Lake Park',
\}];
ReactDOM.render(<Table columns=\{columns\} dataSource=\{data\} bordered />
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-drag-sorting">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Drag sorting</strong>
</h5>
</div>
<div className="card-body pb-0">
By using custom components, we can integrate table with react-dnd to
implement drag sorting.
</div>
<div className="card-body pb-0">
<div id="TableDragsorting" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
import \{ DragDropContext, DragSource, DropTarget \} from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';
function dragDirection(
dragIndex,
hoverIndex,
initialClientOffset,
clientOffset,
sourceClientOffset,
) \{
const hoverMiddleY = (initialClientOffset.y - sourceClientOffset.y) / 2;
const hoverClientY = clientOffset.y - sourceClientOffset.y;
if (dragIndex < hoverIndex && hoverClientY > hoverMiddleY) \{
return 'downward';
\}
if (dragIndex > hoverIndex && hoverClientY < hoverMiddleY) \{
return 'upward';
\}
\}
let BodyRow = (props) => \{
const \{
isOver,
connectDragSource,
connectDropTarget,
moveRow,
dragRow,
clientOffset,
sourceClientOffset,
initialClientOffset,
...restProps
\} = props;
const style = \{ ...restProps.style, cursor\: 'move' \};
let className = restProps.className;
if (isOver && initialClientOffset) \{
const direction = dragDirection(
dragRow.index,
restProps.index,
initialClientOffset,
clientOffset,
sourceClientOffset
);
if (direction === 'downward') \{
className += ' drop-over-downward';
\}
if (direction === 'upward') \{
className += ' drop-over-upward';
\}
\}
return connectDragSource(
connectDropTarget(
<tr
\{...restProps\}
className=\{className\}
style=\{style\}
/>
)
);
\};
const rowSource = \{
beginDrag(props) \{
return \{
index\: props.index,
\};
\},
\};
const rowTarget = \{
drop(props, monitor) \{
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) \{
return;
\}
// Time to actually perform the action
props.moveRow(dragIndex, hoverIndex);
// Note\: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
\},
\};
BodyRow = DropTarget('row', rowTarget, (connect, monitor) => (\{
connectDropTarget\: connect.dropTarget(),
isOver\: monitor.isOver(),
sourceClientOffset\: monitor.getSourceClientOffset(),
\}))(
DragSource('row', rowSource, (connect, monitor) => (\{
connectDragSource\: connect.dragSource(),
dragRow\: monitor.getItem(),
clientOffset\: monitor.getClientOffset(),
initialClientOffset\: monitor.getInitialClientOffset(),
\}))(BodyRow)
);
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
key\: 'name',
\}, \{
title\: 'Age',
dataIndex\: 'age',
key\: 'age',
\}, \{
title\: 'Address',
dataIndex\: 'address',
key\: 'address',
\}];
class DragSortingTable extends React.Component \{
state = \{
data\: [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}],
\}
components = \{
body\: \{
row\: BodyRow,
\},
\}
moveRow = (dragIndex, hoverIndex) => \{
const \{ data \} = this.state;
const dragRow = data[dragIndex];
this.setState(
update(this.state, \{
data\: \{
\$splice\: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
\},
\}),
);
\}
render() \{
return (
<Table
columns=\{columns\}
dataSource=\{this.state.data\}
components=\{this.components\}
onRow=\{(record, index) => (\{
index,
moveRow\: this.moveRow,
\})\}
/>
);
\}
\}
const Demo = DragDropContext(HTML5Backend)(DragSortingTable);
ReactDOM.render(<Demo />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-edit-cell">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Editable Cells</strong>
</h5>
</div>
<div className="card-body pb-0">Table with editable cells.</div>
<div className="card-body pb-0">
<div id="TableEditcell" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Input, Icon, Button, Popconfirm \} from 'antd';
class EditableCell extends React.Component \{
state = \{
value\: this.props.value,
editable\: false,
\}
handleChange = (e) => \{
const value = e.target.value;
this.setState(\{ value \});
\}
check = () => \{
this.setState(\{ editable\: false \});
if (this.props.onChange) \{
this.props.onChange(this.state.value);
\}
\}
edit = () => \{
this.setState(\{ editable\: true \});
\}
render() \{
const \{ value, editable \} = this.state;
return (
<div className="editable-cell">
\{
editable ?
<div className="editable-cell-input-wrapper">
<Input
value=\{value\}
onChange=\{this.handleChange\}
onPressEnter=\{this.check\}
/>
<Icon
type="check"
className="editable-cell-icon-check"
onClick=\{this.check\}
/>
</div>
\:
<div className="editable-cell-text-wrapper">
\{value || ' '\}
<Icon
type="edit"
className="editable-cell-icon"
onClick=\{this.edit\}
/>
</div>
\}
</div>
);
\}
\}
class EditableTable extends React.Component \{
constructor(props) \{
super(props);
this.columns = [\{
title\: 'name',
dataIndex\: 'name',
width\: '30%',
render\: (text, record) => (
<EditableCell
value=\{text\}
onChange=\{this.onCellChange(record.key, 'name')\}
/>
),
\}, \{
title\: 'age',
dataIndex\: 'age',
\}, \{
title\: 'address',
dataIndex\: 'address',
\}, \{
title\: 'operation',
dataIndex\: 'operation',
render\: (text, record) => \{
return (
this.state.dataSource.length > 1 ?
(
<Popconfirm title="Sure to delete?" onConfirm=\{() => this.onDelete(record.key)\}>
<a href="#">Delete</a>
</Popconfirm>
) \: null
);
\},
\}];
this.state = \{
dataSource\: [\{
key\: '0',
name\: '<NAME>',
age\: '32',
address\: 'London, Park Lane no. 0',
\}, \{
key\: '1',
name\: '<NAME>',
age\: '32',
address\: 'London, Park Lane no. 1',
\}],
count\: 2,
\};
\}
onCellChange = (key, dataIndex) => \{
return (value) => \{
const dataSource = [...this.state.dataSource];
const target = dataSource.find(item => item.key === key);
if (target) \{
target[dataIndex] = value;
this.setState(\{ dataSource \});
\}
\};
\}
onDelete = (key) => \{
const dataSource = [...this.state.dataSource];
this.setState(\{ dataSource\: dataSource.filter(item => item.key !== key) \});
\}
handleAdd = () => \{
const \{ count, dataSource \} = this.state;
const newData = \{
key\: count,
name\: \`<NAME> \$\{count\}\`,
age\: 32,
address\: \`London, Park Lane no. \$\{count\}\`,
\};
this.setState(\{
dataSource\: [...dataSource, newData],
count\: count + 1,
\});
\}
render() \{
const \{ dataSource \} = this.state;
const columns = this.columns;
return (
<div>
<Button className="editable-add-btn" onClick=\{this.handleAdd\}>Add</Button>
<Table bordered dataSource=\{dataSource\} columns=\{columns\} />
</div>
);
\}
\}
ReactDOM.render(<EditableTable />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-expand-children">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Tree data</strong>
</h5>
</div>
<div className="card-body pb-0">
Display tree structure data in Table, control the indent width by setting{' '}
<code>{'indentSize'}</code>. > Note, no support for recursive selection of
tree structure data table yet.
</div>
<div className="card-body pb-0">
<div id="TableExpandchildren" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
key\: 'name',
\}, \{
title\: 'Age',
dataIndex\: 'age',
key\: 'age',
width\: '12%',
\}, \{
title\: 'Address',
dataIndex\: 'address',
width\: '30%',
key\: 'address',
\}];
const data = [\{
key\: 1,
name\: '<NAME> sr.',
age\: 60,
address\: 'New York No. 1 Lake Park',
children\: [\{
key\: 11,
name\: '<NAME>',
age\: 42,
address\: 'New York No. 2 Lake Park',
\}, \{
key\: 12,
name\: '<NAME> jr.',
age\: 30,
address\: 'New York No. 3 Lake Park',
children\: [\{
key\: 121,
name\: '<NAME>',
age\: 16,
address\: 'New York No. 3 Lake Park',
\}],
\}, \{
key\: 13,
name\: '<NAME> sr.',
age\: 72,
address\: 'London No. 1 Lake Park',
children\: [\{
key\: 131,
name\: '<NAME>',
age\: 42,
address\: 'London No. 2 Lake Park',
children\: [\{
key\: 1311,
name\: '<NAME> jr.',
age\: 25,
address\: 'London No. 3 Lake Park',
\}, \{
key\: 1312,
name\: '<NAME>.',
age\: 18,
address\: 'London No. 4 Lake Park',
\}],
\}],
\}],
\}, \{
key\: 2,
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}];
// rowSelection objects indicates the need for row selection
const rowSelection = \{
onChange\: (selectedRowKeys, selectedRows) => \{
console.log(\`selectedRowKeys\: \$\{selectedRowKeys\}\`, 'selectedRows\: ', selectedRows);
\},
onSelect\: (record, selected, selectedRows) => \{
console.log(record, selected, selectedRows);
\},
onSelectAll\: (selected, selectedRows, changeRows) => \{
console.log(selected, selectedRows, changeRows);
\},
\};
ReactDOM.render(
<Table columns=\{columns\} rowSelection=\{rowSelection\} dataSource=\{data\} />
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div
className="card card--example"
id="components-table-demo-fixed-columns-header"
>
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Fixed Columns and Header</strong>
</h5>
</div>
<div className="card-body pb-0">
A Solution for displaying large amounts of data with long columns. > Specify
the width of columns if header and cell do not align properly. > A fixed
value which is greater than table width for <code>{'scroll.x'}</code> is
recommended. The sum of unfixed columns should not greater than{' '}
<code>{'scroll.x'}</code>.
</div>
<div className="card-body pb-0">
<div id="TableFixedcolumnsheader" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [
\{ title\: 'Full Name', width\: 100, dataIndex\: 'name', key\: 'name', fixed\: 'left' \},
\{ title\: 'Age', width\: 100, dataIndex\: 'age', key\: 'age', fixed\: 'left' \},
\{ title\: 'Column 1', dataIndex\: 'address', key\: '1', width\: 150 \},
\{ title\: 'Column 2', dataIndex\: 'address', key\: '2', width\: 150 \},
\{ title\: 'Column 3', dataIndex\: 'address', key\: '3', width\: 150 \},
\{ title\: 'Column 4', dataIndex\: 'address', key\: '4', width\: 150 \},
\{ title\: 'Column 5', dataIndex\: 'address', key\: '5', width\: 150 \},
\{ title\: 'Column 6', dataIndex\: 'address', key\: '6', width\: 150 \},
\{ title\: 'Column 7', dataIndex\: 'address', key\: '7', width\: 150 \},
\{ title\: 'Column 8', dataIndex\: 'address', key\: '8' \},
\{
title\: 'Action',
key\: 'operation',
fixed\: 'right',
width\: 100,
render\: () => <a href="#">action</a>,
\},
];
const data = [];
for (let i = 0; i < 100; i++) \{
data.push(\{
key\: i,
name\: \`Edrward \$\{i\}\`,
age\: 32,
address\: \`London Park no. \$\{i\}\`,
\});
\}
ReactDOM.render(<Table columns=\{columns\} dataSource=\{data\} scroll=\{\{ x\: 1500, y\: 300 \}\} />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-fixed-header">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Fixed Header</strong>
</h5>
</div>
<div className="card-body pb-0">
Display large amounts of data in scrollable view. > Specify the width of
each column if header and cell do not align properly.
</div>
<div className="card-body pb-0">
<div id="TableFixedheader" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
width\: 150,
\}, \{
title\: 'Age',
dataIndex\: 'age',
width\: 150,
\}, \{
title\: 'Address',
dataIndex\: 'address',
\}];
const data = [];
for (let i = 0; i < 100; i++) \{
data.push(\{
key\: i,
name\: \`<NAME> \$\{i\}\`,
age\: 32,
address\: \`London, Park Lane no. \$\{i\}\`,
\});
\}
ReactDOM.render(
<Table columns=\{columns\} dataSource=\{data\} pagination=\{\{ pageSize\: 50 \}\} scroll=\{\{ y\: 240 \}\} />
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-head">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Filter and sorter</strong>
</h5>
</div>
<div className="card-body pb-0">
Use <code>{'filters'}</code> to generate filter menu in columns,{' '}
<code>{'onFilter'}</code> to determine filtered result, and{' '}
<code>{'filterMultiple'}</code> to indicate whether it's multiple or single
selection. Use <code>{'sorter'}</code> to make a column sortable.{' '}
<code>{'sorter'}</code> can be a function{' '}
<code>{'function(a, b) { ... }'}</code> for sorting data locally. Uses{' '}
<code>{'defaultSortOrder'}</code> to make a column sorted by default.
</div>
<div className="card-body pb-0">
<div id="TableHead" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
filters\: [\{
text\: 'Joe',
value\: 'Joe',
\}, \{
text\: 'Jim',
value\: 'Jim',
\}, \{
text\: 'Submenu',
value\: 'Submenu',
children\: [\{
text\: 'Green',
value\: 'Green',
\}, \{
text\: 'Black',
value\: 'Black',
\}],
\}],
// specify the condition of filtering result
// here is that finding the name started with \`value\`
onFilter\: (value, record) => record.name.indexOf(value) === 0,
sorter\: (a, b) => a.name.length - b.name.length,
\}, \{
title\: 'Age',
dataIndex\: 'age',
defaultSortOrder\: 'descend',
sorter\: (a, b) => a.age - b.age,
\}, \{
title\: 'Address',
dataIndex\: 'address',
filters\: [\{
text\: 'London',
value\: 'London',
\}, \{
text\: 'New York',
value\: 'New York',
\}],
filterMultiple\: false,
onFilter\: (value, record) => record.address.indexOf(value) === 0,
sorter\: (a, b) => a.address.length - b.address.length,
\}];
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}, \{
key\: '4',
name\: '<NAME>',
age\: 32,
address\: 'London No. 2 Lake Park',
\}];
function onChange(pagination, filters, sorter) \{
console.log('params', pagination, filters, sorter);
\}
ReactDOM.render(
<Table columns=\{columns\} dataSource=\{data\} onChange=\{onChange\} />
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-nested-table">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Nested tables</strong>
</h5>
</div>
<div className="card-body pb-0">Showing more detailed info of every row.</div>
<div className="card-body pb-0">
<div id="TableNestedtable" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`
import \{ Table, Badge, Menu, Dropdown, Icon \} from 'antd';
const menu = (
<Menu>
<Menu.Item>
Action 1
</Menu.Item>
<Menu.Item>
Action 2
</Menu.Item>
</Menu>
);
function NestedTable() \{
const expandedRowRender = () => \{
const columns = [
\{ title\: 'Date', dataIndex\: 'date', key\: 'date' \},
\{ title\: 'Name', dataIndex\: 'name', key\: 'name' \},
\{ title\: 'Status', key\: 'state', render\: () => <span><Badge status="success" />Finished</span> \},
\{ title\: 'Upgrade Status', dataIndex\: 'upgradeNum', key\: 'upgradeNum' \},
\{
title\: 'Action',
dataIndex\: 'operation',
key\: 'operation',
render\: () => (
<span className="table-operation">
<a href="#">Pause</a>
<a href="#">Stop</a>
<Dropdown overlay=\{menu\}>
<a href="#">
More <Icon type="down" />
</a>
</Dropdown>
</span>
),
\},
];
const data = [];
for (let i = 0; i < 3; ++i) \{
data.push(\{
key\: i,
date\: '2014-12-24 23\:12\:00',
name\: 'This is production name',
upgradeNum\: 'Upgraded\: 56',
\});
\}
return (
<Table
columns=\{columns\}
dataSource=\{data\}
pagination=\{false\}
/>
);
\};
const columns = [
\{ title\: 'Name', dataIndex\: 'name', key\: 'name' \},
\{ title\: 'Platform', dataIndex\: 'platform', key\: 'platform' \},
\{ title\: 'Version', dataIndex\: 'version', key\: 'version' \},
\{ title\: 'Upgraded', dataIndex\: 'upgradeNum', key\: 'upgradeNum' \},
\{ title\: 'Creator', dataIndex\: 'creator', key\: 'creator' \},
\{ title\: 'Date', dataIndex\: 'createdAt', key\: 'createdAt' \},
\{ title\: 'Action', key\: 'operation', render\: () => <a href="#">Publish</a> \},
];
const data = [];
for (let i = 0; i < 3; ++i) \{
data.push(\{
key\: i,
name\: 'Screem',
platform\: 'iOS',
version\: '10.3.4.5654',
upgradeNum\: 500,
creator\: 'Jack',
createdAt\: '2014-12-24 23\:12\:00',
\});
\}
return (
<Table
className="components-table-demo-nested"
columns=\{columns\}
expandedRowRender=\{expandedRowRender\}
dataSource=\{data\}
/>
);
\}
ReactDOM.render(<NestedTable />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div
className="card card--example"
id="components-table-demo-row-selection-and-operation"
>
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">Selection and operation</strong>
</h5>
</div>
<div className="card-body pb-0">
To perform operations and clear selections after selecting some rows, use{' '}
<code>{'rowSelection.selectedRowKeys'}</code> to control selected rows.
</div>
<div className="card-body pb-0">
<div id="TableRowselectionandoperation" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table, Button \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
\}, \{
title\: 'Age',
dataIndex\: 'age',
\}, \{
title\: 'Address',
dataIndex\: 'address',
\}];
const data = [];
for (let i = 0; i < 46; i++) \{
data.push(\{
key\: i,
name\: \`<NAME> \$\{i\}\`,
age\: 32,
address\: \`London, Park Lane no. \$\{i\}\`,
\});
\}
class App extends React.Component \{
state = \{
selectedRowKeys\: [], // Check here to configure the default column
loading\: false,
\};
start = () => \{
this.setState(\{ loading\: true \});
// ajax request after empty completing
setTimeout(() => \{
this.setState(\{
selectedRowKeys\: [],
loading\: false,
\});
\}, 1000);
\}
onSelectChange = (selectedRowKeys) => \{
console.log('selectedRowKeys changed\: ', selectedRowKeys);
this.setState(\{ selectedRowKeys \});
\}
render() \{
const \{ loading, selectedRowKeys \} = this.state;
const rowSelection = \{
selectedRowKeys,
onChange\: this.onSelectChange,
\};
const hasSelected = selectedRowKeys.length > 0;
return (
<div>
<div style=\{\{ marginBottom\: 16 \}\}>
<Button
type="primary"
onClick=\{this.start\}
disabled=\{!hasSelected\}
loading=\{loading\}
>
Reload
</Button>
<span style=\{\{ marginLeft\: 8 \}\}>
\{hasSelected ? \`Selected \$\{selectedRowKeys.length\} items\` \: ''\}
</span>
</div>
<Table rowSelection=\{rowSelection\} columns=\{columns\} dataSource=\{data\} />
</div>
);
\}
\}
ReactDOM.render(<App />, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
<div className="card card--example" id="components-table-demo-row-selection">
<div className="card-header">
<h5 className="text-black">
<strong className="text-capitalize">selection</strong>
</h5>
</div>
<div className="card-body pb-0">
Rows can be selectable by making first column as a selectable column. >
selection happens when clicking checkbox defaultly. You can see
https://codesandbox.io/s/000vqw38rl if you need row-click selection
behavior.
</div>
<div className="card-body pb-0">
<div id="TableRowselection" />
</div>
<div className="utils__codeCollapse">
<Collapse bordered={false} defaultActiveKey={['1']}>
<Panel
header={
<span>
<i
className="fa fa-code"
style={{ fontSize: 16, color: '#9f9f9f' }}
/>
<span className="ml-2 text-primary">Show Code</span>
</span>
}
key="2"
showArrow={false}
>
<SyntaxHighlighter
language="jsx"
style={base16AteliersulphurpoolLight}
useInlineStyles={true}
>
{`import \{ Table \} from 'antd';
const columns = [\{
title\: 'Name',
dataIndex\: 'name',
render\: text => <a href="#">\{text\}</a>,
\}, \{
title\: 'Age',
dataIndex\: 'age',
\}, \{
title\: 'Address',
dataIndex\: 'address',
\}];
const data = [\{
key\: '1',
name\: '<NAME>',
age\: 32,
address\: 'New York No. 1 Lake Park',
\}, \{
key\: '2',
name\: '<NAME>',
age\: 42,
address\: 'London No. 1 Lake Park',
\}, \{
key\: '3',
name\: '<NAME>',
age\: 32,
address\: 'Sidney No. 1 Lake Park',
\}, \{
key\: '4',
name\: 'Disabled User',
age\: 99,
address\: 'Sidney No. 1 Lake Park',
\}];
// rowSelection object indicates the need for row selection
const rowSelection = \{
onChange\: (selectedRowKeys, selectedRows) => \{
console.log(\`selectedRowKeys\: \$\{selectedRowKeys\}\`, 'selectedRows\: ', selectedRows);
\},
getCheckboxProps\: record => (\{
disabled\: record.name === 'Disabled User', // Column configuration not to be checked
name\: record.name,
\}),
\};
ReactDOM.render(
<Table rowSelection=\{rowSelection\} columns=\{columns\} dataSource=\{data\} />
, mountNode);
`}
</SyntaxHighlighter>
</Panel>
</Collapse>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default TableItems
|
Sheldan/abstracto | abstracto-application/abstracto-modules/link-embed/link-embed-int/src/main/java/dev/sheldan/abstracto/linkembed/model/template/MessageEmbeddedModel.java | <gh_stars>1-10
package dev.sheldan.abstracto.linkembed.model.template;
import dev.sheldan.abstracto.core.models.cache.CachedMessage;
import dev.sheldan.abstracto.core.models.context.UserInitiatedServerContext;
import dev.sheldan.abstracto.core.models.template.button.ButtonConfigModel;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
@Getter
@Setter
@SuperBuilder
public class MessageEmbeddedModel extends UserInitiatedServerContext {
private CachedMessage embeddedMessage;
private User author;
private TextChannel sourceChannel;
private Member embeddingUser;
private ButtonConfigModel buttonConfigModel;
private Long referencedMessageId;
private Boolean mentionsReferencedMessage;
private Boolean useButton;
}
|
GregDevProjects/carbon-header-fix | node_modules/@carbon/icons-react/es/list--numbered/24.js | import { ListNumbered24 } from '..';
export default ListNumbered24;
|
ramtej/qi4j-sdk | core/runtime/src/main/java/org/qi4j/runtime/structure/LayerInstance.java | <reponame>ramtej/qi4j-sdk<filename>core/runtime/src/main/java/org/qi4j/runtime/structure/LayerInstance.java<gh_stars>1-10
/*
* Copyright (c) 2008, <NAME>. All Rights Reserved.
* Copyright (c) 2012, <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.qi4j.runtime.structure;
import java.util.ArrayList;
import java.util.List;
import org.qi4j.api.activation.ActivationEventListener;
import org.qi4j.api.activation.ActivationException;
import org.qi4j.api.activation.PassivationException;
import org.qi4j.api.common.Visibility;
import org.qi4j.api.service.ServiceReference;
import org.qi4j.api.structure.Layer;
import org.qi4j.functional.Function;
import org.qi4j.runtime.activation.ActivationDelegate;
import org.qi4j.runtime.composite.TransientModel;
import org.qi4j.runtime.entity.EntityModel;
import org.qi4j.runtime.object.ObjectModel;
import org.qi4j.runtime.value.ValueModel;
import static org.qi4j.functional.Iterables.flattenIterables;
import static org.qi4j.functional.Iterables.map;
/**
* Instance of a Qi4j application layer. Contains a list of modules which are managed by this layer.
*/
public class LayerInstance
implements Layer
{
// Constructor parameters
private final LayerModel layerModel;
private final ApplicationInstance applicationInstance;
private final UsedLayersInstance usedLayersInstance;
// Eager instance objects
private final ActivationDelegate activation;
private final List<ModuleInstance> moduleInstances;
public LayerInstance( LayerModel model,
ApplicationInstance applicationInstance,
UsedLayersInstance usedLayersInstance )
{
// Constructor parameters
this.layerModel = model;
this.applicationInstance = applicationInstance;
this.usedLayersInstance = usedLayersInstance;
// Eager instance objects
activation = new ActivationDelegate( this );
moduleInstances = new ArrayList<>();
}
@Override
public String toString()
{
return layerModel.toString();
}
// Implementation of Layer
@Override
public String name()
{
return layerModel.name();
}
// Implementation of MetaInfoHolder
@Override
public <T> T metaInfo( Class<T> infoType )
{
return layerModel.metaInfo( infoType );
}
// Implementation of Activation
@Override
public void activate()
throws ActivationException
{
activation.activate( layerModel.newActivatorsInstance(), moduleInstances );
}
@Override
public void passivate()
throws PassivationException
{
activation.passivate();
}
@Override
public void registerActivationEventListener( ActivationEventListener listener )
{
activation.registerActivationEventListener( listener );
}
@Override
public void deregisterActivationEventListener( ActivationEventListener listener )
{
activation.deregisterActivationEventListener( listener );
}
// Other methods
/* package */ void addModule( ModuleInstance module )
{
module.registerActivationEventListener( activation );
moduleInstances.add( module );
}
/* package */ LayerModel model()
{
return layerModel;
}
public ApplicationInstance applicationInstance()
{
return applicationInstance;
}
/* package */ UsedLayersInstance usedLayersInstance()
{
return usedLayersInstance;
}
/* package */ Iterable<ModelModule<ObjectModel>> visibleObjects( final Visibility visibility )
{
return flattenIterables( map( new Function<ModuleInstance, Iterable<ModelModule<ObjectModel>>>()
{
@Override
public Iterable<ModelModule<ObjectModel>> map( ModuleInstance moduleInstance )
{
return moduleInstance.visibleObjects( visibility );
}
}, moduleInstances ) );
}
/* package */ Iterable<ModelModule<TransientModel>> visibleTransients( final Visibility visibility )
{
return flattenIterables( map( new Function<ModuleInstance, Iterable<ModelModule<TransientModel>>>()
{
@Override
public Iterable<ModelModule<TransientModel>> map( ModuleInstance moduleInstance )
{
return moduleInstance.visibleTransients( visibility );
}
}, moduleInstances ) );
}
/* package */ Iterable<ModelModule<EntityModel>> visibleEntities( final Visibility visibility )
{
return flattenIterables( map( new Function<ModuleInstance, Iterable<ModelModule<EntityModel>>>()
{
@Override
public Iterable<ModelModule<EntityModel>> map( ModuleInstance moduleInstance )
{
return moduleInstance.visibleEntities( visibility );
}
}, moduleInstances ) );
}
/* package */ Iterable<ModelModule<ValueModel>> visibleValues( final Visibility visibility )
{
return flattenIterables( map( new Function<ModuleInstance, Iterable<ModelModule<ValueModel>>>()
{
@Override
public Iterable<ModelModule<ValueModel>> map( ModuleInstance moduleInstance )
{
return moduleInstance.visibleValues( visibility );
}
}, moduleInstances ) );
}
/* package */ Iterable<ServiceReference<?>> visibleServices( final Visibility visibility )
{
return flattenIterables( map( new Function<ModuleInstance, Iterable<ServiceReference<?>>>()
{
@Override
public Iterable<ServiceReference<?>> map( ModuleInstance moduleInstance )
{
return moduleInstance.visibleServices( visibility );
}
}, moduleInstances ) );
}
/* package */ ModuleInstance findModule( String moduleName )
{
for( ModuleInstance moduleInstance : moduleInstances )
{
if( moduleInstance.model().name().equals( moduleName ) )
{
return moduleInstance;
}
}
throw new IllegalArgumentException( "No such module:" + moduleName );
}
}
|
aprorg/myria | src/edu/washington/escience/myria/api/encoding/SingleGroupByAggregateEncoding.java | <filename>src/edu/washington/escience/myria/api/encoding/SingleGroupByAggregateEncoding.java
package edu.washington.escience.myria.api.encoding;
import edu.washington.escience.myria.api.encoding.QueryConstruct.ConstructArgs;
import edu.washington.escience.myria.operator.agg.AggregatorFactory;
import edu.washington.escience.myria.operator.agg.SingleGroupByAggregate;
public class SingleGroupByAggregateEncoding extends UnaryOperatorEncoding<SingleGroupByAggregate> {
@Required
public AggregatorFactory[] aggregators;
@Required
public int argGroupField;
@Override
public SingleGroupByAggregate construct(ConstructArgs args) {
return new SingleGroupByAggregate(null, argGroupField, aggregators);
}
}
|
gemmellr/qpid-site | input/releases/qpid-cpp-master/messaging-api/cpp/api/structqpid_1_1messaging_1_1ReceiverError.js | <reponame>gemmellr/qpid-site
var structqpid_1_1messaging_1_1ReceiverError =
[
[ "ReceiverError", "structqpid_1_1messaging_1_1ReceiverError.html#a4e033da931f45817b016354f15bfebaa", null ]
]; |
kbaseIncubator/cs_uploader | src/us/kbase/cs/orm/dumpers/Biomass.java | <reponame>kbaseIncubator/cs_uploader
package us.kbase.cs.orm.dumpers;
import us.kbase.cs.orm.Column;
import us.kbase.cs.orm.ColumnType;
import us.kbase.cs.orm.Dumper;
import java.io.IOException;
public class Biomass extends Dumper {
@Column(name="id", type=ColumnType.STRING)
private String id;
@Column(name="mod_date", type=ColumnType.DATE)
private Long modDate;
@Column(name="name", type=ColumnType.STRING)
private String name;
@Column(name="dna", type=ColumnType.FLOAT)
private Float dna;
@Column(name="protein", type=ColumnType.FLOAT)
private Float protein;
@Column(name="cell_wall", type=ColumnType.FLOAT)
private Float cellWall;
@Column(name="lipid", type=ColumnType.FLOAT)
private Float lipid;
@Column(name="cofactor", type=ColumnType.FLOAT)
private Float cofactor;
@Column(name="energy", type=ColumnType.FLOAT)
private Float energy;
private Biomass() throws IOException{
super();
}
public static Biomass newDumper() throws IOException{
return new Biomass();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Biomass withId(String id) {
this.id = id;
return this;
}
public Long getMod_date() {
return modDate;
}
public void setMod_date(Long modDate) {
this.modDate = modDate;
}
public Biomass withMod_date(Long modDate) {
this.modDate = modDate;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Biomass withName(String name) {
this.name = name;
return this;
}
public Float getDna() {
return dna;
}
public void setDna(Float dna) {
this.dna = dna;
}
public Biomass withDna(Float dna) {
this.dna = dna;
return this;
}
public Float getProtein() {
return protein;
}
public void setProtein(Float protein) {
this.protein = protein;
}
public Biomass withProtein(Float protein) {
this.protein = protein;
return this;
}
public Float getCell_wall() {
return cellWall;
}
public void setCell_wall(Float cellWall) {
this.cellWall = cellWall;
}
public Biomass withCell_wall(Float cellWall) {
this.cellWall = cellWall;
return this;
}
public Float getLipid() {
return lipid;
}
public void setLipid(Float lipid) {
this.lipid = lipid;
}
public Biomass withLipid(Float lipid) {
this.lipid = lipid;
return this;
}
public Float getCofactor() {
return cofactor;
}
public void setCofactor(Float cofactor) {
this.cofactor = cofactor;
}
public Biomass withCofactor(Float cofactor) {
this.cofactor = cofactor;
return this;
}
public Float getEnergy() {
return energy;
}
public void setEnergy(Float energy) {
this.energy = energy;
}
public Biomass withEnergy(Float energy) {
this.energy = energy;
return this;
}
}
|
Guyutongxue/Practice_of_Programming | RealPractices/08/01.Output200.cpp | <filename>RealPractices/08/01.Output200.cpp
#include<iostream>
using namespace std;
class Number {
public:
int num;
Number(int n=0): num(n) {}
};
#define Number int
int a[1]={
};
int main() {
Number n1(10), n2(20);
Number n3;
n3 = n1*n2;
cout << int(n3) << endl;
return 0;
} |
nastasiaboldyreva/job4j | chapter_002/src/test/java/ru.job4j/encapsulation/StaticMethodTest.java | <gh_stars>1-10
package ru.job4j.encapsulation;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.StringJoiner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import java.util.List;
import java.util.function.Consumer;
public class StaticMethodTest {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final Consumer<String> output = new Consumer<>(){
private final PrintStream stdout = new PrintStream(out);
@Override
public void accept(String s) {
stdout.println(s);
}
@Override
public String toString() {
return out.toString();
}
};
@Test
public void whenAddItem() {
List<String> answers = new ArrayList<>();
answers.add("Fix PC");
Input input = new StubInputStatic(answers);
Tracker tracker = new Tracker();
new CreateAction().execute(input, tracker, output);
//CreateAction::execute;
List<ItemTracker> created = tracker.findAll();
List<ItemTracker> expected = new ArrayList<>();
expected.add(new ItemTracker("Fix PC"));
assertThat(created.get(0).getName(), is(expected.get(0).getName()));
}
@Test
public void whenPrtMenu() {
//private final ByteArrayOutputStream out = new ByteArrayOutputStream();
final PrintStream def = System.out;
System.setOut(new PrintStream(out));
StubInputStatic input = new StubInputStatic(List.of("0"));
StubAction action = new StubAction();
List<UserAction> actions = List.of(action);
//new StaticMethod().init(input, new Tracker(), actions);
new StaticMethod(System.out::println).init(input, new Tracker(), actions);
String expect = new StringJoiner(System.lineSeparator(), "", System.lineSeparator())
.add("Menu: ")
.add("0. Stub action")
.toString();
//assertThat(new String(out.toByteArray()), is(expect));
assertThat(this.output.toString(), is(expect));
System.setOut(def);
}
}
|
lightcopy/history-server | src/main/java/com/github/lightcopy/history/event/SparkListenerJobStart.java | /*
* Copyright 2017 Lightcopy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.lightcopy.history.event;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.annotations.SerializedName;
public class SparkListenerJobStart {
@SerializedName("Job ID") public int jobId;
@SerializedName("Submission Time") public long submissionTime;
@SerializedName("Stage Infos") public List<StageInfo> stageInfos;
@SerializedName("Properties") public Map<String, String> properties;
/** Get job name as the last stage name */
public String getJobName() {
// search for the stage with the largest id and use name as job name
int stageId = -1;
String name = "Job " + jobId + " (unknown)";
for (StageInfo info : stageInfos) {
if (info != null && stageId <= info.stageId && info.stageName != null) {
stageId = info.stageId;
name = info.stageName;
}
}
return name;
}
/** Get total tasks based on stage infos */
public int getTotalTasks() {
// Compute (a potential underestimate of) the number of tasks that will be run by this job.
// This may be an underestimate because the job start event references all of the result
// stages' transitive stage dependencies, but some of these stages might be skipped if their
// output is available from earlier runs.
int numTasks = 0;
for (StageInfo info : stageInfos) {
if (info != null && info.completionTime <= 0) {
numTasks += info.numTasks;
}
}
return numTasks;
}
/** Get query execution id or -1 if there is no link to sql execution */
public int getExecutionId() {
if (properties != null) {
String query = properties.get("spark.sql.execution.id");
if (query != null && !query.isEmpty()) {
// do not fall back to the -1, if query fails to parse
// this might indicate potential incompatibility between Spark versions
return Integer.parseInt(query);
}
}
// could not find query for the job
return -1;
}
/** Get job group or null if no group is not provided */
public String getJobGroup() {
// if property is not found, it is okay to return null
if (properties == null) return null;
return properties.get("spark.jobGroup.id");
}
}
|
Alexloof/TaskApp | client/src/lib/withAuth.js | import React, { Component } from 'react'
export default WrappedComponent => {
return class extends Component {
state = {
isAuth: false
}
componentDidMount() {
const isAuth = localStorage.getItem('token')
if (isAuth) {
this.setState({ isAuth: true })
} else {
this.setState({ isAuth: false }, () => {
this.props.history.replace('/login')
})
}
}
render() {
if (!this.state.isAuth) {
return null
}
return <WrappedComponent {...this.props} />
}
}
}
|
sweeneycai/cs-summary-reflection | java-leetcode/src/main/java/io/github/dreamylost/practice/Main0.java | /* All Contributors (C) 2020 */
package io.github.dreamylost.practice;
/**
* Title: Main.java
*
* <p>Description:小易准备去魔法王国采购魔法神器,购买魔法神器需要使用魔法币,但是小易现在一枚魔法币都没有,
* 但是小易有两台魔法机器可以通过投入x(x可以为0)个魔法币产生更多的魔法币。 魔法机器1:如果投入x个魔法币,魔法机器会将其变为2x+1个魔法币
* 魔法机器2:如果投入x个魔法币,魔法机器会将其变为2x+2个魔法币
*
* <p>小易采购魔法神器总共需要n个魔法币,所以小易只能通过两台魔法机器产生恰好n个魔法币, 小易需要你帮他设计一个投入方案使他最后恰好拥有n个魔法币。 输入描述:
*
* <p>输入包括一行,包括一个正整数n(1 ≤ n ≤ 10^9),表示小易需要的魔法币数量。
*
* <p>输出描述: 输出一个字符串,每个字符表示该次小易选取投入的魔法机器。其中只包含字符'1'和'2'。
*
* <p>输入例子1: 10
*
* <p>输出例子1: 122
*
* <p>Copyright: Copyright (c) 2018
*
* <p>School: jxnu
*
* @author Mr.Li
* @date 2018-2-16
* @version 1.0
*/
public class Main0 {
/** @param args */
public static void main(String[] args) {
Main0 sTest = new Main0();
java.util.Scanner scanner = new java.util.Scanner(System.in);
int s = scanner.nextInt();
String string = sTest.get(s);
System.out.println(string);
scanner.close();
}
/**
* @desciption
* @param n
* @return
*/
public String get(int n) {
String res = "";
while (n > 0) {
if (n % 2 == 0) {
res += '2' + ",";
n = (n - 2) / 2;
} else {
res += '1' + ",";
n = (n - 1) / 2;
}
}
String string = "";
String[] t = res.substring(0, res.length() - 1).split(",");
for (int i = t.length - 1; i >= 0; i--) {
string += t[i];
}
return string;
}
}
|
zarmomin/mrpt | libs/kinematics/src/CVehicleSimul_Holo.cpp | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "kinematics-precomp.h" // Precompiled header
#include <mrpt/kinematics/CVehicleSimul_Holo.h>
#include <mrpt/math/wrap2pi.h>
using namespace mrpt::kinematics;
CVehicleSimul_Holo::CVehicleSimul_Holo()
{
resetStatus();
resetTime();
}
void CVehicleSimul_Holo::internal_simulControlStep(const double dt)
{
// Control:
if (m_vel_ramp_cmd.issue_time >= 0 &&
m_time > m_vel_ramp_cmd.issue_time) // are we executing any cmd?
{
const double t = m_time - m_vel_ramp_cmd.issue_time;
const double T = m_vel_ramp_cmd.ramp_time;
const double vxi = m_vel_ramp_cmd.init_vel.vx;
const double vyi = m_vel_ramp_cmd.init_vel.vy;
const double wi = m_vel_ramp_cmd.init_vel.omega;
const double vxf = m_vel_ramp_cmd.target_vel_x;
const double vyf = m_vel_ramp_cmd.target_vel_y;
// "Blending" for vx,vy
if (t <= m_vel_ramp_cmd.ramp_time)
{
m_odometric_vel.vx = vxi + t * (vxf - vxi) / T;
m_odometric_vel.vy = vyi + t * (vyf - vyi) / T;
}
else
{
m_odometric_vel.vx = m_vel_ramp_cmd.target_vel_x;
m_odometric_vel.vy = m_vel_ramp_cmd.target_vel_y;
}
// Ramp rotvel until aligned:
const double Aang =
mrpt::math::wrapToPi(m_vel_ramp_cmd.dir - m_odometry.phi);
if (std::abs(Aang) < mrpt::DEG2RAD(1.0))
{
m_odometric_vel.omega = .0; // we are aligned.
}
else
{
const double wf =
mrpt::sign(Aang) * std::abs(m_vel_ramp_cmd.rot_speed);
if (t <= m_vel_ramp_cmd.ramp_time)
{
m_odometric_vel.omega = wi + t * (wf - wi) / T;
}
else
{
m_odometric_vel.omega = wf;
}
}
}
}
void CVehicleSimul_Holo::internal_clear() { m_vel_ramp_cmd = TVelRampCmd(); }
void CVehicleSimul_Holo::sendVelRampCmd(
double vel, double dir, double ramp_time, double rot_speed)
{
ASSERT_ABOVE_(ramp_time, 0);
m_vel_ramp_cmd.issue_time = m_time;
m_vel_ramp_cmd.ramp_time = ramp_time;
m_vel_ramp_cmd.rot_speed = rot_speed;
m_vel_ramp_cmd.init_vel = m_odometric_vel;
m_vel_ramp_cmd.target_vel_x = cos(dir) * vel;
m_vel_ramp_cmd.target_vel_y = sin(dir) * vel;
m_vel_ramp_cmd.dir = dir;
}
|
shadowmaster435/The_Beginning_Remaster | src/main/java/shadowmaster435/the_beginning/util/TBParticleFactories.java | <gh_stars>0
package shadowmaster435.the_beginning.util;
public class TBParticleFactories {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.