text
stringlengths
1
1.05M
#!/bin/sh BASE=$(dirname $0)/.. $BASE/build/build.sh if [ $? -ne 0 ] then echo "build failed" exit -1 fi REMOTE=129.204.58.232 echo "=============================" echo "==== deploy to remote server" echo "=============================" scp -i txy_root dist/mahjong.tar.gz root@$REMOTE:/opt/mahjong ssh root@$REMOTE <<EOF cd /opt/mahjong tar -xzvf mahjong.tar.gz chmod +x mahjong ls -al supervisorctl restart mahjong supervisorctl status EOF echo "done"
'use strict'; import moment from 'moment/src/moment.js'; import page from './stock_portfolio.html'; import $ from '/jquery.js'; import _ from 'lodash'; import * as Util from '/util.js'; import * as Api from '/moneydb.js'; import * as Common from '/common.js'; export let location; let table; let refreshing = false; export function refresh(refresh_data) { refreshing = true; if (refresh_data === undefined) refresh_data = false; $.when(Common.getStocks(), Api.getComputeStocksPortfolio(refresh_data)).then((_s, x) => { x = x[0]; let invested = 0.0; let value = 0.0; let hValue = 0.0; let diff = 0.0; let diffDay = 0.0; let stocks = _.map(x.stocks, y => { y.stock = Common.findStock(y.stockId); invested += y.invested; if (y.realtimeValue !== null && y.historicValue !== null && y.historicValue[0] != 0.0) { let perc = (y.realtimeValue[0] - y.historicValue[0]) / y.historicValue[0]; y.diffDay = y.realtimeValue[0] - y.historicValue[0]; y.diffDayS = Util.formatAmount(y.realtimeValue[0] - y.historicValue[0]) + ' (' + Util.formatPercentage(perc) + ')'; if (diffDay !== null) diffDay += y.diffDay; } else { y.diffDay = null; y.diffDayS = null; diffDay = null; } if (y.realtimeValue !== null && y.invested != 0.0) { let perc = (y.realtimeValue[0] - y.invested) / y.invested; y.diff = y.realtimeValue[0] - y.invested; y.diffS = Util.formatAmount(y.realtimeValue[0] - y.invested) + ' (' + Util.formatPercentage(perc) + ')'; if (diff !== null) diff += y.diff; } else { y.diff = null; y.diffS = null; diff = null; } if (y.realtimeValue !== null) { let ex = _.head(_.filter(y.stock.exchanges, x => x.id == y.realtimeValue[2])); y.value = y.realtimeValue[0]; y.valueS = Util.formatAmount(y.value) + '<br />(' + ex.name + ', ' + moment(y.realtimeValue[1]).format('L LT') + ')'; if (value !== null) value += y.value; } else { y.valueS = null; y.value = null; value = null; } if (y.historicValue !== null) { let ex = _.head(_.filter(y.stock.exchanges, x => x.id == y.historicValue[2])); y.hValue = y.historicValue[0]; y.hValueS = Util.formatAmount(y.hValue) + '<br />(' + ex.name + ', ' + moment(y.historicValue[1]).format('L') + ')'; if (hValue !== null) hValue += y.hValue; } else { y.hValueS = null; y.hValue = null; hValue = null; } return y; }); table.clear().rows.add(stocks).draw(); let valueS = ''; if (value !== null) { valueS = Util.formatAmount(value); } let hValueS = ''; if (hValue !== null) { hValueS = Util.formatAmount(hValue); } let investedS = Util.formatAmount(invested); let diffS = ''; if (diff !== null) { diffS = Util.formatAmount(diff); if (invested != 0.0) diffS += ' (' + Util.formatPercentage(diff / invested) + ')'; } let diffDayS = ''; if (diffDay !== null) { diffDayS = Util.formatAmount(diffDay); if (value - diffDay != 0.0) diffDayS += ' (' + Util.formatPercentage(diffDay / (value - diffDay)) + ')'; } let irrS = ''; if (x.portfolioRealtimeIrr !== null) { irrS = Util.formatPercentage(x.portfolioRealtimeIrr) + ' p.a.'; } let irrHS = ''; if (x.portfolioHistoricIrr !== null) { irrHS = Util.formatPercentage(x.portfolioHistoricIrr) + ' p.a.'; } $('#table-portfolio tfoot', location).html('<tr><th>Gesamt</th><th></th><th></th><th class="right aligned">' + investedS + '</th><th class="right aligned">' + valueS + '</th><th class="right aligned">' + hValueS + '</th><th class="right aligned">' + diffDayS + '</th><th class="right aligned">' + diffS + '</th><th class="right aligned">' + irrS + '</th><th class="right aligned">' + irrHS + '</th></tr>'); $('#button-refresh', location).addClass('icon').addClass('labeled').removeClass('loading'); refreshing = false; }); } let showDetails = function(rowjq, data) { let tr = $(rowjq).closest('tr'); let row = table.row(tr); if (row.child.isShown()) { row.child.hide(); // tr.find('a').first().html('<i class="plus circle icon"></i>'); tr.removeClass('shown'); } else { let s = '<div class="ui grid"><div class="row">'; // s += '<div class="wide column">'; // s += '<div class="ui relaxed divided list" style="white-space: normal;">'; // s += '<div class="item"><div class="content"><div class="header">Anzahl Transaktionen</div>' + // '<div class="description">' + data.transactions + '</div></div></div>'; // if (data.exchangeId !== null) { // let ex = _.head(_.filter(data.stock.exchanges, x => x.id == data.exchangeId)); // s += '<div class="item"><div class="content"><div class="header">Handelsplatz für berechnete Werte</div>' + // '<div class="description">' + ex.name + '</div></div></div>'; // s += '<div class="item"><div class="content"><div class="header">Aktueller Kurs</div>' + // '<div class="description">' + Util.formatAmount(data.value / data.units) + '</div></div></div>'; // if (data.previousValue !== null) // s += '<div class="item"><div class="content"><div class="header">Voriger Kurs</div>' + // '<div class="description">' + Util.formatAmount(data.previousValue / data.units) + '</div></div></div>'; // } s += '</div></div>'; row.child(s).show(); // tr.find('a').first().html('<i class="minus circle icon"></i>'); tr.addClass('shown'); } }; export function init(loc) { location = $(loc); location.empty().html(page); table = $('#table-portfolio', location).DataTable({ 'paging': false, 'ordering': true, 'info': false, 'dom': 'rtip', 'data': [], 'language': Util.datatableLanguage, createdRow: function(row, data) { $(row).on('click', () => showDetails(row, data)); if (data.diff !== null) $(row).find('td:nth-child(8)').addClass(data.diff == 0 ? 'warning' : (data.diff < 0 ? 'negative' : 'positive')); if (data.diffDay != null) $(row).find('td:nth-child(7)').addClass(data.diffDay == 0.0 ? 'warning' : (data.diffDay < 0 ? 'negative' : 'positive')); if (data.realtimeIrr != null) $(row).find('td:nth-child(9)').addClass(data.realtimeIrr < 0.0 ? 'negative' : (data.realtimeIrr < 0.02 ? 'warning' : 'positive')); if (data.historicIrr != null) $(row).find('td:nth-child(10)').addClass(data.historicIrr < 0.0 ? 'negative' : (data.historicIrr < 0.02 ? 'warning' : 'positive')); $('td:nth-child(3)', row).addClass('right aligned'); $('td:nth-child(4)', row).addClass('right aligned'); $('td:nth-child(5)', row).addClass('right aligned'); $('td:nth-child(6)', row).addClass('right aligned'); $('td:nth-child(7)', row).addClass('right aligned'); $('td:nth-child(8)', row).addClass('right aligned'); $('td:nth-child(9)', row).addClass('right aligned'); $('td:nth-child(10)', row).addClass('right aligned'); }, columns: [{ title: 'Wertpapier', data: 'stock.info', render: data => data.title + '&nbsp;<a alt="auf onvista ansehen" target="_blank" href="https://www.onvista.de' + data.onvistaUrl + '"><i class="external icon"></i></a>' }, { title: 'ISIN', data: 'stock.isin', width: '10%' }, { title: 'Einheiten', data: 'units', width: '7%' }, { title: 'Kaufpreis', data: 'invested', width: '10%', render: data => Util.formatAmount(data) }, { title: 'Wert (Realtime)', data: 'valueS', width: '10%' }, { title: 'Wert (letzter Handelstag)', data: 'hValueS', width: '10%' }, { title: 'Veränderung (Intraday)', data: 'diffDayS', width: '10%' }, { title: 'Veränderung (Gesamt)', data: 'diffS', width: '10%' }, { title: 'Zinsfuß (Realtime)', data: 'realtimeIrr', width: '8%', render: data => { if (data === null) return ''; else return Util.formatPercentage(data) + ' p.a.'; } }, { title: 'Zinsfuß (<NAME>)', data: 'historicIrr', width: '8%', render: function(data) { if (data === null) return ''; else return Util.formatPercentage(data) + ' p.a.'; } }, ] }); $('#button-refresh', location).click(() => { if (!refreshing) { $('#button-refresh', location).removeClass('labeled').removeClass('icon').addClass('loading'); refresh(true); } }); $('#table-portfolio', location).append('<tfoot></tfoot>'); refresh(); }
#!/usr/bin/env bash pycodestyle --max-line-length=120 --exclude parsetab.py asm_6502 tests && \ nosetests --nocapture --with-coverage --cover-erase --cover-html --cover-html-dir=htmlcov --cover-package=asm_6502 --with-doctest
<filename>CarteService/default/src/main/java/com/sun/jna/PlatformEx.java package com.sun.jna; public class PlatformEx { private static boolean winVista = false; static { String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("windows")) { winVista = osName.contains("vista") || osName.contains(" 7") || osName.contains("2008") || osName.contains("2012") || osName.contains(" 8"); } } public static boolean isWinVista() { return winVista; } }
<filename>src/engine/ColumnConfigurationHelper.cpp /** * @author <NAME> <<EMAIL>> * * @section LICENSE * See LICENSE for more informations. * */ #include "include/columnize/ColumnConfigurationHelper.h" class ColumnConfigurationHelperData : public QSharedData { public: ColConfig colConfig; }; ColumnConfigurationHelper::ColumnConfigurationHelper(const ColConfig &config) : data(new ColumnConfigurationHelperData) { data->colConfig = config; } ColumnConfigurationHelper::ColumnConfigurationHelper(const ColumnConfigurationHelper &rhs) : data(rhs.data) { } ColumnConfigurationHelper &ColumnConfigurationHelper::operator=(const ColumnConfigurationHelper &rhs) { if (this != &rhs) data.operator=(rhs.data); return *this; } ColumnConfigurationHelper::~ColumnConfigurationHelper() { } ColConfig ColumnConfigurationHelper::columnConfiguration() const { return data->colConfig; } ColumnType ColumnConfigurationHelper::type() const { return data->colConfig->type(); } void ColumnConfigurationHelper::setType(ColumnType type) { data->colConfig->setType(type); } void ColumnConfigurationHelper::insert(const QString &key, const QJsonValue &value) { data->colConfig->insert(key, value); } QJsonValue ColumnConfigurationHelper::value(const QString &key) const { return data->colConfig->value(key); }
<filename>src/main/java/br/com/zupacademy/gabrielf/casadocodigo/validation/UniqueNomeValidation.java package br.com.zupacademy.gabrielf.casadocodigo.validation; import br.com.zupacademy.gabrielf.casadocodigo.modelo.Categoria; import br.com.zupacademy.gabrielf.casadocodigo.repository.CategoriaRepository; import org.springframework.beans.factory.annotation.Autowired; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Optional; public class UniqueNomeValidation implements ConstraintValidator<UniqueNome,String> { @Autowired CategoriaRepository categoriaRepository; @Override public void initialize(UniqueNome constraintAnnotation) { } @Override public boolean isValid(String value, ConstraintValidatorContext context) { Optional<Categoria> optional = categoriaRepository.findByNome(value); if(optional.isEmpty()){ return true; } else{ return false; } } }
#!/bin/bash docker-compose exec django pipenv run django-admin.py migrate docker-compose exec django pipenv run python /opt/hsreplay.net/initdb.py docker-compose exec django pipenv run django-admin.py load_cards docker-compose exec django pipenv run django-admin.py load_mercenaries
package com.gaurav.calculator.repo; import org.springframework.stereotype.Repository; @Repository public class CalculatorRepository { }
<filename>web/src/main/java/com/github/egmerittech/web/ApplicationComponents.java package com.github.egmerittech.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.context.event.SimpleApplicationEventMulticaster; import org.springframework.core.env.Environment; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mail.MailSender; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import com.github.egmerittech.repository.EmailTokenRepository; import com.github.egmerittech.web.event.SignupEvent; import com.github.egmerittech.web.event.SignupEventListener; /** * @author <NAME> */ @EnableWebSecurity @EntityScan({ "com.github.egmerittech.model" }) @Import({ com.github.egmerittech.repository.Module.class }) public class ApplicationComponents { @Autowired private Environment environment; @Autowired // this must be autowired to avoid circular dependencies private EmailTokenRepository emailTokenRepository; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public ApplicationEventMulticaster applicationEventMulticaster() { final SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster(); eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor()); return eventMulticaster; } @Bean @ConditionalOnProperty("mymerit.sendverifcationemail") public ApplicationListener<SignupEvent> signupEventListener(MailSender mailSender) { final SignupEventListener eventListener = new SignupEventListener(mailSender, emailTokenRepository); eventListener.setExpiryTimeDays(environment.getProperty("mymerit.emailtoken.expirytimedays", Integer.class)); return eventListener; } }
package main; import java.util.Scanner; public class GMTOffsetCurrentTime { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the timezone offset to GMT: "); long offset = input.nextLong(); // Obtain the total milliseconds since midnight, Jan 1, 1970 long totalMilliseconds = System.currentTimeMillis(); // Obtain the total seconds since midnight, Jan 1, 1970 long totalSeconds = totalMilliseconds / 1000; // Compute the current second in the minute in the hour long currentSecond = (int)(totalSeconds % 60); // Obtain the total minutes long totalMinutes = totalSeconds / 60; // Compute the current minute in the hour long currentMinute = totalMinutes % 60; // Obtain the total hours long totalHours = (totalMinutes / 60) + offset; // Compute the current hour long currentHour = totalHours % 24; System.out.println("The current time is " + currentHour + ":" + currentMinute + ":" + currentSecond); input.close(); } }
# platform = McAfee VirusScan Enterprise for Linux NAILS_CONFIG_FILE="/var/opt/NAI/LinuxShield/etc/ods.cfg" {{{ bash_replace_or_append("$NAILS_CONFIG_FILE", '^nailsd.profile.ODS.program', 'true', '%s: %s') }}}
#!/bin/bash # JBoss, Home of Professional Open Source # Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual # contributors by the @authors tag. See the copyright.txt in the # distribution for a full listing of individual contributors. # # 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. oc env dc/my12factorapp GREETING="Hi {name}! - My Configuration has changed" echo "Configuration updated. Please check again http://12factorappdemo.$OPENSHIFT_IP.nip.io/api/hello/Rafael"
/** */ package PhotosMetaModel.impl; import PhotosMetaModel.PhotosMetaModelPackage; import PhotosMetaModel.Trigger; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Trigger</b></em>'. * <!-- end-user-doc --> * * @generated */ public class TriggerImpl extends MinimalEObjectImpl.Container implements Trigger { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TriggerImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return PhotosMetaModelPackage.Literals.TRIGGER; } } //TriggerImpl
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var ts = require("typescript"); var Lint = require("tslint"); var JsxAttribute_1 = require("./utils/JsxAttribute"); var getImplicitRole_1 = require("./utils/getImplicitRole"); var DOM_SCHEMA = require('./utils/attributes/domSchema.json'); var FAILURE_STRING = 'Elements with event handlers must have role attribute.'; var ROLE_STRING = 'role'; var TARGET_EVENTS = ['click', 'keyup', 'keydown', 'keypress', 'mousedown', 'mouseup', 'mousemove', 'mouseout', 'mouseover', 'onclick', 'onkeyup', 'onkeydown', 'onkeypress', 'onmousedown', 'onmouseup', 'onmousemove', 'onmouseout', 'onmouseover']; var Rule = (function (_super) { __extends(Rule, _super); function Rule() { return _super !== null && _super.apply(this, arguments) || this; } Rule.prototype.apply = function (sourceFile) { return sourceFile.languageVariant === ts.LanguageVariant.JSX ? this.applyWithWalker(new ReactA11yEventHasRoleWalker(sourceFile, this.getOptions())) : []; }; Rule.metadata = { ruleName: 'react-a11y-event-has-role', type: 'maintainability', description: 'Elements with event handlers must have role attribute.', options: null, optionsDescription: '', typescriptOnly: true, issueClass: 'Non-SDL', issueType: 'Warning', severity: 'Important', level: 'Opportunity for Excellence', group: 'Accessibility' }; return Rule; }(Lint.Rules.AbstractRule)); exports.Rule = Rule; var ReactA11yEventHasRoleWalker = (function (_super) { __extends(ReactA11yEventHasRoleWalker, _super); function ReactA11yEventHasRoleWalker() { return _super !== null && _super.apply(this, arguments) || this; } ReactA11yEventHasRoleWalker.prototype.visitJsxElement = function (node) { this.checkJsxOpeningElement(node.openingElement); _super.prototype.visitJsxElement.call(this, node); }; ReactA11yEventHasRoleWalker.prototype.visitJsxSelfClosingElement = function (node) { this.checkJsxOpeningElement(node); _super.prototype.visitJsxSelfClosingElement.call(this, node); }; ReactA11yEventHasRoleWalker.prototype.checkJsxOpeningElement = function (node) { var tagName = node.tagName.getText(); if (!DOM_SCHEMA[tagName]) { return; } var attributes = JsxAttribute_1.getJsxAttributesFromJsxElement(node); var events = TARGET_EVENTS.filter(function (eventName) { return !!attributes[eventName]; }); var hasAriaRole = !!attributes[ROLE_STRING] || !!getImplicitRole_1.getImplicitRole(node); if (events.length > 0 && !hasAriaRole) { this.addFailureAt(node.getStart(), node.getWidth(), FAILURE_STRING); } }; return ReactA11yEventHasRoleWalker; }(Lint.RuleWalker)); //# sourceMappingURL=reactA11yEventHasRoleRule.js.map
function readonly(target: any, key: string) { let value = target[key]; const getter = function () { return value; }; const setter = function (newVal: any) { throw new Error(`Cannot reassign read-only property '${key}'`); }; Object.defineProperty(target, key, { get: getter, set: setter, enumerable: true, configurable: true, }); } class Example { @readonly name: string = "Initial Name"; } const example = new Example(); console.log(example.name); // Output: "Initial Name" example.name = "New Name"; // Throws an error: Cannot reassign read-only property 'name'
package org.terems.webz; import java.io.IOException; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; /** TODO !!! describe !!! **/ public interface WebzReaderDownloader extends WebzFileSpecificDownloader { /** TODO !!! describe !!! **/ public String getActualEncoding(); /** TODO !!! describe !!! **/ public long getActualNumberOfBytes(); /** TODO !!! describe !!! **/ public Reader getReader() throws IOException; /** TODO !!! describe !!! **/ public long copyContentAndClose(OutputStream out) throws WebzReadException, WebzWriteException, IOException; /** TODO !!! describe !!! **/ public long copyContentAndClose(Writer writer) throws WebzReadException, WebzWriteException, IOException; /** TODO !!! describe !!! **/ public String getContentAsStringAndClose() throws WebzReadException, WebzWriteException, IOException; }
import {ANALYTIC_MAX_RESULTS, PER_PAGE} from "../../flows/config" import {SearchArgs, SearchType} from "./types" import {SearchRecord} from "../../types" import {State} from "../types" import {addEveryCountProc} from "../../searches/histogramSearch" import {addHeadProc} from "../../lib/Program" import Current from "../Current" import SearchBar from "../SearchBar" import Tab from "../Tab" import brim from "../../brim" export default { getRecord: (state: State): SearchRecord => { const space = Current.mustGetSpace(state) return { program: SearchBar.getSearchBar(state).previous, pins: SearchBar.getSearchBar(state).pinned, spanArgs: Tab.getSpanArgs(state), spaceName: space.name, spaceId: space.id, target: SearchBar.getTarget(state) } }, getCurrentRecord: (state: State): SearchRecord => { const space = Current.mustGetSpace(state) const searchBar = SearchBar.getSearchBar(state) if (searchBar.editing === null) { return { program: searchBar.current, pins: SearchBar.getSearchBar(state).pinned, spanArgs: Tab.getSpanArgs(state), spaceName: space.name, spaceId: space.id, target: SearchBar.getTarget(state) } } else { return { program: searchBar.previous, pins: SearchBar.getSearchBar(state).pinned, spanArgs: Tab.getSpanArgs(state), spaceName: space.name, spaceId: space.id, target: SearchBar.getTarget(state) } } }, getArgs: (state: State): SearchArgs => { const program = SearchBar.getSearchProgram(state) const span = Tab.getSpanAsDates(state) const spanFocus = Tab.getSpanFocusAsDates(state) const space = Current.mustGetSpace(state) const type: SearchType = getArgsType(program, spanFocus) const perPage = type === "analytics" ? ANALYTIC_MAX_RESULTS : PER_PAGE return { tableProgram: addHeadProc(program, perPage), chartProgram: addEveryCountProc(program, span), span: spanFocus || span, spaceId: space.id, spaceName: space.name, type } } } function getArgsType(program, spanFocus): SearchType { if (brim.program(program).hasAnalytics()) return "analytics" else if (spanFocus) return "zoom" return "events" }
package router import ( "reflect" "testing" "github.com/paulormart/assert" ) func TestNewTrie(t *testing.T) { tr := newTrie() assert.Equal(t, reflect.TypeOf(&trie{}), reflect.TypeOf(tr)) assert.Equal(t, 0, tr.n) assert.Equal(t, 0, tr.Size()) assert.Equal(t, true, tr.IsEmpty()) assert.Equal(t, reflect.TypeOf(&node{}), reflect.TypeOf(tr.root)) } func TestNewData(t *testing.T) { d := newData() d.value = "home" d.prefix = "/" assert.Equal(t, reflect.TypeOf(&data{}), reflect.TypeOf(d)) assert.Equal(t, "home", d.value) assert.Equal(t, "/", d.prefix) assert.Equal(t, []string{}, d.vars) assert.Equal(t, make(map[string]HandlerFunc), d.methods) } func TestPut(t *testing.T) { d := newData() d.value = "home" d.prefix = "/" tr := newTrie() tr.Put("/home", d) assert.Equal(t, 1, tr.Size()) } func TestGet(t *testing.T) { tr := newTrie() // empty assert.Equal(t, 0, tr.Size()) assert.Equal(t, nil, tr.Get("/home")) d := newData() d.value = "/home" d.prefix = "/" tr.Put("/home", d) assert.Equal(t, 1, tr.Size()) assert.Equal(t, true, tr.Contains("/home")) // nil assert.Equal(t, nil, tr.Get("/")) } func TestKeys(t *testing.T) { // key /home d := newData() d.value = "/home" d.prefix = "/" tr := newTrie() tr.Put("/home", d) // key /room d = newData() d.value = "/room" d.prefix = "/" tr.Put("/room", d) assert.Equal(t, 2, tr.Size()) // KeysWithPrefix kwp := tr.KeysWithPrefix("/") assert.Equal(t, 2, len(kwp)) // KeysThatMatch ktm := tr.KeysThatMatch("") assert.Equal(t, 0, len(ktm)) ktm1 := tr.KeysThatMatch("/home") assert.Equal(t, 1, len(ktm1)) ktm2 := tr.KeysThatMatch("/room") assert.Equal(t, 1, len(ktm2)) ktm3 := tr.KeysThatMatch("..o..") assert.Equal(t, 2, len(ktm3)) ktm4 := tr.KeysThatMatch(".....") assert.Equal(t, 2, len(ktm4)) ktm5 := tr.KeysThatMatch(".") assert.Equal(t, 0, len(ktm5)) // Keys k := tr.Keys() assert.Equal(t, 2, len(k)) // LongestPrefixOf lpo := tr.LongestPrefixOf("") assert.Equal(t, "", lpo) lpo1 := tr.LongestPrefixOf("/home") assert.Equal(t, "/home", lpo1) } func BenchmarkPutTrie(b *testing.B) { d := newData() d.value = "home" d.prefix = "/" // run the Put function b.N times for n := 0; n < b.N; n++ { tr := newTrie() tr.Put("/test", d) } }
# ubuntu user with sudo access # 1. create a superset_config.py file touch $HOME/.superset/superset_config.py # 2. set superset_config_path env value in bash_profile to the file path echo 'export SUPERSET_CONFIG_PATH=$HOME/.superset/superset_config.py' >> ~/.bash_profile # 3. execute the bash_profile script in current terminal # new terminals will auto execute this file upon initialization # .bash_profile on your machine should contain at least these commands. # source /usr/local/bin/virtualenvwrapper.sh # export GOOGLE_APPLICATION_CREDENTIALS="$HOME/.google_cdp_key.json" # export SUPERSET_CONFIG_PATH=$HOME/.superset/superset_config.py source ~/.bash_profile # 4. load virtualenv # workon supervenv # 5. install postgres python connector pip install psycopg2 # 6. install os dependencies as sudo user sudo apt-get -y install postgresql postgresql-client postgresql-contrib # 7. switch to postgres user and create superset database # sudo su postgres # cd ~ # postgres@superset:~/$ psql # postgres-# create database superset; # postgres-# CREATE USER superset WITH PASSWORD 'superset'; # postgres-# GRANT ALL PRIVILEGES ON DATABASE "superset" to superset; # postges-# \q # 8. update pg_hba.conf to accept md5 for authentication # postgres@superset:~$ vim /etc/postgresql/9.6/main/pg_hba.conf # # --- inside pg_hba.conf --- # # "local" is for Unix domain socket connections only # # local all postgres peer # # replace with # local all postgres md5 # 9. switch to ubuntu user with sudo access and restart postgres sudo service postgresql restart # 10. install gunicorn and gevent pip install gunicorn gevent # 11. install and run nginx # Install sudo apt-get update sudo apt-get install nginx # Start and Reload sudo nginx -s start sudo nginx -s reload # Check status systemctl status nginx # 12. update superset.conf file for nginx # # -- inside superset.conf -- # # save in /etc/nginx/sites-enabled/ # server { # listen 80; # server_name 35.233.249.126; # root /var/www/superset; # location / { # proxy_buffers 16 4k; # proxy_buffer_size 2k; # proxy_pass http://127.0.0.1:8088; # } # } # 13. link superset.conf to nginx/sites-enabled sudo ln -s /etc/nginx/sites-available/superset.conf /etc/nginx/sites-enabled # test for syntax errors sudo nginx -t # reload sudo nginx -s reload
<gh_stars>0 var fs = require('fs'); var fileName2 = './RetweetsAgg_2018.json'; var file2 = require(fileName2); var retweetsArray = []; for (let [key1, value2] of Object.entries(file2)) { retweetsArray.push(value2.retweets); } console.log(retweetsArray.sort((a,b)=>b-a))
<html> <body> <p class="test">This is a test paragraph.</p> </body> </html>
#!/bin/bash #SBATCH --account=def-dkulic #SBATCH --mem=8000M # memory per node #SBATCH --time=23:00:00 # time (DD-HH:MM) #SBATCH --output=/project/6001934/lingheng/Double_DDPG_Job_output/continuous_RoboschoolInvertedPendulum-v1_doule_ddpg_softcopy_action_noise_seed3_run2_%N-%j.out # %N for node name, %j for jobID module load qt/5.9.6 python/3.6.3 nixpkgs/16.09 gcc/7.3.0 boost/1.68.0 cuda cudnn source ~/tf_cpu/bin/activate python ./ddpg_discrete_action.py --env RoboschoolInvertedPendulum-v1 --random-seed 3 --exploration-strategy action_noise --summary-dir ../Double_DDPG_Results_no_monitor/continuous/RoboschoolInvertedPendulum-v1/doule_ddpg_softcopy_action_noise_seed3_run2 --continuous-act-space-flag
public static int longestSubarrayWithSumLessThanNum(int[] array, int sum) { int maxLength = 0; int windowStart = 0; int windowSum = 0; for (int windowEnd = 0; windowEnd < array.length; windowEnd++) { windowSum += array[windowEnd]; while (windowSum > sum && windowStart < array.length) { windowSum -= array[windowStart]; windowStart++; } maxLength = Math.max(maxLength, windowEnd - windowStart + 1); } return maxLength; }
<reponame>JoeScho/get-param<filename>index.js const get = (req, paramName) => { if (!req) return false; if (req && req.body && req.body[paramName]) return req.body[paramName]; if (req && req.query && req.query[paramName]) return req.query[paramName]; return false; }; module.exports = { get };
#!/bin/bash # Switch to local timezone ln -snf /usr/share/zoneinfo/$TZ /etc/localtime # Create cron tasks & logfile cp /ls_build/services/simplified_crontab /etc/cron.d/metadata touch /var/log/cron.log
<reponame>Yuan-Zhuo/ics_labs #include <stdio.h> extern int mm_init(void); extern void* mm_malloc(size_t size); extern void mm_free(void* ptr); extern void* mm_realloc(void* ptr, size_t size);
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.web; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import ${package}.service.UserService; import ${package}.web.constant.ApiConstant; /** * 用户控制器 * * @author <a href="mailto:<EMAIL>">gyl</a> * @since 2.4.x */ @Slf4j @RequestMapping(ApiConstant.WEB_API_PATH + "/users") @Controller public class UserController { private final UserService userService; public UserController(@Qualifier("userService") UserService userService) { this.userService = userService; } /** * 根据主键获取用户信息 * * @param id * @return */ @GetMapping("/{id}") public String getUserById(@PathVariable Long id, Model model) { userService.getUserById(id, model); return "user/user-detail"; } }
<reponame>wavesplatform/nanos-app-waves /******************************************************************************* * Waves Platform Wallet App for Nano Ledger devices * Copyright (c) 2017-2020 <NAME> (Tolsi) <<EMAIL>> * * Based on Sample code provided (c) 2016 Ledger and * (c) 2017-2018 <NAME>. (Burstcoin app) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #include "stream_eddsa_sign.h" static uint8_t const C_cx_Ed25519_a[] = {0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xec}; static uint8_t const C_cx_Ed25519_d[] = { // d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3 0x52, 0x03, 0x6c, 0xee, 0x2b, 0x6f, 0xfe, 0x73, 0x8c, 0xc7, 0x40, 0x79, 0x77, 0x79, 0xe8, 0x98, 0x00, 0x70, 0x0a, 0x4d, 0x41, 0x41, 0xd8, 0xab, 0x75, 0xeb, 0x4d, 0xca, 0x13, 0x59, 0x78, 0xa3}; static uint8_t const C_cx_Ed25519_q[] = { // q: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xed}; static uint8_t const C_cx_Ed25519_Hq[] = { // Hq: 0x00000000000000000000000000000000000000000000000000000000000005a4 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0xa4}; static uint8_t const C_cx_Ed25519_Bx[] = {0x21, 0x69, 0x36, 0xd3, 0xcd, 0x6e, 0x53, 0xfe, 0xc0, 0xa4, 0xe2, 0x31, 0xfd, 0xd6, 0xdc, 0x5c, 0x69, 0x2c, 0xc7, 0x60, 0x95, 0x25, 0xa7, 0xb2, 0xc9, 0x56, 0x2d, 0x60, 0x8f, 0x25, 0xd5, 0x1a}; static uint8_t const C_cx_Ed25519_By[] = {0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x58}; static uint8_t const C_cx_Ed25519_l[] = { // l: 0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0xDE, 0xF9, 0xDE, 0xA2, 0xF7, 0x9C, 0xD6, 0x58, 0x12, 0x63, 0x1A, 0x5C, 0xF5, 0xD3, 0xED}; static uint8_t const C_cx_Ed25519_Hl[] = { // Hl: 0x0399411b7c309a3dceec73d217f5be65d00e1ba768859347a40611e3449c0f01 0x03, 0x99, 0x41, 0x1b, 0x7c, 0x30, 0x9a, 0x3d, 0xce, 0xec, 0x73, 0xd2, 0x17, 0xf5, 0xbe, 0x65, 0xd0, 0x0e, 0x1b, 0xa7, 0x68, 0x85, 0x93, 0x47, 0xa4, 0x06, 0x11, 0xe3, 0x44, 0x9c, 0x0f, 0x01}; #define C_cx_Ed25519_h 8 cx_curve_twisted_edwards_t const C_cx_Ed25519 = { .curve = CX_CURVE_Ed25519, .bit_size = 256, .length = 32, .a = C_cx_Ed25519_a, .b = C_cx_Ed25519_d, .p = C_cx_Ed25519_q, .Gx = C_cx_Ed25519_Bx, .Gy = C_cx_Ed25519_By, .n = C_cx_Ed25519_l, .h = C_cx_Ed25519_h, .Hp = C_cx_Ed25519_Hq, .Hn = C_cx_Ed25519_Hl, }; /* ----------------------------------------------------------------------- */ /* */ /* ----------------------------------------------------------------------- */ static void cx_encode_int(unsigned char *v, int len) { unsigned char t; int i, j; i = 0; j = len - 1; len = len / 2; while (len--) { t = v[i]; v[i] = v[j]; v[j] = t; i++; j--; } } /* ----------------------------------------------------------------------- */ /* */ /* ----------------------------------------------------------------------- */ // P is 2*size length, encoded as: x|y // leave x untouched static void cx_compress(unsigned char *P, int size) { if (P[size - 1] & 1) { P[size] |= 0x80; } cx_encode_int(P + size, size); } #define cx_decode_int(v, l) cx_encode_int(v, l) /* ----------------------------------------------------------------------- */ /* */ /* ----------------------------------------------------------------------- */ static void cx_eddsa_get_public_key_internal( const cx_ecfp_private_key_t *pv_key, cx_md_t hashID, cx_ecfp_public_key_t *pu_key, unsigned char *a, unsigned int a_len, unsigned char *h, unsigned int h_len, unsigned char *scal /*tmp*/) { cx_curve_twisted_edwards_t *domain = (cx_curve_twisted_edwards_t *)&C_cx_Ed25519; cx_sha512_t hash_ctx; unsigned int size; size = domain->length; switch (hashID) { case CX_SHA512: cx_sha512_init(&hash_ctx); break; default: THROW(INVALID_PARAMETER); } if (pv_key->d_len == size) { /* 1. Hash the 32/57-byte private key using SHA-512/shak256-114, storing the * digest in a 32/114 bytes large buffer, denoted h. Only the lower [CME: * first] 32/57 bytes are used for generating the public key. */ cx_hash(&hash_ctx.header, CX_NONE, pv_key->d, pv_key->d_len, NULL, 0); cx_hash(&hash_ctx.header, CX_LAST, NULL, 0, scal, 64); /* 2. Prune the buffer: The lowest 3 bits of the first octet are * cleared, the highest bit of the last octet is cleared, and the * second highest bit of the last octet is set. */ scal[0] &= 0xF8; scal[31] = (scal[31] & 0x7F) | 0x40; } else { os_memmove(scal, pv_key->d, pv_key->d_len); } /* 3. Interpret the buffer as the little-endian integer, forming a * secret scalar a. Perform a fixed-base scalar multiplication * [a]B. */ cx_decode_int(scal, size); if (a) { os_memmove(a, scal, size); } if (h) { os_memmove(h, scal + size, size); } pu_key->curve = pv_key->curve; pu_key->W_len = 1 + size * 2; pu_key->W[0] = 0x04; os_memmove(pu_key->W + 1, domain->Gx, size); os_memmove(pu_key->W + 1 + size, domain->Gy, size); cx_ecfp_scalar_mult(domain->curve, pu_key->W, pu_key->W_len, scal, size); } void stream_eddsa_sign_step1(streamEddsaContext_t *eddsa_context, const cx_ecfp_private_key_t *pv_key) { os_memset((unsigned char *)eddsa_context, 0, sizeof(streamEddsaContext_t)); cx_curve_twisted_edwards_t *domain = (cx_curve_twisted_edwards_t *)&C_cx_Ed25519; unsigned int size = domain->length; unsigned char scal[64]; // retrieve public key,private scalar a, and private prefix h (stored in r) cx_eddsa_get_public_key_internal( pv_key, CX_SHA512, (cx_ecfp_public_key_t *)&eddsa_context->u.internal_pu_key, eddsa_context->a, sizeof(eddsa_context->a), eddsa_context->r, sizeof(eddsa_context->r), scal); // compress public_key cx_edward_compress_point(domain->curve, &eddsa_context->u.internal_pu_key.W[0], eddsa_context->u.internal_pu_key.W_len); os_memmove(eddsa_context->Y, &eddsa_context->u.internal_pu_key.W[1], size); // compute r // - last size (32/57) bytes of H(sk), h, as big endian bytes ordered. stored // in r // - r = H(h,m) as little endian cx_sha512_init(&eddsa_context->hash_ctx); // hash to compare two data bytes cx_blake2b_init(&eddsa_context->data_hash_ctx, 256); cx_hash(&eddsa_context->hash_ctx.header, CX_NONE, eddsa_context->r, size, NULL, 0); // ... cx_hash(&eddsa_context->hash_ctx.header, CX_NONE, hash, hash_len, // NULL, 0); } void stream_eddsa_sign_step2(streamEddsaContext_t *eddsa_context, const unsigned char *hash, unsigned int hash_len) { cx_hash(&eddsa_context->data_hash_ctx.header, CX_NONE, hash, hash_len, NULL, 0); cx_hash(&eddsa_context->hash_ctx.header, CX_NONE, hash, hash_len, NULL, 0); } void stream_eddsa_sign_step3(streamEddsaContext_t *eddsa_context) { unsigned char scal[64]; cx_curve_twisted_edwards_t *domain = (cx_curve_twisted_edwards_t *)&C_cx_Ed25519; unsigned int size = domain->length; unsigned int hsize = 2 * size; cx_hash(&eddsa_context->data_hash_ctx.header, CX_LAST, NULL, 0, eddsa_context->first_data_hash, 32); cx_hash(&eddsa_context->hash_ctx.header, CX_LAST, NULL, 0, scal, 64); cx_encode_int(scal, hsize); cx_math_modm(scal, hsize, domain->n, size); os_memmove(eddsa_context->r, scal + size, size); // r // compute R = r.B eddsa_context->u.Q[0] = 0x04; os_memmove(eddsa_context->u.Q + 1, domain->Gx, size); os_memmove(eddsa_context->u.Q + 1 + size, domain->Gy, size); cx_ecfp_scalar_mult(CX_CURVE_Ed25519, eddsa_context->u.Q, 1 + 2 * domain->length, eddsa_context->r, size); cx_compress(eddsa_context->u.Q + 1, size); os_memmove(eddsa_context->sig, eddsa_context->u.Q + 1 + size, size); // sig <- R // compute S = r+H(R,A,M).a // - compute H(R,A,M) cx_sha512_init(&eddsa_context->hash_ctx); // hash to compare two data bytes cx_blake2b_init(&eddsa_context->data_hash_ctx, 256); cx_hash(&eddsa_context->hash_ctx.header, CX_NONE, eddsa_context->sig, size, NULL, 0); cx_hash(&eddsa_context->hash_ctx.header, CX_NONE, eddsa_context->Y, size, NULL, 0); } void stream_eddsa_sign_step4(streamEddsaContext_t *eddsa_context, const unsigned char *hash, unsigned int hash_len) { stream_eddsa_sign_step2(eddsa_context, hash, hash_len); } int stream_eddsa_sign_step5(streamEddsaContext_t *eddsa_context, unsigned char *sig) { unsigned char scal[64]; cx_curve_twisted_edwards_t *domain = (cx_curve_twisted_edwards_t *)&C_cx_Ed25519; unsigned int size = domain->length; unsigned int hsize = 2 * size; unsigned char second_data_hash[64]; cx_hash(&eddsa_context->data_hash_ctx.header, CX_LAST, NULL, 0, second_data_hash, 32); if (os_memcmp(&eddsa_context->first_data_hash, &second_data_hash, 32) != 0) { THROW(SW_SIGN_DATA_NOT_MATCH); } cx_hash(&eddsa_context->hash_ctx.header, CX_LAST, NULL, 0, scal, 64); cx_encode_int(scal, hsize); // - compute S = r+H(.)a cx_math_modm(scal, hsize, domain->n, size); cx_math_modm(eddsa_context->a, size, domain->n, size); cx_math_multm(eddsa_context->sig + size, scal + size, eddsa_context->a, domain->n, size); cx_math_addm(eddsa_context->sig + size, eddsa_context->sig + size, eddsa_context->r, domain->n, size); cx_encode_int(eddsa_context->sig + size, size); os_memmove(sig, eddsa_context->sig, 64); os_memset((unsigned char *)eddsa_context, 0, sizeof(streamEddsaContext_t)); return 2 * size; }
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.mammb.code.jpostal; import java.io.Serializable; import java.util.Objects; /** * Address. * * @author naotsugu */ public class Address implements Serializable { private final PostalCode code; private final MunicipalId municipalId; private final String prefecture; private final String city; private final String town; private final String street; private Address(PostalCode code, MunicipalId municipalId, String prefecture, String city, String town, String street) { this.code = Objects.requireNonNull(code); this.municipalId = Objects.requireNonNull(municipalId); this.prefecture = Objects.isNull(prefecture) ? "" : prefecture; this.city = Objects.isNull(city) ? "" : city; this.town = Objects.isNull(town) ? "" : town; this.street = Objects.isNull(street) ? "" : street; } /** * Create the {@code Address}. * @param code the postal code * @param municipalId the MunicipalId * @param prefecture the prefecture name * @param city the city name * @param town the town name * @param street the street name * @return the {@code Address} */ public static Address of(PostalCode code, MunicipalId municipalId, String prefecture, String city, String town, String street) { return new Address(code, municipalId, prefecture, city, town, street); } /** * Get the postal code. * @return the postal code */ public PostalCode getCode() { return code; } /** * Get the municipalId. * @return municipalId */ public MunicipalId getMunicipalId() { return municipalId; } /** * Get the prefecture name. * @return the prefecture name */ public String getPrefecture() { return prefecture; } /** * Get the city name. * @return the city name */ public String getCity() { return city; } /** * Get the town name. * @return the town name */ public String getTown() { return town; } /** * Get the street name. * @return the street name */ public String getStreet() { return street; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address address = (Address) o; return code.equals(address.code) && municipalId.equals(address.municipalId) && prefecture.equals(address.prefecture) && city.equals(address.city) && town.equals(address.town) && street.equals(address.street); } @Override public int hashCode() { return Objects.hash(code, municipalId, prefecture, city, town, street); } @Override public String toString() { return "Address{" + "code=" + code + ", municipalId='" + municipalId + '\'' + ", prefecture='" + prefecture + '\'' + ", city='" + city + '\'' + ", town='" + town + '\'' + ", street='" + street + '\'' + '}'; } /** * Get the json string. * @return the json string */ public String toJsonString() { return String.format( "{'code': '%s', 'prefectureCode': '%s', 'municipalityCode': '%s', 'prefecture': '%s', 'city': '%s', 'town': '%s', 'street': '%s'}".replace("'", "\""), code.getCode(), municipalId.getPrefCode(), municipalId.getMunicipalCode(), prefecture, city, town, street); } }
// binary_gap // 2020.01.10 #include<vector> using namespace std; int solution(int N) { vector<int> v; int cnt = 0; while (N > 0) { if (N % 2 == 1) { v.push_back(cnt); } N /= 2; cnt++; } int ans = 0; if (v.size() == 1) { return 0; } for (int i = 1; i < v.size(); i++) { ans = max(ans, v[i] - v[i - 1] - 1); } return ans; }
class FronzenJSON: def __init__(self, data): self._data = data @classmethod def build(cls, obj): if isinstance(obj, dict): data = {key: cls.build(value) for key, value in obj.items()} return cls(data) elif isinstance(obj, list): data = [cls.build(item) for item in obj] return cls(data) else: return cls(obj)
def huffman_encoding(text): # Creating a dictionary of frequencies of characters in text freq_dict = {} for char in text: if char not in freq_dict.keys(): freq_dict[char] = 0 freq_dict[char] += 1 # Creating a MinHeap from queue import PriorityQueue minHeap = PriorityQueue() # Adding frequencies of characters to minHeap for key in freq_dict: minHeap.put((freq_dict[key], key)) # Building the Huffman tree while (minHeap.qsize()>1): leftChar = minHeap.get() rightChar = minHeap.get() for char in leftChar[1:] + rightChar[1:]: if char not in freq_dict.keys(): freq_dict[char]=0 freq_dict[char] +=1 minHeap.put((leftChar[0]+rightChar[0], leftChar[1]+rightChar[1])) # Tracing the code (binary) code = "" while (minHeap.qsize()): tinyheap = minHeap.get() char = tinyheap[1] freq = tinyheap[0] code += ("1"+char[0]+"0"*(len(char)-1)) c = 0 for ch in char: freq_dict[ch] = ("1"+code[::-1][c:c+len(char)][::-1]) c += len(char) # Inserting in dictionary huffmanCode = {} for key in freq_dict: huffmanCode[key] = freq_dict[key] return huffmanCode
<reponame>ibuttimer/Critter-Chronologer<gh_stars>0 package com.udacity.jdnd.course3.critter.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; import java.util.List; @ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid employee") public class InvalidEmployeeException extends AbstractException { public InvalidEmployeeException() { super(); } public InvalidEmployeeException(String message) { super(message); } public InvalidEmployeeException(List<String> messages) { super(messages); } public InvalidEmployeeException(String message, Throwable cause) { super(message, cause); } }
#!/bin/bash BATCHSIZE=7 componentReportDirectory="./*" # How many files are in the directory numberOfFiles=$(ls 2>/dev/null -Ub1 -- $componentReportDirectory | wc -l) # Gather tracefiles for traceFile in $componentReportDirectory; do Array+=("$traceFile ") done let count=0 # Init our out array ArrayOut=() # Add one because otherwise it won't work for((i=0;i<(($numberOfFiles+1));i++)); do # Add files to our array ArrayOut+=${Array[$count]} let count=$count+1 let modCount=$count%$BATCHSIZE; # If the max batch size is reached, OR the array is at it's end if [[ modCount -eq 0 || i -eq ${#Array[@]} ]]; then # Do stuff in here echo "Array: $ArrayOut" ArrayOut=() fi done
using System; namespace Acheve.Common.Messages { public class AwaitExternalEstimationToBeProcessed { public AwaitExternalEstimationToBeProcessed(Guid caseNumber) { CaseNumber = caseNumber; } public Guid CaseNumber { get; } } public class MessageProcessor { public void ProcessExternalEstimationMessage(AwaitExternalEstimationToBeProcessed message) { // Log the case number to the console Console.WriteLine($"Processing external estimation for case number: {message.CaseNumber}"); // Initiate the processing of the external estimation associated with the case number // Placeholder for the actual processing logic // Example: ExternalEstimationProcessor.Process(message.CaseNumber); } } }
<reponame>ch1huizong/learning #!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 <NAME> All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import imp import sys for i in range(2): print i, try: m = sys.modules['example'] except KeyError: print '(not in sys.modules)', else: print '(have in sys.modules)', f, filename, description = imp.find_module('example') example_package = imp.load_module('example', f, filename, description)
<gh_stars>0 import { createStore, combineReducers, compose, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { serviceDeleteReducer, serviceDetailsReducer, serviceListReducer, serviceSaveReducer, } from "./reducers/serviceReducers"; import { cartReducer } from "./reducers/cartReducer"; import Cookie from "js-cookie"; import { userRegisterReducer, userSigninReducer } from "./reducers/userReducers"; const cartItems = Cookie.getJSON("cartItems") || []; const userInfo = Cookie.getJSON("userInfo") || null; const initialState = { cart: { cartItems }, userSignin:{userInfo} }; const reducer = combineReducers({ serviceList: serviceListReducer, serviceDetails: serviceDetailsReducer, cart: cartReducer, userSignin: userSigninReducer, userRegister: userRegisterReducer, serviceSave: serviceSaveReducer, serviceDelete: serviceDeleteReducer }); const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( reducer, initialState, composeEnhancer(applyMiddleware(thunk)) ); export default store;
<reponame>rz3n/learning<gh_stars>0 /** * question2 - Write a description here. * * @author (your name) * @version (a version number or a date) */ import java.util.*; public class question2 { public static void main (String [] args) { Scanner in = new Scanner (System.in); final Double annualIncomeRate1 = 0.15; final Double annualIncomeConstant1 = 0.0; final Double annualIncomeLimit1 = 45282d; final Double annualIncomeRate2 = 0.205; final Double annualIncomeConstant2 = 2491.0; final Double annualIncomeLimit2 = 90563d; final Double annualIncomeRate3 = 0.260; final Double annualIncomeConstant3 = 7471.0; Double monthlySalary; Double annualSalary; Double annualFederalTax; Double monthlyAFederalTax; Double summary; System.out.printf("\nEnter your monthly pay: "); monthlySalary = in.nextDouble(); annualSalary = monthlySalary * 12; if (annualSalary <= annualIncomeLimit1) { annualFederalTax = (annualIncomeRate1 * annualSalary) - annualIncomeConstant1; } else if (annualSalary <= annualIncomeLimit2) { annualFederalTax = (annualIncomeRate2 * annualSalary) - annualIncomeConstant2; } else { annualFederalTax = (annualIncomeRate3 * annualSalary) - annualIncomeConstant3; } monthlyAFederalTax = annualFederalTax / 12; summary = monthlySalary - monthlyAFederalTax; System.out.printf("\n Desc Amount"); System.out.printf("\n Salary %10.2f", monthlySalary); System.out.printf("\nMonthly fed tax %10.2f", monthlyAFederalTax); System.out.printf("\n Summary %10.2f", summary); } }
import sys n = int(input()) sum_of_all_numbers = 0 max_element = -sys.maxsize for number in range(1, n + 1): num = int(input()) sum_of_all_numbers += num if num > max_element: max_element = num if max_element == sum_of_all_numbers - max_element: print("Yes") print(f"Sum = {max_element}") else: print("No") print(f"Diff = {abs(max_element - (sum_of_all_numbers - max_element))}")
<gh_stars>0 package com.netcracker.ncstore.dto.request; import lombok.AllArgsConstructor; import lombok.Getter; import java.time.LocalDate; @AllArgsConstructor @Getter public class PersonUpdateRequest { private final String emailOfUser; private final String nickName; private final String firstName; private final String lastName; private final LocalDate birthday; }
#!/bin/bash # # CIS Debian 7 Hardening # # # 6.5 Configure Network Time Protocol (NTP) (Scored) # set -e # One error, it's over set -u # One variable unset, it's over PACKAGE='ntp' NTP_CONF_DEFAULT_PATTERN='^restrict -4 default (kod nomodify notrap nopeer noquery|ignore)' NTP_CONF_FILE='/etc/ntp.conf' NTP_INIT_PATTERN='RUNASUSER=ntp' NTP_INIT_FILE='/etc/init.d/ntp' # This function will be called if the script status is on enabled / audit mode audit () { is_pkg_installed $PACKAGE if [ $FNRET != 0 ]; then crit "$PACKAGE is not installed!" else ok "$PACKAGE is installed, checking configuration" does_pattern_exist_in_file $NTP_CONF_FILE $NTP_CONF_DEFAULT_PATTERN if [ $FNRET != 0 ]; then crit "$NTP_CONF_DEFAULT_PATTERN not found in $NTP_CONF_FILE" else ok "$NTP_CONF_DEFAULT_PATTERN found in $NTP_CONF_FILE" fi does_pattern_exist_in_file $NTP_INIT_FILE "^$NTP_INIT_PATTERN" if [ $FNRET != 0 ]; then crit "$NTP_INIT_PATTERN not found in $NTP_INIT_FILE" else ok "$NTP_INIT_PATTERN found in $NTP_INIT_FILE" fi fi } # This function will be called if the script status is on enabled mode apply () { is_pkg_installed $PACKAGE if [ $FNRET = 0 ]; then ok "$PACKAGE is installed" else crit "$PACKAGE is absent, installing it" apt_install $PACKAGE info "Checking $PACKAGE configuration" fi does_pattern_exist_in_file $NTP_CONF_FILE $NTP_CONF_DEFAULT_PATTERN if [ $FNRET != 0 ]; then warn "$NTP_CONF_DEFAULT_PATTERN not found in $NTP_CONF_FILE, adding it" backup_file $NTP_CONF_FILE add_end_of_file $NTP_CONF_FILE "restrict -4 default kod notrap nomodify nopeer noquery" else ok "$NTP_CONF_DEFAULT_PATTERN found in $NTP_CONF_FILE" fi does_pattern_exist_in_file $NTP_INIT_FILE "^$NTP_INIT_PATTERN" if [ $FNRET != 0 ]; then warn "$NTP_INIT_PATTERN not found in $NTP_INIT_FILE, adding it" backup_file $NTP_INIT_FILE add_line_file_before_pattern $NTP_INIT_FILE $NTP_INIT_PATTERN "^UGID" else ok "$NTP_INIT_PATTERN found in $NTP_INIT_FILE" fi } # This function will check config parameters required check_config() { : } # Source Root Dir Parameter if [ ! -r /etc/default/cis-hardening ]; then echo "There is no /etc/default/cis-hardening file, cannot source CIS_ROOT_DIR variable, aborting" exit 128 else . /etc/default/cis-hardening if [ -z ${CIS_ROOT_DIR:-} ]; then echo "No CIS_ROOT_DIR variable, aborting" exit 128 fi fi # Main function, will call the proper functions given the configuration (audit, enabled, disabled) if [ -r $CIS_ROOT_DIR/lib/main.sh ]; then . $CIS_ROOT_DIR/lib/main.sh else echo "Cannot find main.sh, have you correctly defined your root directory? Current value is $CIS_ROOT_DIR in /etc/default/cis-hardening" exit 128 fi
<gh_stars>1-10 /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.course.nodes.pf.ui; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import org.olat.core.commons.modules.bc.FolderModule; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.Component; import org.olat.core.gui.components.download.DownloadComponent; import org.olat.core.gui.components.htmlsite.OlatCmdEvent; import org.olat.core.gui.components.link.Link; import org.olat.core.gui.components.link.LinkFactory; import org.olat.core.gui.components.velocity.VelocityContainer; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; import org.olat.core.gui.control.controller.BasicController; import org.olat.core.gui.util.CSSHelper; import org.olat.core.util.vfs.LocalFileImpl; import org.olat.core.util.vfs.VFSContainer; import org.olat.core.util.vfs.VFSItem; import org.olat.core.util.vfs.VFSLeaf; import org.olat.core.util.vfs.filters.VFSItemFilter; import org.olat.core.util.vfs.filters.VFSSystemItemFilter; import org.springframework.beans.factory.annotation.Autowired; /** * * @author <NAME>, <EMAIL>, http://www.frentix.com * */ public class PFPeekviewController extends BasicController { // comparator to sort the messages list by creation date private static final Comparator<VFSLeaf> dateSortingComparator = (leaf1, leaf2) -> Long.compare(leaf2.getLastModified(), leaf1.getLastModified()); //last first // the current course node id private final String nodeId; private static final VFSItemFilter attachmentExcludeFilter = new VFSSystemItemFilter(); @Autowired private FolderModule folderModule; public PFPeekviewController(UserRequest ureq, WindowControl wControl, List<VFSContainer> folders, String nodeId, int itemsToDisplay) { super(ureq, wControl); this.nodeId = nodeId; VelocityContainer peekviewVC = createVelocityContainer("peekview"); // add items, only as many as configured List<VFSLeaf> allLeafs = new ArrayList<>(); for(VFSContainer rootFolder:folders) { addItems(rootFolder, allLeafs); } // Sort messages by last modified date Collections.sort(allLeafs, dateSortingComparator); boolean forceDownload = folderModule.isForceDownload(); // only take the configured amount of messages List<VFSLeaf> leafs = new ArrayList<>(); for (int i = 0; i<allLeafs.size() && i<itemsToDisplay; i++) { VFSLeaf leaf = allLeafs.get(i); leafs.add(leaf); // add link to item // Add link to jump to course node if (leaf instanceof LocalFileImpl) { DownloadComponent dlComp = new DownloadComponent("nodeLinkDL_"+(i+1), leaf, forceDownload, leaf.getName() + " " + new Date(leaf.getLastModified()), translate("peekview.downloadfile"), CSSHelper.createFiletypeIconCssClassFor(leaf.getName())); dlComp.setElementCssClass("o_gotoNode"); peekviewVC.put("nodeLinkDL_"+(i+1),dlComp); } } peekviewVC.contextPut("leafs", leafs); // Add link to show all items (go to node) Link allItemsLink = LinkFactory.createLink("peekview.allItemsLink", peekviewVC, this); allItemsLink.setIconRightCSS("o_icon o_icon_start"); allItemsLink.setElementCssClass("pull-right"); putInitialPanel(peekviewVC); } @Override protected void event(UserRequest ureq, Component source, Event event) { if (source instanceof Link) { Link nodeLink = (Link) source; String relPath = (String) nodeLink.getUserObject(); if (relPath == null) { fireEvent(ureq, new OlatCmdEvent(OlatCmdEvent.GOTONODE_CMD, nodeId)); } else { fireEvent(ureq, new OlatCmdEvent(OlatCmdEvent.GOTONODE_CMD, nodeId + "/" + relPath)); } } } private void addItems(VFSContainer container, List<VFSLeaf> allLeafs) { // exclude files which are also excluded in FolderComponent for (VFSItem vfsItem : container.getItems(attachmentExcludeFilter)) { if (vfsItem instanceof VFSLeaf) { allLeafs.add((VFSLeaf)vfsItem); } else if (vfsItem instanceof VFSContainer) { // do it recursively for all children addItems((VFSContainer)vfsItem, allLeafs); } } } }
#!/bin/bash # Perform system upgrade and cleanup apt full-upgrade -y apt autoremove -y # Install unattended-upgrades apt install -y unattended-upgrades # Remove existing Docker packages apt remove -y docker docker-engine docker.io containerd runc # Install required dependencies apt install -y apt-transport-https ca-certificates curl gnupg pwgen openssl apache2-utils sqlite3 # Add Docker repository key curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null # Update package index apt update # Install Docker packages apt install -y docker-ce docker-ce-cli containerd.io docker-compose # Check if Docker installation was successful if [ $(which docker) ]; then echo "Docker installation successful" else echo "Docker installation failed" fi
#import "FAKIcon.h" @interface FAKFontAwesome : FAKIcon // Generated Code + (instancetype)glassIconWithSize:(CGFloat)size; + (instancetype)musicIconWithSize:(CGFloat)size; + (instancetype)searchIconWithSize:(CGFloat)size; + (instancetype)envelopeOIconWithSize:(CGFloat)size; + (instancetype)heartIconWithSize:(CGFloat)size; + (instancetype)starIconWithSize:(CGFloat)size; + (instancetype)starOIconWithSize:(CGFloat)size; + (instancetype)userIconWithSize:(CGFloat)size; + (instancetype)filmIconWithSize:(CGFloat)size; + (instancetype)thLargeIconWithSize:(CGFloat)size; + (instancetype)thIconWithSize:(CGFloat)size; + (instancetype)thListIconWithSize:(CGFloat)size; + (instancetype)checkIconWithSize:(CGFloat)size; + (instancetype)timesIconWithSize:(CGFloat)size; + (instancetype)searchPlusIconWithSize:(CGFloat)size; + (instancetype)searchMinusIconWithSize:(CGFloat)size; + (instancetype)powerOffIconWithSize:(CGFloat)size; + (instancetype)signalIconWithSize:(CGFloat)size; + (instancetype)cogIconWithSize:(CGFloat)size; + (instancetype)trashOIconWithSize:(CGFloat)size; + (instancetype)homeIconWithSize:(CGFloat)size; + (instancetype)fileOIconWithSize:(CGFloat)size; + (instancetype)clockOIconWithSize:(CGFloat)size; + (instancetype)roadIconWithSize:(CGFloat)size; + (instancetype)downloadIconWithSize:(CGFloat)size; + (instancetype)arrowCircleODownIconWithSize:(CGFloat)size; + (instancetype)arrowCircleOUpIconWithSize:(CGFloat)size; + (instancetype)inboxIconWithSize:(CGFloat)size; + (instancetype)playCircleOIconWithSize:(CGFloat)size; + (instancetype)repeatIconWithSize:(CGFloat)size; + (instancetype)refreshIconWithSize:(CGFloat)size; + (instancetype)listAltIconWithSize:(CGFloat)size; + (instancetype)lockIconWithSize:(CGFloat)size; + (instancetype)flagIconWithSize:(CGFloat)size; + (instancetype)headphonesIconWithSize:(CGFloat)size; + (instancetype)volumeOffIconWithSize:(CGFloat)size; + (instancetype)volumeDownIconWithSize:(CGFloat)size; + (instancetype)volumeUpIconWithSize:(CGFloat)size; + (instancetype)qrcodeIconWithSize:(CGFloat)size; + (instancetype)barcodeIconWithSize:(CGFloat)size; + (instancetype)tagIconWithSize:(CGFloat)size; + (instancetype)tagsIconWithSize:(CGFloat)size; + (instancetype)bookIconWithSize:(CGFloat)size; + (instancetype)bookmarkIconWithSize:(CGFloat)size; + (instancetype)printIconWithSize:(CGFloat)size; + (instancetype)cameraIconWithSize:(CGFloat)size; + (instancetype)fontIconWithSize:(CGFloat)size; + (instancetype)boldIconWithSize:(CGFloat)size; + (instancetype)italicIconWithSize:(CGFloat)size; + (instancetype)textHeightIconWithSize:(CGFloat)size; + (instancetype)textWidthIconWithSize:(CGFloat)size; + (instancetype)alignLeftIconWithSize:(CGFloat)size; + (instancetype)alignCenterIconWithSize:(CGFloat)size; + (instancetype)alignRightIconWithSize:(CGFloat)size; + (instancetype)alignJustifyIconWithSize:(CGFloat)size; + (instancetype)listIconWithSize:(CGFloat)size; + (instancetype)outdentIconWithSize:(CGFloat)size; + (instancetype)indentIconWithSize:(CGFloat)size; + (instancetype)videoCameraIconWithSize:(CGFloat)size; + (instancetype)pictureOIconWithSize:(CGFloat)size; + (instancetype)pencilIconWithSize:(CGFloat)size; + (instancetype)mapMarkerIconWithSize:(CGFloat)size; + (instancetype)adjustIconWithSize:(CGFloat)size; + (instancetype)tintIconWithSize:(CGFloat)size; + (instancetype)pencilSquareOIconWithSize:(CGFloat)size; + (instancetype)shareSquareOIconWithSize:(CGFloat)size; + (instancetype)checkSquareOIconWithSize:(CGFloat)size; + (instancetype)arrowsIconWithSize:(CGFloat)size; + (instancetype)stepBackwardIconWithSize:(CGFloat)size; + (instancetype)fastBackwardIconWithSize:(CGFloat)size; + (instancetype)backwardIconWithSize:(CGFloat)size; + (instancetype)playIconWithSize:(CGFloat)size; + (instancetype)pauseIconWithSize:(CGFloat)size; + (instancetype)stopIconWithSize:(CGFloat)size; + (instancetype)forwardIconWithSize:(CGFloat)size; + (instancetype)fastForwardIconWithSize:(CGFloat)size; + (instancetype)stepForwardIconWithSize:(CGFloat)size; + (instancetype)ejectIconWithSize:(CGFloat)size; + (instancetype)chevronLeftIconWithSize:(CGFloat)size; + (instancetype)chevronRightIconWithSize:(CGFloat)size; + (instancetype)plusCircleIconWithSize:(CGFloat)size; + (instancetype)minusCircleIconWithSize:(CGFloat)size; + (instancetype)timesCircleIconWithSize:(CGFloat)size; + (instancetype)checkCircleIconWithSize:(CGFloat)size; + (instancetype)questionCircleIconWithSize:(CGFloat)size; + (instancetype)infoCircleIconWithSize:(CGFloat)size; + (instancetype)crosshairsIconWithSize:(CGFloat)size; + (instancetype)timesCircleOIconWithSize:(CGFloat)size; + (instancetype)checkCircleOIconWithSize:(CGFloat)size; + (instancetype)banIconWithSize:(CGFloat)size; + (instancetype)arrowLeftIconWithSize:(CGFloat)size; + (instancetype)arrowRightIconWithSize:(CGFloat)size; + (instancetype)arrowUpIconWithSize:(CGFloat)size; + (instancetype)arrowDownIconWithSize:(CGFloat)size; + (instancetype)shareIconWithSize:(CGFloat)size; + (instancetype)expandIconWithSize:(CGFloat)size; + (instancetype)compressIconWithSize:(CGFloat)size; + (instancetype)plusIconWithSize:(CGFloat)size; + (instancetype)minusIconWithSize:(CGFloat)size; + (instancetype)asteriskIconWithSize:(CGFloat)size; + (instancetype)exclamationCircleIconWithSize:(CGFloat)size; + (instancetype)giftIconWithSize:(CGFloat)size; + (instancetype)leafIconWithSize:(CGFloat)size; + (instancetype)fireIconWithSize:(CGFloat)size; + (instancetype)eyeIconWithSize:(CGFloat)size; + (instancetype)eyeSlashIconWithSize:(CGFloat)size; + (instancetype)exclamationTriangleIconWithSize:(CGFloat)size; + (instancetype)planeIconWithSize:(CGFloat)size; + (instancetype)calendarIconWithSize:(CGFloat)size; + (instancetype)randomIconWithSize:(CGFloat)size; + (instancetype)commentIconWithSize:(CGFloat)size; + (instancetype)magnetIconWithSize:(CGFloat)size; + (instancetype)chevronUpIconWithSize:(CGFloat)size; + (instancetype)chevronDownIconWithSize:(CGFloat)size; + (instancetype)retweetIconWithSize:(CGFloat)size; + (instancetype)shoppingCartIconWithSize:(CGFloat)size; + (instancetype)folderIconWithSize:(CGFloat)size; + (instancetype)folderOpenIconWithSize:(CGFloat)size; + (instancetype)arrowsVIconWithSize:(CGFloat)size; + (instancetype)arrowsHIconWithSize:(CGFloat)size; + (instancetype)barChartOIconWithSize:(CGFloat)size; + (instancetype)twitterSquareIconWithSize:(CGFloat)size; + (instancetype)facebookSquareIconWithSize:(CGFloat)size; + (instancetype)cameraRetroIconWithSize:(CGFloat)size; + (instancetype)keyIconWithSize:(CGFloat)size; + (instancetype)cogsIconWithSize:(CGFloat)size; + (instancetype)commentsIconWithSize:(CGFloat)size; + (instancetype)thumbsOUpIconWithSize:(CGFloat)size; + (instancetype)thumbsODownIconWithSize:(CGFloat)size; + (instancetype)starHalfIconWithSize:(CGFloat)size; + (instancetype)heartOIconWithSize:(CGFloat)size; + (instancetype)signOutIconWithSize:(CGFloat)size; + (instancetype)linkedinSquareIconWithSize:(CGFloat)size; + (instancetype)thumbTackIconWithSize:(CGFloat)size; + (instancetype)externalLinkIconWithSize:(CGFloat)size; + (instancetype)signInIconWithSize:(CGFloat)size; + (instancetype)trophyIconWithSize:(CGFloat)size; + (instancetype)githubSquareIconWithSize:(CGFloat)size; + (instancetype)uploadIconWithSize:(CGFloat)size; + (instancetype)lemonOIconWithSize:(CGFloat)size; + (instancetype)phoneIconWithSize:(CGFloat)size; + (instancetype)squareOIconWithSize:(CGFloat)size; + (instancetype)bookmarkOIconWithSize:(CGFloat)size; + (instancetype)phoneSquareIconWithSize:(CGFloat)size; + (instancetype)twitterIconWithSize:(CGFloat)size; + (instancetype)facebookIconWithSize:(CGFloat)size; + (instancetype)githubIconWithSize:(CGFloat)size; + (instancetype)unlockIconWithSize:(CGFloat)size; + (instancetype)creditCardIconWithSize:(CGFloat)size; + (instancetype)rssIconWithSize:(CGFloat)size; + (instancetype)hddOIconWithSize:(CGFloat)size; + (instancetype)bullhornIconWithSize:(CGFloat)size; + (instancetype)bellIconWithSize:(CGFloat)size; + (instancetype)certificateIconWithSize:(CGFloat)size; + (instancetype)handORightIconWithSize:(CGFloat)size; + (instancetype)handOLeftIconWithSize:(CGFloat)size; + (instancetype)handOUpIconWithSize:(CGFloat)size; + (instancetype)handODownIconWithSize:(CGFloat)size; + (instancetype)arrowCircleLeftIconWithSize:(CGFloat)size; + (instancetype)arrowCircleRightIconWithSize:(CGFloat)size; + (instancetype)arrowCircleUpIconWithSize:(CGFloat)size; + (instancetype)arrowCircleDownIconWithSize:(CGFloat)size; + (instancetype)globeIconWithSize:(CGFloat)size; + (instancetype)wrenchIconWithSize:(CGFloat)size; + (instancetype)tasksIconWithSize:(CGFloat)size; + (instancetype)filterIconWithSize:(CGFloat)size; + (instancetype)briefcaseIconWithSize:(CGFloat)size; + (instancetype)arrowsAltIconWithSize:(CGFloat)size; + (instancetype)usersIconWithSize:(CGFloat)size; + (instancetype)linkIconWithSize:(CGFloat)size; + (instancetype)cloudIconWithSize:(CGFloat)size; + (instancetype)flaskIconWithSize:(CGFloat)size; + (instancetype)scissorsIconWithSize:(CGFloat)size; + (instancetype)filesOIconWithSize:(CGFloat)size; + (instancetype)paperclipIconWithSize:(CGFloat)size; + (instancetype)floppyOIconWithSize:(CGFloat)size; + (instancetype)squareIconWithSize:(CGFloat)size; + (instancetype)barsIconWithSize:(CGFloat)size; + (instancetype)listUlIconWithSize:(CGFloat)size; + (instancetype)listOlIconWithSize:(CGFloat)size; + (instancetype)strikethroughIconWithSize:(CGFloat)size; + (instancetype)underlineIconWithSize:(CGFloat)size; + (instancetype)tableIconWithSize:(CGFloat)size; + (instancetype)magicIconWithSize:(CGFloat)size; + (instancetype)truckIconWithSize:(CGFloat)size; + (instancetype)pinterestIconWithSize:(CGFloat)size; + (instancetype)pinterestSquareIconWithSize:(CGFloat)size; + (instancetype)googlePlusSquareIconWithSize:(CGFloat)size; + (instancetype)googlePlusIconWithSize:(CGFloat)size; + (instancetype)moneyIconWithSize:(CGFloat)size; + (instancetype)caretDownIconWithSize:(CGFloat)size; + (instancetype)caretUpIconWithSize:(CGFloat)size; + (instancetype)caretLeftIconWithSize:(CGFloat)size; + (instancetype)caretRightIconWithSize:(CGFloat)size; + (instancetype)columnsIconWithSize:(CGFloat)size; + (instancetype)sortIconWithSize:(CGFloat)size; + (instancetype)sortAscIconWithSize:(CGFloat)size; + (instancetype)sortDescIconWithSize:(CGFloat)size; + (instancetype)envelopeIconWithSize:(CGFloat)size; + (instancetype)linkedinIconWithSize:(CGFloat)size; + (instancetype)undoIconWithSize:(CGFloat)size; + (instancetype)gavelIconWithSize:(CGFloat)size; + (instancetype)tachometerIconWithSize:(CGFloat)size; + (instancetype)commentOIconWithSize:(CGFloat)size; + (instancetype)commentsOIconWithSize:(CGFloat)size; + (instancetype)boltIconWithSize:(CGFloat)size; + (instancetype)sitemapIconWithSize:(CGFloat)size; + (instancetype)umbrellaIconWithSize:(CGFloat)size; + (instancetype)clipboardIconWithSize:(CGFloat)size; + (instancetype)lightbulbOIconWithSize:(CGFloat)size; + (instancetype)exchangeIconWithSize:(CGFloat)size; + (instancetype)cloudDownloadIconWithSize:(CGFloat)size; + (instancetype)cloudUploadIconWithSize:(CGFloat)size; + (instancetype)userMdIconWithSize:(CGFloat)size; + (instancetype)stethoscopeIconWithSize:(CGFloat)size; + (instancetype)suitcaseIconWithSize:(CGFloat)size; + (instancetype)bellOIconWithSize:(CGFloat)size; + (instancetype)coffeeIconWithSize:(CGFloat)size; + (instancetype)cutleryIconWithSize:(CGFloat)size; + (instancetype)fileTextOIconWithSize:(CGFloat)size; + (instancetype)buildingOIconWithSize:(CGFloat)size; + (instancetype)hospitalOIconWithSize:(CGFloat)size; + (instancetype)ambulanceIconWithSize:(CGFloat)size; + (instancetype)medkitIconWithSize:(CGFloat)size; + (instancetype)fighterJetIconWithSize:(CGFloat)size; + (instancetype)beerIconWithSize:(CGFloat)size; + (instancetype)hSquareIconWithSize:(CGFloat)size; + (instancetype)plusSquareIconWithSize:(CGFloat)size; + (instancetype)angleDoubleLeftIconWithSize:(CGFloat)size; + (instancetype)angleDoubleRightIconWithSize:(CGFloat)size; + (instancetype)angleDoubleUpIconWithSize:(CGFloat)size; + (instancetype)angleDoubleDownIconWithSize:(CGFloat)size; + (instancetype)angleLeftIconWithSize:(CGFloat)size; + (instancetype)angleRightIconWithSize:(CGFloat)size; + (instancetype)angleUpIconWithSize:(CGFloat)size; + (instancetype)angleDownIconWithSize:(CGFloat)size; + (instancetype)desktopIconWithSize:(CGFloat)size; + (instancetype)laptopIconWithSize:(CGFloat)size; + (instancetype)tabletIconWithSize:(CGFloat)size; + (instancetype)mobileIconWithSize:(CGFloat)size; + (instancetype)circleOIconWithSize:(CGFloat)size; + (instancetype)quoteLeftIconWithSize:(CGFloat)size; + (instancetype)quoteRightIconWithSize:(CGFloat)size; + (instancetype)spinnerIconWithSize:(CGFloat)size; + (instancetype)circleIconWithSize:(CGFloat)size; + (instancetype)replyIconWithSize:(CGFloat)size; + (instancetype)githubAltIconWithSize:(CGFloat)size; + (instancetype)folderOIconWithSize:(CGFloat)size; + (instancetype)folderOpenOIconWithSize:(CGFloat)size; + (instancetype)smileOIconWithSize:(CGFloat)size; + (instancetype)frownOIconWithSize:(CGFloat)size; + (instancetype)mehOIconWithSize:(CGFloat)size; + (instancetype)gamepadIconWithSize:(CGFloat)size; + (instancetype)keyboardOIconWithSize:(CGFloat)size; + (instancetype)flagOIconWithSize:(CGFloat)size; + (instancetype)flagCheckeredIconWithSize:(CGFloat)size; + (instancetype)terminalIconWithSize:(CGFloat)size; + (instancetype)codeIconWithSize:(CGFloat)size; + (instancetype)replyAllIconWithSize:(CGFloat)size; + (instancetype)mailReplyAllIconWithSize:(CGFloat)size; + (instancetype)starHalfOIconWithSize:(CGFloat)size; + (instancetype)locationArrowIconWithSize:(CGFloat)size; + (instancetype)cropIconWithSize:(CGFloat)size; + (instancetype)codeForkIconWithSize:(CGFloat)size; + (instancetype)chainBrokenIconWithSize:(CGFloat)size; + (instancetype)questionIconWithSize:(CGFloat)size; + (instancetype)infoIconWithSize:(CGFloat)size; + (instancetype)exclamationIconWithSize:(CGFloat)size; + (instancetype)superscriptIconWithSize:(CGFloat)size; + (instancetype)subscriptIconWithSize:(CGFloat)size; + (instancetype)eraserIconWithSize:(CGFloat)size; + (instancetype)puzzlePieceIconWithSize:(CGFloat)size; + (instancetype)microphoneIconWithSize:(CGFloat)size; + (instancetype)microphoneSlashIconWithSize:(CGFloat)size; + (instancetype)shieldIconWithSize:(CGFloat)size; + (instancetype)calendarOIconWithSize:(CGFloat)size; + (instancetype)fireExtinguisherIconWithSize:(CGFloat)size; + (instancetype)rocketIconWithSize:(CGFloat)size; + (instancetype)maxcdnIconWithSize:(CGFloat)size; + (instancetype)chevronCircleLeftIconWithSize:(CGFloat)size; + (instancetype)chevronCircleRightIconWithSize:(CGFloat)size; + (instancetype)chevronCircleUpIconWithSize:(CGFloat)size; + (instancetype)chevronCircleDownIconWithSize:(CGFloat)size; + (instancetype)html5IconWithSize:(CGFloat)size; + (instancetype)css3IconWithSize:(CGFloat)size; + (instancetype)anchorIconWithSize:(CGFloat)size; + (instancetype)unlockAltIconWithSize:(CGFloat)size; + (instancetype)bullseyeIconWithSize:(CGFloat)size; + (instancetype)ellipsisHIconWithSize:(CGFloat)size; + (instancetype)ellipsisVIconWithSize:(CGFloat)size; + (instancetype)rssSquareIconWithSize:(CGFloat)size; + (instancetype)playCircleIconWithSize:(CGFloat)size; + (instancetype)ticketIconWithSize:(CGFloat)size; + (instancetype)minusSquareIconWithSize:(CGFloat)size; + (instancetype)minusSquareOIconWithSize:(CGFloat)size; + (instancetype)levelUpIconWithSize:(CGFloat)size; + (instancetype)levelDownIconWithSize:(CGFloat)size; + (instancetype)checkSquareIconWithSize:(CGFloat)size; + (instancetype)pencilSquareIconWithSize:(CGFloat)size; + (instancetype)externalLinkSquareIconWithSize:(CGFloat)size; + (instancetype)shareSquareIconWithSize:(CGFloat)size; + (instancetype)compassIconWithSize:(CGFloat)size; + (instancetype)caretSquareODownIconWithSize:(CGFloat)size; + (instancetype)caretSquareOUpIconWithSize:(CGFloat)size; + (instancetype)caretSquareORightIconWithSize:(CGFloat)size; + (instancetype)eurIconWithSize:(CGFloat)size; + (instancetype)gbpIconWithSize:(CGFloat)size; + (instancetype)usdIconWithSize:(CGFloat)size; + (instancetype)inrIconWithSize:(CGFloat)size; + (instancetype)jpyIconWithSize:(CGFloat)size; + (instancetype)rubIconWithSize:(CGFloat)size; + (instancetype)krwIconWithSize:(CGFloat)size; + (instancetype)btcIconWithSize:(CGFloat)size; + (instancetype)fileIconWithSize:(CGFloat)size; + (instancetype)fileTextIconWithSize:(CGFloat)size; + (instancetype)sortAlphaAscIconWithSize:(CGFloat)size; + (instancetype)sortAlphaDescIconWithSize:(CGFloat)size; + (instancetype)sortAmountAscIconWithSize:(CGFloat)size; + (instancetype)sortAmountDescIconWithSize:(CGFloat)size; + (instancetype)sortNumericAscIconWithSize:(CGFloat)size; + (instancetype)sortNumericDescIconWithSize:(CGFloat)size; + (instancetype)thumbsUpIconWithSize:(CGFloat)size; + (instancetype)thumbsDownIconWithSize:(CGFloat)size; + (instancetype)youtubeSquareIconWithSize:(CGFloat)size; + (instancetype)youtubeIconWithSize:(CGFloat)size; + (instancetype)xingIconWithSize:(CGFloat)size; + (instancetype)xingSquareIconWithSize:(CGFloat)size; + (instancetype)youtubePlayIconWithSize:(CGFloat)size; + (instancetype)dropboxIconWithSize:(CGFloat)size; + (instancetype)stackOverflowIconWithSize:(CGFloat)size; + (instancetype)instagramIconWithSize:(CGFloat)size; + (instancetype)flickrIconWithSize:(CGFloat)size; + (instancetype)adnIconWithSize:(CGFloat)size; + (instancetype)bitbucketIconWithSize:(CGFloat)size; + (instancetype)bitbucketSquareIconWithSize:(CGFloat)size; + (instancetype)tumblrIconWithSize:(CGFloat)size; + (instancetype)tumblrSquareIconWithSize:(CGFloat)size; + (instancetype)longArrowDownIconWithSize:(CGFloat)size; + (instancetype)longArrowUpIconWithSize:(CGFloat)size; + (instancetype)longArrowLeftIconWithSize:(CGFloat)size; + (instancetype)longArrowRightIconWithSize:(CGFloat)size; + (instancetype)appleIconWithSize:(CGFloat)size; + (instancetype)windowsIconWithSize:(CGFloat)size; + (instancetype)androidIconWithSize:(CGFloat)size; + (instancetype)linuxIconWithSize:(CGFloat)size; + (instancetype)dribbbleIconWithSize:(CGFloat)size; + (instancetype)skypeIconWithSize:(CGFloat)size; + (instancetype)foursquareIconWithSize:(CGFloat)size; + (instancetype)trelloIconWithSize:(CGFloat)size; + (instancetype)femaleIconWithSize:(CGFloat)size; + (instancetype)maleIconWithSize:(CGFloat)size; + (instancetype)gittipIconWithSize:(CGFloat)size; + (instancetype)sunOIconWithSize:(CGFloat)size; + (instancetype)moonOIconWithSize:(CGFloat)size; + (instancetype)archiveIconWithSize:(CGFloat)size; + (instancetype)bugIconWithSize:(CGFloat)size; + (instancetype)vkIconWithSize:(CGFloat)size; + (instancetype)weiboIconWithSize:(CGFloat)size; + (instancetype)renrenIconWithSize:(CGFloat)size; + (instancetype)pagelinesIconWithSize:(CGFloat)size; + (instancetype)stackExchangeIconWithSize:(CGFloat)size; + (instancetype)arrowCircleORightIconWithSize:(CGFloat)size; + (instancetype)arrowCircleOLeftIconWithSize:(CGFloat)size; + (instancetype)caretSquareOLeftIconWithSize:(CGFloat)size; + (instancetype)dotCircleOIconWithSize:(CGFloat)size; + (instancetype)wheelchairIconWithSize:(CGFloat)size; + (instancetype)vimeoSquareIconWithSize:(CGFloat)size; + (instancetype)tryIconWithSize:(CGFloat)size; + (instancetype)plusSquareOIconWithSize:(CGFloat)size; @end
export default function (config: any, extName: string, version: string): string { return ` /*ext-${extName}-start*/ /*ext.${extName}.ver.${version}*/ class Live2d { live2dWrapper = undefined; // live2d html最外层节点div live2dIframe = undefined; // live2d 的具体 iframe页面 anchorCore = 'br'; // live2d div 定位依赖,初始默认为右下角, 一共有四个情况: tl,tr,bl,br KEY = 'live2d-asoul-config'; // 用于localstorage存储信息的key constructor() { // 添加postmessage事件监听 const receiveMessage = (event) => { const origin = event.origin || event.originalEvent.origin; if (origin !== "vscode-webview://webviewview-vscode-live2d-live2dview" && !origin.startsWith('vscode-webview://')) return; const { type, data } = event?.data || {}; if(type) switch (type) { case 'live2d-asoul-openAutoLodash': this.saveConfig({ autoLodash: true }); break; case 'live2d-asoul-closeAutoLodash': this.saveConfig({ autoLodash: false }); break; case 'live2d-asoul-lodash': this.createLive2d(); break; case 'live2d-asoul-close': this.deleteLive2d(); break; case 'live2d-asoul-setAnchor': this.anchor = data; break; case 'live2d-asoul-resetPosition': this.resetPosition(); break; case 'live2d-asoul-saveCurrentConfig': this.saveCurrentConfig(); break; case 'live2d-asoul-saveBackground': this.saveBackground(); break; case 'live2d-asoul-loadBackground': this.loadBackground(); break; case 'live2d-asoul-openBackgroundSetTime': this.openBackgroundSetTime(data); break; case 'live2d-asoul-closeBackgroundSetTime': this.closeBackgroundSetTime(); break; case 'live2d-asoul-modifyBackgroundConfig': this.modifyBackgroundConfig(data); break; case 'live2d-asoul-downloadBackground': event.source.postMessage({type: 'live2d-asoul-initDownloadBackground', data: this.live2dIframe?.contentWindow?.currentImgs }, origin); break; default: break; } } window.addEventListener('message', receiveMessage, false); // 从localstorage中获取配置信息,进行对应处理 const config = this.getConfig(); if (config.autoLodash === true) this.createLive2d(); this.anchor = config.anchor; } get anchor() { return this.anchorCore; } set anchor(value) { if (['tl', 'tr', 'bl', 'br'].includes(value)) { this.anchorCore = value; this.saveConfig({anchor: value}); this.resetLocationDependency(this.live2dWrapper, value); // 恢复目标定位依赖 } } // 会进行校验,最多只允许创建一个 createLive2d = () => { // if (document.getElementById('live2d-wrapper')) // return; if (this.live2dWrapper) { document.body.appendChild(this.live2dWrapper); return; } this.live2dWrapper = document.createElement('div'); this.live2dWrapper.id = 'live2d-wrapper'; Object.assign(this.live2dWrapper.style, this.getConfig().style); // 显示iframe, live2d const iframe = this.initIframe(); if (!iframe) return; this.live2dIframe = iframe; this.live2dWrapper.appendChild(iframe); // 控制按钮 const controlBar = this.initControlBar(this.live2dWrapper); controlBar && this.live2dWrapper.appendChild(controlBar); this.addWrapperStyle(); document.body.appendChild(this.live2dWrapper); } // 只是将 live2dWrapper 整个节点从body移除,依旧存在内存中,因为还存在事件的引用 deleteLive2d = () => { if (this.live2dWrapper) { this.live2dWrapper.remove(); // this.live2dWrapper = undefined; } } // 外壳wrapper基础样式 addWrapperStyle = () => { let styleNode = document.createElement('style'); let styleContent = \` div#live2d-wrapper { width: 280px; height: 300px; position: fixed; bottom: 50px; right: 50px; z-index: 100; } .live2d-wrapper-controller-wrapper { pointer-events:auto; position: absolute; right: 1px; top: 2px; display:flex; opacity: 0; transition: all 0.2s; } div#live2d-wrapper:hover .live2d-wrapper-controller-wrapper { opacity: 1; } .live2d-wrapper-controller-icon { width:16px; height:16px; cursor: pointer; transition: all 0.3s; } .live2d-wrapper-controller-icon:hover { width:20px; height:20px; } .live2d-wrapper-controller-corner { width: 10px; height: 10px; background-color: #faa; position: absolute; } \`; styleNode.appendChild(document.createTextNode(styleContent)) document.head.appendChild(styleNode); } // iframe, 初始化具体live2d的页面 initIframe = () => { const str = window.location.href; if (!str.includes('workbench.html')) return const iframe = document.createElement('iframe'); iframe.style.cssText = 'width:100%; height:100%; border:0;'; iframe.src = str.replace('workbench.html', 'live2d/index.html'); return iframe; } // 控制图标,三个图标 调整大小,点击穿透,拖拽位置 initControlBar = (container) => { const controlEles = document.createElement('div'); controlEles.classList.add("live2d-wrapper-controller-wrapper"); const borderIconDiv = document.createElement('div'); borderIconDiv.title = '调整大小'; const borderIcon = document.createElement('img'); borderIcon.src = 'https://s3.bmp.ovh/imgs/2021/10/c87f9f3d038d2598.png'; borderIcon.classList.add("live2d-wrapper-controller-icon"); borderIcon.addEventListener('click', (() => { let hasBorder = false; let corners; return () => { hasBorder = !hasBorder; if (hasBorder) corners = this.addBorderCorner(container, corners); else corners.forEach(ele => ele.remove()); // container.style.border = hasBorder ? 'solid 4px white' : '0'; } })()); borderIconDiv.appendChild(borderIcon); controlEles.appendChild(borderIconDiv); const penetrateIconDiv = document.createElement('div'); penetrateIconDiv.title = '是否允许点击穿透'; penetrateIconDiv.style.cssText = 'margin: 0 6px;'; const penetrateIcon = document.createElement('img'); penetrateIcon.src = 'https://s3.bmp.ovh/imgs/2021/10/aa5c35f26d1541b8.png'; penetrateIcon.classList.add("live2d-wrapper-controller-icon"); penetrateIcon.addEventListener('click', (() => { let isPenetrate = false; return () => { isPenetrate = !isPenetrate; controlEles.style.opacity = isPenetrate ? '1' : ''; container.style.pointerEvents = isPenetrate ? 'none' : 'auto'; } })()); penetrateIconDiv.appendChild(penetrateIcon); controlEles.appendChild(penetrateIconDiv); const dragIconDiv = document.createElement('div'); dragIconDiv.title = '鼠标按住拖拽移动'; const dragIcon = document.createElement('img'); dragIcon.src = 'https://s3.bmp.ovh/imgs/2021/10/9e34525e8e70acd8.png'; dragIcon.classList.add("live2d-wrapper-controller-icon"); document.addEventListener("mousedown", e => { // 这里过滤掉非目标元素 if (e.target !== dragIcon) { return; } const disx = e.pageX - container.offsetLeft;//获取鼠标相对元素距离 const disy = e.pageY - container.offsetTop; // 防止鼠标移动到iframe上,使得鼠标移动事件丢失 const iframe = container.getElementsByTagName('iframe')[0]; iframe && (iframe.style.pointerEvents = 'none'); const handleMove = (event) => { container.style.left = event.pageX - disx + 'px'; container.style.top = event.pageY - disy + 'px'; }; const tempMouseUp = () => { iframe && (iframe.style.pointerEvents = 'inherit'); this.resetLocationDependency(container, this.anchor); // 恢复目标定位依赖 document.removeEventListener("mousemove", handleMove); document.removeEventListener("mouseup", tempMouseUp); } document.addEventListener("mousemove", handleMove); document.addEventListener("mouseup", tempMouseUp); e.preventDefault();//阻止浏览器的默认事件 }); dragIconDiv.appendChild(dragIcon); controlEles.appendChild(dragIconDiv); return controlEles; } // 初始化4个角落点,用于后续拖拽缩放大小 initCorner = () => { // 来4个元素 const eles = Array.from({ length: 4 }).map(() => document.createElement("div") ); eles.forEach(x => x.classList.add("live2d-wrapper-controller-corner")); // 分别在topleft、topright、bottomleft、bottomright位置 const [tl, tr, bl, br] = eles; // 每一个角都移动半个身位 Object.assign(tl.style, { top: "-5px", left: "-5px", cursor: "nw-resize" }); Object.assign(tr.style, { top: "-5px", cursor: "ne-resize", right: "-5px" }); Object.assign(bl.style, { bottom: "-5px", cursor: "sw-resize", left: "-5px" }); Object.assign(br.style, { bottom: "-5px", cursor: "se-resize", right: "-5px" }); return { eles }; } // 给4个角落点挂载事件 drag = (ele, container, type) => { if (!type) return; document.addEventListener("mousedown", e => { // 这里过滤掉非目标元素 if (e.target !== ele) { return; } const { width, height } = container.getBoundingClientRect(); // 固定container元素,以使不同定位角可以拉动, 因为是对角拖拽,所以需要用对角定位 const antiType = (type[0] == 't' ? 'b' : 't') + (type[1] == 'l' ? 'r' : 'l'); this.resetLocationDependency(container, antiType); // 防止鼠标移动到iframe上,使得鼠标移动事件丢失 const iframe = container.getElementsByTagName('iframe')[0]; iframe && (iframe.style.pointerEvents = 'none'); const disx = e.pageX;//获取鼠标相对元素距离 const disy = e.pageY; let factorWidth = (type === 'tl' || type === 'bl') ? -1 : 1; let factorHeight = (type === 'tl' || type === 'tr') ? -1 : 1; const Live2dResize = (event) => { const newWidth = width + (event.pageX - disx) * factorWidth; const newHeight = height + (event.pageY - disy) * factorHeight; // 最小宽高 if (newWidth >= 75) container.style.width = newWidth + 'px'; if (newHeight >= 75) container.style.height = newHeight + 'px'; }; const tempMouseUp = () => { iframe && (iframe.style.pointerEvents = 'inherit'); this.resetLocationDependency(container, this.anchor); // 恢复目标定位依赖 document.removeEventListener("mousemove", Live2dResize); document.removeEventListener("mouseup", tempMouseUp); } document.addEventListener("mousemove", Live2dResize); document.addEventListener("mouseup", tempMouseUp); e.preventDefault();//阻止浏览器的默认事件 }); } addBorderCorner = (target, corners) => { if (!target) return; // 获取四个角——eles if (!corners) { const { eles } = this.initCorner(); const [tl, tr, bl, br] = eles; target.appendChild(tl); this.drag(tl, target, 'tl'); target.appendChild(tr); this.drag(tr, target, 'tr'); target.appendChild(bl); this.drag(bl, target, 'bl'); target.appendChild(br); this.drag(br, target, 'br'); return eles; } else { corners.forEach(ele => target.appendChild(ele)); return corners; } } // 重置元素对于某个角落的定位, target目标元素 , type定位角落 resetLocationDependency = (target, type) => { if (target && type) { const { top, bottom, left, right } = target.getBoundingClientRect(); const pageWidth = document.documentElement.clientWidth; const pageHeight = document.documentElement.clientHeight; if (type === 'tl') { target.style.top = top + 'px'; target.style.left = left + 'px'; target.style.right = ''; target.style.bottom = ''; } else if (type === 'tr') { target.style.top = top + 'px'; target.style.left = ''; target.style.right = pageWidth - right + 'px'; target.style.bottom = ''; } else if (type === 'bl') { target.style.top = ''; target.style.left = left + 'px'; target.style.right = ''; target.style.bottom = pageHeight - bottom + 'px'; } else if (type === 'br') { target.style.top = ''; target.style.left = ''; target.style.right = pageWidth - right + 'px'; target.style.bottom = pageHeight - bottom + 'px'; } } } resetPosition = () => { if (this.live2dWrapper) { const style = this.live2dWrapper.style; style.top = ''; style.right = ''; style.bottom = ''; style.left = ''; style.width = ''; style.height = ''; } } saveCurrentConfig = () => { if (this.live2dWrapper) { const { top, right, bottom, left, width, height } = this.live2dWrapper.style; const style = { top, right, bottom, left, width, height }; this.saveConfig({ style }) } } saveConfig = (newData) => { const str = localStorage.getItem(this.KEY); const data = str ? JSON.parse(str) : { autoLodash: false, anchor: 'br', style: {} }; localStorage.setItem(this.KEY, JSON.stringify({ ...data, ...newData })); } getConfig = () => { const str = localStorage.getItem(this.KEY); return str ? JSON.parse(str) : { autoLodash: false, anchor: 'br', style: {} }; } saveBackground = () => { const fn = this.live2dIframe?.contentWindow?.saveBackground; fn && fn(); } loadBackground = () => { const fn = this.live2dIframe?.contentWindow?.loadBackground; fn && fn(); } openBackgroundSetTime = (time) => { const fn = this.live2dIframe?.contentWindow?.openBackgroundSetTime; fn && fn(time); } closeBackgroundSetTime = () => { const fn = this.live2dIframe?.contentWindow?.closeBackgroundSetTime; fn && fn(); } modifyBackgroundConfig = (config) => { const fn = this.live2dIframe?.contentWindow?.modifyBackgroundConfig; fn && fn(config); } } let live2dInstance = new Live2d(); /*ext-${extName}-end*/ `; }
#ifndef COMMON_PUBLIC_GENERATOR_H__ #define COMMON_PUBLIC_GENERATOR_H__ #include "for_each_macros.h" #include "iterator.h" // Derived from: https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html // Design: // - Provide a type-safe iterator // - Define an EOF symbol // - Use a stateful structure, declare variables // - Creates a factory function as well, with initial parameters? // - Instantiate parameters through ITERATOR_BEGIN #define GENERATOR_DEFINE_MEMBER(T, x) T x; #define GENERATOR_LOAD_STATE(T, x) T x = iter->x; #define GENERATOR_SAVE_STATE(T, x) iter->x = x; #define DECLARE_GENERATOR(T, name) \ typedef struct name##Generator name##Generator;\ name##Generator *name##Generator_alloc(void);\ void name##Generator_free(name##Generator *gen);\ bool name##Generator_eof(name##Generator *iter);\ T name(name##Generator *iter); #define DEFINE_GENERATOR(T, name, ...) \ struct name##Generator {\ int state;\ bool eof;\ T current;\ T eof_val;\ DFOR_EACH(GENERATOR_DEFINE_MEMBER, __VA_ARGS__)\ };\ typedef struct name##Generator name##Generator;\ name##Generator *name##Generator_alloc(void) {\ return calloc(1, sizeof(name##Generator));\ }\ void name##Generator_free(name##Generator *gen) {\ free(gen);\ }\ bool name##Generator_eof(name##Generator *iter) {\ return iter->eof;\ }\ T name(name##Generator *iter) {\ T eof;\ DFOR_EACH(GENERATOR_LOAD_STATE, __VA_ARGS__)\ goto branch_label;\ yield_label:\ DFOR_EACH(GENERATOR_SAVE_STATE, __VA_ARGS__)\ iter->eof_val = eof;\ return iter->current;\ branch_label:\ switch (iter->state) { case 0: do{} while(0); #define yield(x) \ do { iter->state = __LINE__; iter->current = (x); goto yield_label; case __LINE__:; } while (0); #define yield_eof }} iter->eof = true; return eof; #endif // COMMON_PUBLIC_GENERATOR_H__
import { NextPage } from 'next'; const Index: NextPage = () => ( <> <h1>Player screen</h1> </> ); export default Index;
#!/usr/bin/env bash #clone latest branch if [ ! -d build ]; then mkdir build fi if [ ! -d release ]; then mkdir release fi cd release if [ ! -d ringcentral-integration ]; then echo "Clone release branch..." git clone "https://$RELEASE_USER:$RELEASE_TOKEN@github.com/$REPO" -b commons-release ringcentral-integration &> /dev/null fi cd ../ echo "start release build" lerna run release --scope ringcentral-integration --stream
#!/bin/bash counter=10 while [ $counter -gt 0 ]; do echo "Loop number: $((counter--))" done
#!/bin/bash # example script of running SED fits on the spectra and photometry # # python run/mini_mocha.py data sim i0 i1 noise method model nthread nwalker burnin niter maxiter overwrite postprocess # args: # 1. data: 'photo'=photometry, 'specphoto'=spectra + photometry # 2. sim: specify simulation 'lgal' # 3. i0: first galaxy index # 4. i1: last galaxy index # 5. noise: 'legacy' for photometry; 'bgs0_legacy' for specphoto # 6. method: SED fitting method 'ispeculator' # 7. model: specify model 'emulator' # 8. nthread: number of cpu # 9. nwalker: nubmer of walkers in MCMC # 10. burnin: number of iterations for burnin # 11. niter: number of iterations. If niter='adaptive' then it uses an # adaptive method. # 12. maxiter: max number of iterations for MCMC # 13. overwrite: True/False overwrite MCMC file. # 14. postprocess: True/False calculate SFR, MW Z from parameters. dir="$(dirname "$0")" # SED fitting for photometry python -W ignore $dir/mini_mocha.py photo lgal 0 0 legacy ispeculator emulator 1 20 200 adaptive 3000 True False # SED fitting for spectra + photometry python -W ignore $dir/mini_mocha.py specphoto lgal 0 0 bg0_legacy ispeculator emulator 1 20 200 adaptive 3000 True False # postprocess the chains generated above python -W ignore $dir/mini_mocha.py photo lgal 0 0 legacy ispeculator emulator 1 20 200 adaptive 3000 False True python -W ignore $dir/mini_mocha.py specphoto lgal 0 0 bg0_legacy ispeculator emulator 1 20 200 adaptive 3000 False True
#!/bin/bash # Copyright (c) 2013, Ruslan Baratov # All rights reserved. [ "$#" == "4" ] || { echo "usage: $0 <build-dir> <lib> <dir> <install-dir>"; exit 1; } BUILD_DIR="$1" LIBNAME="$2" DIRNAME="$3" INSTALL_DIR="$4" COMMON_DIR="${BUILD_DIR}/bin.v2/libs/${DIRNAME}/build" if [[ -d "${COMMON_DIR}/darwin-iphoneos/debug" ]] then IPHONE_DEBUG=`find "${COMMON_DIR}/darwin-iphoneos/debug" -name "libboost_${LIBNAME}[^_]*.a"` fi if [[ -d "${COMMON_DIR}/darwin-iphoneos/release" ]] then IPHONE_RELEASE=`find "${COMMON_DIR}/darwin-iphoneos/release" -name "libboost_${LIBNAME}[^_]*.a"` fi if [[ -d "${COMMON_DIR}/darwin-iphonesimulator/debug" ]] then SIM_DEBUG=`find "${COMMON_DIR}/darwin-iphonesimulator/debug" -name "libboost_${LIBNAME}[^_]*.a"` fi if [[ -d "${COMMON_DIR}/darwin-iphonesimulator/release" ]] then SIM_RELEASE=`find "${COMMON_DIR}/darwin-iphonesimulator/release" -name "libboost_${LIBNAME}[^_]*.a"` fi echo "-- [iOS universal] IPHONE_DEBUG: $IPHONE_DEBUG" echo "-- [iOS universal] IPHONE_RELEASE: $IPHONE_RELEASE" echo "-- [iOS universal] ISIM_DEBUG: $SIM_DEBUG" echo "-- [iOS universal] ISIM_RELEASE: $SIM_RELEASE" if [[ -f "${SIM_DEBUG}" ]] then DEBUG=`basename ${SIM_DEBUG}` else DEBUG=`basename ${IPHONE_DEBUG}` fi if [[ -f "${SIM_RELEASE}" ]] then RELEASE=`basename ${SIM_RELEASE}` else RELEASE=`basename ${IPHONE_RELEASE}` fi function lipo_create { iphone=$1 sim=$2 dst=$3 if [[ -f "${iphone}" || -f "${sim}" ]] then if [[ -f "${iphone}" && -f "${sim}" ]] then lipo -create "${iphone}" "${sim}" -o "${dst}" else if [[ -f "${iphone}" ]] then cp "${iphone}" "${dst}" fi if [[ -f "${sim}" ]] then cp "${sim}" "${dst}" fi fi fi } lipo_create "${IPHONE_DEBUG}" "${SIM_DEBUG}" "${INSTALL_DIR}/${DEBUG}" lipo_create "${IPHONE_RELEASE}" "${SIM_RELEASE}" "${INSTALL_DIR}/${RELEASE}" echo "-- [iOS universal] Done: ${INSTALL_DIR}/{${DEBUG}, ${RELEASE}}"
# Array of formating escape codes declare -A FORMAT FORMAT[nf]="\033[0m" FORMAT[black]="\033[0;30m" FORMAT[red]="\033[0;31m" FORMAT[green]="\033[0;32m" FORMAT[yellow]="\033[0;33m" FORMAT[blue]="\033[0;34m" FORMAT[purple]="\033[0;35m" FORMAT[cyan]="\033[0;36m" FORMAT[lightgrey]="\033[0;37m" FORMAT[darkgrey]="\033[1;30m" FORMAT[lightred]="\033[1;31m" FORMAT[lightgreen]="\033[1;32m" FORMAT[lightyellow]="\033[1;33m" FORMAT[lightblue]="\033[1;34m" FORMAT[lightpurple]="\033[1;35m" FORMAT[lightcyan]="\033[1;36m" FORMAT[white]="\033[1;37m" FORMAT[bold]="\033[1m" FORMAT[dim]="\033[2m" FORMAT[underlined]="\033[4m" FORMAT[notbold]="\033[21m" FORMAT[notdim]="\033[22m" FORMAT[notunderlined]="\033[24m"
<reponame>roscopecoltran/dataflowk<filename>robotstxt/logger.go package robotstxt import ( "log" "os" ) var logger *log.Logger func init() { logger = log.New(os.Stdout, "RobotsTxt: ", log.Lshortfile) }
<gh_stars>1-10 module PoolParty module Resources =begin rdoc == Mount The mount specifies a mount that is to be mounted on the instances == Usage has_mount(:name => '...') do # More options. # This block is optional end == Options * <tt>name</tt> The location of the mount (default: /data) * <tt>device</tt> The device location for the mount. This mounts at the directory set by the name * <tt>options</tt> The options to be set in the mount file fstab (default: rw,nosuid,noquota) * <tt>fstype</tt> The Type of mount (default: xfs) == Examples has_mount(:name => "/data", :device => "/dev/sda100") =end class Mount < Resource default_options({ :mountpoint => "/data", :remounts => "true", :mount_options => "rw,nosuid,noquota", :fstype => "xfs", :atboot => "yes" }) def disallowed_options [:name] end end end end
<reponame>dcoloma/gaia 'use strict'; var Monitor = require(__dirname + '/monitor.js').Monitor; // Execute the script. var watchList = process.env.WATCH || 'apps,test_apps', monitor = new Monitor(process.cwd(), {'directories': watchList.split(',')}); monitor.watch();
#!/bin/bash #Support for CQHTTP api. Push notification on CoolQ #CQHTTP_TOKEN="" Recommended to be not empty, QQ application token #CQHTTP_USER="" Required, QQ receiver ID #CQHTTP_APIROOT="" Required, CQHTTP Server URL (without slash suffix) #CQHTTP_CUSTOM_MSGHEAD="" Optional, custom message header CQHTTP_APIPATH="/send_private_msg" cqhttp_send() { _subject="$1" _content="$2" _statusCode="$3" #0: success, 1: error 2($RENEW_SKIP): skipped _debug "_statusCode" "$_statusCode" CQHTTP_TOKEN="${CQHTTP_TOKEN:-$(_readaccountconf_mutable CQHTTP_TOKEN)}" if [ -z "$CQHTTP_TOKEN" ]; then CQHTTP_TOKEN="" _info "You didn't specify a CQHTTP application token yet, which is unsafe. Assuming it to be empty." else _saveaccountconf_mutable CQHTTP_TOKEN "$CQHTTP_TOKEN" fi CQHTTP_USER="${CQHTTP_USER:-$(_readaccountconf_mutable CQHTTP_USER)}" if [ -z "$CQHTTP_USER" ]; then CQHTTP_USER="" _err "You didn't specify a QQ user yet." return 1 fi _saveaccountconf_mutable CQHTTP_USER "$CQHTTP_USER" CQHTTP_APIROOT="${CQHTTP_APIROOT:-$(_readaccountconf_mutable CQHTTP_APIROOT)}" if [ -z "$CQHTTP_APIROOT" ]; then CQHTTP_APIROOT="" _err "You didn't specify the API root yet." return 1 fi _saveaccountconf_mutable CQHTTP_APIROOT "$CQHTTP_APIROOT" CQHTTP_CUSTOM_MSGHEAD="${CQHTTP_CUSTOM_MSGHEAD:-$(_readaccountconf_mutable CQHTTP_CUSTOM_MSGHEAD)}" if [ -z "$CQHTTP_CUSTOM_MSGHEAD" ]; then CQHTTP_CUSTOM_MSGHEAD="A message from acme.sh:" else _saveaccountconf_mutable CQHTTP_CUSTOM_MSGHEAD "$CQHTTP_CUSTOM_MSGHEAD" fi _access_token="$(printf "%s" "$CQHTTP_TOKEN" | _url_encode)" _user_id="$(printf "%s" "$CQHTTP_USER" | _url_encode)" _message="$(printf "$CQHTTP_CUSTOM_MSGHEAD %s\\n%s" "$_subject" "$_content" | _url_encode)" _finalUrl="$CQHTTP_APIROOT$CQHTTP_APIPATH?access_token=$_access_token&user_id=$_user_id&message=$_message" response="$(_get "$_finalUrl")" if [ "$?" = "0" ] && _contains "$response" "\"retcode\":0,\"status\":\"ok\""; then _info "QQ send success." return 0 fi _err "QQ send error." _debug "URL" "$_finalUrl" _debug "Response" "$response" return 1 }
#include <unordered_map> class IMetaTypeCreator { // ... (other members and methods) }; class DefinitionManager { private: std::unordered_map<std::string, Context*> definitionManagerContexts_; DefinitionManager* globalDefinitionManager_; std::unique_ptr<IMetaTypeCreator> globalMetaTypeCreator_; public: void registerDefinitions() { for (auto context : definitionManagerContexts_) { context.second->registerDefinitions(); } } void deregisterDefinitions() { for (auto context : definitionManagerContexts_) { context.second->deregisterDefinitions(); } } void globalDeregisterDefinitions() { globalDefinitionManager_->deregisterDefinitions(); } IMetaTypeCreator* getGlobalMetaTypeCreator() { return globalMetaTypeCreator_.get(); } };
package cmd import "github.com/spf13/cobra" var resumeCmd = &cobra.Command{ Use: "resume [ sequence ]", Short: "Resumes the execution of a sequence", } func init() { rootCmd.AddCommand(resumeCmd) }
#!/bin/bash source $(dirname $0)/getopts.sh # Check if build exists. if [ ! -d ${PUBLIC_DIR:-dist} ]; then echo "No build found in ${PUBLIC_DIR:-dist}" exit 0 fi echo "Generating build archive..." # Compress build into .zip file. mkdir -p build zip -r build/$PACKAGE_FILE ${PUBLIC_DIR:-dist} echo -e "Successfully generated archive at $(cyan "$(pwd)/build/$PACKAGE_FILE")"
package cn.springmvc.controller; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Scope("prototype") @Controller @RequestMapping("/logs") public class UserActionLogController { }
<filename>libs/core/src/mutiltenancy/service/mongo-multitenant-config.service.ts import { MongoModuleOptions, MongoOptionsFactory } from '@juicycleff/repo-orm'; import { Inject, Injectable, Scope } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; import { CONTEXT } from '@nestjs/graphql'; import { ConsulDatabaseConfig } from '@ultimatebackend/common'; import { InjectConfig } from '@nestcloud/config'; import { EtcdConfig } from '@nestcloud/config/etcd-config'; import { Metadata } from 'grpc'; import { RequestContextHost } from '@nestjs/microservices/context/request-context-host'; import { TenantDatabaseStrategy, TenantInfo } from '../'; import { RpcException } from '@nestjs/microservices'; import { TenantEntity } from '@ultimatebackend/repository'; @Injectable({ scope: Scope.REQUEST }) export class MongoMultiTenantConfigService implements MongoOptionsFactory { /** * @description All this params are injected * @param request * @param context * @param config */ constructor( @Inject(REQUEST) private readonly request: Request, @Inject(CONTEXT) private readonly context: RequestContextHost, @InjectConfig() private readonly config: EtcdConfig, ) {} createMongoOptions(): Promise<MongoModuleOptions> | MongoModuleOptions { const database = this.config.get<ConsulDatabaseConfig>('database'); const metadata: Metadata = this.context.getContext(); const gmap = metadata.getMap(); let tenantInfo: TenantInfo = null; let tenant: TenantEntity = null; if (gmap['x-tenant-info']) { tenantInfo = JSON.parse(gmap['x-tenant-info'] as string); } if (gmap['x-tenant']) { tenant = JSON.parse(gmap['x-tenant'] as string); } const uriWithName = database.mongodb.uri.endsWith('/') ? `${database.mongodb.uri}${database.mongodb.name}${database.mongodb.options}` : `${database.mongodb.uri}/${database.mongodb.name}${database.mongodb.options}`; /** * This block of code is the default config if for some reason, the req object is empty */ if (tenantInfo === null || !tenantInfo.config.enabled) { return { uri: uriWithName, dbName: database.mongodb.name, clientOptions: { useNewUrlParser: true, useUnifiedTopology: true, }, }; } if (!tenantInfo.tenantId) { throw new RpcException('Tenant name must be provided'); } /** * We resolve a valid Mongo connection string */ let uri = database.mongodb.uri; // Set database Url const appConString = this.resolveMongoUriString( database.mongodb.uri, tenantInfo.tenantId, database.mongodb.options); let databaseName = database.mongodb.name; /** * Applying the right connection string for DatabaseIsolation database strategy */ if (tenantInfo.config.databaseStrategy === TenantDatabaseStrategy.DatabaseIsolation) { databaseName = 'tenant-' + tenantInfo.tenantId; if (tenant && tenant?.settings?.database?.host) { uri = tenant?.settings?.database?.host; } else { uri = appConString; } } /** * Applying the right connection string for both DatabaseIsolation and DataIsolation database strategy */ if (tenantInfo.config.databaseStrategy === TenantDatabaseStrategy.Both) { if (tenant && tenant?.settings?.database?.host) { databaseName = 'tenant-' + tenantInfo.tenantId; uri = tenant?.settings?.database?.host || appConString; } else { databaseName = database.mongodb.name; uri = uriWithName; } } /** * Applying the right connection string for DataIsolation database strategy */ if (tenantInfo.config.databaseStrategy === TenantDatabaseStrategy.DataIsolation) { databaseName = database.mongodb.name; uri = this.resolveMongoUriString(database.mongodb.uri, database.mongodb.name, database.mongodb.options); } /** * Return the final db configuration to the module */ return { uri, dbName: databaseName, clientOptions: { useNewUrlParser: true, useUnifiedTopology: true, }, tenantName: tenantInfo.tenantId ?? '*', }; } /** * @description Generates correct mongo uri string * @param uri * @param databaseName * @param replicaName */ private resolveMongoUriString(uri: string, databaseName: string, replicaName: string = null): string { if (uri === null || databaseName === null) { throw new RpcException('A missing database uri and name in a multi tenant service'); } if (uri === undefined || databaseName === undefined) { throw new RpcException('A missing database uri and a name in multi tenant service'); } return uri.endsWith('/') ? `${uri}${databaseName}${replicaName ? '?replicaSet=' + replicaName : ''}` : `${uri}/${databaseName}${replicaName ? '?replicaSet=' + replicaName : ''}`; } }
#include <iostream> #include <set> void process_packet(std::set<int>& pending_acks, int pkt_channel) { pending_acks.insert(pkt_channel); #if DEBUG_LINK std::cout << "Received pkt on channel " << pkt_channel << std::endl; #endif }
<gh_stars>10-100 package com.hapramp.ui.activity; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import com.hapramp.R; import com.hapramp.analytics.AnalyticsParams; import com.hapramp.analytics.EventReporter; import com.hapramp.models.CommunityModel; import com.hapramp.preferences.HaprampPreferenceManager; import com.hapramp.steem.CommunityListWrapper; import com.hapramp.ui.callbacks.communityselection.CommunitySelectionPageCallback; import com.hapramp.utils.CrashReporterKeys; import com.hapramp.viewmodel.communityselectionpage.CommunitySelectionPageViewModel; import com.hapramp.views.CommunitySelectionView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /* * This activity is responsible for community selection by user. * Activity is opened when User has not selected this earlier. * LoginActivity gets all the relevant about user after successful login. * After which decisions are taken. * */ public class CommunitySelectionActivity extends BaseActivity implements CommunitySelectionPageCallback, CommunitySelectionView.CommunitySelectionListener { public static final String EXTRA_PRESELECTED_MODE = "preselected_mode"; @BindView(R.id.action_bar_title) TextView actionBarTitle; @BindView(R.id.communitySelectionView) CommunitySelectionView communitySelectionView; @BindView(R.id.toolbar_drop_shadow) FrameLayout toolbarDropShadow; @BindView(R.id.communityContinueButton) TextView communityContinueButton; @BindView(R.id.communityLoadingProgressBar) ProgressBar communityLoadingProgressBar; @BindView(R.id.backBtn) ImageView backBtn; private CommunitySelectionPageViewModel communitySelectionPageViewModel; @Override protected void onStart() { super.onStart(); EventReporter.addEvent(AnalyticsParams.SCREEN_COMMUNITY); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_community_selection); ButterKnife.bind(this); boolean editable = getIntent().getBooleanExtra(EXTRA_PRESELECTED_MODE, false); setMode(editable); init(false); } private void setMode(boolean editable) { String userSelectedCommunity = HaprampPreferenceManager.getInstance(). getUserSelectedCommunityAsJson(); if (userSelectedCommunity.length() > 0) { CommunityListWrapper cwr = new Gson().fromJson(HaprampPreferenceManager.getInstance(). getUserSelectedCommunityAsJson(), CommunityListWrapper.class); if (cwr != null) { if (cwr.getCommunityModels().size() > 0) { if (!editable) { navigateToHome(); return; } } } } init(editable); } private void navigateToHome() { Intent i = new Intent(this, HomeActivity.class); startActivity(i); finish(); } private void init(final boolean editable) { communitySelectionView.setCommunitySelectionListener(this); communitySelectionPageViewModel = ViewModelProviders.of(this).get(CommunitySelectionPageViewModel.class); communitySelectionPageViewModel.getCommunities(this) .observe(this, new Observer<List<CommunityModel>>() { @Override public void onChanged(@Nullable List<CommunityModel> communityModels) { if (editable) { CommunityListWrapper cwr = new Gson().fromJson(HaprampPreferenceManager.getInstance(). getUserSelectedCommunityAsJson(), CommunityListWrapper.class); communitySelectionView.setCommunityList(communityModels, cwr.getCommunityModels()); } else { communitySelectionView.setCommunityList(communityModels); } if (communityLoadingProgressBar != null) { communityLoadingProgressBar.setVisibility(View.GONE); } HaprampPreferenceManager.getInstance() .saveAllCommunityListAsJson(new Gson().toJson(new CommunityListWrapper(communityModels))); } }); communityContinueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProgressDialog(getString(R.string.community_save_progress_mesaage), true); communitySelectionPageViewModel.updateServer(communitySelectionView.getSelectionList()); } }); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } @Override public void onCommunityFetchFailed() { toast(getString(R.string.failed_to_fetch_communities)); } @Override public void onCommunityUpdated(List<CommunityModel> selectedCommunities) { showProgressDialog("", false); toast(getString(R.string.community_updated)); HaprampPreferenceManager.getInstance() .saveUserSelectedCommunitiesAsJson(new Gson().toJson(new CommunityListWrapper(selectedCommunities))); navigateToHome(); } @Override public void onCommunityUpdateFailed() { showProgressDialog("", false); toast(getString(R.string.failed_to_update_communities)); } @Override public void onCommunitySelectionChanged(List<Integer> selections) { communityContinueButton.setEnabled(selections.size() > 0); } }
import { Component, Input } from '@angular/core'; @Component({ selector: 'herospace', directives: [], pipes: [], styles: [require('./herospace.scss')], template: require('./herospace.html') }) export class Herospace {}
import plotly.graph_objects as go from numpy import argmin from ..parameters import MOVEMENT_SYMBOL, MOVEMENT_LINE, FINGER_COLOR def plot_dataglove(tsv, events, mov=None): traces = [] i = 0 for finger, color in FINGER_COLOR.items(): traces.append( go.Scatter( x=tsv['time'], y=tsv[finger] - i, name=finger, line=dict( color=color, width=1, ), )) i += 1 if mov is not None: y, circle_color, symbol = _plot_movements(mov, tsv) traces.append( go.Scatter( x=mov['onset'], y=y, mode='markers', marker=dict( color=circle_color, size=10, symbol=symbol, ), )) fig = go.Figure( traces, layout=go.Layout( showlegend=False, xaxis=dict( title='time (s)', ), yaxis=dict( tickvals=[.5, -.5, -1.5, -2.5, -3.5], ticktext=list(FINGER_COLOR), ) )) for ev in events: tt = ev['trial_type'] if tt == 'n/a': continue finger, movement = tt.split(' ')[:2] if finger not in FINGER_COLOR: continue fig.add_shape( dict( type="line", x0=ev['onset'], x1=ev['onset'], xref="x", yref="paper", y0=0, y1=1, line=dict( color=FINGER_COLOR[finger], width=1, dash=MOVEMENT_LINE[movement], ) )) return fig def _plot_movements(mov, tsv): y = [] circle_color = [] symbol = [] for m in mov: finger, action = m['trial_type'].split() i_min = argmin(abs(m['onset'] - tsv['time'])) y.append( (tsv[finger] - list(FINGER_COLOR).index(finger))[i_min] ) circle_color.append( FINGER_COLOR[finger] ) symbol.append(MOVEMENT_SYMBOL[action]) return y, circle_color, symbol
#!/bin/bash set -x API_FILES=("docs/api/paddle") for API_FILE in ${API_FILES[*]}; do API_CHANGE=`git diff --name-only upstream/$BRANCH | grep "${API_FILE}"` if [ "${API_CHANGE}" ];then set +x approval_line=`curl -H "Authorization: token ${GITHUB_API_TOKEN}" https://api.github.com/repos/PaddlePaddle/docs/pulls/${GIT_PR_ID}/reviews?per_page=10000` set -x if [ "${API_FILE}" == "docs/api/paddle" ];then APPROVALS=`echo ${approval_line} | python ./check_pr_approval.py 1 29231 23093488 11935832 39876205` fi fi if [ "${APPROVALS}" == "FALSE" ]; then if [ "${API_FILE}" == "docs/api/paddle" ];then set +x echo "==========================================================================================" echo "You must have one TPM (jzhang533/ZhangJun or dingjiaweiww/DingJiaWei or TCChenlong/ChenLong or Ligoml/LiMengLiu) approval for the api change! ${API_FILE} for the management reason of API interface and API document." echo "==========================================================================================" set -x fi exit 1 fi done
#!/bin/sh # =================================================================================== # Generic startup script for running arbitrary Java applications with # being optimized for running in containers # # Usage: # # Execute a Java app: # ./run-java.sh <args given to Java code> # # # Get options which can be used for invoking Java apps like Maven or Tomcat # ./run-java.sh options [....] # # # This script will pick up either a 'fat' jar which can be run with "-jar" # or you can sepcify a JAVA_MAIN_CLASS. # # Source and Documentation can be found # at https://github.com/fabric8io-images/run-java-sh # # Env-variables evaluated in this script: # # JAVA_OPTIONS: Checked for already set options # JAVA_MAX_MEM_RATIO: Ratio use to calculate a default maximum Memory, in percent. # E.g. the "50" value implies that 50% of the Memory # given to the container is used as the maximum heap memory with # '-Xmx'. # It defaults to "25" when the maximum amount of memory available # to the container is below 300M, otherwise defaults to "50". # It is a heuristic and should be better backed up with real # experiments and measurements. # For a good overviews what tuning options are available --> # https://youtu.be/Vt4G-pHXfs4 # https://www.youtube.com/watch?v=w1rZOY5gbvk # https://vimeo.com/album/4133413/video/181900266 # Also note that heap is only a small portion of the memory used by a JVM. There are lot # of other memory areas (metadata, thread, code cache, ...) which addes to the overall # size. When your container gets killed because of an OOM, then you should tune # the absolute values. # JAVA_INIT_MEM_RATIO: Ratio use to calculate a default intial heap memory, in percent. # By default this value is not set. # # The following variables are exposed to your Java application: # # CONTAINER_MAX_MEMORY: Max memory for the container (if running within a container) # MAX_CORE_LIMIT: Number of cores available for the container (if running within a container) # ========================================================== # Fail on a single failed command in a pipeline (if supported) (set -o | grep -q pipefail) && set -o pipefail # Fail on error and undefined vars set -eu # Save global script args ARGS="$@" # ksh is different for defining local vars if [ -n "${KSH_VERSION:-}" ]; then alias local=typeset fi # Error is indicated with a prefix in the return value check_error() { local error_msg="$1" if echo "${error_msg}" | grep -q "^ERROR:"; then echo "${error_msg}" exit 1 fi } # The full qualified directory where this script is located in script_dir() { # Default is current directory local dir=$(dirname "$0") local full_dir=$(cd "${dir}" && pwd) echo ${full_dir} } # Try hard to find a sane default jar-file auto_detect_jar_file() { local dir="$1" # Filter out temporary jars from the shade plugin which start with 'original-' local old_dir="$(pwd)" cd ${dir} if [ $? = 0 ]; then # NB: Find both (single) JAR *or* WAR <https://github.com/fabric8io-images/run-java-sh/issues/79> local nr_jars="$(ls 2>/dev/null | grep -e '.*\.jar$' -e '.*\.war$' | grep -v '^original-' | wc -l | awk '{print $1}')" if [ "${nr_jars}" = 1 ]; then ls 2>/dev/null | grep -e '.*\.jar$' -e '.*\.war$' | grep -v '^original-' exit 0 fi cd "${old_dir}" echo "ERROR: Neither JAVA_MAIN_CLASS nor JAVA_APP_JAR is set and ${nr_jars} found in ${dir} (1 expected)" else echo "ERROR: No directory ${dir} found for auto detection" fi } # Check directories (arg 2...n) for a jar file (arg 1) find_jar_file() { local jar="$1" shift; # Absolute path check if jar specifies an absolute path if [ "${jar}" != ${jar#/} ]; then if [ -f "${jar}" ]; then echo "${jar}" else echo "ERROR: No such file ${jar}" fi else for dir in $*; do if [ -f "${dir}/$jar" ]; then echo "${dir}/$jar" return fi done echo "ERROR: No ${jar} found in $*" fi } # Generic formula evaluation based on awk calc() { local formula="$1" shift echo "$@" | awk ' function ceil(x) { return x % 1 ? int(x) + 1 : x } function log2(x) { return log(x)/log(2) } function max2(x, y) { return x > y ? x : y } function round(x) { return int(x + 0.5) } {print '"int(${formula})"'} ' } # Based on the cgroup limits, figure out the max number of core we should utilize core_limit() { local cpu_period_file="/sys/fs/cgroup/cpu/cpu.cfs_period_us" local cpu_quota_file="/sys/fs/cgroup/cpu/cpu.cfs_quota_us" if [ -r "${cpu_period_file}" ]; then local cpu_period="$(cat ${cpu_period_file})" if [ -r "${cpu_quota_file}" ]; then local cpu_quota="$(cat ${cpu_quota_file})" # cfs_quota_us == -1 --> no restrictions if [ ${cpu_quota:-0} -ne -1 ]; then echo $(calc 'ceil($1/$2)' "${cpu_quota}" "${cpu_period}") fi fi fi } max_memory() { # High number which is the max limit until which memory is supposed to be # unbounded. local mem_file="/sys/fs/cgroup/memory/memory.limit_in_bytes" if [ -r "${mem_file}" ]; then local max_mem_cgroup="$(cat ${mem_file})" local max_mem_meminfo_kb="$(cat /proc/meminfo | awk '/MemTotal/ {print $2}')" local max_mem_meminfo="$(expr $max_mem_meminfo_kb \* 1024)" if [ ${max_mem_cgroup:-0} != -1 ] && [ ${max_mem_cgroup:-0} -lt ${max_mem_meminfo:-0} ] then echo "${max_mem_cgroup}" fi fi } init_limit_env_vars() { # Read in container limits and export the as environment variables local core_limit="$(core_limit)" if [ -n "${core_limit}" ]; then export CONTAINER_CORE_LIMIT="${core_limit}" fi local mem_limit="$(max_memory)" if [ -n "${mem_limit}" ]; then export CONTAINER_MAX_MEMORY="${mem_limit}" fi } load_env() { local script_dir="$1" # Configuration stuff is read from this file local run_env_sh="run-env.sh" # Load default default config if [ -f "${script_dir}/${run_env_sh}" ]; then . "${script_dir}/${run_env_sh}" fi # Check also $JAVA_APP_DIR. Overrides other defaults # It's valid to set the app dir in the default script JAVA_APP_DIR="${JAVA_APP_DIR:-${script_dir}}" if [ -f "${JAVA_APP_DIR}/${run_env_sh}" ]; then . "${JAVA_APP_DIR}/${run_env_sh}" fi export JAVA_APP_DIR # JAVA_LIB_DIR defaults to JAVA_APP_DIR export JAVA_LIB_DIR="${JAVA_LIB_DIR:-${JAVA_APP_DIR}}" if [ -z "${JAVA_MAIN_CLASS:-}" ] && [ -z "${JAVA_APP_JAR:-}" ]; then JAVA_APP_JAR="$(auto_detect_jar_file ${JAVA_APP_DIR})" check_error "${JAVA_APP_JAR}" fi if [ -n "${JAVA_APP_JAR:-}" ]; then local jar="$(find_jar_file ${JAVA_APP_JAR} ${JAVA_APP_DIR} ${JAVA_LIB_DIR})" check_error "${jar}" export JAVA_APP_JAR="${jar}" else export JAVA_MAIN_CLASS fi } # Check for standard /opt/run-java-options first, fallback to run-java-options in the path if not existing run_java_options() { if [ -f "/opt/run-java-options" ]; then echo "$(. /opt/run-java-options)" else which run-java-options >/dev/null 2>&1 if [ $? = 0 ]; then echo "$(run-java-options)" fi fi } debug_options() { if [ -n "${JAVA_ENABLE_DEBUG:-}" ] || [ -n "${JAVA_DEBUG_ENABLE:-}" ] || [ -n "${JAVA_DEBUG:-}" ]; then local debug_port="${JAVA_DEBUG_PORT:-5005}" local suspend_mode="n" if [ -n "${JAVA_DEBUG_SUSPEND:-}" ]; then if ! echo "${JAVA_DEBUG_SUSPEND}" | grep -q -e '^\(false\|n\|no\|0\)$'; then suspend_mode="y" fi fi echo "-agentlib:jdwp=transport=dt_socket,server=y,suspend=${suspend_mode},address=${debug_port}" fi } # Read in a classpath either from a file with a single line, colon separated # or given line-by-line in separate lines # Arg 1: path to claspath (must exist), optional arg2: application jar, which is stripped from the classpath in # multi line arrangements format_classpath() { local cp_file="$1" local app_jar="${2:-}" local wc_out="$(wc -l $1 2>&1)" if [ $? -ne 0 ]; then echo "Cannot read lines in ${cp_file}: $wc_out" exit 1 fi local nr_lines=$(echo $wc_out | awk '{ print $1 }') if [ ${nr_lines} -gt 1 ]; then local sep="" local classpath="" while read file; do local full_path="${JAVA_LIB_DIR}/${file}" # Don't include app jar if include in list if [ "${app_jar}" != "${full_path}" ]; then classpath="${classpath}${sep}${full_path}" fi sep=":" done < "${cp_file}" echo "${classpath}" else # Supposed to be a single line, colon separated classpath file cat "${cp_file}" fi } # ========================================================================== memory_options() { echo "$(calc_init_memory) $(calc_max_memory)" return } # Check for memory options and set max heap size if needed calc_max_memory() { # Check whether -Xmx is already given in JAVA_OPTIONS if echo "${JAVA_OPTIONS:-}" | grep -q -- "-Xmx"; then return fi if [ -z "${CONTAINER_MAX_MEMORY:-}" ]; then return fi # Check for the 'real memory size' and calculate Xmx from the ratio if [ -n "${JAVA_MAX_MEM_RATIO:-}" ]; then if [ "${JAVA_MAX_MEM_RATIO}" -eq 0 ]; then # Explicitely switched off return fi calc_mem_opt "${CONTAINER_MAX_MEMORY}" "${JAVA_MAX_MEM_RATIO}" "mx" # When JAVA_MAX_MEM_RATIO not set and JVM >= 10 no max_memory elif [ "${JAVA_MAJOR_VERSION:-0}" -ge "10" ]; then return elif [ "${CONTAINER_MAX_MEMORY}" -le 314572800 ]; then # Restore the one-fourth default heap size instead of the one-half below 300MB threshold # See https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size calc_mem_opt "${CONTAINER_MAX_MEMORY}" "25" "mx" else calc_mem_opt "${CONTAINER_MAX_MEMORY}" "50" "mx" fi } # Check for memory options and set initial heap size if requested calc_init_memory() { # Check whether -Xms is already given in JAVA_OPTIONS. if echo "${JAVA_OPTIONS:-}" | grep -q -- "-Xms"; then return fi # Check if value set if [ -z "${JAVA_INIT_MEM_RATIO:-}" ] || [ -z "${CONTAINER_MAX_MEMORY:-}" ] || [ "${JAVA_INIT_MEM_RATIO}" -eq 0 ]; then return fi # Calculate Xms from the ratio given calc_mem_opt "${CONTAINER_MAX_MEMORY}" "${JAVA_INIT_MEM_RATIO}" "ms" } calc_mem_opt() { local max_mem="$1" local fraction="$2" local mem_opt="$3" local val=$(calc 'round($1*$2/100/1048576)' "${max_mem}" "${fraction}") echo "-X${mem_opt}${val}m" } c2_disabled() { if [ -n "${CONTAINER_MAX_MEMORY:-}" ]; then # Disable C2 compiler when container memory <=300MB if [ "${CONTAINER_MAX_MEMORY}" -le 314572800 ]; then echo true return fi fi echo false } jit_options() { if [ "${JAVA_MAJOR_VERSION:-0}" -ge "10" ]; then return fi # Check whether -XX:TieredStopAtLevel is already given in JAVA_OPTIONS if echo "${JAVA_OPTIONS:-}" | grep -q -- "-XX:TieredStopAtLevel"; then return fi if [ $(c2_disabled) = true ]; then echo "-XX:TieredStopAtLevel=1" fi } # Switch on diagnostics except when switched off diagnostics_options() { if [ -n "${JAVA_DIAGNOSTICS:-}" ]; then if [ "${JAVA_MAJOR_VERSION:-0}" -ge "11" ]; then echo "-XX:NativeMemoryTracking=summary -Xlog:gc*:stdout:time -XX:+UnlockDiagnosticVMOptions" else echo "-XX:NativeMemoryTracking=summary -XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+UnlockDiagnosticVMOptions" fi fi } # Replicate thread ergonomics for tiered compilation. # This could ideally be skipped when tiered compilation is disabled. # The algorithm is taken from: # OpenJDK / jdk8u / jdk8u / hotspot # src/share/vm/runtime/advancedThresholdPolicy.cpp ci_compiler_count() { local core_limit="$1" local log_cpu=$(calc 'log2($1)' "$core_limit") local loglog_cpu=$(calc 'log2(max2($1,1))' "$log_cpu") local count=$(calc 'max2($1*$2,1)*3/2' "$log_cpu" "$loglog_cpu") local c1_count=$(calc 'max2($1/3,1)' "$count") local c2_count=$(calc 'max2($1-$2,1)' "$count" "$c1_count") [ $(c2_disabled) = true ] && echo "$c1_count" || echo $(calc '$1+$2' "$c1_count" "$c2_count") } cpu_options() { # JVMs >= 10 know about CPU limits if [ "${JAVA_MAJOR_VERSION:-0}" -ge "10" ]; then return fi local core_limit="${JAVA_CORE_LIMIT:-}" if [ "$core_limit" = "0" ]; then return fi if [ -n "${CONTAINER_CORE_LIMIT:-}" ]; then if [ -z ${core_limit} ]; then core_limit="${CONTAINER_CORE_LIMIT}" fi echo "-XX:ParallelGCThreads=${core_limit} " \ "-XX:ConcGCThreads=${core_limit} " \ "-Djava.util.concurrent.ForkJoinPool.common.parallelism=${core_limit} " \ "-XX:CICompilerCount=$(ci_compiler_count $core_limit)" fi } #-XX:MinHeapFreeRatio=20 These parameters tell the heap to shrink aggressively and to grow conservatively. #-XX:MaxHeapFreeRatio=40 Thereby optimizing the amount of memory available to the operating system. heap_ratio() { echo "-XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=40" } # These parameters are necessary when running parallel GC if you want to use the Min and Max Heap Free ratios. # Skip setting gc_options if any other GC is set in JAVA_OPTIONS. # -XX:GCTimeRatio=4 # -XX:AdaptiveSizePolicyWeight=90 gc_options() { if echo "${JAVA_OPTIONS:-}" | grep -q -- "-XX:.*Use.*GC"; then return fi local opts="" # for JVMs < 10 set GC settings if [ -z "${JAVA_MAJOR_VERSION:-}" ] || [ "${JAVA_MAJOR_VERSION:-0}" -lt "10" ]; then opts="${opts} -XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 $(heap_ratio)" fi if [ -z "${JAVA_MAJOR_VERSION:-}" ] || [ "${JAVA_MAJOR_VERSION:-}" != "7" ]; then opts="${opts} -XX:+ExitOnOutOfMemoryError" fi echo $opts } java_default_options() { # Echo options, trimming trailing and multiple spaces echo "$(memory_options) $(jit_options) $(diagnostics_options) $(cpu_options) $(gc_options)" | awk '$1=$1' } # ============================================================================== # parse the URL parse_url() { #[scheme://][user[:password]@]host[:port][/path][?params] echo "$1" | sed -e "s+^\(\([^:]*\)://\)\?\(\([^:@]*\)\(:\([^@]*\)\)\?@\)\?\([^:/?]*\)\(:\([^/?]*\)\)\?.*$+ local scheme='\2' username='\4' password='\6' hostname='\7' port='\9'+" } java_proxy_options() { local url="$1" local transport="$2" local ret="" if [ -n "$url" ] ; then eval $(parse_url "$url") if [ -n "$hostname" ] ; then ret="-D${transport}.proxyHost=${hostname}" fi if [ -n "$port" ] ; then ret="$ret -D${transport}.proxyPort=${port}" fi if [ -n "$username" -o -n "$password" ] ; then echo "WARNING: Proxy URL for ${transport} contains authentication credentials, these are not supported by java" >&2 fi fi echo "$ret" } # Check for proxy options and echo if enabled. proxy_options() { local ret="" ret="$(java_proxy_options "${https_proxy:-${HTTPS_PROXY:-}}" https)" ret="$ret $(java_proxy_options "${http_proxy:-${HTTP_PROXY:-}}" http)" local noProxy="${no_proxy:-${NO_PROXY:-}}" if [ -n "$noProxy" ] ; then ret="$ret -Dhttp.nonProxyHosts=$(echo "|$noProxy" | sed -e 's/,[[:space:]]*/|/g' | sed -e 's/[[:space:]]//g' | sed -e 's/|\./|\*\./g' | cut -c 2-)" fi echo "$ret" } # ============================================================================== # Set process name if possible exec_args() { EXEC_ARGS="" if [ -n "${JAVA_APP_NAME:-}" ]; then # Not all shells support the 'exec -a newname' syntax.. if $(exec -a test true 2>/dev/null); then echo "-a '${JAVA_APP_NAME}'" fi fi } # Combine all java options java_options() { # Normalize spaces with awk (i.e. trim and elimate double spaces) # See e.g. https://www.physicsforums.com/threads/awk-1-1-1-file-txt.658865/ for an explanation # of this awk idiom echo "${JAVA_OPTIONS:-} $(run_java_options) $(debug_options) $(proxy_options) $(java_default_options)" | awk '$1=$1' } # Fetch classpath from env or from a local "run-classpath" file classpath() { local cp_path="." if [ "${JAVA_LIB_DIR}" != "${JAVA_APP_DIR}" ]; then cp_path="${cp_path}:${JAVA_LIB_DIR}" fi if [ -z "${JAVA_CLASSPATH:-}" ] && [ -n "${JAVA_MAIN_CLASS:-}" ]; then if [ -n "${JAVA_APP_JAR:-}" ]; then cp_path="${cp_path}:${JAVA_APP_JAR}" fi if [ -f "${JAVA_LIB_DIR}/classpath" ]; then # Classpath is pre-created and stored in a 'run-classpath' file cp_path="${cp_path}:$(format_classpath ${JAVA_LIB_DIR}/classpath ${JAVA_APP_JAR:-})" else # No order implied cp_path="${cp_path}:${JAVA_APP_DIR}/*" fi elif [ -n "${JAVA_CLASSPATH:-}" ]; then # Given from the outside cp_path="${JAVA_CLASSPATH}" fi echo "${cp_path}" } # Checks if a flag is present in the arguments. hasflag() { local filters="$@" for var in $ARGS; do for filter in $filters; do if [ "$var" = "$filter" ]; then echo 'true' return fi done done } # ============================================================================== options() { if [ -z ${1:-} ]; then java_options return fi local ret="" if [ $(hasflag --debug) ]; then ret="$ret $(debug_options)" fi if [ $(hasflag --proxy) ]; then ret="$ret $(proxy_options)" fi if [ $(hasflag --java-default) ]; then ret="$ret $(java_default_options)" fi if [ $(hasflag --memory) ]; then ret="$ret $(memory_options)" fi if [ $(hasflag --jit) ]; then ret="$ret $(jit_options)" fi if [ $(hasflag --diagnostics) ]; then ret="$ret $(diagnostics_options)" fi if [ $(hasflag --cpu) ]; then ret="$ret $(cpu_options)" fi if [ $(hasflag --gc) ]; then ret="$ret $(gc_options)" fi echo $ret | awk '$1=$1' } # Start JVM run() { # Initialize environment load_env $(script_dir) local args cd ${JAVA_APP_DIR} if [ -n "${JAVA_MAIN_CLASS:-}" ] ; then args="${JAVA_MAIN_CLASS}" elif [ -n "${JAVA_APP_JAR:-}" ]; then args="-jar ${JAVA_APP_JAR}" else echo "Either JAVA_MAIN_CLASS or JAVA_APP_JAR needs to be given" exit 1 fi # Don't put ${args} in quotes, otherwise it would be interpreted as a single arg. # However it could be two args (see above). zsh doesn't like this btw, but zsh is not # supported anyway. echo exec $(exec_args) java $(java_options) -cp "$(classpath)" ${args} "$@" exec $(exec_args) java $(java_options) -cp "$(classpath)" ${args} "$@" } # ============================================================================= # Fire up # Set env vars reflecting limits init_limit_env_vars first_arg=${1:-} if [ "${first_arg}" = "options" ]; then # Print out options only shift options $@ exit 0 elif [ "${first_arg}" = "run" ]; then # Run is the default command, but can be given to allow "options" # as first argument to your shift fi run "$@"
STATES_NAME=stack_100K_0518 time python enjoy.py \ --env-name InmoovHandPlaceBulletEnv-v9 \ --load-dir trained_models_0404_0_n_place_0404_0/ppo \ --non-det 0 \ --seed=18980 \ --random_top_shape 1 \ --renders 0 \ --exclude_hard 0 \ --obs_noise 1 \ --n_best_cand 2 \ --cotrain_stack_place 0 \ --place_floor 0 \ --grasp_pi_name "0404_0_n_20_40" \ --use_obj_heights 1 \ --with_stack_place_bit 0 \ --save_states 1 \ --states_dir /home/mguo/states/partial/$STATES_NAME \ --n_trials 100000
<gh_stars>1-10 package proptics.std import cats.arrow.Strong import proptics._ import proptics.rank2types.Rank2TypeLensLike import proptics.typeclass.{Field1, Field2} trait TuplesOptics extends LensTupleOptics with ALensTupleOptics private[std] trait LensTupleOptics { /** extract the first element of a tuple using polymorphic [[Lens_]] */ final def _1P[A, B, C]: Lens_[(A, C), (B, C), A, B] = Lens_(new Rank2TypeLensLike[(A, C), (B, C), A, B] { override def apply[P[_, _]](pab: P[A, B])(implicit ev: Strong[P]): P[(A, C), (B, C)] = ev.first(pab) }) /** synonym for [[_1P]] */ final def firstP[A, B, C]: Lens_[(A, C), (B, C), A, B] = _1P /** extract the first element of a tuple using monomorphic [[Lens]] */ final def _1[A, B](implicit ev: Field1[(A, B), A]): Lens[(A, B), A] = ev.first /** extract the second element of a tuple using polymorphic [[Lens_]] */ final def _2P[A, B, C]: Lens_[(C, A), (C, B), A, B] = Lens_(new Rank2TypeLensLike[(C, A), (C, B), A, B] { override def apply[P[_, _]](pab: P[A, B])(implicit ev: Strong[P]): P[(C, A), (C, B)] = ev.second(pab) }) /** synonym for [[_2P]] */ final def secondP[A, B, C]: Lens_[(C, A), (C, B), A, B] = _2P /** extract the second element of a tuple using monomorphic [[Lens_]] */ final def _2[A, B](implicit ev: Field2[(A, B), B]): Lens[(A, B), B] = ev.second /** swap the elements of a Tuple */ final def swapTuple[A, B]: Iso[(A, B), (B, A)] = Iso.iso[(A, B), (B, A)](_.swap)(_.swap) } private[std] trait ALensTupleOptics { /** extract the first element of a tuple using polymorphic [[Lens_]] */ final def _1PA[A, B, C]: ALens_[(A, C), (B, C), A, B] = ALens_.lens[(A, C), (B, C), A, B](_._1) { case (_, c) => b => (b, c) } /** extract the first element of a tuple using polymorphic [[Lens_]] */ final def fstPA[A, B, C]: ALens_[(A, C), (B, C), A, B] = _1PA /** extract the first element of a tuple using polymorphic [[Lens_]] */ final def _1A[A, B](implicit ev: Field1[(A, B), A]): ALens[(A, B), A] = ev.first.asALens /** extract the second element of a tuple using polymorphic [[Lens_]] */ final def _2PA[A, B, C]: ALens_[(C, A), (C, B), A, B] = ALens_.lens[(C, A), (C, B), A, B](_._2) { case (c, _) => b => (c, b) } /** extract the second element of a tuple using polymorphic [[Lens_]] */ final def secondPA[A, B, C]: ALens_[(C, A), (C, B), A, B] = _2PA /** extract the second element of a tuple using polymorphic [[Lens_]] */ final def _2A[A, B](implicit ev: Field2[(A, B), B]): ALens[(A, B), B] = ev.second.asALens /** extract the first element of a tuple using polymorphic [[Lens_]] */ final def secondA[A, B](implicit ev: Field2[(A, B), B]): ALens[(A, B), B] = _2A }
bnc_name="objinst" ; lnk_name="$bnc_name.rbc" ; prf_name="$bnc_name.ibc" ; obj_name="$bnc_name.o" ; exe_name="$bnc_name.exe" ; source_files=($(ls *.c)) ; CXXFLAGS=" -lm " ; RUN_OPTIONS=" " ;
function filterConsentPurposes($consent_purposes) { $filteredPurposes = array_filter($consent_purposes, function($purpose) { return stripos($purpose, "marketing") === false; }); sort($filteredPurposes); return $filteredPurposes; } // Test the function $consent_purposes = ["Analytics", "Marketing emails", "Personalization", "Marketing calls", "Service improvement"]; $result = filterConsentPurposes($consent_purposes); print_r($result);
describe("pc.SceneRegistry", function () { it("new registry is empty", function () { var registry = new pc.SceneRegistry(); expect(registry.list().length).to.equal(0); }); it("add", function () { var registry = new pc.SceneRegistry(); registry.add("New Scene", "/test.json"); expect(registry.list().length).to.equal(1); }); it("find", function () { var registry = new pc.SceneRegistry(); registry.add("New Scene", "/test.json"); var result = registry.find("New Scene"); expect(result.name).to.equal("New Scene"); expect(result.url).to.equal("/test.json"); }); it("remove", function () { var registry = new pc.SceneRegistry(); registry.add("New Scene", "/test.json"); registry.remove("New Scene"); expect(registry.list().length).to.equal(0); expect(registry.find("New Scene")).to.equal(null); }); it("add multiple", function () { var registry = new pc.SceneRegistry(); registry.add("New Scene 1", "/test1.json"); registry.add("New Scene 2", "/test2.json"); registry.add("New Scene 3", "/test3.json"); expect(registry.list().length).to.equal(3); expect(registry.list()[0].url).to.equal('/test1.json'); expect(registry.list()[1].url).to.equal('/test2.json'); expect(registry.list()[2].url).to.equal('/test3.json'); expect(registry.find("New Scene 1").url).to.equal("/test1.json"); expect(registry.find("New Scene 2").url).to.equal("/test2.json"); expect(registry.find("New Scene 3").url).to.equal("/test3.json"); }); it("remove middle value", function () { var registry = new pc.SceneRegistry(); registry.add("New Scene 1", "/test1.json"); registry.add("New Scene 2", "/test2.json"); registry.add("New Scene 3", "/test3.json"); registry.remove("New Scene 2"); expect(registry.list().length).to.equal(2); expect(registry.list()[0].url).to.equal('/test1.json'); expect(registry.list()[1].url).to.equal('/test3.json'); expect(registry.find("New Scene 1").url).to.equal("/test1.json"); expect(registry.find("New Scene 3").url).to.equal("/test3.json"); }); it("url index", function () { var registry = new pc.SceneRegistry(); registry.add("New Scene 1", "/test1.json"); var result = registry.findByUrl('/test1.json'); expect(result.name).to.equal("New Scene 1"); expect(result.url).to.equal("/test1.json"); }); it("remove middle, url index", function () { var registry = new pc.SceneRegistry(); registry.add("New Scene 1", "/test1.json"); registry.add("New Scene 2", "/test2.json"); registry.add("New Scene 3", "/test3.json"); registry.remove("New Scene 2"); expect(registry.findByUrl("/test1.json").name).to.equal("New Scene 1"); expect(registry.findByUrl("/test2.json")).to.equal(null); expect(registry.findByUrl("/test3.json").name).to.equal("New Scene 3"); }); });
apt-get -qqy update apt-get -qqy install postgresql python-psycopg2 apt-get -qqy install python-flask python-sqlalchemy apt-get -qqy install python-pip pip install bleach pip install oauth2client pip install requests pip install httplib2 pip install redis pip install passlib pip install itsdangerous pip install flask-httpauth
<reponame>zwennesm/pre-commit-k8s from typing import List from hooks.rule import Rule, ValidationResult class KubernetesSecretRule(Rule): """Check if commit contains Kubernetes Secret object.""" @staticmethod def name() -> str: return "kubernetes-secrets" def validate(self, files: List[str]) -> ValidationResult: for file_name in files: with open(file_name, "r") as current: error_msg = f"File contains a Kubernetes Secret: {file_name}" if "kind: Secret" in current.read(): return ValidationResult(False, error_msg) return ValidationResult(True, None)
<reponame>namlook/eureka-widget-application-navbar /* jshint node: true */ 'use strict'; module.exports = { name: 'eureka-widget-application-navbar', included: function included(app) { this._super.included(app); app.import('vendor/widget.css'); } };
#! /bin/sh # fetch ripe.db.route # unpack wget "ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.as-set.gz" gzcat ripe.db.as-set | awk 'BEGIN{ORS=""} $1 == "asSet:" { asset = $2; } $1 == "members:" { for (i = 2; i <= NF; i++) {sub(/,/, "", $i); print("db.asSet.insert({ asSet : \"" asset "\" , member : \"" $i "\"});\n");}}' >> db.as-set.js # First delete the entries we already have, then load what we just worked out mongo routes --eval "db.asSet.drop()" mongo routes < db.as-set.js # Delete the files rm db.as-set.js
<filename>test/unit/demutils.js import * as THREE from 'three'; import ElevationLayer from 'Layer/ElevationLayer'; import WMTSSource from 'Source/WMTSSource'; import HttpsProxyAgent from 'https-proxy-agent'; import assert from 'assert'; import GlobeView from 'Core/Prefab/GlobeView'; import Coordinates from 'Core/Geographic/Coordinates'; import Extent from 'Core/Geographic/Extent'; import { updateLayeredMaterialNodeElevation } from 'Process/LayeredMaterialNodeProcessing'; import TileMesh from 'Core/TileMesh'; import OBB from 'Renderer/OBB'; import LayerUpdateState from 'Layer/LayerUpdateState'; import DEMUtils from 'Utils/DEMUtils'; import { RasterElevationTile } from 'Renderer/RasterTile'; import Renderer from './bootstrap'; describe('DemUtils', function () { const renderer = new Renderer(); const placement = { coord: new Coordinates('EPSG:4326', 1.5, 43), zoom: 10 }; const viewer = new GlobeView(renderer.domElement, placement, { renderer }); const source = new WMTSSource({ format: 'image/x-bil;bits=32', crs: 'EPSG:4326', url: 'https://wxs.ign.fr/altimetrie/geoportail/wmts', name: 'ELEVATION.ELEVATIONGRIDCOVERAGE.SRTM3', tileMatrixSet: 'WGS84G', networkOptions: process.env.HTTPS_PROXY ? { agent: new HttpsProxyAgent(process.env.HTTPS_PROXY) } : { // referrerPolicy: 'origin-when-cross-origin', crossOrigin: 'anonymous', // referrer: 'http://localhost:8080/examples/view_3d_map.html', }, }); source.url = 'https://github.com/iTowns/iTowns2-sample-data/blob/master/dem3_3_8.bil?raw=true'; const elevationlayer = new ElevationLayer('worldelevation', { source }); const context = { camera: viewer.camera, engine: viewer.mainLoop.gfxEngine, scheduler: { execute: (command) => { const provider = viewer.mainLoop.scheduler.getProtocolProvider(command.layer.protocol); return provider.executeCommand(command); }, }, view: viewer, }; it('add elevation layer', (done) => { viewer.addLayer(elevationlayer).then((l) => { assert.equal('worldelevation', l.id); done(); }); }); const tiles = []; const extent = new Extent('EPSG:4326', 5.625, 11.25, 45, 50.625); const coord = extent.center(); it('load elevation texture', (done) => { const geom = new THREE.BufferGeometry(); geom.OBB = new OBB(new THREE.Vector3(), new THREE.Vector3(1, 1, 1)); const material = new THREE.Material(); const nodeLayer = new RasterElevationTile(material, elevationlayer); material.getElevationLayer = () => nodeLayer; const tile = new TileMesh(geom, material, viewer.tileLayer, extent, 5); tile.layerUpdateState[elevationlayer.id] = new LayerUpdateState(); tiles.push(tile); updateLayeredMaterialNodeElevation(context, elevationlayer, tile, {}).then(() => { assert.equal(nodeLayer.textures[0].image.data[0], 357.3833923339844); done(); }); }); it('get elevation value at with PRECISE_READ_Z', () => { const elevation = DEMUtils.getElevationValueAt(viewer.tileLayer, coord, DEMUtils.PRECISE_READ_Z, tiles); assert.equal(elevation, 369.72571563720703); }); it('get elevation value at with FAST_READ_Z', () => { const elevation = DEMUtils.getElevationValueAt(viewer.tileLayer, coord, DEMUtils.FAST_READ_Z, tiles); assert.equal(elevation, 311.4772033691406); }); it('get terrain at with PRECISE_READ_Z', () => { const elevation = DEMUtils.getTerrainObjectAt(viewer.tileLayer, coord, DEMUtils.PRECISE_READ_Z, tiles); assert.equal(elevation.coord.z, 369.72571563720703); }); it('get terrain at with FAST_READ_Z', () => { const elevation = DEMUtils.getTerrainObjectAt(viewer.tileLayer, coord, DEMUtils.FAST_READ_Z, tiles); assert.equal(elevation.coord.z, 311.4772033691406); }); });
<filename>src/components/EditReview.js import React, { useState, useEffect, useCallback } from 'react' import { useHistory } from 'react-router-dom' import ReactStars from 'react-rating-stars-component' import { Alert } from 'react-bootstrap' import { db, storage } from '../firebase/index' import drinkCategories from '../lib/drinkCategories' const reviewsRef = db.collection('reviews') export default function EditReview() { const history = useHistory() const [review, setReview] = useState('') const [drinkName, setDrinkName] = useState('') const [drinkCategory, setDrinkCategory] = useState('') const [price, setPrice] = useState(0) const [rating, setRating] = useState(3) const [comment, setComment] = useState('') const [photoURL, setPhotoURL] = useState('') const [image, setImage] = useState(null) const [errMsg, setErrMsg] = useState('') const [successMsg, setSuccessMsg] = useState('') const [popupOpen, setPopupOpen] = useState(false) const review_id = window.location.pathname.split('/review/edit/', 2)[1] const reviewRef = reviewsRef.doc(review_id) useEffect(() => { reviewRef.get().then(doc => { const reviewData = doc.data() const imageFulPath = reviewData.fullPath setReview(reviewData) setDrinkName(reviewData.drink_name) setDrinkCategory(reviewData.drink_category) setPrice(reviewData.price) setRating(reviewData.rating) setComment(reviewData.comment) storage .ref(imageFulPath) ?.getDownloadURL() .then(url => setPhotoURL(url)) }) }, []) const handleDrinkNameChange = useCallback(e => setDrinkName(e.target.value), [setDrinkName]) const handleDrinkCategoryChange = useCallback(e => setDrinkCategory(e.target.value), [ setDrinkCategory, ]) const handlePriceChange = useCallback(e => setPrice(parseFloat(e.target.value)), [setPrice]) const handleRatingChange = useCallback(e => setRating(parseInt(e)), [setRating]) const handleCommentChange = useCallback(e => setComment(e.target.value), [setComment]) const handleImageChange = e => { setImage(e.target.files[0]) setPhotoURL(window.URL.createObjectURL(e.target.files[0])) } const handleUpdate = e => { e.preventDefault() setErrMsg('') setSuccessMsg('') if (image !== null) { const randomID = Math.random().toString(32).substring(2) const fullPath = 'reviewPhoto/' + randomID + image.name const storageRef = storage.ref().child(fullPath) storageRef .put(image) .then(res => reviewRef .update({ fullPath }) .catch(err => console.log('Failed to update path to image', err)) ) .catch(err => console.log('Failed to upload image', err)) } reviewRef .update({ drink_name: drinkName, drink_category: drinkCategory, price, rating, comment, }) .then(() => setSuccessMsg('Review is successfully updated!')) .catch(err => { setErrMsg('Failed to update review') console.log('Failed to update review: ', err) }) } const handlePopupOpen = e => { e.preventDefault() setPopupOpen(true) } const handlePopupClose = () => setPopupOpen(false) const handleDelete = () => { handlePopupClose() setDrinkName('') setDrinkCategory('') setPrice('') setRating('') setComment('') setPhotoURL('') setErrMsg('') setSuccessMsg('') reviewRef.delete().then(() => { reviewsRef .where('shop', '==', review.shop) .get() .then(querySnapshot => { if (querySnapshot.empty) { review.shop.delete() } setSuccessMsg('Review is successfully deleted.') setReview('') setTimeout(() => history.push('/'), 1500) }) .catch(err => { setErrMsg('Failed to delete review.') console.error('Failed to delete review: ', err) }) }) } const Popup = () => { return ( <div className="overlay--trans"> <div className="popup"> <p className="popup-message">Are you sure to delete this review?</p> <div className="btn-area--half"> <button onClick={handlePopupClose} className="btn--secondary btn--half"> Cancel </button> <button onClick={handleDelete} className="btn--primary btn--half"> Delete </button> </div> </div> </div> ) } return ( <> {popupOpen ? <Popup /> : null} <form className="edit-review" onSubmit={handleUpdate}> <input label="Drink name" required={true} rows={1} value={drinkName} type="text" onChange={handleDrinkNameChange} placeholder="Drink name" /> <div className="select-container"> <select required={true} value={drinkCategory} onChange={handleDrinkCategoryChange}> <option value="">Select drink category</option> {drinkCategories.map(category => ( <option key={category} value={category}> {category} </option> ))} </select> </div> <input required label="Price" max="99999" rows={1} value={price} type="number" onChange={handlePriceChange} placeholder="Price" /> <ReactStars count={5} value={rating} onChange={handleRatingChange} size={24} activeColor="#de9e48" /> <textarea className="comment" value={comment} placeholder="Please write a review" name="comment" rows="4" cols="40" onChange={handleCommentChange} /> <div className="image_wrapper"> <input type="file" onChange={handleImageChange} /> {photoURL ? <img src={photoURL} className="w-100" alt="drink" /> : null} </div> {successMsg && <Alert variant="success">{successMsg}</Alert>} {errMsg && <Alert variant="danger">{errMsg}</Alert>} <div className="btn-area--half"> <button className="btn--secondary btn--half" label="Delete" onClick={handlePopupOpen}> Delete </button> <button type="submit" className="btn--primary btn--half"> Update </button> </div> </form> </> ) }
// // Created by ooooo on 2020/4/11. // #ifndef CPP_055_2__SOLUTION1_H_ #define CPP_055_2__SOLUTION1_H_ #include "TreeNode.h" #include <math.h> #include <unordered_map> class Solution { public: int getHeight(TreeNode *node) { if (map.find(node) != map.end()) return map[node]; if (!node) return 0; return map[node] = max(getHeight(node->left), getHeight(node->right)) + 1; } unordered_map<TreeNode *, int> map; bool isBalanced(TreeNode *root) { if (!root) return true; if (abs(getHeight(root->left) - getHeight(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } }; #endif //CPP_055_2__SOLUTION1_H_
#!/bin/bash source $REPO_HOME/toolchain/share.sh set -e set -x # ------ riscv-arch-test ---------------------------------------------------------- cd $DIR_ARCH_TEST git apply $PATCH_ARCH_TEST --whitespace=nowarn git add --all
#!/bin/bash theme=$(awk -F '"' 'END { m = $(NF - 1); print (m == "icons") ? "list" : m }' ~/.config/rofi/main.rasi) function populate_menu() { toggle=$(echo -e $1 | rofi -dmenu -theme $theme) } populate_menu 'rofi\nbash\ntmux\nbuttons\nfolders\ntitlebar' [[ $toggle ]] && case $toggle in rofi) while [[ $toggle ]]; do case $toggle in rofi) populate_menu 'mode\nprompt';; mode) populate_menu 'list\ndmenu\nfullscreen';; prompt) prompt='prompt -c' && populate_menu 'list\nicons\ndmenu';; *) ~/.orw/scripts/toggle.sh rofi $prompt $toggle exit;; esac done;; titlebar) ~/.orw/scripts/toggle.sh titlebar;; buttons) populate_menu 'box\nbars\nturq\ndots\nplus\nslim\nsmall\nnumix\nround\nsharp\nelegant\nsurreal' [[ $toggle ]] && ~/.orw/scripts/toggle.sh buttons $toggle;; folders) ~/.orw/scripts/toggle.sh folders;; *) ~/.orw/scripts/toggle.sh $toggle;; esac
'use strict'; // define the module angular.module('familyView', []);
#!/bin/bash function start() { if [ ! -L /dev/sgx/enclave ]&&[ ! -L /dev/sgx/provision ]&&[ ! -c /dev/sgx_enclave ]&&[ ! -c /dev/sgx_provision ]&&[ ! -c /dev/isgx ]; then install elif ! type jq curl wget unzip zip docker docker-compose node yq dkms > /dev/null; then install_depenencies fi local node_name=$(cat $installdir/.env | grep 'NODE_NAME' | awk -F "=" '{print $NF}') local cores=$(cat $installdir/.env | grep 'CORES' | awk -F "=" '{print $NF}') local mnemonic=$(cat $installdir/.env | grep 'MNEMONIC' | awk -F "=" '{print $NF}') local pool_address=$(cat $installdir/.env | grep 'OPERATOR' | awk -F "=" '{print $NF}') if [ -z "$node_name" ]||[ -z "$cores" ]||[ -z "$mnemonic" ]||[ -z "$pool_address" ]; then log_err "----------节点未配置,开始配置节点!----------" config set fi local pruntime_devices=$(cat $installdir/docker-compose.yml | grep 'sgx') if [ -z "$pruntime_devices" ]; then log_err "---------- 请重新安装驱动!----------" fi cd $installdir docker-compose up -d }
let dataSet = [ [10.67, 22.20, 15.00, 18.60], [24.21, 18.50, 32.12, 33.22] ]; let ctx = document.getElementById("myChart").getContext('2d'); let myChart = new Chart(ctx, { type: 'line', data: { labels: ["1", "2", "3", "4"], datasets: [{ label: 'Data', data: dataSet, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', ], lineTension: 0, fill: false }] }, options: { animation: { duration: 1000, easing: 'linear' } } });
package arouter.dawn.zju.edu.module_mine.ui.collection; import java.util.List; import baselib.base.BaseContract; import arouter.dawn.zju.edu.lib_net.bean.goods.Goods; /** * @Auther: Dawn * @Date: 2018/11/22 22:01 * @Description: */ public interface CollectionContract { interface View extends BaseContract.BaseView { void refresh(List<Goods> goodsList); } interface Presenter extends BaseContract.BasePresenter<View> { void refresh(); } }
paths=( /usr/bin /bin /usr/local/bin ~/.local/bin $DOTFILES/bin ) export PATH for p in "${paths[@]}"; do [[ -d "$p" ]] && PATH="$p:$(path_remove "$p")" done unset p paths
<reponame>ToastCheng/ecpay<gh_stars>10-100 package ecpay // ActionType defines the struct of credit card action. type ActionType string const ( // ActionTypeC (關帳). ActionTypeC ActionType = "C" // ActionTypeR (退刷). ActionTypeR ActionType = "R" // ActionTypeE (取消). ActionTypeE ActionType = "E" // ActionTypeN (放棄). ActionTypeN ActionType = "N" ) // CarrierType defines the struct of carrier options (載具類別). type CarrierType string const ( // CarrierTypeNone none (無載具). CarrierTypeNone CarrierType = "" // CarrierTypeMember member (特店載具). CarrierTypeMember CarrierType = "1" // CarrierTypeCitizen citizen (買受人之自然人憑證號碼). CarrierTypeCitizen CarrierType = "2" // CarrierTypeCellphone phone (買受人之手機條碼資料). CarrierTypeCellphone CarrierType = "3" ) // DonationType defines the struct of donation options (捐贈). type DonationType string const ( // DonationTypeYes yes (捐贈). DonationTypeYes DonationType = "1" // DonationTypeNo no (不捐贈或統一編號CustomerIdentifier有值). DonationTypeNo DonationType = "2" ) // InvoiceType defines the struct of invoice options (發票). type InvoiceType string const ( // InvoiceTypeGeneral 一般稅額 InvoiceTypeGeneral InvoiceType = "07" // InvoiceTypeSpecial 特種稅額 InvoiceTypeSpecial InvoiceType = "08" ) // PeriodType defines the struct of period options (週期種類). type PeriodType string const ( // PeriodTypeYear year. PeriodTypeYear PeriodType = "Y" // PeriodTypeMonth month. PeriodTypeMonth PeriodType = "M" // PeriodTypeDay day. PeriodTypeDay PeriodType = "D" ) // TaxType defines the struct of tax type options (課稅類別). type TaxType string const ( // TaxTypeDutiable (應稅). TaxTypeDutiable TaxType = "1" // TaxTypeZero (零稅率). TaxTypeZero TaxType = "2" // TaxTypeFree (免稅). TaxTypeFree TaxType = "3" // TaxTypeMix (若為混合應稅與免稅或零稅率時,限收銀機發票無法分辨時使用,且需通過申請核可). TaxTypeMix TaxType = "9" ) // UnionPayType defines the struct of UnionPay options (銀聯卡交易選項). type UnionPayType string const ( // UnionPayTypeSelect customer choose whether use UnionPay or not in webpage (消費者於交易頁面可選擇是否使用銀聯交易). UnionPayTypeSelect UnionPayType = "0" // UnionPayTypeOnly use UnionPay (只使用銀聯卡交易,且綠界會將交易頁面直接導到銀聯網站). UnionPayTypeOnly UnionPayType = "1" // UnionPayTypeHidden do not use UnionPay (不可使用銀聯卡,綠界會將交易頁面隱藏銀聯選項). UnionPayTypeHidden UnionPayType = "2" ) // PaymentType defines the struct of payment type options (銀聯卡交易選項). type PaymentType string const ( // PaymentTypeAIO all in one. PaymentTypeAIO PaymentType = "aio" // PaymentTypeWebATMTaishin Taishin Bank (台新銀行). PaymentTypeWebATMTaishin PaymentType = "WebATM_TAISHIN" // PaymentTypeWebATMBOT Bank of Taiwan (台灣銀行). PaymentTypeWebATMBOT PaymentType = "WebATM_BOT" // PaymentTypeWebATMChinaTrust ChinaTrust Bank (中國信託). PaymentTypeWebATMChinaTrust PaymentType = "WebATM_CHINATRUST" // PaymentTypeWebATMCathay Cathay Bank (花旗銀行). PaymentTypeWebATMCathay PaymentType = "WebATM_CATHAY" // PaymentTypeWebATMLand Land Bank (土地銀行). PaymentTypeWebATMLand PaymentType = "WebATM_LAND" // PaymentTypeWebATMSinoPac SinoPac Bank (永豐銀行). PaymentTypeWebATMSinoPac PaymentType = "WebATM_SINOPAC" // PaymentTypeATMESUN E.SUN Bank (玉山銀行). PaymentTypeATMESUN PaymentType = "ATM_ESUN" // PaymentTypeATMFubon Fubon (富邦銀行). PaymentTypeATMFubon PaymentType = "ATM_FUBON" // PaymentTypeATMFirst First Commercial Bank (第一銀行). PaymentTypeATMFirst PaymentType = "ATM_FIRST" // PaymentTypeATMCathay Cathay Bank (花旗銀行). PaymentTypeATMCathay PaymentType = "ATM_CATHAY" // PaymentTypeCVSCVS convenience store payment code (超商代碼繳款). PaymentTypeCVSCVS PaymentType = "CVS_CVS" // PaymentTypeCVSFamily Family mart (全家). PaymentTypeCVSFamily PaymentType = "CVS_FAMILY" // PaymentTypeCVSIbon 7-11 ibon. PaymentTypeCVSIbon PaymentType = "CVS_IBON" // PaymentTypeCreditCreditCard credit card (信用卡). PaymentTypeCreditCreditCard PaymentType = "Credit_CreditCard" ) // ChoosePaymentType defines the struct of default payment type options (選擇預設付款方式). type ChoosePaymentType string const ( // ChoosePaymentTypeAll all type. ChoosePaymentTypeAll ChoosePaymentType = "ALL" // ChoosePaymentTypeCredit credit card (信用卡). ChoosePaymentTypeCredit ChoosePaymentType = "Credit" // ChoosePaymentTypeWebATM web ATM (網路ATM). ChoosePaymentTypeWebATM ChoosePaymentType = "WebATM" // ChoosePaymentTypeATM ATM. ChoosePaymentTypeATM ChoosePaymentType = "ATM" // ChoosePaymentTypeCVS convenience store payment code (超商代碼繳款) ChoosePaymentTypeCVS ChoosePaymentType = "CVS" // ChoosePaymentTypeBarCode bar code (超商條碼繳款). ChoosePaymentTypeBarCode ChoosePaymentType = "BARCODE" // ChoosePaymentTypeGooglePay Google Pay. ChoosePaymentTypeGooglePay ChoosePaymentType = "GooglePay" ) // ChooseSubpaymentType defines the struct of subpayment type options (付款子項目). type ChooseSubpaymentType string const ( // ChooseSubpaymentTypeTaishin Taishin Bank (台新銀行). ChooseSubpaymentTypeTaishin ChooseSubpaymentType = "TAISHIN" // ChooseSubpaymentTypeESUN E.SUN Bank (玉山銀行). ChooseSubpaymentTypeESUN ChooseSubpaymentType = "ESUN" // ChooseSubpaymentTypeBOT Bank of Taiwan (台灣銀行). ChooseSubpaymentTypeBOT ChooseSubpaymentType = "BOT" // ChooseSubpaymentTypeFubon Fubon (富邦銀行). ChooseSubpaymentTypeFubon ChooseSubpaymentType = "FUBON" // ChooseSubpaymentTypeChinaTrust ChinaTrust Bank (中國信託). ChooseSubpaymentTypeChinaTrust ChooseSubpaymentType = "CHINATRUST" // ChooseSubpaymentTypeFirst First Commercial Bank (第一銀行). ChooseSubpaymentTypeFirst ChooseSubpaymentType = "FIRST" // ChooseSubpaymentTypeCathay Cathay Bank (花旗銀行). ChooseSubpaymentTypeCathay ChooseSubpaymentType = "CATHAY" // ChooseSubpaymentTypeMega Mega International Commercial Bank (兆豐銀行). ChooseSubpaymentTypeMega ChooseSubpaymentType = "MEGA" // ChooseSubpaymentTypeLand Land Bank (土地銀行). ChooseSubpaymentTypeLand ChooseSubpaymentType = "LAND" // ChooseSubpaymentTypeTachong (大眾銀行). ChooseSubpaymentTypeTachong ChooseSubpaymentType = "TACHONG" // ChooseSubpaymentTypeSinoPac SinoPac Bank (永豐銀行). ChooseSubpaymentTypeSinoPac ChooseSubpaymentType = "SINOPAC" // ChooseSubpaymentTypeCVS convenience store payment code (超商代碼繳款). ChooseSubpaymentTypeCVS ChooseSubpaymentType = "CVS" // ChooseSubpaymentTypeOK OK Mart. ChooseSubpaymentTypeOK ChooseSubpaymentType = "OK" // ChooseSubpaymentTypeFamily Family mart (全家). ChooseSubpaymentTypeFamily ChooseSubpaymentType = "FAMILY" // ChooseSubpaymentTypeHiLife HiFife. ChooseSubpaymentTypeHiLife ChooseSubpaymentType = "HILIFE" // ChooseSubpaymentTypeIBon 7-11 ibon. ChooseSubpaymentTypeIBon ChooseSubpaymentType = "IBON" // ChooseSubpaymentTypeBarcode barcode. ChooseSubpaymentTypeBarcode ChooseSubpaymentType = "BARCODE" ) // NeedExtraPaidInfoType defines the struct of extra payment info options (是否需要額外的付款資訊). type NeedExtraPaidInfoType string const ( // NeedExtraPaidInfoTypeYes yes. NeedExtraPaidInfoTypeYes NeedExtraPaidInfoType = "Y" // NeedExtraPaidInfoTypeNo no. NeedExtraPaidInfoTypeNo NeedExtraPaidInfoType = "N" ) // InvoiceMarkType defines the struct of invoice options (電子發票開立註記). type InvoiceMarkType string const ( // InvoiceMarkTypeYes yes. InvoiceMarkTypeYes InvoiceMarkType = "Y" // InvoiceMarkTypeNo no. InvoiceMarkTypeNo InvoiceMarkType = "N" ) // LanguageType defines the struct of language options (語系設定). type LanguageType string const ( // LanguageTypeEnglish English. LanguageTypeEnglish LanguageType = "ENG" // LanguageTypeKorean Korean. LanguageTypeKorean LanguageType = "KOR" // LanguageTypeJapanese Japanese. LanguageTypeJapanese LanguageType = "JPN" // LanguageTypeSimplifiedChinese SimplifiedChinese. LanguageTypeSimplifiedChinese LanguageType = "CHI" ) // BindingCardType defines the struct of binding card options (記憶卡號). type BindingCardType string const ( // BindingCardTypeYes (使用記憶信用卡). BindingCardTypeYes BindingCardType = "1" // BindingCardTypeNo (不使用記憶信用卡). BindingCardTypeNo BindingCardType = "0" ) // RedeemType defines the struct of redeem options (信用卡是否使用紅利折抵). type RedeemType string const ( // RedeemTypeYes yes. RedeemTypeYes RedeemType = "Y" // RedeemTypeNo no. RedeemTypeNo RedeemType = "N" ) // ClearanceMarkType defines the struct of redeem options (通關方式). type ClearanceMarkType string const ( // ClearanceMarkTypeNormal (非海關出口). ClearanceMarkTypeNormal ClearanceMarkType = "1" // ClearanceMarkTypeCustoms (經海關出口). ClearanceMarkTypeCustoms ClearanceMarkType = "2" ) // PrintType defines the struct of redeem options (列印註記). type PrintType string const ( // PrintTypeYes yes. PrintTypeYes PrintType = "1" // PrintTypeNo no. PrintTypeNo PrintType = "0" ) // PayDateType defines the struct of pay date type options (查詢日期類別). type PayDateType string const ( // PayDateTypeFund (依交易款項結算日期). PayDateTypeFund PayDateType = "fund" // PayDateTypeClose (依操作關帳或自動關帳日期). PayDateTypeClose PayDateType = "close" // PayDateTypeEnter (依撥款至特店綠界帳戶日期). PayDateTypeEnter PayDateType = "enter" ) // DateType defines the struct of date type options (查詢日期類別). type DateType string const ( // DateTypePayment (付款日期). DateTypePayment DateType = "2" // DateTypeAllocation (撥款日期). DateTypeAllocation DateType = "4" // DateTypeOrder (訂單日期). DateTypeOrder DateType = "6" ) // MerchantPaymentType defines the struct of payment type options (查詢日期類別). type MerchantPaymentType string const ( // MerchantPaymentTypeCreditCard (付款日期). MerchantPaymentTypeCreditCard MerchantPaymentType = "01" // MerchantPaymentTypeWebATM (網路ATM). MerchantPaymentTypeWebATM MerchantPaymentType = "02" // MerchantPaymentTypeATM (ATM). MerchantPaymentTypeATM MerchantPaymentType = "03" // MerchantPaymentTypeCVS (超商代碼). MerchantPaymentTypeCVS MerchantPaymentType = "04" // MerchantPaymentTypeBarcode (超商條碼). MerchantPaymentTypeBarcode MerchantPaymentType = "05" ) // PlatformStatusType defines the struct of platform status options (訂單類型). type PlatformStatusType string const ( // PlatformStatusTypeAll (全部). PlatformStatusTypeAll PlatformStatusType = "0" // PlatformStatusTypeNormal (一般). PlatformStatusTypeNormal PlatformStatusType = "1" // PlatformStatusTypePlatform (平台). PlatformStatusTypePlatform PlatformStatusType = "2" ) // PaymentStatusType defines the struct of payment status options (付款狀態). type PaymentStatusType string const ( // PaymentStatusTypeUnpaid (未付款). PaymentStatusTypeUnpaid PaymentStatusType = "0" // PaymentStatusTypePaid (已付款). PaymentStatusTypePaid PaymentStatusType = "1" // PaymentStatusTypeFailed (訂單失敗). PaymentStatusTypeFailed PaymentStatusType = "2" ) // AllocateStatusType defines the struct of allocation status options (撥款狀態). type AllocateStatusType string const ( // AllocateStatusTypeDone (已撥款). AllocateStatusTypeDone AllocateStatusType = "0" // AllocateStatusTypeNotYet (未撥款). AllocateStatusTypeNotYet AllocateStatusType = "1" ) // MediaFormatedType defines the media format options (CSV格式). type MediaFormatedType string const ( // MediaFormatedTypeOld (舊版格式). MediaFormatedTypeOld MediaFormatedType = "0" // MediaFormatedTypeNew (新版格式). MediaFormatedTypeNew MediaFormatedType = "1" ) // CharSetType defines the charset options (檔案編碼格式). type CharSetType string const ( // CharSetTypeBig5 Big-5. CharSetTypeBig5 CharSetType = "1" // CharSetTypeUTF8 UTF-8. CharSetTypeUTF8 CharSetType = "2" )
<reponame>Uniquex/TrafficSimulation<filename>src/RingBufferTest.java public class RingBufferTest { public static void main(String[] args) { RingBuffer<Vehicle> rb = new RingBuffer<>(10); try { for (int x = 0; x < 10; x++) { rb.push(new Vehicle(null)); } rb.pop(); rb.pop(); System.out.println(rb.size()); rb.push(new Vehicle(null)); System.out.println(rb.size()); rb.pop(); System.out.println(rb.size()); System.out.println(rb.toString()); Object[] veh = rb.getAllItems(); Vehicle v = (Vehicle) veh[4]; //rb.removeSpecific(v); rb.push(new Vehicle(null)); System.out.println(rb.toString()); } catch (Exception e) { e.printStackTrace(); } } }
<filename>open-sphere-base/core/src/main/java/io/opensphere/core/util/ObservableListListenerHandle.java package io.opensphere.core.util; /** * Listener handle for ObservableList. * * @param <E> the type of elements in the list */ public class ObservableListListenerHandle<E> implements Service { /** The observable list. */ private final ObservableList<E> myObservable; /** The listener. */ private final ListDataListener<E> myListener; /** * Constructor. * * @param observable the observable list * @param listener the listener */ public ObservableListListenerHandle(ObservableList<E> observable, ListDataListener<E> listener) { myObservable = observable; myListener = listener; } @Override public void open() { myObservable.addChangeListener(myListener); } @Override public void close() { myObservable.removeChangeListener(myListener); } }
#!/bin/bash # Copyright 2017 - 2018 Crunchy Data Solutions, 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. echo "Cleaning up..." PRIMARY_CONTAINER_NAME=primary PRIMARY_VOLUME_NAME=${PRIMARY_CONTAINER_NAME?}-pgdata REPLICA_CONTAINER_NAME=replica REPLICA_VOLUME_NAME=${REPLICA_CONTAINER_NAME?}-pgdata docker stop ${PRIMARY_CONTAINER_NAME?} docker rm -v ${PRIMARY_CONTAINER_NAME?} docker volume rm ${PRIMARY_VOLUME_NAME?} docker stop ${REPLICA_CONTAINER_NAME?} docker rm -v ${REPLICA_CONTAINER_NAME?} docker volume rm ${REPLICA_VOLUME_NAME?}
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-old/7-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-old/7-1024+0+512-SS-N-VB-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_sentences_remove_all_but_nouns_and_verbs_first_two_thirds_sixth --eval_function last_sixth_eval
import os from PIL import ImageFont def get_file(path): dir = os.path.dirname(__file__) return os.path.join(dir, path) def get_std_font(): return ImageFont.load_default() def get_tiny_font(): file_path = get_file('assets/4x6.pil') fnt = ImageFont.load(file_path) return fnt
package main import ( "fmt" "os" "strings" "github.com/mugli/go-kill-mysql-query/configuration" "github.com/mugli/go-kill-mysql-query/mysql" "github.com/gookit/color" "github.com/jmoiron/sqlx" "github.com/manifoldco/promptui" ) func main() { var config configuration.Config if len(os.Args) >= 2 { switch os.Args[1] { case "generate", "init": generateConfig() case "help", "-h", "--help": showHelp() default: config = readConfig(os.Args[1]) } } else { config = readConfig("") } killQueries(config) } func readConfig(filePath string) configuration.Config { config, err := configuration.Read(filePath) if err != nil { fmt.Println(err) os.Exit(1) } return config } func killQueries(config configuration.Config) { dbConn, err := mysql.Connect(config) if err != nil { fmt.Println(err) os.Exit(1) } defer mysql.Disconnect() for { longQueries, err := mysql.GetLongRunningQueries(dbConn, config) if err != nil { fmt.Println(err) os.Exit(1) } showKillPrompt(longQueries, dbConn, config) fmt.Println("💫 Rechecking...") } } func generateConfig() { var file string if len(os.Args) > 2 { file = os.Args[2] } err := configuration.Generate(file) if err != nil { fmt.Println(err) os.Exit(1) } os.Exit(0) } func showHelp() { help := ` _____ ____ / \ | o | | |/ ___\| |_________/ |_|_| |_|_| kill-mysql-query interactively shows long running queries in MySQL database and provides option to kill them one by one. Great for firefighting. 🔥🚨🚒 It can connect to MySQL server as configured, using SSH Tunnel if necessary and let you decide which query to kill. By default queries running for more than 10 seconds will be marked as long running queries, but it can be configured. ------ Usage: kill-mysql-query [config.toml]: Checks for long running queries in the configured server. If no file is given, it tries to read from config.toml in the current directory. Other commands: generate [config.toml]: Generates a new empty configuration file init: Alias for generate help, --help, -h: Shows this message ` fmt.Println(help) os.Exit(0) } func showKillPrompt(longQueries []mysql.MysqlProcess, dbConn *sqlx.DB, config configuration.Config) { if len(longQueries) == 0 { fmt.Printf("✨ No queries are running for more than %d second(s). Quitting! 👋\n", config.LongQuery.TimeoutSecond) os.Exit(0) } cyan := color.FgCyan.Render green := color.FgGreen.Render if len(longQueries) == 1 { fmt.Println() fmt.Println() fmt.Printf("❄️ Found %s long running query!\n", cyan("1")) query := longQueries[0] label := fmt.Sprintf("🐢 This query is running for %s second(s) in the `%s` database:\n\n%s\n\n", cyan(query.Time), cyan(query.DB), cyan(query.TruncatedQuery)) fmt.Println(label) prompt := promptui.Prompt{ Label: "🧨 Kill it?", IsConfirm: true, Default: "n", } result, _ := prompt.Run() if strings.TrimSpace(strings.ToLower(result)) == "y" { err := mysql.KillMySQLProcess(query.KillCommand, dbConn) if err != nil { fmt.Printf("😓 There was an error killing the query: %v\n", err) os.Exit(1) } } else { fmt.Println("Quitting! 👋") os.Exit(0) } } if len(longQueries) > 1 { fmt.Println() fmt.Println() fmt.Printf("❄️ Found %s long running queries!\n", cyan(len(longQueries))) fmt.Println() templates := &promptui.SelectTemplates{ Label: "{{ . }}?", Active: "👉 DB `{{ .DB | cyan }}`, Running Time: {{ .Time | cyan }}s, Query: {{ .TruncatedQuery | cyan }}", Inactive: " DB `{{ .DB }}`, Running Time: {{ .Time }}s, Query: {{ .TruncatedQuery }}", Selected: "💥 DB `{{ .DB | cyan }}`, Running Time: {{ .Time | cyan }}s, Query: {{ .TruncatedQuery | cyan }}", Details: ` --------- QUERY ---------- {{ "ID:" | faint }} {{ .ID }} {{ "DB:" | faint }} {{ .DB }} {{ "State:" | faint }} {{ .State.String }} {{ "Command:" | faint }} {{ .Command }} {{ "Running Time:" | faint }} {{ .Time }} second(s) {{ "Query:" | faint }} {{ .TruncatedQuery }}`, } label := fmt.Sprintf("Press %s to confirm. Which one to kill?", green("ENTER")) prompt := promptui.Select{ Label: label, Items: longQueries, Templates: templates, Size: 10, } i, _, err := prompt.Run() if err != nil { fmt.Printf("😓 There was an error: %v\n", err) os.Exit(1) } selectedQuery := longQueries[i] err = mysql.KillMySQLProcess(selectedQuery.KillCommand, dbConn) if err != nil { fmt.Printf("😓 There was an error killing the query: %v\n", err) os.Exit(1) } } }
#! /bin/bash # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. set -x sudo apt-get update sudo apt-get install uml-utilities qemu-kvm bridge-utils virtinst libvirt-bin -y # net-start will fail if the network is already started. # we ignore this error here. sudo virsh net-start default || true sudo tunctl -t tap0 sudo ifconfig tap0 up sudo brctl addif virbr0 tap0 echo "Current iptable rules:" sudo iptables -L --line-numbers sudo iptables -D FORWARD 4 sudo iptables -D FORWARD 4 # For debugging purpose, output the iptable rules. There should be no REJECT rules # at this point echo "There should be no REJECT rules now:" sudo iptables -L --line-numbers
package plain import ( "os" "gopkg.in/src-d/go-billy.v4" ) var requiredGitPaths = []string{"HEAD", "objects", "refs/heads"} // IsRepository return true if the given path in the given filesystem contains a // valid repository. // // The identifciation method is based on the stat of 3 different files/folder, // cgit, makes a extra validation in the content on the HEAD file. func IsRepository(fs billy.Filesystem, path string, isBare bool) (bool, error) { if !isBare { path = fs.Join(path, ".git") } return isDotGitRepository(fs, path) } func isDotGitRepository(fs billy.Filesystem, path string) (bool, error) { for _, p := range requiredGitPaths { _, err := fs.Stat(fs.Join(path, p)) if err != nil { if os.IsNotExist(err) { return false, nil } return false, err } } return true, nil }
package io.cattle.platform.metadata.impl; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import io.cattle.platform.core.addon.metadata.InstanceInfo; import io.cattle.platform.core.constants.AccountConstants; import io.cattle.platform.core.constants.HealthcheckConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.constants.ProjectConstants; import io.cattle.platform.core.dao.ClusterDao; import io.cattle.platform.core.model.Account; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.Network; import io.cattle.platform.core.model.Service; import io.cattle.platform.core.model.Stack; import io.cattle.platform.engine.manager.LoopManager; import io.cattle.platform.engine.model.Trigger; import io.cattle.platform.eventing.EventService; import io.cattle.platform.lock.LockManager; import io.cattle.platform.metadata.Metadata; import io.cattle.platform.metadata.MetadataManager; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.meta.ObjectMetaDataManager; import io.cattle.platform.util.type.CollectionUtils; import io.github.ibuildthecloud.gdapi.condition.Condition; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import static java.util.stream.Collectors.*; public class EnvironmentResourceManagerImpl implements MetadataManager { private static final Class<?>[] LOAD_TYPES = new Class<?>[]{ Host.class, Instance.class, Service.class, Stack.class, Network.class, Account.class, }; private static final Set<Class<?>> CLUSTER_TYPES = CollectionUtils.set( Account.class, Host.class, Network.class ); ClusterDao clusterDao; MetadataObjectFactory factory; LoopManager loopManager; LockManager lockManager; ObjectManager objectManager; EventService eventService; List<Trigger> triggers; NullMetadata nullMetadata; LoadingCache<Long, Metadata> metadataCache = CacheBuilder.newBuilder() .expireAfterAccess(30, TimeUnit.MINUTES) .build(new CacheLoader<Long, Metadata>() { @Override public Metadata load(Long accountId) throws Exception { return buildMetadata(accountId); } }); public EnvironmentResourceManagerImpl(MetadataObjectFactory factory, LoopManager loopManager, LockManager lockManager, ObjectManager objectManager, EventService eventService, ClusterDao clusterDao, List<Trigger> triggers) { this.factory = factory; this.loopManager = loopManager; this.lockManager = lockManager; this.objectManager = objectManager; this.eventService = eventService; this.clusterDao = clusterDao; this.triggers = triggers; this.nullMetadata = new NullMetadata(objectManager); } private Metadata buildMetadata(long accountId) { Account account = objectManager.loadResource(Account.class, accountId); MetadataImpl metadata = new MetadataImpl(account, eventService, factory, loopManager, lockManager, objectManager, triggers); for (Class<?> clz : LOAD_TYPES) { List<?> objectList = Collections.emptyList(); if (CLUSTER_TYPES.contains(clz)) { if (account.getClusterOwner()) { if (clz == Account.class) { objectList = objectManager.find(clz, ObjectMetaDataManager.CLUSTER_FIELD, account.getClusterId(), ObjectMetaDataManager.KIND_FIELD, Condition.in(AccountConstants.TYPE, ProjectConstants.TYPE), ObjectMetaDataManager.REMOVED_FIELD, null); } else { objectList = objectManager.find(clz, ObjectMetaDataManager.CLUSTER_FIELD, account.getClusterId(), ObjectMetaDataManager.REMOVED_FIELD, null); } } } else { objectList = objectManager.find(clz, ObjectMetaDataManager.ACCOUNT_FIELD, accountId, ObjectMetaDataManager.REMOVED_FIELD, null); } objectList.forEach(metadata::changed); } return metadata; } @Override public Metadata getMetadataForCluster(long clusterId) { Long clusterAccountId = clusterDao.getOwnerAcccountIdForCluster(clusterId); if (clusterAccountId == null) { return nullMetadata; } return getMetadataForAccount(clusterAccountId); } @Override public Metadata getMetadataForAccount(long accountId) { Metadata metadata = metadataCache.getUnchecked(accountId); if (metadata instanceof NullMetadata) { metadataCache.invalidate(accountId); } return metadata; } @Override public List<Long> getAgentProvider(String providedServiceLabel, long clusterId) { return getMetadataForCluster(clusterId).getInstances().stream() .filter((instance) -> instance.getAgentId() != null) .filter(this::healthyAndActive) .filter((instance) -> instance.getLabels().containsKey(providedServiceLabel)) .map(InstanceInfo::getAgentId) .collect(toList()); } @Override public List<Long> getAgentProviderIgnoreHealth(String providedServiceLabel, long clusterId) { return getMetadataForCluster(clusterId).getInstances().stream() .filter(instance -> instance.getAgentId() != null) .filter(instance -> instance.getLabels().containsKey(providedServiceLabel)) .map(InstanceInfo::getAgentId) .collect(toList()); } private boolean healthyAndActive(InstanceInfo instance) { return HealthcheckConstants.isHealthy(instance.getHealthState()) && InstanceConstants.STATE_RUNNING.equals(instance.getState()); } }
#!/bin/bash function docker_tag_exists() { EXISTS=$(curl -s https://hub.docker.com/v2/repositories/$1/tags/?page_size=10000 | jq -r "[.results | .[] | .name == \"$2\"] | any") test $EXISTS = true } if docker_tag_exists svenruppert/maven-3.6.1-liberica 1.12.0; then echo skip building, image already existing - svenruppert/maven-3.6.1-liberica 1.12.0 else echo start building the images docker build -t svenruppert/maven-3.6.1-liberica . docker tag svenruppert/maven-3.6.1-liberica:latest svenruppert/maven-3.6.1-liberica:1.12.0 docker push svenruppert/maven-3.6.1-liberica:1.12.0 fi
<reponame>arif25169/prime3fix<filename>components/datatable/BodyRow.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BodyRow = void 0; var _react = _interopRequireWildcard(require("react")); var _classnames = _interopRequireDefault(require("classnames")); var _BodyCell = require("./BodyCell"); var _DomHandler = _interopRequireDefault(require("../utils/DomHandler")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } var BodyRow = /*#__PURE__*/ function (_Component) { _inherits(BodyRow, _Component); function BodyRow(props) { var _this; _classCallCheck(this, BodyRow); _this = _possibleConstructorReturn(this, _getPrototypeOf(BodyRow).call(this, props)); _this.onClick = _this.onClick.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onDoubleClick = _this.onDoubleClick.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_assertThisInitialized(_this))); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_assertThisInitialized(_this))); return _this; } _createClass(BodyRow, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onDoubleClick", value: function onDoubleClick(event) { if (this.props.onDoubleClick) { this.props.onDoubleClick({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onTouchEnd", value: function onTouchEnd(event) { if (this.props.onTouchEnd) { this.props.onTouchEnd(event); } } }, { key: "onRightClick", value: function onRightClick(event) { if (this.props.onRightClick) { this.props.onRightClick({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onMouseDown", value: function onMouseDown(event) { if (_DomHandler.default.hasClass(event.target, 'p-table-reorderablerow-handle')) event.currentTarget.draggable = true;else event.currentTarget.draggable = false; } }, { key: "onDragEnd", value: function onDragEnd(event) { if (this.props.onDragEnd) { this.props.onDragEnd(event); } event.currentTarget.draggable = false; } }, { key: "onDragOver", value: function onDragOver(event) { if (this.props.onDragOver) { this.props.onDragOver({ originalEvent: event, rowElement: this.container }); } event.preventDefault(); } }, { key: "onDragLeave", value: function onDragLeave(event) { if (this.props.onDragLeave) { this.props.onDragLeave({ originalEvent: event, rowElement: this.container }); } } }, { key: "onDrop", value: function onDrop(event) { if (this.props.onDrop) { this.props.onDrop({ originalEvent: event, rowElement: this.container }); } event.preventDefault(); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.selectionMode) { var row = event.target; switch (event.which) { //down arrow case 40: var nextRow = this.findNextSelectableRow(row); if (nextRow) { nextRow.focus(); } event.preventDefault(); break; //up arrow case 38: var prevRow = this.findPrevSelectableRow(row); if (prevRow) { prevRow.focus(); } event.preventDefault(); break; //enter case 13: this.onClick(event); break; default: //no op break; } } } }, { key: "findNextSelectableRow", value: function findNextSelectableRow(row) { var nextRow = row.nextElementSibling; if (nextRow) { if (_DomHandler.default.hasClass(nextRow, 'p-datatable-row')) return nextRow;else return this.findNextSelectableRow(nextRow); } else { return null; } } }, { key: "findPrevSelectableRow", value: function findPrevSelectableRow(row) { var prevRow = row.previousElementSibling; if (prevRow) { if (_DomHandler.default.hasClass(prevRow, 'p-datatable-row')) return prevRow;else return this.findPrevSelectableRow(prevRow); } else { return null; } } }, { key: "render", value: function render() { var _this2 = this; var columns = _react.default.Children.toArray(this.props.children); var conditionalStyles = { 'p-highlight': this.props.selected, 'p-highlight-contextmenu': this.props.contextMenuSelected }; if (this.props.rowClassName) { var rowClassNameCondition = this.props.rowClassName(this.props.rowData); conditionalStyles = _objectSpread({}, conditionalStyles, rowClassNameCondition); } var className = (0, _classnames.default)('p-datatable-row', conditionalStyles); var hasRowSpanGrouping = this.props.rowGroupMode === 'rowspan'; var cells = []; for (var i = 0; i < columns.length; i++) { var column = columns[i]; var rowSpan = void 0; if (hasRowSpanGrouping) { if (this.props.sortField === column.props.field) { if (this.props.groupRowSpan) rowSpan = this.props.groupRowSpan;else continue; } } var cell = _react.default.createElement(_BodyCell.BodyCell, _extends({ key: i }, column.props, { value: this.props.value, rowSpan: rowSpan, rowData: this.props.rowData, rowIndex: this.props.rowIndex, onRowToggle: this.props.onRowToggle, expanded: this.props.expanded, onRadioClick: this.props.onRadioClick, onCheckboxClick: this.props.onCheckboxClick, responsive: this.props.responsive, selected: this.props.selected })); cells.push(cell); } return _react.default.createElement("tr", { tabIndex: this.props.selectionMode ? '0' : null, ref: function ref(el) { _this2.container = el; }, className: className, onClick: this.onClick, onDoubleClick: this.onDoubleClick, onTouchEnd: this.onTouchEnd, onContextMenu: this.onRightClick, onMouseDown: this.onMouseDown, onDragStart: this.props.onDragStart, onDragEnd: this.onDragEnd, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDrop: this.onDrop, style: { height: this.props.virtualRowHeight }, onKeyDown: this.onKeyDown }, cells); } }]); return BodyRow; }(_react.Component); exports.BodyRow = BodyRow;
<gh_stars>1-10 /* * Copyright (c) Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.domain.product; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.List; import org.ofbiz.base.util.UtilValidate; import org.opentaps.base.entities.GoodIdentification; import org.opentaps.base.entities.ProductCategory; import org.opentaps.base.entities.ProductFeatureAndAppl; import org.opentaps.base.entities.ProductType; import org.opentaps.foundation.entity.EntityFieldInterface; import org.opentaps.foundation.repository.RepositoryException; /** * Product entity, encapsulate product specific functionality. */ public class Product extends org.opentaps.base.entities.Product { private List<ProductFeatureAndAppl> features; private List<ProductFeatureAndAppl> stdFeatures; private Product variantOf; private ProductCategory primaryCategory; /** * Default public constructor. */ public Product() { super(); } /** * Tests product if this product is physical. * @return a <code>Boolean</code> value * @throws RepositoryException if an error occurs */ public Boolean isPhysical() throws RepositoryException { return !("N".equals(getType().getIsPhysical())); } /** * Tests if the product is virtual. A virtual product * is the parent product of a set of variants. * @return <code>true</code> if the product is virtual */ public Boolean isVirtual() { return "Y".equals(getIsVirtual()); } /** * Tests if the product is a variant. * @return <code>true</code> if the product is a variant */ public Boolean isVariant() { return "Y".equals(getIsVariant()); } /** * Gets this product type. * @return the <code>ProductType</code> * @throws RepositoryException if an error occurs */ public ProductType getType() throws RepositoryException { return this.getProductType(); } /** * Returns this product <code>GoodIdentification</code> for the given type. * @param goodIdentificationTypeId the type of good identifation to find * @return the <code>GoodIdentification</code> found, or null * @throws RepositoryException if an error occurs */ public GoodIdentification getGoodIdentificationByType(String goodIdentificationTypeId) throws RepositoryException { return getRepository().getGoodIdentificationByType(this.getProductId(), goodIdentificationTypeId); } /** * Gets the unit price for this product. * @return the unit price for the default currency * @exception RepositoryException if an error occurs */ public BigDecimal getUnitPrice() throws RepositoryException { return getRepository().getUnitPrice(this); } /** * Gets the unit price for this product. * @param currencyUomId the currency for which the cost is calculated * @return the unit price for the given currency * @exception RepositoryException if an error occurs */ public BigDecimal getUnitPrice(String currencyUomId) throws RepositoryException { return getRepository().getUnitPrice(this, currencyUomId); } /** * Gets the standard cost for this product. * @return the standard cost for the default currency * @exception RepositoryException if an error occurs */ public BigDecimal getStandardCost() throws RepositoryException { return getRepository().getStandardCost(this); } /** * Gets the standard cost for this product. * @param currencyUomId the currency for which the cost is calculated * @return the standard cost for the given currency * @exception RepositoryException if an error occurs */ public BigDecimal getStandardCost(String currencyUomId) throws RepositoryException { return getRepository().getStandardCost(this, currencyUomId); } /** * Gets the variant products. This product must be virtual. If no * variants found, returns an empty list. * @return Variants or an empty list. * @throws RepositoryException if an error occurs */ public List<Product> getVariants() throws RepositoryException { return getRepository().getVariants(this); } /** * Gets the Product this Product is a variant of. If no * variants found, returns null. * @return Product this is a Variant of or null * @throws RepositoryException if an error occurs */ public Product getVariantOf() throws RepositoryException { if (variantOf == null) { variantOf = getRepository().getVariantOf(this); } return variantOf; } private ProductRepositoryInterface getRepository() { return ProductRepositoryInterface.class.cast(repository); } /** * Gets the sale price for this product. * @return the sale price for the default currency * @exception RepositoryException if an error occurs */ public BigDecimal getSalePrice() throws RepositoryException { return getRepository().getSalePrice(this); } /** * Gets the sale price for this product. * @param currencyUomId the currency for which the sale price is calculated * @return the sale price for the given currency * @exception RepositoryException if an error occurs */ public BigDecimal getSalePrice(String currencyUomId) throws RepositoryException { return getRepository().getSalePrice(this, currencyUomId); } /** * Gets the base price for this product. * @return the unit price for the default currency * @exception RepositoryException if an error occurs */ public BigDecimal getBasePrice() throws RepositoryException { return getRepository().getBasePrice(this); } /** * Gets the base price for this product. * @param currencyUomId the currency for which the cost is calculated * @return the unit price for the given currency * @exception RepositoryException if an error occurs */ public BigDecimal getBasePrice(String currencyUomId) throws RepositoryException { return getRepository().getBasePrice(this, currencyUomId); } /** * Gets all the features of this product. * @return a list of <code>ProductFeatureAndAppl</code> values * @exception RepositoryException if an error occurs * @see #getStandardFeatures() */ public List<ProductFeatureAndAppl> getFeatures() throws RepositoryException { if (features == null) { features = getRepository().getProductFeatures(this); } return features; } /** * Gets the standard features of this product. * @return a list of <code>ProductFeatureAndAppl</code> values * @exception RepositoryException if an error occurs * @see #getFeatures() */ public List<ProductFeatureAndAppl> getStandardFeatures() throws RepositoryException { if (stdFeatures == null) { stdFeatures = getRepository().getProductFeatures(this, "STANDARD_FEATURE"); } return stdFeatures; } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param field a <code>EntityFieldInterface</code> value * @return a <code>String</code> value, or null if not found */ public Object getAndFallbackToParent(EntityFieldInterface<? extends org.opentaps.base.entities.Product> field) { return getAndFallbackToParent(field.getName()); } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param fieldName a <code>String</code> value * @return a <code>String</code> value, or null if not found */ public Object getAndFallbackToParent(String fieldName) { if (UtilValidate.isEmpty(super.get(fieldName)) && isVariant()) { try { Product parent = getVariantOf(); if (parent != null) { return parent.getAndFallbackToParent(fieldName); } } catch (RepositoryException e) { return null; } } return super.get(fieldName); } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param field a <code>EntityFieldInterface</code> value * @return a <code>String</code> value, or null if not found */ public String getStringAndFallbackToParent(EntityFieldInterface<? extends org.opentaps.base.entities.Product> field) { return getStringAndFallbackToParent(field.getName()); } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param fieldName a <code>String</code> value * @return a <code>String</code> value, or null if not found */ public String getStringAndFallbackToParent(String fieldName) { if (UtilValidate.isEmpty(super.getString(fieldName)) && isVariant()) { try { Product parent = getVariantOf(); if (parent != null) { return parent.getStringAndFallbackToParent(fieldName); } } catch (RepositoryException e) { return null; } } return super.getString(fieldName); } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param field a <code>EntityFieldInterface</code> value * @return a <code>String</code> value, or null if not found */ public Timestamp getTimestampAndFallbackToParent(EntityFieldInterface<? extends org.opentaps.base.entities.Product> field) { return getTimestampAndFallbackToParent(field.getName()); } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param fieldName a <code>String</code> value * @return a <code>String</code> value, or null if not found */ public Timestamp getTimestampAndFallbackToParent(String fieldName) { if (UtilValidate.isEmpty(super.getTimestamp(fieldName)) && isVariant()) { try { Product parent = getVariantOf(); if (parent != null) { return parent.getTimestampAndFallbackToParent(fieldName); } } catch (RepositoryException e) { return null; } } return super.getTimestamp(fieldName); } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param field a <code>EntityFieldInterface</code> value * @return a <code>String</code> value, or null if not found */ public BigDecimal getBigDecimalAndFallbackToParent(EntityFieldInterface<? extends org.opentaps.base.entities.Product> field) { return getBigDecimalAndFallbackToParent(field.getName()); } /** * Gets the field value, check the parent if this product is variant and its field value is empty. * @param fieldName a <code>String</code> value * @return a <code>String</code> value, or null if not found */ public BigDecimal getBigDecimalAndFallbackToParent(String fieldName) { if (UtilValidate.isEmpty(super.getBigDecimal(fieldName)) && isVariant()) { try { Product parent = getVariantOf(); if (parent != null) { return parent.getBigDecimalAndFallbackToParent(fieldName); } } catch (RepositoryException e) { return null; } } return super.getBigDecimal(fieldName); } /** * Gets the product primary category. * @return a <code>ProductCategory</code> value, or null if not found * @exception RepositoryException if an error occurs */ public ProductCategory getPrimaryCategory() throws RepositoryException { if (primaryCategory == null) { primaryCategory = getRepository().getPrimaryParentCategory(this); } return primaryCategory; } }
<reponame>lpellegr/lettusearch package com.redislabs.lettusearch.aggregate.reducer; import lombok.Builder; import lombok.Data; @Builder public @Data class By { private String property; private Order order; }