text
stringlengths
1
1.05M
import { Module } from '@nestjs/common'; import { WebsitesService } from './websites.service'; import { WebsitesController } from './websites.controller'; import {TypeOrmModule} from "@nestjs/typeorm"; import {Websites} from "./entities/Websites"; import {AuthModule} from "../auth/auth.module"; @Module({ providers: [WebsitesService], controllers: [WebsitesController], imports: [ TypeOrmModule.forFeature([Websites]), AuthModule, ], exports: [WebsitesService] }) export class WebsitesModule {}
#!/usr/bin/env bash # Script Name: count_files.sh # Description: Counts the total number of lines of code in a given git repository. # Usage: count_files.sh [<repository_path>] # [<repository_path>] - the path to the git repository. # Example: ./count_files.sh path/to/repository main() { if [ $# -eq 0 ]; then path="." elif [ -d $1 ]; then path="$1" else echo "provided path is not valid!" exit 1 fi cd $path git ls-files -z | xargs -0 wc -l | awk 'END{print}' } main "$@"
#!/bin/sh # # Utility tools for building configure/packages by AntPickax # # Copyright 2018 Yahoo Japan Corporation. # # AntPickax provides utility tools for supporting autotools # builds. # # These tools retrieve the necessary information from the # repository and appropriately set the setting values of # configure, Makefile, spec,etc file and so on. # These tools were recreated to reduce the number of fixes and # reduce the workload of developers when there is a change in # the project configuration. # # For the full copyright and license information, please view # the license file that was distributed with this source code. # # AUTHOR: Takeshi Nakatani # CREATE: Fri, Apr 13 2018 # REVISION: # # # This script gets short/long description from man page. # func_usage() { echo "" echo "Usage: $1 <man page file path> [-short | -long | -esclong | -deblong]" echo "" echo " man page file path Input file path for man page file in source directory" echo " -short return short(summary) description" echo " -long return long description" echo " -esclong return long description with escaped LF" echo " -deblong return long description for debian in debian control file" echo "" } PRGNAME=$(basename "$0") MYSCRIPTDIR=$(dirname "$0") # shellcheck disable=SC2034 SRCTOP=$(cd "${MYSCRIPTDIR}/.." || exit 1; pwd) # # Check options # INFILE="" ISSHORT=0 SPACECHAR=0 ESCLF="" while [ $# -ne 0 ]; do if [ "X$1" = "X" ]; then break; elif [ "X$1" = "X-h" ] || [ "X$1" = "X-help" ]; then func_usage "${PRGNAME}" exit 0 elif [ "X$1" = "X-short" ]; then ISSHORT=1 elif [ "X$1" = "X-long" ]; then ISSHORT=0 SPACECHAR=0 elif [ "X$1" = "X-esclong" ]; then ISSHORT=0 ESCLF="\\n\\" elif [ "X$1" = "X-deblong" ]; then ISSHORT=0 SPACECHAR=1 else if [ "X${INFILE}" != "X" ]; then echo "ERROR: already ${INFILE} file is specified." 1>&2 echo "No description by $PRGNAME with error." exit 1 fi if [ ! -f "$1" ]; then echo "ERROR: $1 file is not existed." 1>&2 echo "No description by $PRGNAME with error." exit 1 fi INFILE=$1 fi shift done # # put man page formatted by nroff and insert space head. # TEMPFILE=/tmp/"${PRGNAME}_$$".tmp nroff -man "${INFILE}" 2>/dev/null | col -b 2>/dev/null | sed 's/[0-9][0-9]*m//g' 2>/dev/null | sed 's/^\s/_____/g' > "${TEMPFILE}" 2>/dev/null if [ $? -ne 0 ]; then echo "ERROR: Could not read ${INFILE} file with converting." 1>&2 echo "No description by $PRGNAME with error." rm -f "${TEMPFILE}" > /dev/null 2>&1 exit 1 fi # # Loop for printing with converting # LINELEVEL=0 LONGDEST_START="no" while read -r LINE; do # # revert inserted special chars. # CHKLINE=$(echo "${LINE}" | sed -e 's/^_____//g' -e 's/\t/ /g' -e 's/^[ ]*//g' -e 's/ \+/ /g') if [ "${LINELEVEL}" -eq 0 ]; then if [ "X${CHKLINE}" = "XNAME" ]; then LINELEVEL=1 fi elif [ "${LINELEVEL}" -eq 1 ]; then if [ "${ISSHORT}" -eq 1 ]; then echo "${CHKLINE}${ESCLF}" | sed 's/.* - //g' break fi LINELEVEL=2 elif [ "${LINELEVEL}" -eq 2 ]; then if [ "X${CHKLINE}" = "XDESCRIPTION" ]; then LINELEVEL=3 fi elif [ "${LINELEVEL}" -eq 3 ]; then if [ "X${CHKLINE}" = "X" ]; then if [ "${SPACECHAR}" -eq 1 ]; then echo " .${ESCLF}" else echo "${ESCLF}" fi else if [ "X${LINE}" = "X$CHKLINE" ]; then # # This is new section # break fi if [ "${SPACECHAR}" -eq 0 ]; then echo "${CHKLINE}${ESCLF}" else if [ "X${LONGDEST_START}" = "Xno" ]; then echo " ${CHKLINE}${ESCLF}" LONGDEST_START="yes" else echo " ${CHKLINE}${ESCLF}" fi fi fi fi done < "${TEMPFILE}" rm -f "${TEMPFILE}" > /dev/null 2>&1 exit 0 # # Local variables: # tab-width: 4 # c-basic-offset: 4 # End: # vim600: noexpandtab sw=4 ts=4 fdm=marker # vim<600: noexpandtab sw=4 ts=4 #
<reponame>brandonpittman/redwood<gh_stars>0 #!/usr/bin/env node // This downloads the latest release of Redwood from https://github.com/redwoodjs/create-redwood-app/ // and extracts it into the supplied directory. // // Usage: // `$ yarn create redwood-app ./path/to/new-project` import fs from 'fs' import path from 'path' import decompress from 'decompress' import axios from 'axios' import Listr from 'listr' import execa from 'execa' import tmp from 'tmp' const RELEASE_URL = 'https://api.github.com/repos/redwoodjs/create-redwood-app/releases' const latestReleaseZipFile = async () => { const response = await axios.get(RELEASE_URL) return response.data[0].zipball_url } const downloadFile = async (sourceUrl, targetFile) => { const writer = fs.createWriteStream(targetFile) const response = await axios.get(sourceUrl, { responseType: 'stream', }) response.data.pipe(writer) return new Promise((resolve, reject) => { writer.on('finish', resolve) writer.on('error', reject) }) } const tmpDownloadPath = tmp.tmpNameSync({ prefix: 'redwood', postfix: '.zip', }) // To run any commands, use these to set path for the working dir const targetDir = String(process.argv.slice(2)).replace(/,/g, '-') const newAppDir = path.resolve(process.cwd(), targetDir) // Uses Listr: https://github.com/SamVerschueren/listr // Sequencial terminal tasks and output // Individual task error stops execution unless `exitOnError: false` const tasks = new Listr( [ { title: 'Pre-Installation Check', task: () => { return new Listr( [ { title: 'Checking for path in command', task: () => { if (!targetDir) { throw new Error( 'Missing path arg. Usage `yarn create redwood-app ./path/to/new-project`' ) } }, }, { title: 'Checking if directory already exists', task: () => { if (fs.existsSync(newAppDir)) { throw new Error( `Install error: directory ${targetDir} already exists.` ) } }, }, ], { concurrent: true } ) }, }, { title: `Creating "${newAppDir}/"`, task: () => { fs.mkdirSync(newAppDir, { recursive: true }) }, }, { title: 'Extracting “Create-Redwood-App” Current Release', task: () => { return new Listr([ { title: `Downloading latest release from ${RELEASE_URL}`, task: async () => { const url = await latestReleaseZipFile() return downloadFile(url, tmpDownloadPath) }, }, { title: 'Extracting...', task: async () => { await decompress(tmpDownloadPath, newAppDir, { strip: 1 }) }, }, { title: 'Set Local App Development README.md', task: (_ctx, task) => { try { fs.unlinkSync(path.join(newAppDir, './README.md')) } catch (e) { task.skip( 'Could not replace source README.md with a local copy' ) } try { fs.renameSync( path.join(newAppDir, './README_APP.md'), path.join(newAppDir, './README.md') ) } catch (e) { task.skip( 'Could not replace source README.md with a local copy' ) } }, }, { title: 'Set Local App Development .gitignore', task: (_ctx, task) => { try { fs.unlinkSync(path.join(newAppDir, './.gitignore')) } catch (e) { task.skip( 'Could not replace source .gitignore with a local copy' ) } try { fs.renameSync( path.join(newAppDir, './.gitignore.app'), path.join(newAppDir, './.gitignore') ) } catch (e) { task.skip( 'Could not replace source .gitignore with a local copy' ) } }, }, { title: 'Renaming index.html Meta Title', task: (_ctx, task) => { try { const indexHtml = path.join(newAppDir, './web/src/index.html') const data = fs.readFileSync(indexHtml, 'utf8') const newTitle = String(targetDir) .split('/') .slice(-1)[0] .split(/[ _-]/) .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .join(' ') fs.writeFileSync( indexHtml, data.replace( RegExp('<title>(.*?)</title>'), '<title>' + String(newTitle) + '</title>' ), 'utf8' ) task.title = `index.html Meta Title is now "${newTitle}"` } catch (e) { task.skip('Error updating title tag for /web/src/index.html') } }, }, ]) }, }, { title: 'Installing Packages', task: async (ctx, task) => { task.output = `...installing packages...` return execa('yarn install', { shell: true, cwd: `${targetDir}`, }).catch(() => { ctx.stop = true task.title = `${task.title} (or not)` throw new Error('Yarn not installed. Cannot proceed.') }) }, }, { title: '...Redwood planting in progress...', task: (_ctx, task) => { task.title = 'SUCCESS: Your Redwood is Ready to Grow!' console.log('') }, }, ], { collapse: false } ) tasks.run().catch((e) => { console.log(e.message) })
#!/usr/bin/env bash read -p "Input the index you want to start: " index read -p "Input file format: " suffix for file in $(ls *.$suffix) do mv $file $index.$suffix index=$((index+1)) done
import { ArgsType, Field } from '@nestjs/graphql'; @ArgsType() export class CreateUserArgs { @Field() username!: string; @Field() email!: string; }
<gh_stars>1-10 // Copyright 2016-present Province of British Columbia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {AnyObject, Filter} from '@loopback/repository'; let server: any; module.exports.request = require('axios'); module.exports.mailParser = require('mailparser'); module.exports.app = function (...argsArr: any[]) { return new Promise((resolve, reject) => { let app, cb: Function | undefined; if (argsArr.length > 0) { if (argsArr[0] instanceof Object) { app = argsArr[0]; } if (argsArr[argsArr.length - 1] instanceof Function) { cb = argsArr[argsArr.length - 1]; } } if (server) { resolve(server); return cb && process.nextTick(cb.bind(null, null, server)); } let urlPrefix = process.env.API_URL_PREFIX ?? 'http://localhost:3000/api'; let port = process.env.LISTENING_SMTP_PORT ?? '0'; let allowedSmtpDomains = process.env.ALLOWED_SMTP_DOMAINS?.split( ',', ).map(e => e.trim().toLowerCase()); let bounceUnsubThreshold = parseInt( process.env.BOUNCE_UNSUBSCRIBE_THRESHOLD ?? '5', ); const smtpOptsString = process.env.SMTP_SERVER_OPTIONS; let smtpOpts = (smtpOptsString && JSON.parse(smtpOptsString)) || {}; let handleBounce: any = process.env.SMTP_HANDLE_BOUNCE; let bounceSubjectRegex = process.env.BOUNCE_SUBJECT_REGEX && new RegExp(process.env.BOUNCE_SUBJECT_REGEX); let bounceSmtpStatusCodeRegex = process.env.BOUNCE_SMTP_STATUS_CODE_REGEX && new RegExp(process.env.BOUNCE_SMTP_ERROR_CODE_REGEX as string); let bounceFailedRecipientRegex = process.env.BOUNCE_FAILED_RECIPIENT_REGEX && new RegExp(process.env.BOUNCE_FAILED_RECIPIENT_REGEX); if (app) { const smtpSvr = app.email.inboundSmtpServer; const internalHttpHost = app.internalHttpHost; if (internalHttpHost) { urlPrefix = internalHttpHost + app.restApiRoot; } smtpSvr.listeningSmtpPort && (port = smtpSvr.listeningSmtpPort); smtpSvr.domain && (allowedSmtpDomains = smtpSvr.domain .split(',') .map((e: string) => e.trim().toLowerCase())); smtpSvr.options && (smtpOpts = smtpSvr.options); if (app.email?.bounce?.enabled !== undefined) { handleBounce = app.email.bounce.enabled; } bounceUnsubThreshold = app.email.bounce.unsubThreshold; if ( app.email.bounce.subjectRegex && app.email.bounce.subjectRegex.length > 0 ) { bounceSubjectRegex = new RegExp(app.email.bounce.subjectRegex); } bounceSmtpStatusCodeRegex = new RegExp( app.email.bounce.smtpStatusCodeRegex, ); if ( app.email.bounce.failedRecipientRegex && app.email.bounce.failedRecipientRegex.length > 0 ) { bounceFailedRecipientRegex = new RegExp( app.email.bounce.failedRecipientRegex, ); } } if (require.main === module) { const getOpt = require('node-getopt') .create([ [ 'a', 'api-url-prefix=<string>', 'NotifyBC api url prefix; default to http://localhost:3000/api', ], [ 'd', 'allowed-smtp-domains=<string>+', 'allowed recipient email domains; if missing all are allowed; repeat the option to create multiple entries.', ], [ 'p', 'listening-smtp-port=<integer>', 'if missing a random free port is chosen. Proxy is required if port is not 25.', ], [ 'b', 'handle-bounce=<true|false>', 'whether to enable bounce handling or not.', ], [ 'B', 'bounce-unsubscribe-threshold=<integer>', 'bounce count threshold above which unsubscribe all.', ], ['s', 'bounce-subject-regex=<string>', 'bounce email subject regex'], [ 'r', 'bounce-smtp-status-code-regex=<string>', 'bounce smtp status code regex', ], [ 'R', 'bounce-failed-recipient-regex=<string>', 'bounce failed recipient regex', ], ['o', 'smtp-server-options', 'stringified json smtp server options'], ['h', 'help', 'display this help'], ]) .bindHelp( 'Usage: node ' + process.argv[1] + ' [Options]\n[Options]:\n[[OPTIONS]]', ); const args = getOpt.parseSystem(); args.options['api-url-prefix'] && (urlPrefix = args.options['api-url-prefix']); args.options['listening-smtp-port'] && (port = args.options['listening-smtp-port']); args.options['allowed-smtp-domains'] && (allowedSmtpDomains = args.options[ 'allowed-smtp-domains' ].map((e: string) => e.toLowerCase())); args.options['bounce-unsubscribe-threshold'] && (bounceUnsubThreshold = parseInt( args.options['bounce-unsubscribe-threshold'], )); args.options['smtp-server-options'] && (smtpOpts = JSON.parse(args.options['smtp-server-options'])); args.options['handle-bounce'] && (handleBounce = args.options['handle-bounce'] === 'true'); args.options['bounce-subject-regex'] && (bounceSubjectRegex = new RegExp(args.options['bounce-subject-regex'])); args.options['bounce-smtp-status-code-regex'] && (bounceSmtpStatusCodeRegex = new RegExp( args.options['bounce-smtp-status-code-regex'], )); args.options['bounce-failed-recipient-regex'] && (bounceFailedRecipientRegex = new RegExp( args.options['bounce-failed-recipient-regex'], )); } const SMTPServer = require('smtp-server').SMTPServer; const validEmailRegEx = /(un|bn)-(.+?)-(.*)@(.+)/; const _ = require('lodash'); const MaxMsgSize = 1000000; smtpOpts = _.assign({}, smtpOpts, { authOptional: true, disabledCommands: ['AUTH'], size: MaxMsgSize, onRcptTo(address: {address: string}, session: any, callback: Function) { try { const match = address.address.match(validEmailRegEx); if (match) { const domain = match[4]; if ( !allowedSmtpDomains || allowedSmtpDomains.indexOf(domain.toLowerCase()) >= 0 ) return callback(); } } catch (ex) {} return callback(new Error('invalid recipient')); }, onData(stream: any, session: any, callback: Function) { stream.setEncoding('utf8'); let msg = ''; stream.on('data', (chunk: any) => { if (msg.length < MaxMsgSize) { msg += chunk; } }); stream.on('end', async () => { for (const e of session.envelope.rcptTo) { const match = e.address.match(validEmailRegEx); const type = match[1]; const id = match[2]; const unsubscriptionCode = match[3]; switch (type) { case 'un': await exports.request.get( urlPrefix + '/subscriptions/' + id + '/unsubscribe?unsubscriptionCode=' + encodeURIComponent(unsubscriptionCode) + '&userChannelId=' + encodeURIComponent(session.envelope.mailFrom.address), { headers: { // eslint-disable-next-line @typescript-eslint/naming-convention is_anonymous: true, }, }, ); break; case 'bn': { if (!handleBounce) { break; } let parsed: AnyObject = {}; try { parsed = await exports.mailParser.simpleParser(msg); } catch (err) { console.error(err); const error: any = new Error('parsing error'); error.responseCode = 451; return callback(error); } let incrementBounceCnt = true; if ( incrementBounceCnt && bounceSubjectRegex && (!parsed.subject || !parsed.subject.match(bounceSubjectRegex)) ) { console.info(`subject doesn't match filter`); incrementBounceCnt = false; } let smtpBody = parsed.html || parsed.text; if (parsed.attachments && parsed.attachments.length > 0) { const deliveryStatusAttachment = parsed.attachments.find( (ele: {contentType: string}) => { return ( ele.contentType && ele.contentType.toLowerCase() === 'message/delivery-status' ); }, ); if (deliveryStatusAttachment?.content) { smtpBody = deliveryStatusAttachment.content.toString( 'utf8', ); } } if ( incrementBounceCnt && (!smtpBody || !smtpBody.match(bounceSmtpStatusCodeRegex)) ) { console.info(`smtp status code doesn't match filter`); incrementBounceCnt = false; } let bouncedUserChannelId; if (bounceFailedRecipientRegex) { const bouncedUserChannelIdMatch = smtpBody.match( bounceFailedRecipientRegex, ); if (bouncedUserChannelIdMatch) { bouncedUserChannelId = bouncedUserChannelIdMatch[0]; } } const xfr = parsed.headers?.get('x-failed-recipients'); if (xfr) { bouncedUserChannelId = xfr; } let filter: Filter = { where: { id: id, channel: 'email', state: 'confirmed', unsubscriptionCode: unsubscriptionCode, }, }; let body; try { const res = await exports.request.get( urlPrefix + '/subscriptions?filter=' + encodeURIComponent(JSON.stringify(filter)), ); body = res.data; } catch (err) { console.error(err); const error: any = new Error('processing error'); error.responseCode = 451; return callback(error); } if (!(body instanceof Array) || body.length !== 1) { return callback(null); } const userChannelId = body[0]?.userChannelId; if ( incrementBounceCnt && bouncedUserChannelId && userChannelId !== bouncedUserChannelId ) { console.info( `userChannelId ${userChannelId} mismatches bouncedUserChannelId ${bouncedUserChannelId}`, ); incrementBounceCnt = false; } filter = { where: { channel: 'email', state: 'active', userChannelId: userChannelId, }, }; try { const res = await exports.request.get( urlPrefix + '/bounces?filter=' + encodeURIComponent(JSON.stringify(filter)), ); body = res.data; } catch (err) { console.error(err); const error: any = new Error('processing error'); error.responseCode = 451; return callback(error); } let bncCnt = body?.[0]?.hardBounceCount || 0, bncId = body?.[0]?.id; const bounceMessages = body?.[0]?.bounceMessages || []; if (incrementBounceCnt) { bncCnt += 1; } bounceMessages.unshift({ date: new Date().toISOString(), message: msg, }); // upsert bounce if (bncId) { await exports.request.patch(urlPrefix + '/bounces/' + bncId, { hardBounceCount: bncCnt, bounceMessages: bounceMessages, }); } else { const res = await exports.request.post( urlPrefix + '/bounces', { channel: 'email', userChannelId: userChannelId, hardBounceCount: bncCnt, bounceMessages: bounceMessages, }, ); bncId = res.data.id; } // unsub user if (bncCnt > bounceUnsubThreshold) { await exports.request.get( urlPrefix + '/subscriptions/' + id + '/unsubscribe?unsubscriptionCode=' + encodeURIComponent(unsubscriptionCode) + '&userChannelId=' + encodeURIComponent(userChannelId) + '&additionalServices=_all', { headers: { // eslint-disable-next-line @typescript-eslint/naming-convention is_anonymous: true, }, maxRedirects: 0, validateStatus: function (status: number) { return status >= 200 && status < 400; }, }, ); await exports.request.patch(urlPrefix + '/bounces/' + bncId, { state: 'deleted', }); } break; } } } return callback(null); }); }, }); server = new SMTPServer(smtpOpts); server.on('error', () => {}); server.listen(parseInt(port), function (this: any) { console.info( `smtp server started listening on port ${ this.address().port } with:\napi-url-prefix=${urlPrefix}`, ); allowedSmtpDomains && console.info(`allowed-smtp-domains=${allowedSmtpDomains}`); cb?.(null, server); resolve(server); }); }); }; if (require.main === module) { module.exports.app(); }
const express = require('express'); const db = require('./db'); const router = express.Router(); router.get('/', async (req, res) => { try { const results = await db.query('SELECT name, email, password FROM users'); return res.json(results.rows); } catch (err) { return res.status(500).json({ error: err.message }); } }); module.exports = router;
package com.google.api.control.model; import static com.google.common.truth.Truth.assertThat; import com.google.api.Http; import com.google.api.HttpRule; import com.google.api.Service; import com.google.api.control.model.MethodRegistry.Info; import org.junit.Test; /** * Tests for {@link MethodRegistry}. */ public class MethodRegistryTest { private static final String SELECTOR = "a.selector"; private static final String SLASH_SELECTOR = "slash.selector"; private static final Service SERVICE = Service.newBuilder() .setName("the-service") .setHttp(Http.newBuilder() .addRules(HttpRule.newBuilder() .setSelector(SELECTOR) .setGet("/v1/foo/{bar}/baz")) .addRules(HttpRule.newBuilder() .setSelector(SLASH_SELECTOR) .setGet("/v1/baz/{bar}/foo/"))) .build(); @Test public void lookup_matchesWithOrWithoutTrailingSlashes() { MethodRegistry r = new MethodRegistry(SERVICE); assertSuccess(r.lookup("GET", "/v1/foo/2/baz"), SELECTOR); assertSuccess(r.lookup("GET", "/v1/foo/2/baz/"), SELECTOR); assertFailure(r.lookup("POST", "/v1/foo/2/baz")); assertFailure(r.lookup("POST", "/v1/foo/2/baz/")); assertSuccess(r.lookup("GET", "/v1/baz/2/foo"), SLASH_SELECTOR); assertSuccess(r.lookup("GET", "/v1/baz/2/foo/"), SLASH_SELECTOR); assertFailure(r.lookup("POST", "/v1/baz/2/foo")); assertFailure(r.lookup("POST", "/v1/baz/2/foo/")); } private static void assertFailure(Info info) { assertThat(info).isNull(); } private static void assertSuccess(Info info, String selector) { assertThat(info).isNotNull(); assertThat(info.getSelector()).isEqualTo(selector); } }
# https://developer.zendesk.com/rest_api/docs/core/macros#create-unassociated-macro-attachment zdesk_macros_attachment_create () { method=POST url=/api/v2/macros/attachments.json }
<filename>cla-frontend-project-console/src/ionic/app/app.module.ts // Copyright The Linux Foundation and each contributor to CommunityBridge. // SPDX-License-Identifier: MIT import { BrowserModule } from '@angular/platform-browser'; import { NgModule, ErrorHandler } from '@angular/core'; import { HttpModule } from '@angular/http'; import { CurrencyPipe } from '@angular/common'; import { DatePipe } from '@angular/common'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { HttpClient } from '../services/http-client'; import { CincoService } from '../services/cinco.service'; import { S3Service } from '../services/s3.service'; import { XHRBackend, RequestOptions } from '@angular/http'; import { KeycloakService } from '../services/keycloak/keycloak.service'; import { KeycloakHttp, keycloakHttpFactory } from '../services/keycloak/keycloak.http'; import { SortService } from '../services/sort.service'; import { FilterService } from '../services/filter.service'; import { ClaService } from '../services/cla.service'; import { AuthService } from '../services/auth.service'; import { AuthPage } from '../pages/auth/auth'; import { MyApp } from './app.component'; import { LfxHeaderService } from '../services/lfx-header.service'; import { LayoutModule } from '../layout/layout.module'; @NgModule({ declarations: [MyApp, AuthPage], imports: [BrowserModule, HttpModule, IonicModule.forRoot(MyApp), LayoutModule], bootstrap: [IonicApp], entryComponents: [MyApp, AuthPage], providers: [ StatusBar, SplashScreen, CurrencyPipe, DatePipe, HttpClient, CincoService, S3Service, KeycloakService, SortService, FilterService, ClaService, AuthService, LfxHeaderService, { provide: ErrorHandler, useClass: IonicErrorHandler }, { provide: KeycloakHttp, useFactory: keycloakHttpFactory, deps: [XHRBackend, RequestOptions, AuthService] } ] }) export class AppModule { }
#!/usr/bin/env sh set -e case "$1" in "") echo "No command detected. Please run container with command ('api' or 'debug')" echo "shutting down..." ;; "api") NODE_ENV=production node /app/build/services/mailer/src/index.js ;; "debug") NODE_ENV=debug node /app/build/services/mailer/src/index.js ;; *) exec "$@" ;; esac
is_zsh || return catch_signal_usr1() { trap catch_signal_usr1 USR1 stty sane reset } trap catch_signal_usr1 USR1
package malte0811.controlengineering.blocks.tape; import blusunrize.immersiveengineering.api.client.IModelOffsetProvider; import malte0811.controlengineering.blockentity.CEBlockEntities; import malte0811.controlengineering.blockentity.tape.KeypunchBlockEntity; import malte0811.controlengineering.blocks.CEBlock; import malte0811.controlengineering.blocks.placement.HorizontalStructurePlacement; import malte0811.controlengineering.blocks.shapes.CachedShape; import malte0811.controlengineering.blocks.shapes.DirectionalShapeProvider; import malte0811.controlengineering.blocks.shapes.FromBlockFunction; import malte0811.controlengineering.gui.CEContainers; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Vec3i; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.block.state.properties.Property; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class KeypunchBlock extends CEBlock<Direction> implements IModelOffsetProvider { public static final String CONTAINER_NAME = "screen.controlengineering.keypunch"; public static final Property<Direction> FACING = BlockStateProperties.HORIZONTAL_FACING; public static final Property<Boolean> UPPER = BooleanProperty.create("upper"); private static final VoxelShape BASE_SHAPE = Shapes.or(box(0, 0, 0, 16, 7, 8), box(0, 0, 8, 16, 2, 16)); public static final CachedShape<Direction> SHAPE_PROVIDER = new DirectionalShapeProvider( FromBlockFunction.getProperty(FACING), BASE_SHAPE ); public KeypunchBlock() { super( defaultPropertiesNotSolid(), HorizontalStructurePlacement.column2(FACING, UPPER), FromBlockFunction.either( FromBlockFunction.getProperty(UPPER), FromBlockFunction.constant(Shapes.block()), SHAPE_PROVIDER ), CEBlockEntities.KEYPUNCH ); } @Override protected void createBlockStateDefinition(@Nonnull StateDefinition.Builder<Block, BlockState> builder) { super.createBlockStateDefinition(builder); builder.add(FACING, UPPER); } @Nullable @Override public MenuProvider getMenuProvider( @Nonnull BlockState state, @Nonnull Level worldIn, @Nonnull BlockPos pos ) { var masterPos = getMasterPos(state, pos); var keypunchBE = worldIn.getBlockEntity(masterPos); if (keypunchBE instanceof KeypunchBlockEntity keypunch) { return new SimpleMenuProvider( CEContainers.KEYPUNCH.argConstructor(keypunch), new TranslatableComponent(CONTAINER_NAME) ); } else { return null; } } public static boolean isMaster(BlockState state) { return !state.getValue(UPPER); } public static BlockPos getMasterPos(BlockState state, BlockPos here) { return state.getValue(UPPER) ? here.below() : here; } @Override public BlockPos getModelOffset(BlockState state, @Nullable Vec3i size) { return state.getValue(UPPER) ? BlockPos.ZERO.above() : BlockPos.ZERO; } @Nullable @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker( @Nonnull Level pLevel, @Nonnull BlockState pState, @Nonnull BlockEntityType<T> pBlockEntityType ) { if (!pLevel.isClientSide()) { return CEBlockEntities.KEYPUNCH.makeMasterTicker(pBlockEntityType, KeypunchBlockEntity::tickServer); } return super.getTicker(pLevel, pState, pBlockEntityType); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package juegodecartas21; import javax.swing.ImageIcon; /** * * @author ~Antares~ */ public class Carta { private ImageIcon imagenCarta; private int valorCarta; private boolean usada; Carta(ImageIcon imagenX, int valorX){ imagenCarta=imagenX; valorCarta=valorX; usada=false; } public void setValor(int valorX){ valorCarta=valorX; } public void turnUsada(){ usada=true; } public ImageIcon getImagen(){ return imagenCarta; } public int getValor(){ return valorCarta; } public boolean getUsada(){ return usada; } }
<gh_stars>0 import request from '../utils/request'; import sys from '@/config/config'; /** * @description 登录接口 * @param data 参数 */ export function login(data){ return request({ url: sys.sysName + '/sys/login.json', method: 'post', data }); }
#include <stdio.h> const char* getEventDescription(int eventConstant) { switch (eventConstant) { case IN_DELETE_SELF: return "Watched file/directory was itself deleted."; case IN_MOVE_SELF: return "Watched file/directory was itself moved."; default: return "Unknown event"; } } int main() { int event1 = IN_DELETE_SELF; int event2 = IN_MOVE_SELF; int event3 = 123; // Unknown event printf("%s\n", getEventDescription(event1)); // Output: Watched file/directory was itself deleted. printf("%s\n", getEventDescription(event2)); // Output: Watched file/directory was itself moved. printf("%s\n", getEventDescription(event3)); // Output: Unknown event return 0; }
package logger import ( "github.com/fatih/color" "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" ) type LogLevel uint8 var logger *zap.Logger var logLevelSeverity = map[zapcore.Level]string{ zapcore.DebugLevel: "%", zapcore.InfoLevel: "*", zapcore.WarnLevel: "-", zapcore.ErrorLevel: "!", zapcore.DPanicLevel: "!", zapcore.PanicLevel: "!!", zapcore.FatalLevel: "!!", } var logLevelColor = map[zapcore.Level]func(a ...interface{}) string{ zapcore.DebugLevel: color.New().SprintFunc(), zapcore.InfoLevel: color.New(color.FgCyan).SprintFunc(), zapcore.WarnLevel: color.New(color.FgYellow).SprintFunc(), zapcore.ErrorLevel: color.New(color.FgHiRed).SprintFunc(), zapcore.DPanicLevel: color.New(color.FgWhite, color.BgRed).SprintFunc(), zapcore.PanicLevel: color.New(color.FgWhite, color.BgRed).SprintFunc(), zapcore.FatalLevel: color.New(color.FgWhite, color.BgRed).SprintFunc(), } func init() { config := zapcore.EncoderConfig{ MessageKey: "message", LevelKey: "severity", CallerKey: "caller", EncodeLevel: customEncodeLevel, EncodeCaller: zapcore.FullCallerEncoder, ConsoleSeparator: " ", } consoleDebugging := zapcore.Lock(os.Stdout) level := zap.InfoLevel if os.Getenv("GBOX_DEBUG") == "true" { level = zap.DebugLevel } core := zapcore.NewTee( zapcore.NewCore(zapcore.NewConsoleEncoder(config), consoleDebugging, level), ) logger = zap.New(core) } func customEncodeLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(logLevelColor[level](logLevelSeverity[level])) } func Logger() *zap.SugaredLogger { return logger.Sugar() }
#!/usr/bin/env bash openssl genrsa -out server.key 2048 openssl req -config openssl.cnf -new -x509 -key server.key -out server.pem -days 3650 #openssl x509 -req -days 1024 -in server.csr -signkey server.key -out server.crt #openssl req -config openssl.cnf -new -key server.key -out server.csr
#!/usr/bin/env bash # Script for running all tests and reporting coverage. # Run from project root. set -e coverage run --source=snappiershot -m pytest --quiet && coverage report
package ancient_encryption; /** * * @author erso * * Udleveret interface til opgave 2, VOP eksamen 10 juni 2016 */ public interface CipherInterface { char[] ALPHABETH = {'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F' , 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M' , 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T' , 'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z'}; String encrypt(String original); String decrypt(String encrypted); }
CURRDIR=$(pwd) echo $CURRDIR if [ ! -f "config.py" ] then touch config.py fi if grep -Fxq "TODO_DIR='${CURRDIR}'" ./config.py then echo "Env variable found" else echo "Adding env variable to bash file" rm config.py touch config.py echo "TODO_DIR='${CURRDIR}'" >> ./config.py fi if grep -Fxq "TODO_STORE_DIR='/home/$(whoami)/.todo_tracker'" ./config.py then echo "Env variable found" else echo "Adding env variable to bash file" echo "TODO_STORE_DIR='/home/$(whoami)/.todo_tracker'" >> ./config.py fi echo "x-terminal-emulator --working-directory=$CURRDIR --geometry=50x20 -e 'bash -c \"cd $CURRDIR; ./run.sh\"'" > open_terminal.sh chmod +x open_terminal.sh chmod +x run.sh
def prime_range(n): primeList = [] for number in range(2, n+1): if number > 1: for i in range(2, number): if (number % i) == 0: break else: primeList.append(number) return primeList print(prime_range(1000))
if [[ "${target_platform}" == osx-* ]]; then cmake ${CMAKE_ARGS} . elif [[ "${target_platform}" == linux-* ]]; then export CXXFLAGS="$CXXFLAGS -std=c++14" cmake ${CMAKE_ARGS} . fi cmake --build . --config release -j${CPU_COUNT} cmake --install . --config release
<reponame>arez/arez-spytools<filename>src/main/java/arez/spytools/WhyRun.java package arez.spytools; import akasha.Console; import arez.Arez; import arez.spy.ComputableValueInfo; import arez.spy.ObservableValueInfo; import arez.spy.ObserverInfo; import arez.spy.Spy; import arez.spy.TransactionInfo; import java.util.List; import javax.annotation.Nonnull; /** * A very simple utility that describes why an observer or computed value runs. */ public final class WhyRun { private WhyRun() { } public static void log() { Console.log( whyRun() ); } public static String whyRun() { return whyRun( Arez.context().getSpy() ); } /** * Return a human readable explanation why the current transaction is running. * This method will cause an invariant failure if called outside a transaction. * * @param spy the spy to introspect. * @return a human readable explanation why the current transaction is running. */ @Nonnull public static String whyRun( @Nonnull final Spy spy ) { if ( spy.isTransactionActive() ) { final TransactionInfo transaction = spy.getTransaction(); if ( transaction.isTracking() ) { return whyRun( spy, transaction.getTracker() ); } else { return "Transaction '" + transaction.getName() + "' not tracking, must be an action."; } } else { return "WhyRun invoked when no active transaction."; } } /** * Return a human readable explanation why the specified observer is/will run. * * @param spy the spy to introspect. * @param observer the observer that we want to investigate. * @return a human readable explanation why the node is/will run. */ @Nonnull public static String whyRun( @Nonnull final Spy spy, @Nonnull final ObserverInfo observer ) { if ( observer.isComputableValue() ) { return whyComputableValueRun( spy, observer.asComputableValue() ); } else { return whyObserverRun( spy, observer ); } } @Nonnull private static String whyObserverRun( @Nonnull final Spy spy, @Nonnull final ObserverInfo observer ) { final StringBuilder sb = new StringBuilder(); sb.append( "Observer '" ); sb.append( observer.getName() ); sb.append( "':\n" ); sb.append( " Status: " ); sb.append( describeStatus( spy, observer ) ); sb.append( "\n" ); sb.append( " Mode: " ); sb.append( observer.isReadOnly() ? "read-only" : "read-write" ); sb.append( "\n" ); sb.append( " * The Observer will run if any of the following observables change:\n" ); describeDependencies( sb, observer.getDependencies() ); if ( observer.isRunning() ) { sb.append( " - (... or any other observable that is accessed in the remainder of the observers transaction)\n" ); } return sb.toString(); } @Nonnull private static String whyComputableValueRun( @Nonnull final Spy spy, @Nonnull final ComputableValueInfo computableValue ) { final StringBuilder sb = new StringBuilder(); sb.append( "ComputableValue '" ); sb.append( computableValue.getName() ); sb.append( "':\n" ); sb.append( " * Status: " ); sb.append( describeComputableValueStatus( computableValue ) ); sb.append( "\n" ); if ( computableValue.isActive() ) { sb.append( " * If the ComputableValue changes the following observers will react:\n" ); for ( final ObserverInfo observer : computableValue.getObservers() ) { sb.append( " - " ); describeObserver( sb, observer ); sb.append( "\n" ); } sb.append( " * The ComputableValue will recalculate if any of the following observables change\n" ); describeDependencies( sb, computableValue.getDependencies() ); if ( spy.isTransactionActive() && computableValue.isComputing() ) { sb.append( " - (... or any other observable is accessed the remainder of the transaction computing value)\n" ); } } return sb.toString(); } /** * Return the status of specified observer as human readable string. * * @param observer the Observer. * @return the status description. */ @Nonnull private static String describeStatus( @Nonnull final Spy spy, @Nonnull final ObserverInfo observer ) { final boolean running = observer.isRunning(); if ( running ) { final TransactionInfo transaction = spy.getTransaction(); if ( transaction.isTracking() && transaction.getTracker() == observer ) { return "Running (Current Transaction)"; } else { return "Running (Suspended Transaction)"; } } else if ( observer.isDisposed() ) { return "Dispose"; } else if ( observer.isScheduled() ) { return "Scheduled"; } else { return "Idle"; } } /** * Return the status of specified ComputableValue as human readable string. * * @param computableValue the ComputableValue. * @return the status description. */ private static String describeComputableValueStatus( @Nonnull final ComputableValueInfo computableValue ) { if ( computableValue.isActive() ) { return "Active (The value is used by " + computableValue.getObservers().size() + " observers)"; } else if ( computableValue.isDisposed() ) { return "Dispose (The value has been disposed)"; } else { return "Inactive (The value is not used by any observers)"; } } private static void describeDependencies( @Nonnull final StringBuilder sb, @Nonnull final List<ObservableValueInfo> dependencies ) { for ( final ObservableValueInfo observable : dependencies ) { sb.append( " - " ); describeObservable( sb, observable ); sb.append( "\n" ); } } private static void describeObservable( @Nonnull final StringBuilder sb, @Nonnull final ObservableValueInfo observable ) { sb.append( observable.isComputableValue() ? "ComputableValue" : "Observable" ); sb.append( " '" ); sb.append( observable.getName() ); sb.append( "'" ); } private static void describeObserver( @Nonnull final StringBuilder sb, @Nonnull final ObserverInfo observer ) { sb.append( observer.isComputableValue() ? "ComputableValue" : "Observer" ); sb.append( " '" ); sb.append( observer.getName() ); sb.append( "'" ); } }
def addBinary(a, b): # Initialize result result = [] # First convert both to arrays a = list(map(int, a)) b = list(map(int, b)) # Iterate through two arrays and perform addition carry = 0 i, j = len(a)-1, len(b)-1 while i >= 0 or j >= 0: s = carry if i >= 0: s += a[i] if j >= 0: s += b[j] result.append(s%2) carry = s//2 i, j = i-1, j-1 # If carry is still left, append to result if carry != 0: result.append(carry) # print result result = result[::-1] print(''.join(str(c) for c in result)) # Driver code a = '11001100' b = '11110000' addBinary(a, b) // 100101100
process.noDeprecation = true; const webpack = require('webpack'); const path = require('path'); const modules = require('../shared/module'); // set rules like babel-loader, css-loader, etc... const resolve = require('../shared/resolve'); // write paths... const plugins = require('./plugins'); // use plugins like ExtractTextPlugin... const nodeExternals = require('webpack-node-externals'); const root = (src) => path.resolve(process.cwd(), src); const PRODUCTION = process.env.NODE_ENV === 'production'; const SERVER = true; const config = { name: 'Webpack server', devtool: 'cheap-module-eval-source-map', target: 'node', node: { __dirname: false, __filename: false, fs: 'empty' }, externals: [nodeExternals()], context: root('src'), entry : { app : [ root('src/server/entry.js'), ] }, output: { filename : 'index.js', path : root('src/server'), chunkFilename : '../../build/public/chunks/[name].[chunkhash].js', hotUpdateChunkFilename : '../../build/public/hot/[id].[hash].hot-update.js', sourceMapFilename : '../../build/public/source-maps/[id].[name].[chunkhash].map', }, module: modules(SERVER, PRODUCTION), resolve: resolve, plugins: plugins, }; module.exports = config;
#!/usr/bin/env bash set -xe # A script to build a static readline library for osx # # PREREQUESITES: # - curl # - wget # - C/C++ compiler # - /opt/nrnwheel folder created with access rights (this specific path is kept for consistency wrt `build_wheels.bash`) set -e if [[ `uname -s` != 'Darwin' ]]; then echo "Error: this script is for macOS only. readline is already built statically in the linux Docker images" exit 1 fi NRNWHEEL_DIR=/opt/nrnwheel if [[ ! -d "$NRNWHEEL_DIR" || ! -x "$NRNWHEEL_DIR" ]]; then echo "Error: /opt/nrnwheel must exist and be accessible, i.e: sudo mkdir -p /opt/nrnwheel && sudo chown -R $USER /opt/nrnwheel" exit 1 fi # 10.9 regardless of x86_64/arm64/universal2. if you want 11 for universal2 python3.8, see nrn PR #1649 comments export MACOSX_DEPLOYMENT_TARGET=10.9 (wget http://ftpmirror.gnu.org/ncurses/ncurses-6.2.tar.gz \ && tar -xvzf ncurses-6.2.tar.gz \ && cd ncurses-6.2 \ && ./configure --prefix=/opt/nrnwheel/ncurses --without-shared CFLAGS="-fPIC" \ && make -j install) (curl -L -o readline-7.0.tar.gz https://ftp.gnu.org/gnu/readline/readline-7.0.tar.gz \ && tar -xvzf readline-7.0.tar.gz \ && cd readline-7.0 \ && ./configure --prefix=/opt/nrnwheel/readline --disable-shared CFLAGS="-fPIC" \ && make -j install) (cd /opt/nrnwheel/readline/lib \ && ar -x libreadline.a \ && ar -x ../../ncurses/lib/libncurses.a \ && ar cq libreadline.a *.o \ && rm *.o) RDL_MINOS=`otool -l /opt/nrnwheel/readline/lib/libreadline.a | grep -e "minos \|version " | uniq | awk '{print $2}'` if [ "$RDL_MINOS" != "$MACOSX_DEPLOYMENT_TARGET" ]; then echo "Error: /opt/nrnwheel/readline/lib/libreadline.a doesn't match MACOSX_DEPLOYMENT_TARGET ($MACOSX_DEPLOYMENT_TARGET)" exit 1 fi echo "Done."
#!/bin/sh # # Vivado(TM) # runme.sh: a Vivado-generated Runs Script for UNIX # Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. # echo "This script was generated under a different operating system." echo "Please update the PATH and LD_LIBRARY_PATH variables below, before executing this script" exit if [ -z "$PATH" ]; then PATH=C:/Apps/Xilinx/Vivado/2020.2/ids_lite/ISE/bin/nt64;C:/Apps/Xilinx/Vivado/2020.2/ids_lite/ISE/lib/nt64:C:/Apps/Xilinx/Vivado/2020.2/bin else PATH=C:/Apps/Xilinx/Vivado/2020.2/ids_lite/ISE/bin/nt64;C:/Apps/Xilinx/Vivado/2020.2/ids_lite/ISE/lib/nt64:C:/Apps/Xilinx/Vivado/2020.2/bin:$PATH fi export PATH if [ -z "$LD_LIBRARY_PATH" ]; then LD_LIBRARY_PATH= else LD_LIBRARY_PATH=:$LD_LIBRARY_PATH fi export LD_LIBRARY_PATH HD_PWD='D:/Documents/GitHub/Digital-electronics-1/Labs/03-vivado/mux_2bit_4to1/mux_2bit_4to1.runs/synth_1' cd "$HD_PWD" HD_LOG=runme.log /bin/touch $HD_LOG ISEStep="./ISEWrap.sh" EAStep() { $ISEStep $HD_LOG "$@" >> $HD_LOG 2>&1 if [ $? -ne 0 ] then exit fi } EAStep vivado -log mux_2bit_4to1.vds -m64 -product Vivado -mode batch -messageDb vivado.pb -notrace -source mux_2bit_4to1.tcl
#! /bin/bash . "$(dirname "$0")/config.sh" NAME=c1 DOMAIN=weave.local HOSTNAME=$NAME-hostname.$DOMAIN # Docker inspect hostname + domainname of container $2 on host $1 docker_inspect_fqdn() { FQDN=$(docker_on $1 inspect --format='{{.Config.Hostname}}.{{.Config.Domainname}}' $2) echo ${FQDN%.} } # Start container with args $2.. and assert fqdn of $1 assert_expected_fqdn() { EXPECTED_FQDN=$1 shift start_container_with_dns $HOST1 "$@" assert "docker_inspect_fqdn $HOST1 $NAME" $EXPECTED_FQDN rm_containers $HOST1 $NAME } start_suite "Use container name as hostname" weave_on $HOST1 launch --ipalloc-range 10.2.0.0/24 assert_expected_fqdn "$NAME.$DOMAIN" --name=$NAME assert_expected_fqdn "$NAME.$DOMAIN" --name $NAME assert_expected_fqdn "$HOSTNAME" --name=$NAME -h $HOSTNAME assert_expected_fqdn "$HOSTNAME" --name=$NAME --hostname=$HOSTNAME assert_expected_fqdn "$HOSTNAME" --name=$NAME --hostname $HOSTNAME assert_expected_fqdn "$HOSTNAME" -h $HOSTNAME --name=$NAME assert_expected_fqdn "$HOSTNAME" --hostname=$HOSTNAME --name=$NAME assert_expected_fqdn "$HOSTNAME" --hostname $HOSTNAME --name=$NAME end_suite
#!/bin/sh set -x python 0.init.py EXP_FOLDER=$(cat .exp_folder) # Check significance for seed in $(seq 0 10) do # best_alignment in mutate 2: best_alignment=0,1,2,3,4,5,6,7::1,2,0,3,4,5,6,7::1,2,3,0,4,5,6,7::1,2,3,4,5,7,6,0::1,2,3,4,5,6,0,7::1,0,2,3,4,5,6,7::2,0,1,3,4,5,6,7::2,3,0,1,4,5,6,7 # 4eff43cf706a9cacdde5a2c8b68ff941 # worst_alignment in mutate 2: worst_alignment=0,1,2,3,4,5,6,7::1,2,0,3,4,5,6,7::1,2,3,0,4,7,6,5::1,2,3,4,5,0,6,7::1,2,3,4,5,6,0,7::1,0,2,3,4,5,6,7::0,2,1,3,4,5,6,7::2,3,0,1,4,5,6,7 # 12b3d68266e041fb3f7a912208c742d8 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$best_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$worst_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 # best_alignment in mutate 4: best_alignment=1,0,2,3,4,5,6,7::1,2,0,3,4,5,6,7::1,2,3,0,4,5,6,7::1,2,3,0,5,4,6,7::7,2,3,4,5,6,0,1::1,7,2,3,4,5,6,0::2,0,1,3,4,5,6,7::2,3,0,1,4,5,6,7 # 36494bcd6bc1c3838b1806fdfe235a38 # worst_alignment in mutate 4: worst_alignment=0,7,2,3,4,5,6,1::1,7,0,3,4,5,6,2::1,2,3,0,4,5,6,7::3,2,1,4,5,0,6,7::1,2,3,4,5,6,0,7::1,0,2,3,4,5,6,7::2,0,1,3,4,5,6,7::2,3,0,1,5,4,6,7 # bc301f1d5cf455bf3f7b3576b491d68d sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$best_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$worst_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 # best_alignment in mutate 8: best_alignment=4,1,3,2,5,0,7,6::1,2,0,3,4,5,6,7::1,2,3,5,4,0,6,7::1,2,0,4,5,3,6,7::1,2,3,4,5,6,0,7::1,0,2,3,4,5,7,6::2,0,1,3,4,5,6,7::2,3,0,1,4,5,6,7 # 62fe719074fc13bd2543f7f2bb21173b # worst_alignment in mutate 8: worst_alignment=2,1,0,3,4,5,6,7::6,5,0,3,4,2,1,7::1,2,3,0,4,5,6,7::1,2,3,5,4,0,6,7::5,3,2,4,1,6,0,7::5,0,2,3,4,1,6,7::2,0,1,3,4,5,6,7::3,2,0,1,4,5,6,7 # 56acd7d427a9f0756e9d6392b1e68d69 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$best_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$worst_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 # best_alignment in mutate 16: best_alignment=0,1,2,3,4,5,6,7::6,1,0,2,4,5,3,7::1,2,3,0,4,5,6,7::1,2,3,4,5,0,6,7::6,2,0,4,3,1,5,7::1,6,2,3,4,5,0,7::2,0,1,6,4,7,5,3::2,3,0,1,4,5,6,7 # c3ef005cd7b44e114050f60aedcd3ac8 # worst_alignment in mutate 16: worst_alignment=7,1,2,3,4,5,6,0::6,2,1,3,4,0,5,7::1,0,3,2,4,5,6,7::1,3,6,2,4,0,5,7::1,2,3,4,7,6,5,0::4,3,2,5,1,0,6,7::5,0,6,3,4,2,1,7::2,3,0,1,4,5,6,7 # 58d804231b4fef8dff98232e1903f8e9 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$best_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$worst_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 # best_alignment in mutate 32: best_alignment=7,1,2,3,4,5,6,0::1,2,0,4,7,5,6,3::3,6,1,5,4,0,2,7::1,6,3,5,4,7,2,0::6,2,0,4,5,1,3,7::0,7,2,5,3,4,1,6::2,0,7,3,4,5,1,6::2,3,0,4,6,5,1,7 # 010fe7ded85ea075dd045f067458bd4b # worst_alignment in mutate 32: worst_alignment=0,7,6,5,3,2,4,1::5,2,3,4,1,0,6,7::3,1,2,0,4,6,5,7::7,4,1,2,0,5,6,3::7,2,3,5,0,6,4,1::1,4,2,6,3,5,0,7::4,0,1,3,2,5,6,7::2,4,0,1,3,5,6,7 # 0ef1b0953b9e880b3f88f5ba0e7efe15 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$best_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 sbatch -J search_9xx_check_significance submit-short.sh python 1.train.py --seed=$seed --custom_alignment=$worst_alignment --tensorboard=tensorboard/9xx_mutate_confirm --topology_wrapper=CustomAlignWrapper --custom_align_max_joints=8 --train_bodies=900,901,902,903,904,905,906,907 --test_bodies=900,901,902,903,904,905,906,907 done
<reponame>uzelac92/jsPDF-AutoTable import { UserOptions, ColumnInput, RowInput, CellInput } from './config' import { parseHtml } from './htmlParser' import { assign } from './polyfills' import { parseSpacing } from './common' import { DocHandler, jsPDFDocument } from './documentHandler' import validateOptions from './inputValidator' import { StyleProp, StylesProps, CellHook, PageHook, Settings, HookProps, } from './models' interface ContentInput { body: RowInput[] head: RowInput[] foot: RowInput[] columns: ColumnInput[] } export interface TableInput { id: string | number | undefined settings: Settings styles: StylesProps hooks: HookProps content: ContentInput } export function parseInput(d: jsPDFDocument, current: UserOptions): TableInput { const doc = new DocHandler(d) const document = doc.getDocumentOptions() const global = doc.getGlobalOptions() validateOptions(doc, global, document, current) const options = assign({}, global, document, current) let win: Window | undefined if (typeof window !== 'undefined') { win = window } const styles = parseStyles(global, document, current) const hooks = parseHooks(global, document, current) const settings = parseSettings(doc, options) const content = parseContent(doc, options, win) return { id: current.tableId, content, hooks, styles, settings, } } function parseStyles( gInput: UserOptions, dInput: UserOptions, cInput: UserOptions ) { const styleOptions: StylesProps = { styles: {}, headStyles: {}, bodyStyles: {}, footStyles: {}, alternateRowStyles: {}, columnStyles: {}, } for (const prop of Object.keys(styleOptions) as StyleProp[]) { if (prop === 'columnStyles') { const global = gInput[prop] const document = dInput[prop] const current = cInput[prop] styleOptions.columnStyles = assign({}, global, document, current) } else { const allOptions = [gInput, dInput, cInput] const styles = allOptions.map((opts) => opts[prop] || {}) styleOptions[prop] = assign({}, styles[0], styles[1], styles[2]) } } return styleOptions } function parseHooks( global: UserOptions, document: UserOptions, current: UserOptions ) { const allOptions = [global, document, current] const result = { didParseCell: [] as CellHook[], willDrawCell: [] as CellHook[], didDrawCell: [] as CellHook[], didDrawPage: [] as PageHook[], } for (const options of allOptions) { if (options.didParseCell) result.didParseCell.push(options.didParseCell) if (options.willDrawCell) result.willDrawCell.push(options.willDrawCell) if (options.didDrawCell) result.didDrawCell.push(options.didDrawCell) if (options.didDrawPage) result.didDrawPage.push(options.didDrawPage) } return result } function parseSettings(doc: DocHandler, options: UserOptions): Settings { const margin = parseSpacing(options.margin, 40 / doc.scaleFactor()) const startY = getStartY(doc, options.startY) ?? margin.top let showFoot: 'everyPage' | 'lastPage' | 'never' if (options.showFoot === true) { showFoot = 'everyPage' } else if (options.showFoot === false) { showFoot = 'never' } else { showFoot = options.showFoot ?? 'everyPage' } let showHead: 'everyPage' | 'firstPage' | 'never' if (options.showHead === true) { showHead = 'everyPage' } else if (options.showHead === false) { showHead = 'never' } else { showHead = options.showHead ?? 'everyPage' } const useCss = options.useCss ?? false const theme = options.theme || (useCss ? 'plain' : 'striped') const horizontalPageBreak: boolean = options.horizontalPageBreak ? true : false const horizontalPageBreakRepeat = options.horizontalPageBreakRepeat ?? null return { includeHiddenHtml: options.includeHiddenHtml ?? false, useCss, theme, startY, margin, pageBreak: options.pageBreak ?? 'auto', rowPageBreak: options.rowPageBreak ?? 'auto', tableWidth: options.tableWidth ?? 'auto', showHead, showFoot, tableLineWidth: options.tableLineWidth ?? 0, tableLineColor: options.tableLineColor ?? 200, horizontalPageBreak, horizontalPageBreakRepeat, } } function getStartY(doc: DocHandler, userStartY: number | false | undefined) { const previous = doc.getLastAutoTable() const sf = doc.scaleFactor() const currentPage = doc.pageNumber() let isSamePageAsPreviousTable = false if (previous && previous.startPageNumber) { const endingPage = previous.startPageNumber + previous.pageNumber - 1 isSamePageAsPreviousTable = endingPage === currentPage } if (typeof userStartY === 'number') { return userStartY } else if (userStartY == null || userStartY === false) { if (isSamePageAsPreviousTable && previous?.finalY != null) { // Some users had issues with overlapping tables when they used multiple // tables without setting startY so setting it here to a sensible default. return previous.finalY + 20 / sf } } return null } function parseContent(doc: DocHandler, options: UserOptions, window?: Window) { let head = options.head || [] let body = options.body || [] let foot = options.foot || [] if (options.html) { const hidden = options.includeHiddenHtml if (window) { const htmlContent = parseHtml(doc, options.html, window, hidden, options.useCss) || {} head = htmlContent.head || head body = htmlContent.body || head foot = htmlContent.foot || head } else { console.error('Cannot parse html in non browser environment') } } const columns = options.columns || parseColumns(head, body, foot) return { columns, head, body, foot, } } function parseColumns(head: RowInput[], body: RowInput[], foot: RowInput[]) { const firstRow: RowInput = head[0] || body[0] || foot[0] || [] const result: ColumnInput[] = [] Object.keys(firstRow) .filter((key) => key !== '_element') .forEach((key) => { let colSpan = 1 let input: CellInput if (Array.isArray(firstRow)) { input = firstRow[parseInt(key)] } else { input = firstRow[key] } if (typeof input === 'object' && !Array.isArray(input)) { colSpan = input?.colSpan || 1 } for (let i = 0; i < colSpan; i++) { let id if (Array.isArray(firstRow)) { id = result.length } else { id = key + (i > 0 ? `_${i}` : '') } const rowResult: ColumnInput = { dataKey: id } result.push(rowResult) } }) return result }
# Copyright 2018 Jamiel Almeida # # 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. # characters considered to be part of a word for zle (zsh line editor) typeset -gx WORDCHARS='*?_-.[]~&;!#$%^(){}|' # this is the function used to generate the zkbd files mentioned below autoload -Uz zkbd typeset ZKBD_DIR="${${(%):-%x}:A:h:h}/zkbd" # expected default file to load with terminal key code definitions typeset ZKBD_FILE="${ZKBD_DIR}/${TERM}-${${${DISPLAY:-}:t}:-${VENDOR}-${OSTYPE}}" if [[ "$(uname -v)" == *"Microsoft"* ]]; then # override file to load if running on the Windows Subsystem for Linux ZKBD_FILE="${ZKBD_DIR}/${TERM}-WSL" fi if [[ -e "${ZKBD_FILE}" ]]; then source "${ZKBD_FILE}" fi unset ZKBD_DIR unset ZKBD_FILE # default the zsh mappings to be the emacs-y ones bindkey -e # accept-and-hold runs the command but keeps it in the line editor buffer bindkey '^j' accept-and-hold # copies the last word, conevient for renames for example bindkey '^o' copy-prev-shell-word # Based on the file: plugins/fancy-ctrl-z/fancy-ctrl-z.plugin.zsh # that is part of: https://github.com/robbyrussell/oh-my-zsh # # It's attributed to (broken link) on that repository # http://sheerun.net/2014/03/21/how-to-boost-your-vim-productivity/ # # As such, this function `fancy-ctrl-z` retains copyright notice and # license defined in the source repository. The text was taken verbatim and # re-formatted to fit into 80 columns. Added myself to the copyright notice # above the one it had. fancy-ctrl-z () { # Copyright 2018 Jamiel Almeida # Copyright (c) 2009-2018 Robby Russell and contributors # # See the full list at # https://github.com/robbyrussell/oh-my-zsh/contributors # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. local NUM_JOBS="${(%):-%j}" if [[ "${NUM_JOBS}" -gt 0 ]] && [[ $#BUFFER -eq 0 ]]; then # background jobs present and empty buffer, runs `fg` fg zle push-input BUFFER="" zle accept-line elif [[ $#BUFFER -ne 0 ]]; then # non-empty buffer # push-input sends text in buffer to the buffer stack and clears the # buffer zle push-input else zle clear-screen fi } zle -N fancy-ctrl-z bindkey '^z' fancy-ctrl-z insert-newline () { BUFFER="${BUFFER}"$'\n' CURSOR=$(( CURSOR + 1 )) } zle -N insert-newline insert-tab () { BUFFER="${BUFFER}"$'\t' CURSOR=$(( CURSOR + 1 )) } zle -N insert-tab # Edit the command line using your usual editor. # # If the editor returns with exit code 0 load the contents of the file onto the # buffer otherwise empty the buffer and discard whatever was on the tempfile. # # Inspired by the functionality provided by function edit-command-line in # zshcontrib. Although behavior is different and code is disjunct, credit for # the idea goes to the Zsh Development Group as the authors of the original # function. # # Source for that function is on the file: Functions/Zle/edit-command-line # that is part of: git://git.code.sf.net/p/zsh/code edit-command-line () { local ts_format="%D{%Y%m%dT%H%M%S.%6.}" local tmpfile="${TMPDIR:-/tmp}/zsh-buf-$$.${(%)ts_format}" install -m 'u=rw,go=' /dev/null "${tmpfile}" print -R - "${PREBUFFER}${BUFFER}" >"${tmpfile}" exec </dev/tty ${=${VISUAL:-${EDITOR:-vi}}} "${tmpfile}" local RETURN_CODE="${?}" if [[ "${RETURN_CODE}" -eq 0 ]]; then print -Rz - "$(<"${tmpfile}")" fi command rm -f "${tmpfile}" zle send-break CURSOR="${#BUFFER}" zle redisplay zle reset-prompt } zle -N edit-command-line bindkey '^x^e' edit-command-line # Draw a fancy horizontal line with timestamp. Useful for presentations. horizontal-rule () { local how_many="${COLUMNS:-}" [[ -n "${how_many}" ]] || return local timestamp_format="%D{%Y-%m-%dT%H:%M:%S.%3.%z}" local ruler_char=$'\u2501' local ruler_pre="" if [[ "${how_many}" -gt 31 ]]; then how_many=$(( how_many - 31 )) ruler_pre="${ruler_char} ${(%)timestamp_format} " fi local ruler="$(printf "${ruler_char}%.0s" {1..${how_many}})" local prev_cursor="${CURSOR}" CURSOR=0 zle -R print - "\r${ruler_pre}${ruler}" CURSOR="${prev_cursor}" zle redisplay 2>/dev/null zle reset-prompt 2>/dev/null } zle -N horizontal-rule # I set these codes to be sent by my terminal, the definitions for them are in: # - Xresources for URxvt # - ~/.config/alacritty/alacritty.yml for alacritty # - ~/.config/kitty/kitty.conf for kitty # # Some of these codes are not available on my configurations of other shells I # use less frequently, for which a direct bind is used, or omitted # C-Space bindkey -s '\0' ' ' # M-Space bindkey '<F33>' horizontal-rule bindkey '[45~' horizontal-rule bindkey ' ' horizontal-rule # S-Space bindkey -s '<F34>' ' ' bindkey -s '[46~' ' ' # C-Enter bindkey '<F35>' accept-and-hold bindkey '[47~' accept-and-hold # M-Enter bindkey '<F36>' pound-insert bindkey '[48~' pound-insert bindkey ' ' pound-insert # S-Enter bindkey '<F37>' insert-newline bindkey '[49~' insert-newline # C-Tab bindkey '<F32>' insert-tab bindkey '[50~' insert-tab # Bind C-p to previous history entry, can still use Up for "up-line-or-history" bindkey '^p' up-history # remove the annoying ^T mapping that's default on zsh bindkey -r '^T'
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for USN-2309-1 # # Security announcement date: 2014-08-11 00:00:00 UTC # Script generation date: 2017-01-01 21:03:54 UTC # # Operating System: Ubuntu 12.04 LTS # Architecture: i386 # # Vulnerable packages fix on version: # - libavformat53:4:0.8.15-0ubuntu0.12.04.1 # - libavcodec53:4:0.8.15-0ubuntu0.12.04.1 # - libavcodec53:4:0.8.15-0ubuntu0.12.04.1 # # Last versions recommanded by security team: # - libavformat53:4:0.8.17-0ubuntu0.12.04.2 # - libavcodec53:4:0.8.17-0ubuntu0.12.04.2 # - libavcodec53:4:0.8.17-0ubuntu0.12.04.2 # # CVE List: # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo apt-get install --only-upgrade libavformat53=4:0.8.17-0ubuntu0.12.04.2 -y sudo apt-get install --only-upgrade libavcodec53=4:0.8.17-0ubuntu0.12.04.2 -y sudo apt-get install --only-upgrade libavcodec53=4:0.8.17-0ubuntu0.12.04.2 -y
#!/bin/bash mkdir -p build cd build || true export HDF5_ROOT=${PREFIX} cmake .. ${CMAKE_ARGS} \ -DPYTHON_EXECUTABLE="${PYTHON}" \ -DPYTHON_PREFIX="${PREFIX}" \ -DHDF5_INCLUDE_DIRS="${PREFIX}/include" \ -DREADDY_CREATE_TEST_TARGET:BOOL=OFF \ -DREADDY_INSTALL_UNIT_TEST_EXECUTABLE:BOOL=OFF \ -DREADDY_VERSION=${PKG_VERSION} \ -DREADDY_BUILD_STRING=${PKG_BUILDNUM} \ -DSP_DIR="${SP_DIR}" \ -GNinja ninja -j${CPU_COUNT} ninja install
function commonElements(array1, array2) { let intersection = []; array1.forEach((val) => { if(array2.indexOf(val) >= 0) { intersection.push(val); } }); return intersection; } array1 = [1, 2, 3, 4, 5]; array2 = [3, 5, 6, 7, 8]; common = commonElements(array1, array2); console.log(common); // [3, 5]
<gh_stars>0 #include <Core/GameConstants.h> namespace Lunia { namespace XRated { const int Constants::LocaleSpecificSetting::COUNTRY_CODE = Constants::LocaleSpecificSetting::CountryCode::KR; const int Constants::LocaleSpecificSetting::WRAPTYPE = WrapType::CharacterWrap; const float Mail::FeeFactor = 0.05f; const uint32 Mail::Limit::GoldWithoutStamp = 1000000; const uint8 Mail::Limit::ItemWithoutStamp = 1; const int Mail::Limit::TARGETLEN_MAX = 24; const float Constants::MapTileSizeWidth = 3.2f; const float Constants::MapTileSizeHeight = 4.525f; const float Constants::PIXELPERMAYA = 7.4f; const float Constants::CampfireDelayCooperative = 10.0f; const float Constants::CampfireDelayPVP = 10.0f; const float Constants::Tick = 0.5f; const float Constants::PvPLimitTime = 1.5f; const float3 Constants::DirectionF::LeftDown(-0.7071f, 0, -0.7071f); const float3 Constants::DirectionF::Down(0, 0, -1); const float3 Constants::DirectionF::RightDown(0.7071f, 0, -0.7071f); const float3 Constants::DirectionF::Left(-1, 0, 0); const float3 Constants::DirectionF::Right(1, 0, 0); const float3 Constants::DirectionF::LeftUp(-0.7071f, 0, 0.7071f); const float3 Constants::DirectionF::Up(0, 0, 1); const float3 Constants::DirectionF::RightUp(0.7071f, 0, 0.7071f); const float Constants::GhostRules::tGhostWhenInstantPop = 3.0f; const float Constants::GhostRules::tGhostWhenAutoTimeRevive_Sec10 = 10.0f; const float Constants::GhostRules::tGhostWhenAutoTimeRevive_Sec5 = 5.0f; const float Constants::GhostRules::tGhostWhenAutoTimeRevive_Sec3 = 3.0f; const DateTime::Date Quest::NotUsedDate = DateTime::Date(2001, 1, 1); const float Gamble::SlimeRace::BettingLimitInSec = 10.0f; const float Gamble::SlimeRace::Constants::Chip2MoneyConversionTax = 0.05f; const float3 Constants::Familiar::FormationPosition[Constants::Familiar::Formation::FormationCount][Constants::Familiar::MaxCount] = { {float3(-15,0,-15),float3(15,0,-15),float3(6,0,-6)}, {float3(0,0,-15),float3(0,0,15),float3(6,0,-6)}, {float3(-15,0,0),float3(15,0,0),float3(6,0,-6)}, {float3(-15,0,15),float3(15,0,15),float3(6,0,-6)} }; const int Constants::Familiar::MaxCountForEachType[TypeCount] = { 0, 1, 1, 2 }; const float Fishing::CorkRelativePosition = 30.f; const Constants::Direction Constants::DirectionF::GetDirectionEnum(const float3& dir) { if (dir.x == 0) { if (dir.z < 0) return Constants::Direction::Down; else return Constants::Direction::Up; } else if (dir.x < 0) { if (dir.z == 0) return Constants::Direction::Left; else if (dir.z < 0) return Constants::Direction::LeftDown; else return Constants::Direction::LeftUp; } else { if (dir.z == 0) return Constants::Direction::Right; else if (dir.z < 0) return Constants::Direction::RightDown; else return Constants::Direction::RightUp; } } const float3& Constants::DirectionF::GetDirection(Constants::Direction dir) { switch (dir) { case Constants::Direction::LeftDown: return LeftDown; case Constants::Direction::Down: return Down; case Constants::Direction::RightDown: return RightDown; case Constants::Direction::Left: return Left; case Constants::Direction::Right: return Right; case Constants::Direction::LeftUp: return LeftUp; case Constants::Direction::Up: return Up; case Constants::Direction::RightUp: return RightUp; case Constants::Direction::None: break; } return Down; } const float3 Constants::DirectionF::GetDirection(const float3& dir) { if (dir.x == 0) { if (dir.z < 0) return Constants::DirectionF::Down; else return Constants::DirectionF::Up; } else if (dir.x < 0) { if (dir.z == 0) return Constants::DirectionF::Left; else if (dir.z < 0) return Constants::DirectionF::LeftDown; else return Constants::DirectionF::LeftUp; } else { if (dir.z == 0) return Constants::DirectionF::Right; else if (dir.z < 0) return Constants::DirectionF::RightDown; else return Constants::DirectionF::RightUp; } } const Constants::Direction Constants::DirectionF::GetRealDirection(Constants::Direction myDir, Constants::Direction relativeD) { //��ġ� �ũ� �ΰ�� ǽ��ġ��� ��ġ� �� ��´. //��ġ�� �ε���ȭ �ؼ� �� ��ϸ ��� �� ���ϰ��, ���� �̺�� ���� ϼ ���. switch (myDir) { case Constants::Direction::Up: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::Up; case Constants::Direction::LeftUp: return Constants::Direction::LeftUp; case Constants::Direction::Left: return Constants::Direction::Left; case Constants::Direction::LeftDown: return Constants::Direction::LeftDown; case Constants::Direction::Down: return Constants::Direction::Down; case Constants::Direction::RightDown: return Constants::Direction::RightDown; case Constants::Direction::Right: return Constants::Direction::Right; case Constants::Direction::RightUp: return Constants::Direction::RightUp; default: return Constants::Direction::Up; } break; case Constants::Direction::LeftUp: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::LeftUp; case Constants::Direction::LeftUp: return Constants::Direction::Left; case Constants::Direction::Left: return Constants::Direction::LeftDown; case Constants::Direction::LeftDown: return Constants::Direction::Down; case Constants::Direction::Down: return Constants::Direction::RightDown; case Constants::Direction::RightDown: return Constants::Direction::Right; case Constants::Direction::Right: return Constants::Direction::RightUp; case Constants::Direction::RightUp: return Constants::Direction::Up; default: return Constants::Direction::LeftUp; } break; case Constants::Direction::Left: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::Left; case Constants::Direction::LeftUp: return Constants::Direction::LeftDown; case Constants::Direction::Left: return Constants::Direction::Down; case Constants::Direction::LeftDown: return Constants::Direction::RightDown; case Constants::Direction::Down: return Constants::Direction::Right; case Constants::Direction::RightDown: return Constants::Direction::RightUp; case Constants::Direction::Right: return Constants::Direction::Up; case Constants::Direction::RightUp: return Constants::Direction::LeftUp; default: return Constants::Direction::Left; } break; case Constants::Direction::LeftDown: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::LeftDown; case Constants::Direction::LeftUp: return Constants::Direction::Down; case Constants::Direction::Left: return Constants::Direction::RightDown; case Constants::Direction::LeftDown: return Constants::Direction::Right; case Constants::Direction::Down: return Constants::Direction::RightUp; case Constants::Direction::RightDown: return Constants::Direction::Up; case Constants::Direction::Right: return Constants::Direction::LeftUp; case Constants::Direction::RightUp: return Constants::Direction::Left; default: return Constants::Direction::LeftDown; } break; case Constants::Direction::Down: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::Down; case Constants::Direction::LeftUp: return Constants::Direction::RightDown; case Constants::Direction::Left: return Constants::Direction::Right; case Constants::Direction::LeftDown: return Constants::Direction::RightUp; case Constants::Direction::Down: return Constants::Direction::Up; case Constants::Direction::RightDown: return Constants::Direction::LeftUp; case Constants::Direction::Right: return Constants::Direction::Left; case Constants::Direction::RightUp: return Constants::Direction::LeftDown; default: return Constants::Direction::Down; } break; case Constants::Direction::RightDown: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::RightDown; case Constants::Direction::LeftUp: return Constants::Direction::Right; case Constants::Direction::Left: return Constants::Direction::RightUp; case Constants::Direction::LeftDown: return Constants::Direction::Up; case Constants::Direction::Down: return Constants::Direction::LeftUp; case Constants::Direction::RightDown: return Constants::Direction::Left; case Constants::Direction::Right: return Constants::Direction::LeftDown; case Constants::Direction::RightUp: return Constants::Direction::Down; default: return Constants::Direction::RightDown; } break; case Constants::Direction::Right: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::Right; case Constants::Direction::LeftUp: return Constants::Direction::RightUp; case Constants::Direction::Left: return Constants::Direction::Up; case Constants::Direction::LeftDown: return Constants::Direction::LeftUp; case Constants::Direction::Down: return Constants::Direction::Left; case Constants::Direction::RightDown: return Constants::Direction::LeftDown; case Constants::Direction::Right: return Constants::Direction::Down; case Constants::Direction::RightUp: return Constants::Direction::RightDown; default: return Constants::Direction::Right; } break; case Constants::Direction::RightUp: switch (relativeD) { case Constants::Direction::Up: return Constants::Direction::RightUp; case Constants::Direction::LeftUp: return Constants::Direction::Up; case Constants::Direction::Left: return Constants::Direction::LeftUp; case Constants::Direction::LeftDown: return Constants::Direction::Left; case Constants::Direction::Down: return Constants::Direction::LeftDown; case Constants::Direction::RightDown: return Constants::Direction::Down; case Constants::Direction::Right: return Constants::Direction::RightDown; case Constants::Direction::RightUp: return Constants::Direction::Right; default: return Constants::Direction::RightUp; } break; } Logger::GetInstance().Info("[Constants::DirectionF::GetRealDirection] Unknown Direction ({0}/{1})", (int)myDir, (int)relativeD); return Constants::Direction::Up; } Constants::DamageType Constants::StringToDmgType(const std::wstring& str) { if (str == L"FIRE") return Constants::DamageType::FIRE; else if (str == L"WATER") return Constants::DamageType::WATER; else if (str == L"ICE") return Constants::DamageType::ICE; else if (str == L"LIGHTNING") return Constants::DamageType::LIGHTNING; else if (str == L"LAND") return Constants::DamageType::LAND; else if (str == L"WIND") return Constants::DamageType::WIND; else if (str == L"POISON") return Constants::DamageType::POISON; else if (str == L"LIGHT") return Constants::DamageType::LIGHT; else if (str == L"CURSE") return Constants::DamageType::CURSE; else if (str == L"PHYSICAL") return Constants::DamageType::PHYSICAL; else if (str == L"INDEPENDENCE") return Constants::DamageType::INDEPENDENCE; else { //throw Exception(ALLM_EXCEPTION((L"Warning : Not Exist Constants::DamageType : %s", str.c_str()))); Logger::GetInstance().Info("Warning : Not Exist Constants::DamageType : {0}", StringUtil::ToASCII(str.c_str())); throw(fmt::format(L"Warning : Not Exist Constants::DamageType : {0}", str.c_str())); } } uint64 XRated::Mail::CalculatePostalCharge(uint64 money, uint16 itemCount) { return static_cast<uint64>(Mail::MailFee + money * Mail::FeeFactor + itemCount * Mail::ItemDeliverFee); } uint32 Constants::GetClassHash(ClassType type) { const static uint32 classHash[17] = { 7120, //Eir 637401, //Sieg 5672366, //Dainn 21518, //Tia 61041505, //SlimeCharacter 182804, //Dacy 12643174, //Krieg 57369345, //IceGirlCharacter 46469254, //ElfArcherCharacter 4357310, //BountyHunterCharacter 58604409, //BardCharacter 1307419, //DualWieldCharacter 51352876, //FighterCharacter 7494098, //DarkEirCharacter 18654328, //ArutaCharacter 26017521, //GaonCharacter 62917719 //IrisCharacter }; if (type < ClassType::Healer || type >= ClassType::NumberOfClassTypes) { //throw Exception(ALLM_EXCEPTION((L"Warring : Constants::GetClassHash : %d", (int)type))); Logger::GetInstance().Info("Warring : Constants::GetClassHash : {0}", (int)type); throw(fmt::format(L"Warring : Constants::GetClassHash : {0}", (int)type)); //return classHash[0]; } return classHash[(int)type]; } float XRated::Gamble::SlimeRace::GetDividendRate(BettingPosition position) { switch (position) { case Position::One: case Position::Two: case Position::Three: case Position::Four: case Position::Six: case Position::Seven: case Position::Eight: case Position::Nine: return 8.f; case Position::Red: case Position::Black: case Position::Low: case Position::High: return 2.f; case Position::StreetBets123: case Position::StreetBets789: return 2.5f; case Position::StreetBets456: return 3.5f; case Position::InsideFive: return 30.f; } return 0.0f; } void XRated::Gamble::BettingState::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Gamble::BettingInfo"); out.Write(L"RecentRate",RecentRate); out.Write(L"MyChips",MyChips); out.Write(L"TotalChips",TotalChips); } void XRated::Gamble::BettingState::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Gamble::BettingInfo"); in.Read(L"RecentRate", RecentRate); in.Read(L"MyChips", MyChips); in.Read(L"TotalChips", TotalChips); } bool Constants::IsDefaultClass(ClassType type) { switch (type) { case ClassType::Healer: case ClassType::Knight: case ClassType::Wizard: case ClassType::Thief: case ClassType::DollMaster: case ClassType::DarkTemplar: case ClassType::DarkEir: case ClassType::Aruta: case ClassType::Gaon: case ClassType::Iris: return true; } return false; } const wchar_t* Constants::GetClassStr(ClassType type) { if (type >= ClassType::Genus_1 && type < ClassType::NumberOfGenusClassTypes) { const static std::wstring genusClass[] = { L"Genus_1" , L"Genus_2" , L"Genus_3" , L"Genus_4" , L"Genus_5" , L"Genus_6" , L"Genus_7" , L"Genus_8" , L"Genus_9" , L"Genus_10" , L"Genus_11" , L"Genus_12" , L"Genus_13" , L"Genus_14" , L"Genus_15" , L"Genus_16" , L"Genus_17" , L"Genus_18" , L"Genus_19" , L"Genus_20" , L"AnyGenus" }; return genusClass[static_cast<int>(type) - static_cast<int>(ClassType::Genus_1)].c_str(); } if (type < ClassType::Healer || type >= ClassType::NumberOfClassTypes) { Logger::GetInstance().Info("Warring : Constants::GetClassStr : {0}", (int)type); throw(fmt::format(L"Warring : Constants::GetClassHash : {0}", (int)type)); //return L"Eir"; } const static std::wstring classStr[17] = { L"Eir", L"Sieg", L"Dainn", L"Tia", L"SlimeCharacter", L"Dacy",L"Krieg", L"IceGirlCharacter", L"ElfArcherCharacter", L"BountyHunterCharacter", L"BardCharacter", L"DualWieldCharacter", L"FighterCharacter", L"DarkEirCharacter", L"ArutaCharacter", L"GaonCharacter", L"IrisCharacter" }; return classStr[(int)type].c_str(); } const std::wstring Constants::GetClassLocaleStr(ClassType type) { std::wstring value = L"$UI.Global.CharacterClass."; value += GetClassStr(type); value += L"$"; return value; } bool Constants::IsEquippable(Equipment e1, EquipParts e2) { if (e1 == Equipment::Body && e2 == EquipParts::CHEST) return true; if (e1 == Equipment::Head && e2 == EquipParts::HEAD) return true; if (e1 == Equipment::Weapon && e2 == EquipParts::WEAPON) return true; if (e1 == Equipment::Legs && e2 == EquipParts::LEG) return true; if (e1 == Equipment::Gloves && e2 == EquipParts::HAND) return true; if (e1 == Equipment::Shoes && e2 == EquipParts::FOOT) return true; if (e1 == Equipment::Support && e2 == EquipParts::SUPPORT) return true; if (e1 == Equipment::Necklace && e2 == EquipParts::NECKLACE) return true; if ((e1 == Equipment::Ring1 || e1 == Equipment::Ring2) && e2 == EquipParts::RING) return true; if ((e1 == Equipment::Earing1 || e1 == Equipment::Earing2) && e2 == EquipParts::EARING) return true; if (e1 == Equipment::CashBody && e2 == EquipParts::CASH_CHEST) return true; if (e1 == Equipment::CashHead && e2 == EquipParts::CASH_HEAD) return true; if (e1 == Equipment::CashWeapon && e2 == EquipParts::CASH_WEAPON) return true; if (e1 == Equipment::CashLegs && e2 == EquipParts::CASH_LEG) return true; if (e1 == Equipment::CashGloves && e2 == EquipParts::CASH_HAND) return true; if (e1 == Equipment::CashShoes && e2 == EquipParts::CASH_FOOT) return true; if (e1 == Equipment::CashSupport && e2 == EquipParts::CASH_SUPPORT) return true; if (e1 == Equipment::CashMask && e2 == EquipParts::CASH_MASK) return true; if (e1 == Equipment::CashBack && e2 == EquipParts::CASH_BACK) return true; if (e1 == Equipment::CashHip && e2 == EquipParts::CASH_HIP) return true; if (e1 == Equipment::CashEtc1 && e2 == EquipParts::CASH_ETC1) return true; if (e1 == Equipment::CashEtc2 && e2 == EquipParts::CASH_ETC2) return true; if (e1 == Equipment::FameAdj && e2 == EquipParts::FAMEADJ) return true; if (e1 == Equipment::FameNoun && e2 == EquipParts::FAMENOUN) return true; if (e1 == Equipment::Pet && e2 == EquipParts::PET) return true; if (e1 == Equipment::Pet_Mask && e2 == EquipParts::PET_MASK) return true; if (e1 == Equipment::Pet_Etc1 && e2 == EquipParts::PET_ETC1) return true; if (e1 == Equipment::Pet_Etc2 && e2 == EquipParts::PET_ETC2) return true; return false; } bool Constants::IsAccessory(EquipParts part) { switch (part) { case EquipParts::SUPPORT: case EquipParts::NECKLACE: case EquipParts::RING: case EquipParts::EARING: return true; } return false; } Constants::Equipment Constants::GetEquipPosition(EquipParts part) { switch (part) { case WEAPON: return Equipment::Weapon; case HEAD: return Equipment::Head; case CHEST: return Equipment::Body; case LEG: return Equipment::Legs; case HAND: return Equipment::Gloves; case FOOT: return Equipment::Shoes; case SUPPORT: return Equipment::Support; case NECKLACE: return Equipment::Necklace; case RING: return Equipment::Ring1; case EARING: return Equipment::Earing1; case CASH_WEAPON: return Equipment::CashWeapon; case CASH_HEAD: return Equipment::CashHead; case CASH_CHEST: return Equipment::CashBody; case CASH_LEG: return Equipment::CashLegs; case CASH_HAND: return Equipment::CashGloves; case CASH_FOOT: return Equipment::CashShoes; case CASH_SUPPORT: return Equipment::CashSupport; case CASH_MASK: return Equipment::CashMask; case CASH_BACK: return Equipment::CashBack; case CASH_HIP: return Equipment::CashHip; case CASH_ETC1: return Equipment::CashEtc1; case CASH_ETC2: return Equipment::CashEtc2; case FAMEADJ: return Equipment::FameAdj; case FAMENOUN: return Equipment::FameNoun; case PET: return Equipment::Pet; case PET_MASK: return Equipment::Pet_Mask; case PET_ETC1: return Equipment::Pet_Etc1; case PET_ETC2: return Equipment::Pet_Etc2; } Logger::GetInstance().Info("can not found Equip position: {0}", static_cast<int>(part)); throw(fmt::format(L"can not found Equip position: {0}", static_cast<int>(part))); } Constants::EquipFlag Constants::GetEquipFlag(Constants::EquipParts part) { switch (part) { case EquipParts::CASH_WEAPON: return EquipFlag::CASH_Weapon; case EquipParts::CASH_HEAD: return EquipFlag::CASH_Head; case EquipParts::CASH_CHEST: return EquipFlag::CASH_Chest; case EquipParts::CASH_LEG: return EquipFlag::CASH_Leg; case EquipParts::CASH_HAND: return EquipFlag::CASH_Hand; case EquipParts::CASH_FOOT: return EquipFlag::CASH_Foot; case EquipParts::CASH_SUPPORT: return EquipFlag::CASH_Support; case EquipParts::CASH_MASK: return EquipFlag::CASH_Mask; case EquipParts::CASH_BACK: return EquipFlag::CASH_Back; case EquipParts::CASH_HIP: return EquipFlag::CASH_Hip; case EquipParts::CASH_ETC1: return EquipFlag::CASH_Etc1; case EquipParts::CASH_ETC2: return EquipFlag::CASH_Etc2; } Logger::GetInstance().Info("can not found Equip Flag: {0}", static_cast<int>(part)); throw(fmt::format(L"can not found Equip Flag: {0}", static_cast<int>(part))); } Constants::EquipParts Constants::GetEquipParts(Equipment position) { switch (position) { case Equipment::Weapon: return EquipParts::WEAPON; case Equipment::Head: return EquipParts::HEAD; case Equipment::Body: return EquipParts::CHEST; case Equipment::Legs: return EquipParts::LEG; case Equipment::Gloves: return EquipParts::HAND; case Equipment::Shoes: return EquipParts::FOOT; case Equipment::Support: return EquipParts::SUPPORT; case Equipment::Necklace: return EquipParts::NECKLACE; case Equipment::Ring1: return EquipParts::RING; case Equipment::Ring2: return EquipParts::RING; case Equipment::Earing1: return EquipParts::EARING; case Equipment::Earing2: return EquipParts::EARING; case Equipment::CashWeapon: return EquipParts::CASH_WEAPON; case Equipment::CashHead: return EquipParts::CASH_HEAD; case Equipment::CashBody: return EquipParts::CASH_CHEST; case Equipment::CashLegs: return EquipParts::CASH_LEG; case Equipment::CashGloves: return EquipParts::CASH_HAND; case Equipment::CashShoes: return EquipParts::CASH_FOOT; case Equipment::CashSupport: return EquipParts::CASH_SUPPORT; case Equipment::CashMask: return EquipParts::CASH_MASK; case Equipment::CashBack: return EquipParts::CASH_BACK; case Equipment::CashHip: return EquipParts::CASH_HIP; case Equipment::CashEtc1: return EquipParts::CASH_ETC1; case Equipment::CashEtc2: return EquipParts::CASH_ETC2; case Equipment::FameAdj: return EquipParts::FAMEADJ; case Equipment::FameNoun: return EquipParts::FAMENOUN; case Equipment::Pet: return EquipParts::PET; case Equipment::Pet_Mask: return EquipParts::PET_MASK; case Equipment::Pet_Etc1: return EquipParts::PET_ETC1; case Equipment::Pet_Etc2: return EquipParts::PET_ETC2; } Logger::GetInstance().Info("can not found Equip Part: {0}", static_cast<int>(position)); throw(fmt::format(L"can not found Equip Part: {0}", static_cast<int>(position))); } const wchar_t* Constants::GetDefaultEquipmentMeshName(Constants::ClassType type, Constants::EquipParts part) { switch (type) { case Constants::ClassType::Knight: switch (part) { case Constants::EquipParts::CHEST: return L"Sieg_Body_000"; case Constants::EquipParts::WEAPON: return L"Sieg_Weapon_000"; case Constants::EquipParts::HEAD: return L"Sieg_Head_000"; case Constants::EquipParts::HAND: return L"Sieg_Hand_000"; case Constants::EquipParts::LEG: return L"Sieg_Leg_000"; case Constants::EquipParts::FOOT: return L"Sieg_Foot_000"; case Constants::EquipParts::CASH_CHEST: return L"Sieg_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Sieg_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Sieg_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Sieg_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Sieg_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Sieg_Foot_000"; } break; case Constants::ClassType::Healer: switch (part) { case Constants::EquipParts::CHEST: return L"Eir_Body_000"; case Constants::EquipParts::WEAPON: return L"Eir_Weapon_000"; case Constants::EquipParts::HEAD: return L"Eir_Head_000"; case Constants::EquipParts::HAND: return L"Eir_Hand_000"; case Constants::EquipParts::LEG: return L"Eir_Leg_000"; case Constants::EquipParts::FOOT: return L"Eir_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Eir_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Eir_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Eir_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Eir_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Eir_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Eir_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Eir_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Eir_Support_000"; //case Constants::EquipParts::CASH_MASK : return L"Eir_Empty"; //case Constants::EquipParts::CASH_BACK : return L"Eir_Empty"; //case Constants::EquipParts::CASH_HIP : return L"Eir_Empty"; //case Constants::EquipParts::CASH_ETC1 : return L"Eir_Empty"; //case Constants::EquipParts::CASH_ETC2 : return L"Eir_Empty"; } break; case Constants::ClassType::Wizard: switch (part) { case Constants::EquipParts::CHEST: return L"Dainn_Body_000"; case Constants::EquipParts::WEAPON: return L"Dainn_Weapon_000"; case Constants::EquipParts::HEAD: return L"Dainn_Head_000"; case Constants::EquipParts::HAND: return L"Dainn_Hand_000"; case Constants::EquipParts::LEG: return L"Dainn_Leg_000"; case Constants::EquipParts::FOOT: return L"Dainn_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Dainn_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Dainn_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Dainn_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Dainn_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Dainn_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Dainn_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Dainn_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Dainn_Support_000"; //case Constants::EquipParts::CASH_MASK : return L"Dainn_Empty"; //case Constants::EquipParts::CASH_BACK : return L"Dainn_Empty"; //case Constants::EquipParts::CASH_HIP : return L"Dainn_Empty"; //case Constants::EquipParts::CASH_ETC1 : return L"Dainn_Empty"; //case Constants::EquipParts::CASH_ETC2 : return L"Dainn_Empty"; } break; case Constants::ClassType::Thief: switch (part) { case Constants::EquipParts::CHEST: return L"Tia_Body_000"; case Constants::EquipParts::WEAPON: return L"Tia_Weapon_000"; case Constants::EquipParts::HEAD: return L"Tia_Head_000"; case Constants::EquipParts::HAND: return L"Tia_Hand_000"; case Constants::EquipParts::LEG: return L"Tia_Leg_000"; case Constants::EquipParts::FOOT: return L"Tia_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Tia_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Tia_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Tia_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Tia_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Tia_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Tia_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Tia_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Tia_Support_000"; //case Constants::EquipParts::CASH_MASK : return L"Tia_Empty"; //case Constants::EquipParts::CASH_BACK : return L"Tia_Empty"; //case Constants::EquipParts::CASH_HIP : return L"Tia_Empty"; //case Constants::EquipParts::CASH_ETC1 : return L"Tia_Empty"; //case Constants::EquipParts::CASH_ETC2 : return L"Tia_Empty"; } break; case Constants::ClassType::Slime: switch (part) { case Constants::EquipParts::CHEST: return L"CSlime"; //case Constants::EquipParts::WEAPON : return L"CSlime_Empty"; //case Constants::EquipParts::HEAD : return L"CSlime_Empty"; //case Constants::EquipParts::HAND : return L"CSlime_Empty"; //case Constants::EquipParts::LEG : return L"CSlime_Empty"; //case Constants::EquipParts::FOOT : return L"CSlime_Empty"; //case Constants::EquipParts::SUPPORT : return L"CSlime_Empty"; case Constants::EquipParts::CASH_CHEST: return L"CSlime"; //case Constants::EquipParts::CASH_WEAPON : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_HEAD : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_HAND : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_LEG : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_FOOT : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_SUPPORT : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_MASK : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_BACK : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_HIP : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_ETC1 : return L"CSlime_Empty"; //case Constants::EquipParts::CASH_ETC2 : return L"CSlime_Empty"; } break; case Constants::ClassType::DollMaster: switch (part) { case Constants::EquipParts::CHEST: return L"Dacy_Body_000"; case Constants::EquipParts::WEAPON: return L"Dacy_Weapon_000"; case Constants::EquipParts::HEAD: return L"Dacy_Head_000"; case Constants::EquipParts::HAND: return L"Dacy_Hand_000"; case Constants::EquipParts::LEG: return L"Dacy_Leg_000"; case Constants::EquipParts::FOOT: return L"Dacy_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Dacy_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Dacy_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Dacy_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Dacy_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Dacy_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Dacy_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Dacy_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Dacy_Support_000"; //case Constants::EquipParts::CASH_MASK : return L"Dacy_Empty"; //case Constants::EquipParts::CASH_BACK : return L"Dacy_Empty"; //case Constants::EquipParts::CASH_HIP : return L"Dacy_Empty"; //case Constants::EquipParts::CASH_ETC1 : return L"Dacy_Empty"; //case Constants::EquipParts::CASH_ETC2 : return L"Dacy_Empty"; } break; case Constants::ClassType::DarkTemplar: switch (part) { case Constants::EquipParts::CHEST: return L"Krieg_Body_000"; case Constants::EquipParts::WEAPON: return L"Krieg_Weapon_000"; case Constants::EquipParts::HEAD: return L"Krieg_Head_000"; case Constants::EquipParts::HAND: return L"Krieg_Hand_000"; case Constants::EquipParts::LEG: return L"Krieg_Leg_000"; case Constants::EquipParts::FOOT: return L"Krieg_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Krieg_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Krieg_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Krieg_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Krieg_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Krieg_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Krieg_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Krieg_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Krieg_Support_000"; //case Constants::EquipParts::CASH_MASK : return L"Krieg_Empty"; //case Constants::EquipParts::CASH_BACK : return L"Krieg_Empty"; //case Constants::EquipParts::CASH_HIP : return L"Krieg_Empty"; //case Constants::EquipParts::CASH_ETC1 : return L"Krieg_Empty"; //case Constants::EquipParts::CASH_ETC2 : return L"Krieg_Empty"; } break; case Constants::ClassType::IceSorceress: switch (part) { case Constants::EquipParts::CHEST: return L"IceGirl_Body_000"; case Constants::EquipParts::WEAPON: return L"IceGirl_Weapon_000"; case Constants::EquipParts::HEAD: return L"IceGirl_Head_000"; case Constants::EquipParts::HAND: return L"IceGirl_Hand_000"; case Constants::EquipParts::LEG: return L"IceGirl_Leg_000"; case Constants::EquipParts::FOOT: return L"IceGirl_Foot_000"; case Constants::EquipParts::SUPPORT: return L"IceGirl_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"IceGirl_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"IceGirl_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"IceGirl_Head_000"; case Constants::EquipParts::CASH_HAND: return L"IceGirl_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"IceGirl_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"IceGirl_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"IceGirl_Support_000"; } break; case Constants::ClassType::Archer: switch (part) { case Constants::EquipParts::CHEST: return L"ElfArcher_Body_000"; case Constants::EquipParts::WEAPON: return L"ElfArcher_Weapon_000"; case Constants::EquipParts::HEAD: return L"ElfArcher_Head_000"; case Constants::EquipParts::HAND: return L"ElfArcher_Hand_000"; case Constants::EquipParts::LEG: return L"ElfArcher_Leg_000"; case Constants::EquipParts::FOOT: return L"ElfArcher_Foot_000"; case Constants::EquipParts::SUPPORT: return L"ElfArcher_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"ElfArcher_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"ElfArcher_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"ElfArcher_Head_000"; case Constants::EquipParts::CASH_HAND: return L"ElfArcher_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"ElfArcher_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"ElfArcher_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"ElfArcher_Support_000"; } break; case Constants::ClassType::BountyHunter: switch (part) { case Constants::EquipParts::CHEST: return L"BountyHunter_Body_000"; case Constants::EquipParts::WEAPON: return L"BountyHunter_Weapon_000"; case Constants::EquipParts::HEAD: return L"BountyHunter_Head_000"; case Constants::EquipParts::HAND: return L"BountyHunter_Hand_000"; case Constants::EquipParts::LEG: return L"BountyHunter_Leg_000"; case Constants::EquipParts::FOOT: return L"BountyHunter_Foot_000"; case Constants::EquipParts::SUPPORT: return L"BountyHunter_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"BountyHunter_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"BountyHunter_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"BountyHunter_Head_000"; case Constants::EquipParts::CASH_HAND: return L"BountyHunter_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"BountyHunter_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"BountyHunter_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"BountyHunter_Support_000"; } break; case Constants::ClassType::Bard: switch (part) { case Constants::EquipParts::CHEST: return L"Bard_Body_000"; case Constants::EquipParts::WEAPON: return L"Bard_Weapon_000"; case Constants::EquipParts::HEAD: return L"Bard_Head_000"; case Constants::EquipParts::HAND: return L"Bard_Hand_000"; case Constants::EquipParts::LEG: return L"Bard_Leg_000"; case Constants::EquipParts::FOOT: return L"Bard_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Bard_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Bard_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Bard_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Bard_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Bard_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Bard_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Bard_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Bard_Support_000"; } break; case Constants::ClassType::DualWield:///ͽű�ij�� by kpongky( 09.06.09 ) switch (part) { case Constants::EquipParts::CHEST: return L"DualWield_Body_000"; case Constants::EquipParts::WEAPON: return L"DualWield_Weapon_000"; case Constants::EquipParts::HEAD: return L"DualWield_Head_000"; case Constants::EquipParts::HAND: return L"DualWield_Hand_000"; case Constants::EquipParts::LEG: return L"DualWield_Leg_000"; case Constants::EquipParts::FOOT: return L"DualWield_Foot_000"; case Constants::EquipParts::SUPPORT: return L"DualWield_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"DualWield_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"DualWield_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"DualWield_Head_000"; case Constants::EquipParts::CASH_HAND: return L"DualWield_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"DualWield_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"DualWield_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"DualWield_Support_000"; } break; case Constants::ClassType::Fighter:///�ű�ij�� by kpongky( 09.08.10 ) switch (part) { case Constants::EquipParts::CHEST: return L"Fighter_Body_000"; case Constants::EquipParts::WEAPON: return L"Fighter_Weapon_000"; case Constants::EquipParts::HEAD: return L"Fighter_Head_000"; case Constants::EquipParts::HAND: return L"Fighter_Hand_000"; case Constants::EquipParts::LEG: return L"Fighter_Leg_000"; case Constants::EquipParts::FOOT: return L"Fighter_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Fighter_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Fighter_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Fighter_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Fighter_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Fighter_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Fighter_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Fighter_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Fighter_Support_000"; } break; case Constants::ClassType::DarkEir:///�ű�ij�� by kpongky( 09.11.19 ) switch (part) { case Constants::EquipParts::CHEST: return L"DarkEir_Body_000"; case Constants::EquipParts::WEAPON: return L"DarkEir_Weapon_000"; case Constants::EquipParts::HEAD: return L"DarkEir_Head_000"; case Constants::EquipParts::HAND: return L"DarkEir_Hand_000"; case Constants::EquipParts::LEG: return L"DarkEir_Leg_000"; case Constants::EquipParts::FOOT: return L"DarkEir_Foot_000"; case Constants::EquipParts::SUPPORT: return L"DarkEir_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"DarkEir_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"DarkEir_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"DarkEir_Head_000"; case Constants::EquipParts::CASH_HAND: return L"DarkEir_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"DarkEir_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"DarkEir_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"DarkEir_Support_000"; } break; case Constants::ClassType::Aruta:///�ű�ij�� by kpongky( 09.11.19 ) switch (part) { case Constants::EquipParts::CHEST: return L"Aruta_Body_000"; case Constants::EquipParts::WEAPON: return L"Aruta_Weapon_000"; case Constants::EquipParts::HEAD: return L"Aruta_Head_000"; case Constants::EquipParts::HAND: return L"Aruta_Hand_000"; case Constants::EquipParts::LEG: return L"Aruta_Leg_000"; case Constants::EquipParts::FOOT: return L"Aruta_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Aruta_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Aruta_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Aruta_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Aruta_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Aruta_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Aruta_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Aruta_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Aruta_Support_000"; } break; case Constants::ClassType::Gaon:///�ű�ij�� by kpongky( 09.11.19 ) switch (part) { case Constants::EquipParts::CHEST: return L"Gaon_Body_000"; case Constants::EquipParts::WEAPON: return L"Gaon_Weapon_000"; case Constants::EquipParts::HEAD: return L"Gaon_Head_000"; case Constants::EquipParts::HAND: return L"Gaon_Hand_000"; case Constants::EquipParts::LEG: return L"Gaon_Leg_000"; case Constants::EquipParts::FOOT: return L"Gaon_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Gaon_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Gaon_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Gaon_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Gaon_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Gaon_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Gaon_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Gaon_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Gaon_Support_000"; } break; case Constants::ClassType::Iris:///�ű�ij�� by kpongky( 09.11.19 ) switch (part) { case Constants::EquipParts::CHEST: return L"Iris_Body_000"; case Constants::EquipParts::WEAPON: return L"Iris_Weapon_000"; case Constants::EquipParts::HEAD: return L"Iris_Head_000"; case Constants::EquipParts::HAND: return L"Iris_Hand_000"; case Constants::EquipParts::LEG: return L"Iris_Leg_000"; case Constants::EquipParts::FOOT: return L"Iris_Foot_000"; case Constants::EquipParts::SUPPORT: return L"Iris_Support_000"; case Constants::EquipParts::CASH_CHEST: return L"Iris_Body_000"; case Constants::EquipParts::CASH_WEAPON: return L"Iris_Weapon_000"; case Constants::EquipParts::CASH_HEAD: return L"Iris_Head_000"; case Constants::EquipParts::CASH_HAND: return L"Iris_Hand_000"; case Constants::EquipParts::CASH_LEG: return L"Iris_Leg_000"; case Constants::EquipParts::CASH_FOOT: return L"Iris_Foot_000"; case Constants::EquipParts::CASH_SUPPORT: return L"Iris_Support_000"; } break; //�ű�ij���߰� : ���⿡ �⺻ �޽� �̸�� �Է��ϴ °Ŵ. //ٱ�� ij����� ǰ�� �����ؼ� �ٿ��ְ ���ξ �ٲ��. //��۾ �Ϸ �ȸ��� Ҷ� � ̳���� �����ؼ� �������Ѵ. //ٿ���) //ID : DualWieldCharacter //Hash : 1307419 //Index : 11 //DefaultMesh //CHEST : DualWield_Body_000 //WEAPON : DualWield_Weapon_000 //HEAD : DualWield_Head_000 //HAND : DualWield_Hand_000 //LEG : DualWield_Leg_000 //FOOT : DualWield_Foot_000 //SUPPORT : DualWield_Support_000 //CASH_CHEST : DualWield_Body_000 //CASH_WEAPON : DualWield_Weapon_000 //CASH_HEAD : DualWield_Head_000 //CASH_HAND : DualWield_Hand_000 //CASH_LEG : DualWield_Leg_000 //CASH_FOOT : DualWield_Foot_000 //CASH_SUPPORT : DualWield_Support_000 // //�̱ۿ ��Ű: Shift + F6 << �� Lunia2 �����Ʈ�� �߰��ϰ Lunia2/KeyInput_Lunia.xml??�� '�ű�ij��'�� ΰ˻��ϸ //��۾ �ȳ��� �ִ. } return L""; //return L"DefaultEquipment"; //assert(false); // unable to find //return L""; } //ChatTypes Convert /////////////////////////////////////////////////////////////////////////// Constants::ChatTypes Constants::ConvertStringToChatTypes(const wchar_t* string) { if (wcscmp(string, L"NormalChat") == 0) return XRated::Constants::ChatTypes::NormalChat; else if (wcscmp(string, L"EmoteChat") == 0) return XRated::Constants::ChatTypes::EmoteChat; else if (wcscmp(string, L"TradeChat") == 0) return XRated::Constants::ChatTypes::TradeChat; else if (wcscmp(string, L"TradeSellChat") == 0) return XRated::Constants::ChatTypes::TradeSellChat; else if (wcscmp(string, L"TradeBuyChat") == 0) return XRated::Constants::ChatTypes::TradeBuyChat; else if (wcscmp(string, L"ShoutChat") == 0) return XRated::Constants::ChatTypes::ShoutChat; else if (wcscmp(string, L"GlobalShoutChat") == 0) return XRated::Constants::ChatTypes::GlobalShoutChat; else if (wcscmp(string, L"LastTextBoardMsg") == 0) return XRated::Constants::ChatTypes::LastTextBoardMsg; else if (wcscmp(string, L"TextBoardChat") == 0) return XRated::Constants::ChatTypes::TextBoardChat; else if (wcscmp(string, L"WhisperChat") == 0) return XRated::Constants::ChatTypes::WhisperChat; else if (wcscmp(string, L"OneToOneChat") == 0) return XRated::Constants::ChatTypes::OneToOneChat; else if (wcscmp(string, L"TeamChat") == 0) return XRated::Constants::ChatTypes::TeamChat; else if (wcscmp(string, L"GuildChat") == 0) return XRated::Constants::ChatTypes::GuildChat; else if (wcscmp(string, L"SystemChat") == 0) return XRated::Constants::ChatTypes::SystemChat; else if (wcscmp(string, L"ErrorChat") == 0) return XRated::Constants::ChatTypes::ErrorChat; else if (wcscmp(string, L"SystemInfoChat") == 0) return XRated::Constants::ChatTypes::SystemInfoChat; else if (wcscmp(string, L"EpisodeChat") == 0) return XRated::Constants::ChatTypes::EpisodeChat; else if (wcscmp(string, L"FamilyChat") == 0) return XRated::Constants::ChatTypes::FamilyChat; else if (wcscmp(string, L"PartyChat") == 0) return XRated::Constants::ChatTypes::PartyChat; else if (wcscmp(string, L"PartyNoticeChat") == 0) return XRated::Constants::ChatTypes::PartyNoticeChat; Logger::GetInstance().Info("can't found chat types = {0}", StringUtil::ToASCII(string)); throw(fmt::format(L"can't found chat types = {0}", string)); } const wchar_t* Constants::ConvertChatTypesToString(Constants::ChatTypes type) { switch (type) { case Constants::ChatTypes::NormalChat: return L"NormalChat"; case Constants::ChatTypes::EmoteChat: return L"EmoteChat"; case Constants::ChatTypes::TradeChat: return L"TradeChat"; case Constants::ChatTypes::TradeSellChat: return L"TradeSellChat"; case Constants::ChatTypes::TradeBuyChat: return L"TradeBuyChat"; case Constants::ChatTypes::ShoutChat: return L"ShoutChat"; case Constants::ChatTypes::GlobalShoutChat: return L"GlobalShoutChat"; case Constants::ChatTypes::LastTextBoardMsg: return L"LastTextBoardMsg"; case Constants::ChatTypes::TextBoardChat: return L"TextBoardChat"; case Constants::ChatTypes::WhisperChat: return L"WhisperChat"; case Constants::ChatTypes::OneToOneChat: return L"OneToOneChat"; case Constants::ChatTypes::TeamChat: return L"TeamChat"; case Constants::ChatTypes::GuildChat: return L"GuildChat"; case Constants::ChatTypes::SystemChat: return L"SystemChat"; case Constants::ChatTypes::ErrorChat: return L"ErrorChat"; case Constants::ChatTypes::SystemInfoChat: return L"SystemInfoChat"; case Constants::ChatTypes::EpisodeChat: return L"EpisodeChat"; case Constants::ChatTypes::FamilyChat: return L"Family"; case Constants::ChatTypes::PartyChat: return L"PartyChat"; case Constants::ChatTypes::PartyNoticeChat: return L"PartyNoticeChat"; default: Logger::GetInstance().Info("can't found chat types = {0}", type); throw(fmt::format(L"can't found chat types = {0}", type)); } } // ISerializable implementation /////////////////////////////////////////////////////////////// void StageEvent::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::StageEvent"); out.Write(L"Type", static_cast<const int>(Type)); out.Write(L"Value", static_cast<const int>(Value)); out.Write(L"Position", Position); out.Write(L"Direction", static_cast<const int>(Direction)); out.Write(L"Scale", Scale); out.Write(L"Effect", Effect); out.Write(L"Area", Area); } void StageEvent::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::StageEvent"); in.Read(L"Type", reinterpret_cast<int&>(Type)); in.Read(L"Value", reinterpret_cast<int&>(Value)); in.Read(L"Position", Position); in.Read(L"Direction", reinterpret_cast<int&>(Direction), 2); in.Read(L"Scale", Scale, float3(1, 1, 1)); in.Read(L"Effect", Effect, Locator()); in.Read(L"Area", Area); } void ActivePoint::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::ActivePoint"); out.Write(L"Type", static_cast<const int>(Type)); out.Write(L"Animation", Animation); out.Write(L"Position", Position); out.Write(L"Direction", static_cast<const int>(Direction)); out.Write(L"Scale", Scale); out.Write(L"Effect", Effect); out.Write(L"Area", Area); } void ActivePoint::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::ActivePoint"); in.Read(L"Type", reinterpret_cast<int&>(Type)); in.Read(L"Animation", Animation); in.Read(L"Position", Position); in.Read(L"Direction", reinterpret_cast<int&>(Direction), 2); in.Read(L"Scale", Scale, float3(1, 1, 1)); in.Read(L"Effect", Effect, Locator()); in.Read(L"Area", Area); } const ItemPosition ItemPosition::Invalid(0xff, 0xff); ItemPosition::ItemPosition() : Bag(0), Position(0) { } ItemPosition::ItemPosition(uint8 bag, uint8 position) : Bag(bag), Position(position) { } void ItemPosition::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"ItemPosition"); out.Write(L"Bag", Bag); out.Write(L"Position", Position); } void ItemPosition::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"ItemPosition"); in.Read(L"Bag", Bag); in.Read(L"Position", Position); } //bool operator<(const ItemPosition& lhs, const ItemPosition& rhs) //{ // if(lhs.Bag < rhs.Bag) // return true; // if(lhs.Position < rhs.Position) // return true; // return false; //} void ItemPack::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"ItemPack"); out.Write(L"Position", Position); out.Write(L"Count", Count); out.Write(L"ExtendInfo", ExtendInfo); } void ItemPack::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"ItemPack"); in.Read(L"Position", Position); in.Read(L"Count", Count); in.Read(L"ExtendInfo", ExtendInfo); } void Item::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"Item"); out.Write(L"Id", Id); out.Write(L"InstanceEx", InstanceEx); } void Item::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"Item"); in.Read(L"Id", Id); in.Read(L"InstanceEx", InstanceEx); } void ItemSlot::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"ItemSlot"); out.Write(L"Id", Id); out.Write(L"Position", Position); out.Write(L"Stacked", Stacked); out.Write(L"instanceEx", InstanceEx); } void ItemSlot::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"ItemSlot"); in.Read(L"Id", Id); in.Read(L"Position", Position); in.Read(L"Stacked", Stacked); in.Read(L"instanceEx", InstanceEx); } void InvalidEquippedItem::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"InvalidEquippedItem"); out.Write(L"Where", static_cast<int>(where)); out.Write(L"Enable", enable); } void InvalidEquippedItem::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"InvalidEquippedItem"); in.Read(L"Where", reinterpret_cast<int&>(where)); in.Read(L"Enable", enable); } void EquippedItem::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"InvalidEquippedItem"); out.Write(L"itemHash", itemHash); out.Write(L"instanceEx", InstanceEx); out.WriteEnum(L"Where", where); } void EquippedItem::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"InvalidEquippedItem"); in.Read(L"itemHash", itemHash); in.Read(L"instanceEx", InstanceEx); in.ReadEnum(L"Where", where); } void StoreSlot::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"StoreSlot"); out.Write(L"ItemHash", ItemHash); out.Write(L"StackedCount", StackedCount); out.Write(L"instanceEx", InstanceEx); out.Write(L"SellPrice", SellPrice); } void StoreSlot::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"StoreSlot"); in.Read(L"ItemHash", ItemHash); in.Read(L"StackedCount", StackedCount); in.Read(L"instanceEx", InstanceEx); in.Read(L"SellPrice", SellPrice); } bool StoreSlot::operator ==(const StoreSlot& rhs) const { return (ItemHash == rhs.ItemHash && StackedCount == rhs.StackedCount && this->InstanceEx == rhs.InstanceEx && SellPrice == rhs.SellPrice); } void ItemBasicInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"ItemInfo"); out.Write(L"ItemHash", ItemHash); out.Write(L"instanceEx", this->InstanceEx); out.Write(L"StackCount", StackCount); } void ItemBasicInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"ItemInfo"); in.Read(L"ItemHash", ItemHash); in.Read(L"instanceEx", this->InstanceEx); in.Read(L"StackCount", StackCount); } void RewardItem::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"RewardItem"); out.Write(L"ItemHash", ItemHash); out.Write(L"instanceEx", InstanceEx); out.Write(L"StackCount", StackCount); } void RewardItem::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"RewardItem"); in.Read(L"ItemHash", ItemHash); in.Read(L"instanceEx", InstanceEx); in.Read(L"StackCount", StackCount); } void PresentEventMailReward::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"PresentEventMailReward"); out.WriteEnum(L"ExpireInfo", expireInfo); out.Write(L"Item", item); } void PresentEventMailReward::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"PresentEventMailReward"); in.ReadEnum(L"ExpireInfo", expireInfo); in.Read(L"Item", item); } void Skill::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"Skill"); out.Write(L"Id", Id); out.Write(L"Level", Level); } void Skill::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"Skill"); in.Read(L"Id", Id); in.Read(L"Level", Level); } void QuickSlot::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"QuickSlot"); out.Write(L"Id", Id); out.Write(L"IsSkill", IsSkill); out.Write(L"Pos", Pos); out.Write(L"instanceEx", InstanceEx); } void QuickSlot::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"QuickSlot"); in.Read(L"Id", Id); in.Read(L"IsSkill", IsSkill); in.Read(L"Pos", Pos); in.Read(L"instanceEx", InstanceEx); } void Friend::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Friend"); out.Write(L"CharacterName", CharacterName); out.Write(L"IsOnline", IsOnline); out.Write(L"ClassType", static_cast<int>(ClassType)); out.Write(L"Level", Level); out.Write(L"CurrentLocation", CurrentLocation); out.Write(L"Memo", Memo); } void Friend::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Friend"); in.Read(L"CharacterName", CharacterName); in.Read(L"IsOnline", IsOnline); in.Read(L"ClassType", reinterpret_cast<int&>(ClassType)); in.Read(L"Level", Level); in.Read(L"CurrentLocation", CurrentLocation); in.Read(L"Memo", Memo); } void LobbyPlayerInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::TeamMember"); out.Write(L"CharacterName", CharacterName); out.Write(L"CharacterSerial", CharacterSerial); out.Write(L"VirtualIdCode", VirtualIdCode); out.Write(L"ClassType", static_cast<int>(ClassType)); out.Write(L"Level", Level); out.Write(L"Exp", Exp); out.Write(L"PvpLevel", PvpLevel); out.Write(L"PvpExp", PvpExp); out.Write(L"WarLevel", WarLevel); out.Write(L"WarExp", WarExp); out.Write(L"StoredLevel", StoredLevel); out.Write(L"RebirthCount", RebirthCount); out.Write(L"LastLoggedDate", LastLoggedDate); out.Write(L"Equipments", Equipments); out.Write(L"Licenses", Licenses); out.Write(L"LadderPoint", LadderPoint); out.Write(L"LadderWinCount", LadderWinCount); out.Write(L"LadderLoseCount", LadderLoseCount); out.Write(L"LadderMatchCount", LadderMatchCount); out.Write(L"CharacterStateFlags", static_cast<int>(StateFlags)); } void LobbyPlayerInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::TeamMember"); in.Read(L"CharacterName", CharacterName); in.Read(L"CharacterSerial", CharacterSerial); in.Read(L"VirtualIdCode", VirtualIdCode); in.Read(L"ClassType", reinterpret_cast<int&>(ClassType)); in.Read(L"Level", Level); in.Read(L"Exp", Exp); in.Read(L"PvpLevel", PvpLevel); in.Read(L"PvpExp", PvpExp); in.Read(L"WarLevel", WarLevel); in.Read(L"WarExp", WarExp); in.Read(L"StoredLevel", StoredLevel); in.Read(L"RebirthCount", RebirthCount); in.Read(L"LastLoggedDate", LastLoggedDate); in.Read(L"Equipments", Equipments); in.Read(L"Licenses", Licenses); in.Read(L"LadderPoint", LadderPoint); in.Read(L"LadderWinCount", LadderWinCount); in.Read(L"LadderLoseCount", LadderLoseCount); in.Read(L"LadderMatchCount", LadderMatchCount); in.Read(L"CharacterStateFlags", reinterpret_cast<int&>(StateFlags)); } void ItemPackage::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"ItemPackage"); out.Write(L"ItemHash", ItemHash); out.Write(L"Count", Count); out.Write(L"ExpireDay", ExpireDay); out.Write(L"Description", Description); out.Write(L"Attr1", Attr1); out.Write(L"Attr2", Attr2); out.Write(L"Attr2", Attr3); // 3.1 by ultimate ???-> this a new scroll statuses? :D } void ItemPackage::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"ItemPackage"); in.Read(L"ItemHash", ItemHash); in.Read(L"Count", Count); in.Read(L"ExpireDay", ExpireDay); in.Read(L"Description", Description); in.Read(L"Attr1", Attr1); in.Read(L"Attr2", Attr2); in.Read(L"Attr3", Attr3); // 3.1 by ultimate ???-> this a new scroll statuses? :D } void CashItem::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"CashItem"); out.Write(L"OrderNumber", OrderNumber); out.Write(L"ProductNumber", ProductNumber); out.Write(L"Quantity", Quantity); out.Write(L"RepresentativeItemHash", RepresentativeItemHash); out.Write(L"Name", Name); out.Write(L"Packages", Packages); } void CashItem::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"CashItem"); in.Read(L"OrderNumber", OrderNumber); in.Read(L"ProductNumber", ProductNumber); in.Read(L"Quantity", Quantity); in.Read(L"RepresentativeItemHash", RepresentativeItemHash); in.Read(L"Name", Name); in.Read(L"Packages", Packages); } void BagState::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"BagState"); out.Write(L"BagNumber", BagNumber); out.Write(L"ExpireDate", ExpireDate); out.Write(L"Expired", Expired); } void BagState::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"BagState"); in.Read(L"BagNumber", BagNumber); in.Read(L"ExpireDate", ExpireDate); in.Read(L"Expired", Expired); } void StageLocation::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::StageLocation"); out.Write(L"StageGroupHash", StageGroupHash); out.Write(L"Level", Level); out.Write(L"Difficulty", Difficulty); out.Write(L"Tags", Tags); } void StageLocation::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::StageLocation"); in.Read(L"StageGroupHash", StageGroupHash); in.Read(L"Level", Level); in.Read(L"Difficulty", Difficulty, uint8(1)); in.Read(L"Tags", Tags, std::vector< std::wstring >()); } void SquareInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"SquareInfo"); out.Write(L"Name", Name); out.Write(L"Status", static_cast<const int>(Status)); out.Write(L"StageGroupHash", StageGroupHash); out.Write(L"AccessLevel", AccessLevel); out.Write(L"Capacity", Capacity); out.Write(L"OrderNumber", OrderNumber); } void SquareInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"SquareInfo"); in.Read(L"Name", Name); in.Read(L"Status", reinterpret_cast<int&>(Status)); in.Read(L"StageGroupHash", StageGroupHash); in.Read(L"AccessLevel", AccessLevel); in.Read(L"Capacity", Capacity); in.Read(L"OrderNumber", OrderNumber); } void GameMode::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::PvpGameType"); out.Write(L"GameType", static_cast<int>(GameType)); out.Write(L"ItemPopup", ItemPopup); } void GameMode::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::PvpGameType"); in.Read(L"GameType", reinterpret_cast<int&>(GameType)); in.Read(L"ItemPopup", ItemPopup); } void StateFlag::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"StateFlag"); out.Write(L"Id", Id); out.Write(L"Level", (short)Level); } void StateFlag::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"StateFlag"); in.Read(L"Id", Id); in.Read(L"Level", (short&)Level); } void Quest::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"Quest"); out.Write(L"Id", Id); out.Write(L"CurrentState", CurrentState); out.Write(L"ExpiredDate", ExpiredDate); out.Write(L"Params", Params); } void Quest::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"Quest"); in.Read(L"Id", Id); in.Read(L"CurrentState", CurrentState); in.Read(L"ExpiredDate", ExpiredDate); in.Read(L"Params", Params); } /////////////////////////////////////////////////////////////// ISerializable implementation // ObjectData::ObjectData() : GameObjectSerial(0), Type(Constants::ObjectType::Player), Radius(0) { } void ObjectData::operator =(const ObjectData& obj) { GameObjectSerial = obj.GameObjectSerial; Name = obj.Name; Type = obj.Type; Position = obj.Position; Direction = obj.Direction; Radius = obj.Radius; } ItemData::ItemData(ObjectData& obj) : BaseObject(obj) { } CharacterData::CharacterData(ObjectData& obj) : BaseObject(obj), Xp(0), Level(0), Money(0), BankMoney(0), Team(0), Alliance(0) , Hp(0), MaxHp(0), Mp(0), MaxMp(0), Speed(0), SpeedVector(1) { } void ItemData::operator= (const ItemData& item) { BaseObject = item.BaseObject; OwnerId = item.OwnerId; StackCount = item.StackCount; PrivateItem = item.PrivateItem; this->InstanceEx = item.InstanceEx; } void CharacterData::operator =(const CharacterData& ch) { BaseObject = ch.BaseObject; Xp = ch.Xp; Level = ch.Level; Money = ch.Money; BankMoney = ch.BankMoney; Team = ch.Team; Alliance = ch.Alliance; Hp = ch.Hp; MaxHp = ch.MaxHp; Mp = ch.Mp; MaxMp = ch.MaxMp; Speed = ch.Speed; SpeedVector = ch.SpeedVector; } NonPlayerData::NonPlayerData(CharacterData& character) : BaseCharacter(character), Npc(NpcType::Normal) { } void NonPlayerData::operator =(const NonPlayerData& npc) { BaseCharacter = npc.BaseCharacter; Npc = npc.Npc; //Scale=npc.Scale; } PlayerData::PlayerData(CharacterData& character) : BaseCharacter(character), Job(Constants::ClassType::Healer), Life(0), MaxLife(0), SkillPoint(0) , BonusLife(0), UsableBonusLifeInStage(0) , Sp(0), MaxSp(0), AddedSkillPointPlus(0), StoredLevel(0), RebirthCount(0), StoredSkillPoint(0), LastRebirthDateTime(DateTime::Infinite) , achievementScore(0) //, fullFactor(1.0f), goodFactor(1.0f), sosoFactor(1.0f), hungryFactor(1.0f) { //PS.Xp = 0; } void PlayerData::operator =(const PlayerData& pc) { BaseCharacter = pc.BaseCharacter; Job = pc.Job; Life = pc.Life; MaxLife = pc.MaxLife; BonusLife = pc.BonusLife; UsableBonusLifeInStage = std::min<unsigned short>(pc.UsableBonusLifeInStage, pc.BonusLife); SkillPoint = pc.SkillPoint; AddedSkillPointPlus = pc.AddedSkillPointPlus; Sp = pc.Sp; MaxSp = pc.MaxSp; Skills = pc.Skills; Equipments = pc.Equipments; //PS = pc.PS; StoredLevel = pc.StoredLevel; RebirthCount = pc.RebirthCount; StoredSkillPoint = pc.StoredSkillPoint; LastRebirthDateTime = pc.LastRebirthDateTime; achievementScore = pc.achievementScore; } void NexonGuildInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"NexonGuildInfo"); out.Write(L"GuildOid", GuildOid); out.Write(L"GuildId", GuildId); out.Write(L"GuildName", GuildName); out.Write(L"CreatedDate", CreatedDate); out.Write(L"MasterCharacterName", MasterCharacterName); out.Write(L"NumberOfMembers", NumberOfMembers); out.Write(L"Intro", Intro); } void NexonGuildInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"NexonGuildInfo"); in.Read(L"GuildOid", GuildOid); in.Read(L"GuildId", GuildId); in.Read(L"GuildName", GuildName); in.Read(L"CreatedDate", CreatedDate); in.Read(L"MasterCharacterName", MasterCharacterName); in.Read(L"NumberOfMembers", NumberOfMembers); in.Read(L"Intro", Intro); } void AllMGuildInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"AllMGuildInfo"); out.Write(L"GuildId", GuildId); out.Write(L"GuildExp", GuildExp); out.Write(L"GuildAlias", GuildAlias); out.Write(L"MyPlayTime", MyPlayTime); out.Write(L"TotalPlayTime", TotalPlayTime); out.Write(L"StartedTimeToPlay", StartedTimeToPlay); out.Write(L"MyContributed", MyContributed); out.Write(L"Point", Point); out.Write(L"ShopOpenDate", ShopOpenDate); out.Write(L"ShopCloseDate", ShopCloseDate); out.Write(L"Rank", Rank); out.Write(L"RankExpiredDate", RankExpiredDate); out.Write(L"Tax", Tax); out.Write(L"TaxPayDay", TaxPayDay); out.Write(L"GuildName", GuildName); out.Write(L"Message", Message); out.Write(L"MasterName", MasterName); out.Write(L"GuildLevel", static_cast<const int>(GuildLevel)); out.Write(L"MemberCount", MemberCount); out.Write(L"CreatedDate", CreatedDate); out.Write(L"Grade", Grade); out.Write(L"MyGrade", MyGrade); out.Write(L"GuildMemberId", GuildMemberId); } void AllMGuildInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"AllMGuildInfo"); in.Read(L"GuildId", GuildId); in.Read(L"GuildExp", GuildExp); in.Read(L"GuildAlias", GuildAlias); in.Read(L"MyPlayTime", MyPlayTime); in.Read(L"TotalPlayTime", TotalPlayTime); in.Read(L"StartedTimeToPlay", StartedTimeToPlay); in.Read(L"MyContributed", MyContributed); in.Read(L"Point", Point); in.Read(L"ShopOpenDate", ShopOpenDate); in.Read(L"ShopCloseDate", ShopCloseDate); in.Read(L"Rank", Rank); in.Read(L"RankExpiredDate", RankExpiredDate); in.Read(L"Tax", Tax); in.Read(L"TaxPayDay", TaxPayDay); in.Read(L"GuildName", GuildName); in.Read(L"Message", Message); in.Read(L"MasterName", MasterName); in.Read(L"GuildLevel", reinterpret_cast<int&>(GuildLevel), 3); in.Read(L"MemberCount", MemberCount); in.Read(L"CreatedDate", CreatedDate); in.Read(L"Grade", Grade); in.Read(L"MyGrade", MyGrade); in.Read(L"GuildMemberId", GuildMemberId); } void AllMGuildInfo::GradeInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"AllMGuildInfo::GradeInfo"); out.Write(L"GradeName", GradeName); out.Write(L"Authority", Authority); } void AllMGuildInfo::GradeInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"AllMGuildInfo::GradeInfo"); in.Read(L"GradeName", GradeName); in.Read(L"Authority", Authority); } uint16 AllMGuildInfo::GetLimitMemberCount() const { #if !defined(_JAPAN) && !defined(_KOREA) switch (GuildLevel) { case 0: return 15; case 1: return 30; case 2: return 60; case 3: return 90; case 4: return 130; case 5: return 200; default: return 15; } #else return 200; #endif } void GuildRankInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::GuildRankInfo"); out.Write(L"GuildID", GuildID); out.Write(L"Rank", Rank); out.Write(L"GuildName", GuildName); out.Write(L"GuildMemberCount", GuildMemberCount); out.Write(L"TotalContribution", TotalContribution); out.Write(L"TotalPlayTime", TotalPlayTime); out.Write(L"CurrentTotalPlayTime", CurrentTotalPlayTime); out.Write(L"GuildLevel", GuildLevel); } void GuildRankInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::GuildRankInfo"); in.Read(L"GuildID", GuildID); in.Read(L"Rank", Rank); in.Read(L"GuildName", GuildName); in.Read(L"GuildMemberCount", GuildMemberCount); in.Read(L"TotalContribution", TotalContribution); in.Read(L"TotalPlayTime", TotalPlayTime); in.Read(L"CurrentTotalPlayTime", CurrentTotalPlayTime); in.Read(L"GuildLevel", GuildLevel); } bool GuildRankInfo::CompareByRank::operator()(const GuildRankInfo& guild1, const GuildRankInfo& guild2) const { return guild1.Rank > guild2.Rank; } bool GuildRankInfo::CompareByName::operator()(const GuildRankInfo& guild1, const GuildRankInfo& guild2) const { return (std::wcscmp(guild1.GuildName.c_str(), guild2.GuildName.c_str()) > 0); } bool GuildRankInfo::CompareByMemberCount::operator()(const GuildRankInfo& guild1, const GuildRankInfo& guild2) const { return guild1.GuildMemberCount > guild2.GuildMemberCount; } bool GuildRankInfo::CompareByContribution::operator()(const GuildRankInfo& guild1, const GuildRankInfo& guild2) const { return guild1.TotalContribution > guild2.TotalContribution; } bool GuildRankInfo::CompareByLevel::operator()(const GuildRankInfo& guild1, const GuildRankInfo& guild2) const { return guild1.GuildLevel > guild2.GuildLevel; } bool GuildRankInfo::CompareByPlayTime::operator()(const GuildRankInfo& guild1, const GuildRankInfo& guild2) const { return guild1.TotalPlayTime > guild2.TotalPlayTime; } bool GuildRankInfo::CompareByCurrentPlayTime::operator()(const GuildRankInfo& guild1, const GuildRankInfo& guild2) const { return guild1.CurrentTotalPlayTime > guild2.CurrentTotalPlayTime; } void GuildShopItem::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::GuildShopItem"); out.Write(L"ItemHash", ItemHash); out.Write(L"ExpiredDate", ExpiredDate); } void GuildShopItem::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::GuildShopItem"); in.Read(L"ItemHash", ItemHash); in.Read(L"ExpiredDate", ExpiredDate); } void AllMBasicGuildInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"AllMBasicGuildInfo"); out.Write(L"GuildName", GuildName); out.Write(L"GuildId", GuildId); out.Write(L"MemberCount", MemberCount); } void AllMBasicGuildInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"AllMBasicGuildInfo"); in.Read(L"GuildName", GuildName); in.Read(L"GuildId", GuildId); in.Read(L"MemberCount", MemberCount); } void AllMGuildUserInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"AllMGuildUserInfo"); out.Write(L"GuildMemberId", GuildMemberId); out.Write(L"CharacterName", CharacterName); uint64 Instance; Instance = CharacterInfo; out.Write(L"CharacterInfo", Instance); out.Write(L"LastLogin", LastLogin); out.Write(L"Contributed", Contributed); out.Write(L"PrivateMessage", PrivateMessage); } void AllMGuildUserInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"AllMGuildUserInfo"); in.Read(L"GuildMemberId", GuildMemberId); in.Read(L"CharacterName", CharacterName); uint64 Instance; in.Read(L"CharacterInfo", Instance); CharacterInfo = Instance; in.Read(L"LastLogin", LastLogin); in.Read(L"Contributed", Contributed); in.Read(L"PrivateMessage", PrivateMessage); } void Mail::HeaderInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"Mail::HeaderInfo"); out.Write(L"Index", Index); out.Write(L"Title", Title); out.Write(L"Flag", Flag); out.Write(L"IsRead", IsRead); out.Write(L"Sender", Sender); out.Write(L"SentDate", SentDate); } void Mail::HeaderInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"Mail::HeaderInfo"); in.Read(L"Index", Index); in.Read(L"Title", Title); in.Read(L"Flag", Flag); in.Read(L"IsRead", IsRead); in.Read(L"Sender", Sender); in.Read(L"SentDate", SentDate); } void Mail::ContentsInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"Mail::ContentsInfo"); out.Write(L"Index", Index); out.Write(L"Message", Message); out.Write(L"AttachedMoney", AttachedMoney); out.Write(L"AttachedItems", AttachedItems); out.Write(L"StampItemHash", StampItemHash); out.Write(L"IsSystemMail", IsSystemMail); } void Mail::ContentsInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"Mail::ContentsInfo"); in.Read(L"Index", Index); in.Read(L"Message", Message); in.Read(L"AttachedMoney", AttachedMoney); in.Read(L"AttachedItems", AttachedItems); in.Read(L"StampItemHash", StampItemHash); in.Read(L"IsSystemMail", IsSystemMail); } void Fishing::FishingInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"Fishing::FishingInfo"); out.Write(L"ItemHash", ItemHash); out.Write(L"Count", Count); out.Write(L"CharacterName", CharacterName); out.Write(L"FishingTime", FishingTime); } void Fishing::FishingInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"Fishing::FishingInfo"); in.Read(L"ItemHash", ItemHash); in.Read(L"Count", Count); in.Read(L"CharacterName", CharacterName); in.Read(L"FishingTime", FishingTime); } std::wstring GetRank(uint8 rank) { std::wstring missionRank; switch (rank) { case XRated::RankS: missionRank = L"S"; break; case XRated::RankA: missionRank = L"A"; break; case XRated::RankB: missionRank = L"B"; break; case XRated::RankC: missionRank = L"C"; break; case XRated::RankF: missionRank = L"F"; break; } return missionRank; } int32 GetGainXPByStatisticsRank(uint8 rank, float gainXp) { float xp = 0; switch (rank) { case XRated::RankS: xp = gainXp * 0.1f; break; case XRated::RankA: xp = gainXp * 0.06f; break; case XRated::RankB: xp = gainXp * 0.04f; break; case XRated::RankC: xp = gainXp * 0.02f; break; case XRated::RankF: xp = gainXp * 0.0f; break; } return static_cast<int>(xp + 0.5f); } float GetGainXPRateByReviveCount(uint16 totalReviveCount) { if (totalReviveCount < 5) return 0.0f; else if (totalReviveCount >= 5 && totalReviveCount < 10) return 0.1f; else if (totalReviveCount >= 10 && totalReviveCount < 15) return 0.2f; else if (totalReviveCount >= 15) return 0.3f; return 0.0f; } int GetNextRankTime(uint8 rank, int standatdTime) { //if (rank == XRated::RankS) return 0; float TargetVal = 0.0f; switch (rank) { case XRated::RankS: break; case XRated::RankA: TargetVal = 0.75f; break; case XRated::RankB: TargetVal = 1.0f; break; case XRated::RankC: TargetVal = 1.5f; break; /// RankF۴ ¹��Ѵ??......... case XRated::RankF: TargetVal = 2.0f; break; } return static_cast<int>(TargetVal * standatdTime); } float GetGradeRank(uint8 rank) { float grade = 0.f; switch (rank) { case XRated::RankS: grade = 7; break; case XRated::RankA: grade = 5; break; case XRated::RankB: grade = 4; break; case XRated::RankC: grade = 3; break; case XRated::RankF: grade = 0; break; } return grade; } uint8 GetPlayerRankWithLevelGap(uint16 playerLevel, uint8 playerRank, int proprietyLevel) //�??����ġ�̴.. { if (playerRank == XRated::RankF) return playerRank; if ((playerLevel > proprietyLevel) && (playerLevel - proprietyLevel >= 10)) ++playerRank; return playerRank; } void MissionResultInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::MissionResultInfo"); out.Write(L"MaxAirCombo", MaxAirCombo); out.Write(L"Rank", Rank); out.Write(L"ClearXp", ClearXp); out.Write(L"StageXp", StageXp); } void MissionResultInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::MissionResultInfo"); in.Read(L"MaxAirCombo", MaxAirCombo); in.Read(L"Rank", Rank); in.Read(L"ClearXp", ClearXp); in.Read(L"StageXp", StageXp); } uint8 MissionResultFunctions::GetPlayTimeRank(int clearTime, int standardTime) { if (standardTime == 0) return XRated::RankF; //ٸ�� ���ؽð�� ̹��� Fdz��� -0-;; float val = static_cast<float>(clearTime) / static_cast<float>(standardTime); if (val <= 0.75f) return XRated::RankS; else if (val <= 1.0f) return XRated::RankA; else if (val <= 1.5f) return XRated::RankB; else if (val <= 2.0f) return XRated::RankC; return XRated::RankF; } uint8 MissionResultFunctions::GetLifeRank(bool death, uint16 curLife) { if (curLife >= 2) return XRated::RankS; else if (curLife == 1) return XRated::RankA; //curLife԰� 0�ΰ� if (death) return XRated::RankF; return XRated::RankB; } uint8 MissionResultFunctions::GetSecretRank(int foundSecret, int totalSecret) { float point = (static_cast<float>(foundSecret) + 1.0f) / (static_cast<float>(totalSecret) + 1.0f); //�Ҽ�� 2��° �ڸ����� �ݿø� point *= 10.0f; point += 0.5f; int p = static_cast<int>(point); point = (static_cast<float>(p) / 10.f) * 6.f; if (point >= 6.0f) return XRated::RankS; else if (point >= 4.0f && point < 6.0f) return XRated::RankA; else if (point >= 2.0f && point < 4.0f) return XRated::RankB; else if (point >= 1.3f && point < 2.0f) return XRated::RankC; return XRated::RankF; } uint8 MissionResultFunctions::GetAirComboRank(uint32 maxAirComboCount) { if (maxAirComboCount > 15) return XRated::RankS; else if (maxAirComboCount >= 8 && maxAirComboCount <= 15) return XRated::RankA; else if (maxAirComboCount >= 4 && maxAirComboCount <= 7) return XRated::RankB; else if (maxAirComboCount >= 1 && maxAirComboCount <= 3) return XRated::RankC; return XRated::RankF; } uint8 MissionResultFunctions::GetStylePointRank(float stylePointPercentage) { if (stylePointPercentage >= 0.8) return XRated::RankS; else if (stylePointPercentage >= 0.6) return XRated::RankA; else if (stylePointPercentage >= 0.4) return XRated::RankB; else if (stylePointPercentage >= 0.2) return XRated::RankC; return XRated::RankF; } uint8 MissionResultFunctions::GetStageClearRank(bool clear, int playTime, int standardTime, bool death, uint16 curLife, int foundSecret, int totalSecret, uint32 maxAirComboCount, float stylePointPercentage) { if (!clear) return XRated::RankF; uint8 playTimeRank = GetPlayTimeRank(playTime, standardTime); uint8 lifeRank = GetLifeRank(death, curLife); uint8 secretRank = GetSecretRank(foundSecret, totalSecret); uint8 airComboRank = GetAirComboRank(maxAirComboCount); uint8 stylePointRank = GetStylePointRank(stylePointPercentage); float totalGrade = static_cast<float>((GetGradeRank(playTimeRank) * 0.25) + (GetGradeRank(lifeRank) * 0.35) + (GetGradeRank(secretRank) * 0.05) + (GetGradeRank(airComboRank) * 0.15) + (GetStylePointRank(stylePointRank) * 0.2)); if (totalGrade >= 6.0f) return XRated::RankS; else if (totalGrade >= 4.5f && totalGrade < 6.0f) return XRated::RankA; else if (totalGrade >= 3.0f && totalGrade < 4.5f) return XRated::RankB; else if (totalGrade >= 1.5f && totalGrade < 3.0f) return XRated::RankC; return XRated::RankF; } /* int Rank(int kill,int life,int combo) { //TODO: calculate rank by statisics values int value; value = kill * 100; value += (life * 10000); value += (combo * 100); if( value >= 35000 ) return XRated::RankAPlusPlus; else if( value > 33000 ) return XRated::RankAPlus; else if( value > 31000 ) return XRated::RankA; if( value >= 25000 ) return XRated::RankBPlusPlus; else if( value > 23000 ) return XRated::RankBPlus; else if( value > 21000 ) return XRated::RankB; if( value >= 15000 ) return XRated::RankCPlusPlus; else if( value > 13000 ) return XRated::RankCPlus; else return XRated::RankC; //return XRated::RankC; } */ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Exp Functions float ExpFunctions::Pvp::CalculateSurvivalXpWithLevelDifference(uint16 opLv, uint16 myLv) { float xp = (float)opLv * 5.0f + 10.0f; int32 levelGap = (int32)opLv - (int32)myLv; if (levelGap >= 0 && levelGap <= 4) return xp * 7.0f; else if (levelGap > 4 && levelGap < 14) return (float)xp * (float)(14 - levelGap) * 0.7f; // /10.0f * 7.0f; else if (levelGap < 0 && levelGap > -10) return (float)xp * (float)(10 + levelGap) * 0.7f; // /10.0f * 7.0f; else return 0; } int ExpFunctions::Pvp::CalculateXpForWinner(uint16 myLv, uint16 myPvpLv, float avgLv, float deter, int memCnt) { if (avgLv == 0) avgLv = 0.1f; float xp = (deter * (10.0f + 4.0f * (float)(memCnt - 1)) + 100.0f); xp = xp * ((float)myLv > avgLv ? 1.0f : (float)myLv / avgLv); int lvGap = (int)myPvpLv - (int)myLv; if (lvGap > 0) xp = xp - xp * (lvGap > 4 ? 1.0f : (float)lvGap * 0.2f); if (xp < 80) xp = 80; return (int)xp; } int ExpFunctions::Pvp::CalculateXpForLoser(uint16 myLv, uint16 myPvpLv) { int xp = 0; if (myPvpLv < 30) { xp = 20; int lvGap = (int)myPvpLv - (int)myLv; if (lvGap > 0) xp = (int)((float)xp * (lvGap > 4 ? 1.0f : lvGap * 0.2f)); } else //return 0; xp = ((int)myPvpLv - 30) * -5; //return xp < 0 ? 0 : xp; return xp; } int ExpFunctions::Pvp::CalculateMinimumPlayMinute(int memCnt) { return (60 * memCnt + 120) / 60; } float ExpFunctions::Pvp::CalculateLevelGapBonusRate(float deltaAvgLv) { int gap = static_cast<int>(deltaAvgLv); if (gap < 0 || gap > 7) /* �츮��� Ƿ�� ̳����쳪 ��� �ʹ� ��� ̳�� °�(���¡�� κ�)*/ { return 1.0f; } else { float rate = 1.0f + 0.02f * gap; if (rate > 1.1f) rate = 1.1f; // (�ִ 1.1���� ��� � ����) return rate; } } float ExpFunctions::Pvp::CalculateMemCntBonusRate(int memCnt) { return (static_cast<float>(memCnt) * 0.2f) + 0.6f; } int ExpFunctions::Pvp::CalculateStageXpForWinner(uint16 myLv, float deltaAvgLv /* �������lv - տ츮����lv */, float /*playTime*/ /*մ��:�*/, int memCnt) { //if ( playTime/60 >= CalculateMinimumPlayMinute( memCnt ) ) //{ float bonus = CalculateLevelGapBonusRate(deltaAvgLv); /*ALLM_IMPORTANT((L"CalculateStageXpForWinner: %d ( Lv: %d, dALv: %f, playtime: %f sec, members: %d )", static_cast<int>( myLv * 82 * CalculateMinimumPlayMinute( memCnt ) * bonus ) , myLv , deltaAvgLv , playTime , memCnt )); */ return static_cast<int>(myLv * 82 * CalculateMinimumPlayMinute(memCnt) * CalculateMemCntBonusRate(memCnt) * bonus); //} //else //{ // //ALLM_IMPORTANT((L"CalculateStageXpForWinner: PlayTime is defficient!( %f sec / Members : %d )", playTime, memCnt )); // return 0; //} } int ExpFunctions::Pvp::CalculateStageXpForLoser(uint16 myLv, float deltaAvgLv /* ʻ������lv - տ츮����lv */, float playTime /*մ��:�*/, int memCnt) { int r = CalculateStageXpForWinner(myLv, deltaAvgLv, playTime, memCnt); //ALLM_IMPORTANT((L"CalculateStageXpForLoser : %d ( 75% of winner )" , static_cast<int>( r * 0.75f ) )); return static_cast<int>(r * 0.1f); } int ExpFunctions::Pvp::GetXp(int memberCnt) { return (10 * memberCnt + 90) * memberCnt; } float ExpFunctions::Stage::CalculateXpWithLevelGap(float xp, int levelGap) { if (levelGap > 0) { //ʽ������ � �??�̴ switch (levelGap) { case 1: case 2: case 3: break; case 4: case 5: xp *= 1.05f; break; case 6: case 7: xp *= 1.1f; break; case 8: case 9: xp *= 1.15f; break; case 10: case 11: xp *= 1.2f; break; default: xp *= 1.25f; break; } } else { //��÷��̾ � �??�̴ switch (levelGap) { case 0: case -1: case -2: case -3: break; case -4: xp *= 0.75f; break; case -5: xp *= 0.5f; break; case -6: xp *= 0.25f; break; case -7: xp *= 0.12f; break; case -8: xp *= 0.1f; break; case -9: xp *= 0.08f; break; case -10: xp *= 0.06f; break; case -11: xp *= 0.04f; break; case -12: xp *= 0.02f; break; default: xp *= 0.01f; break; } } return xp; } float ExpFunctions::Stage::GetAddExpFactorByRebirthCount(const uint16 rebirthCount) { if (rebirthCount <= 0) return 1.0f; uint16 count = rebirthCount; if (count > 15) count = 15; return pow(1.2f, static_cast<float>(count)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Gold Functions float GoldFunctions::Pvp::GetPlayTimeRate(int memCnt) { return (30.f * static_cast<float>(memCnt) + 60.f) / 60.f; } float GoldFunctions::Pvp::GetBasicMoneyPerMin(uint16 level) { return 10.625f * static_cast<float>(level) + 59.375f; } float GoldFunctions::Pvp::GetLifeBonusRate(int deathCount) { return 0.24f - (0.08f * static_cast<float>(deathCount)); } float GoldFunctions::Pvp::GetKillBonusRate(int killCount) { if (killCount > 12) killCount = 12; return 0.5f * static_cast<float>(killCount) / 6.f; } uint32 GoldFunctions::Pvp::CacluateVictoryMoneyReward(uint16 level, int memCnt, int killCount, int deathCount) { return static_cast<uint32>((GetBasicMoneyPerMin(level) * GetPlayTimeRate(memCnt) * (1.f + GetLifeBonusRate(deathCount) + GetKillBonusRate(killCount))) + 0.5f); } uint32 GoldFunctions::Pvp::CacluateDefeatedMoneyReward(uint16 level, int memCnt, int killCount, int deathCount) { #if defined(_TAIWAN) || defined(_CHINA) return static_cast<uint32>(CacluateVictoryMoneyReward(level, memCnt, killCount, deathCount) * 0.1f); #else return static_cast<uint32>(CacluateVictoryMoneyReward(level, memCnt, killCount, deathCount) * 0.9f); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Status Functions // float StatusFunctions::GetHpRatePerUserCnt(NonPlayerData::NpcType type, int userCnt) // { // float hpRateTable[NonPlayerData::NpcType::Cnt][8] = { //#if defined (_TAIWAN) // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.32f, 1.44f, 1.56f, 1.68f, 1.8f, 1.92f, 2.04f}, // {1.0f, 1.32f, 1.44f, 1.56f, 1.68f, 1.8f, 1.92f, 2.04f} //#else // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {1.0f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {0.5f, 1.03f, 1.06f, 1.09f, 1.12f, 1.15f, 1.18f, 1.21f}, // {0.5f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f}, // {0.5f, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f} //#endif // }; // if ( userCnt>0 && userCnt<=8 ) // return hpRateTable[type][userCnt-1]; // // return hpRateTable[type][7]; // } float StatusFunctions::GetHPperVit(uint16 lv) { if (lv < 20) return 5; else if (lv < 60) return 6; return 7; } float StatusFunctions::GetMPperInt(uint16 lv) { if (lv < 20) return 5; else if (lv < 60) return 6; return 7; } float StatusFunctions::GetReducedCooldownRate(int dex) { //#ifdef _TAIWAN // return 1.0f - ( dex > Constants::MaxStat ? (float)Constants::MaxStat / (float)220 * 0.1f : (float)dex / (float)220 * 0.1f ); //#else return 1.0f - (float)dex / (float)330 * 0.1f; //#endif } float GetIncreasedRateFactor(int value) { if (value > 2000) return 0.5f; else if (value > 1500) return 0.4f; else if (value > 1000) return 0.3f; else if (value > 500) return 0.2f; return 0.1f; } float StatusFunctions::GetIncreasedDamageRate(int str)//ٿ�� ����ϸ StatCalculator.cpp 鵵 ����ؾ��. �ã�ƺ�� ����. { //#ifdef _TAIWAN // return 1.0f + ( str > Constants::MaStat ? (float)Constants::MaxStat / (float)200 * 0.1f : (float)str / (float)200 * 0.1f ); //#else if (str > 10000) { double value = static_cast<double>((str - 1000) / 1000 * 1.35); return static_cast<float>(((value * value) * 0.03) + ((0.0008 * static_cast<double>(str)) + 8.28)); } else if (str > 3000) { ////��� 10000�̻�� �����ϰ �ó���ϵ�� ��Ѵ. //if( str > 10000 ) { // str = 10000; //} double value = static_cast<double>(static_cast<int>((str - 1000) / 1000 * 2)); return static_cast<float>(((value * value) * 0.03) + ((0.0008 * static_cast<double>(str)) + 2.99)); } else { return 1.0f + (float)str / 330.0f * GetIncreasedRateFactor(str); } //#endif } float StatusFunctions::GetIncreasedDamageRateInPvp(int str)//ٿ�� ����ϸ StatCalculator.cpp 鵵 ����ؾ��. �ã�ƺ�� ����. { if (str > 500) { //((((0.6 * Str - 300) ^ 0.17) * 10) -1.9) * 0.01 = Dmg% return 1.0f + (pow((0.6f * (float)str - 300.f), 0.17f) * 10.f - 1.9f) * 0.01f; //hitIgnoreMultiplyValue = (1.f * pow(abs(hitIgnoreMultiplyValue0), 0.7f) * 2.f + 80.f) / 100.f * hitIgnoreMultiply; } else { return 1.0f + (float)str / 330.0f * 0.1f; } } float StatusFunctions::GetIncreasedDamageRateByAtk(float atkVal) { if (atkVal <= 0) return 0.0f; if (atkVal / 2 > 10000) { double value = static_cast<double>((atkVal / 2 - 1000) / 1000 * 1.35); return static_cast<float>(((value * value) * 0.03 - 1) + (0.0004 * atkVal + 8.28)) * 0.2; } else if (atkVal / 2 > 3000) { double value = static_cast<double>((atkVal / 2 - 1000) / 1000 * 2); return static_cast<float>(((value * value) * 0.03 - 1) + (0.0004 * atkVal + 2.99)) * 0.2; } else if (atkVal / 2 > 2000) { return static_cast<float>(atkVal / 660 * 0.1); } else { return static_cast<float>(atkVal / 660 * (atkVal / 1000 * 0.1 + 0.1) * 0.5); } } float StatusFunctions::GetIncreasedDamageRateByAtkInPvp(float atkVal) { if (atkVal <= 0) return 0.0f; if (atkVal / 2 > 500) { return ((pow((0.6f * ((float)atkVal / 2.f) - 300.f), 0.17f) * 10.f - 1.9f) * 0.01f) * 0.5f; } else { return (((float)atkVal / 2.f) / 330.0f * 0.1f) * 0.5f; } } float StatusFunctions::GetIncreasedDamageRateForNonPlayer(int str) { //#ifdef _TAIWAN // return 1.0f + ( str > Constants::MaxStat ? (float)Constants::MaxStat / (float)200 * 0.1f : (float)str / (float)200 * 0.1f ); //#else return 1.0f + (float)str / 660.0f * GetIncreasedRateFactor(str); //#endif } float StatusFunctions::GetIncreasedHealRate(int intelligence) { return 1.0f + (float)intelligence / 330.0f * GetIncreasedRateFactor(intelligence); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Physical Functions float4x4 PhysicalFunctions::GetOrientation(const float3& position, const float3& direction) { float4x4 tmp; tmp.Direction(position, direction, float3(0, 1, 0)); return tmp; } float3 PhysicalFunctions::ApplyGravity(const float3& prev, float dt) { // h = (-(t/T-1)^2n+1)*H (t>=T) // h = (-(-t/T+1)^2n+1)*H (t<T) // --> v = v0-((t-v0)^m)*(1/v0^(m-1)) : m=2n //float m=4; //float t=dt; //float v0=prev.y; //float v = v0 - abs(pow(t-v0, m)*(pow(1/v0, m-1))); float3 g(0, -9.8f, 0); float3 v = prev + g * dt; return v; } float3 PhysicalFunctions::ApplyGravity(const float3& position, const float3& prev, float dt) { float3 v = ApplyGravity(prev, dt); float3 pos = position + v * dt; if (pos.y < 0) pos.y = 0; return pos; } const float3& PhysicalFunctions::DirectionToDefinedDirection(float3 dir) { //if (backward) dir *= -1; if (dir.x == 0) dir.x = 0.000001f;// devide by zero if (dir.x >= 0 && dir.z > 0) {//1��и if (dir.x < dir.z) { //1��Ⱥи -_-餻 if (dir.z / dir.x > 2.4f) //67.5��� DZ��. -_-;; return Constants::DirectionF::Up; else return Constants::DirectionF::RightUp; } else {//2��Ⱥи if (dir.z / dir.x >= 0.414213f) return Constants::DirectionF::RightUp; else return Constants::DirectionF::Right; } } else if (dir.x >= 0 && dir.z <= 0) {//2��и if (dir.x >= -dir.z) {//3��Ⱥи if (-dir.z / dir.x < 0.414213f) return Constants::DirectionF::Right; else return Constants::DirectionF::RightDown; } else {//4��Ⱥи if (-dir.z / dir.x <= 2.4f) return Constants::DirectionF::RightDown; else return Constants::DirectionF::Down; } } else if (dir.x < 0 && dir.z < 0) {//3��и if (dir.x > dir.z) {//5��Ⱥи if (dir.z / dir.x > 2.4f) //67.5鵵� DZ��. -_-;; return Constants::DirectionF::Down; else return Constants::DirectionF::LeftDown; } else {//6��Ⱥи if (dir.z / dir.x >= 0.414213f) return Constants::DirectionF::LeftDown; else return Constants::DirectionF::Left; } } else {//4��и if (-dir.x >= dir.z) { if (dir.z / (-dir.x) < 0.414213f) return Constants::DirectionF::Left; else return Constants::DirectionF::LeftUp; } else { if (dir.z / (-dir.x) < 2.4f) return Constants::DirectionF::LeftUp; else return Constants::DirectionF::Up; } } } float3 PhysicalFunctions::GetSpinnedDirection(const float3& targetDirection, float3 sourceDirection, uint16 spinLimit, float dt) { float spinByTime = spinLimit * (dt / 0.1f); float SINLEFT = sin((float)spinByTime * Math::pi / 180.0f), COSLEFT = cos((float)spinByTime * Math::pi / 180.0f); float SINRIGHT = sin((float)(360 - spinByTime) * Math::pi / 180.0f), COSRIGHT = cos((float)(360 - spinByTime) * Math::pi / 180.0f); int quarterA, quarterB; float inclineA = sourceDirection.x ? sourceDirection.z / sourceDirection.x : sourceDirection.z / 0.0000001f; float inclineB = targetDirection.x ? targetDirection.z / targetDirection.x : targetDirection.z / 0.0000001f; float3 spinnedDirectionLeft(sourceDirection.x * COSLEFT - sourceDirection.z * SINLEFT, 0, sourceDirection.x * SINLEFT + sourceDirection.z * COSLEFT); float3 spinnedDirectionRight(sourceDirection.x * COSRIGHT - sourceDirection.z * SINRIGHT, 0, sourceDirection.x * SINRIGHT + sourceDirection.z * COSRIGHT); if (sourceDirection.x >= 0 && sourceDirection.z >= 0) quarterA = 1; else if (sourceDirection.x >= 0 && sourceDirection.z < 0) quarterA = 2; else if (sourceDirection.x < 0 && sourceDirection.z < 0) quarterA = 3; else quarterA = 4; if (targetDirection.x >= 0 && targetDirection.z >= 0) quarterB = 1; else if (targetDirection.x >= 0 && targetDirection.z < 0) quarterB = 2; else if (targetDirection.x < 0 && targetDirection.z < 0) quarterB = 3; else quarterB = 4; switch (quarterA) { case 1: //����� 1̻�и switch (quarterB) { case 2: //��ȸ� sourceDirection = spinnedDirectionRight; break; case 4: //���ȸ� sourceDirection = spinnedDirectionLeft; break; case 1: if (inclineA < inclineB) {//���ȸ� sourceDirection = spinnedDirectionLeft; } else {//��ȸ� sourceDirection = spinnedDirectionRight; } break; default: if (inclineA < inclineB) {//��ȸ� sourceDirection = spinnedDirectionRight; } else {//���ȸ� sourceDirection = spinnedDirectionLeft; } } break; case 2: //����� 2̻�и switch (quarterB) { case 1: //���ȸ� sourceDirection = spinnedDirectionLeft; break; case 3: //��ȸ� sourceDirection = spinnedDirectionRight; break; case 2: if (inclineA < inclineB) {//���ȸ� sourceDirection = spinnedDirectionLeft; } else {//��ȸ� sourceDirection = spinnedDirectionRight; } break; default: if (inclineA < inclineB) {//��ȸ� sourceDirection = spinnedDirectionRight; } else {//���ȸ� sourceDirection = spinnedDirectionLeft; } } break; case 3: //����� 3̻�и switch (quarterB) { case 2: //���ȸ� sourceDirection = spinnedDirectionLeft; break; case 4: //��ȸ� sourceDirection = spinnedDirectionRight; break; case 3: if (inclineA < inclineB) {//���ȸ� sourceDirection = spinnedDirectionLeft; } else {//��ȸ� sourceDirection = spinnedDirectionRight; } break; default: if (inclineA < inclineB) {//��ȸ� sourceDirection = spinnedDirectionRight; } else {//���ȸ� sourceDirection = spinnedDirectionLeft; } } break; default: //����� 4̻�и switch (quarterB) { case 3: //���ȸ� sourceDirection = spinnedDirectionLeft; break; case 1: //��ȸ� sourceDirection = spinnedDirectionRight; break; case 4: if (inclineA < inclineB) {//���ȸ� sourceDirection = spinnedDirectionLeft; } else {//��ȸ� sourceDirection = spinnedDirectionRight; } break; default: if (inclineA < inclineB) {//��ȸ� sourceDirection = spinnedDirectionRight; } else {//���ȸ� sourceDirection = spinnedDirectionLeft; } } } return sourceDirection; } float3 PhysicalFunctions::RotatePositionByDirection(const float3& position, int angle, const float3& direction) { //������� ̱���� if (direction.x == 0) { if (direction.z > 0) //8 return RotatePosition(position, angle); else if (direction.z < 0) //2 return RotatePosition(position, 180 - angle); //360-180 } else if (direction.x < 0) { if (direction.z == 0) //4 return RotatePosition(position, 90 - angle); //360-270 else if (direction.z > 0) //7 return RotatePosition(position, 45 - angle); //360-315 else //1 return RotatePosition(position, 135 - angle); //360-225 } else {//��� if (direction.z > 0) //9 return RotatePosition(position, 315 - angle); //360-45 else if (direction.z == 0) //6 return RotatePosition(position, 270 - angle); //360-90 else // 3 return RotatePosition(position, 225 - angle); //360-135 } throw; //return float3(0,0,0); //�����Ҽ �� ��ڵ� ��ּ�ó�� by Caspian 071002 } float3 PhysicalFunctions::RotatePosition(const float3& position, int angle) { float3 spinnedPos = position; //ȸ� �ȯ. Up �϶�� ±״� spinnedPos.x = position.x * cos(Math::DegToRad<float>((float)angle)) - position.z * sin(Math::DegToRad<float>((float)angle)); spinnedPos.z = position.x * sin(Math::DegToRad<float>((float)angle)) + position.z * cos(Math::DegToRad<float>((float)angle)); return spinnedPos; } float3 PhysicalFunctions::RotatePositionLimitedAngle(const float3& targetPos, int direction) { switch (direction) { case 1: return RotatePosition(targetPos, 135); case 2: return float3(-targetPos.x, 0, -targetPos.z); case 3: return RotatePosition(targetPos, 225); case 4: return float3(-targetPos.z, 0, targetPos.x); case 6: return float3(targetPos.z, 0, -targetPos.x); case 7: return RotatePosition(targetPos, 45); case 8: return targetPos; case 9: return RotatePosition(targetPos, 315); } throw; } bool PhysicalFunctions::CheckCollision(const float3& targetPos, float range, ObjectData& objData) { if (Math::Length<float>(objData.Position - targetPos) <= objData.Radius + range) //if ( Math::Length<float>( float2(objData.Position.x-targetPos.x, objData.Position.z-targetPos.z) ) <= objData.Radius+range ) return true; return false; } bool PhysicalFunctions::CheckCollision(const float3& targetPos, const float3& targetDirection, float range, ObjectData& objData) { float3 pos = objData.Position; float radius = objData.Radius; //��.. ڼ�� а� ĵ��. //ټ����϶� (y=b), �����϶� (x=X), a=1 �϶�, a=-1 �϶� �װ��� α����ؼ� Ǯ�����. if (targetDirection.x == 0) { //ڼ�� ��϶� (x=X) float startY = targetPos.z, endY = targetPos.z + range * targetDirection.z; //�ϴ ���� Ǽ ������. (r^2 - (X-a')^2 float determinant = pow(radius, 2) - pow((targetPos.x - pos.x), 2); if (determinant < 0) //ڱ��� ̾�. �� ��� �ʾҴ. return false; else if (determinant == 0) {//ٱ��� ��ϳ��. float y = pos.z; if (y >= (startY > endY ? endY : startY) && y < (startY > endY ? startY : endY)) // ٵ�� �¾Ҵ پ���. ��׾�. return true; } else {//���� ̵ΰ��. float sqrtDeterminant = sqrt(determinant); float y1 = pos.z + sqrtDeterminant, y2 = pos.z - sqrtDeterminant; if (y1 >= (startY > endY ? endY : startY) && y1 < (startY > endY ? startY : endY)) // ٵ�� �¾Ҵ پ���. ��׾�. return true; else if (y2 >= (startY > endY ? endY : startY) && y2 < (startY > endY ? startY : endY)) return true; } } else if (targetDirection.z == 0) { //��� ��϶� (y=b) float startX = targetPos.x, endX = targetPos.x + range * targetDirection.x; //�ϴ ���� Ǽ ������. (r^2 - (Y-b')^2 float determinant = pow(radius, 2) - pow((targetPos.z - pos.z), 2); if (determinant < 0) //ڱ��� ̾�. �� ��� �ʾҴ. return false; else if (determinant == 0) {//ٱ��� ��ϳ��. float x = pos.x; if (x >= (startX > endX ? endX : startX) && x < (startX > endX ? startX : endX)) // ٵ�� �¾Ҵ پ���. ��׾�. return true; } else {//���� ̵ΰ��. float sqrtDeterminant = sqrt(determinant); float x1 = pos.x + sqrtDeterminant, x2 = pos.x - sqrtDeterminant; if (x1 >= (startX > endX ? endX : startX) && x1 < (startX > endX ? startX : endX)) return true; else if (x2 >= (startX > endX ? endX : startX) && x2 < (startX > endX ? startX : endX)) return true; } } else if (targetDirection.z / targetDirection.x == 1) { // a=1��϶� float startX = targetPos.x, endX = targetPos.x + (sqrt(pow(range, 2) / 2)) * targetDirection.x; //��� Ǽ ��. (b+a`+b`)^2 - 2(b^2 + 2a`b + a`^2 + b`^2 - r^2) float b = targetPos.z - targetPos.x; float determinant = pow((b + pos.x + pos.z), 2) - 2 * (pow(b, 2) + 2 * pos.x * b + pow(pos.x, 2) + pow(pos.z, 2) - pow(radius, 2)); if (determinant < 0) //걳�� ̾�. �� ��� �ʾҴ. return false; else if (determinant == 0) {//ٱ��� ��ϳ��. float y = (b + pos.x + pos.z) / 2; float x = y - b; if (x >= (startX > endX ? endX : startX) && x < (startX > endX ? startX : endX)) // ٵ�� �¾Ҵ پ���. ��׾�. return true; } else {//���� ̵ΰ��. float sqrtDeterminant = sqrt(determinant); float y1 = ((b + pos.x + pos.z) + sqrtDeterminant) / 2, y2 = ((b + pos.x + pos.z) - sqrtDeterminant) / 2; float x1 = y1 - b, x2 = y2 - b; if (x1 >= (startX > endX ? endX : startX) && x1 < (startX > endX ? startX : endX)) return true; else if (x2 >= (startX > endX ? endX : startX) && x2 < (startX > endX ? startX : endX)) return true; } } else if (targetDirection.z / targetDirection.x == -1) { // a=-1��϶� float startX = targetPos.x, endX = targetPos.x + (sqrt(pow(range, 2) / 2)) * targetDirection.x; float b = targetPos.z + targetPos.x; float determinant = pow((b - pos.x + pos.z), 2) - 2 * (pow(b, 2) - 2 * pos.x * b + pow(pos.x, 2) + pow(pos.z, 2) - pow(radius, 2)); if (determinant < 0) //걳�� ̾�. �� ��� �ʾҴ. return false; else if (determinant == 0) {//ٱ��� ��ϳ��. float y = (b - pos.x + pos.z) / 2; float x = b - y; if (x >= (startX > endX ? endX : startX) && x < (startX > endX ? startX : endX)) // ٵ�� �¾Ҵ پ���. ��׾�. return true; } else {//���� ̵ΰ��. float sqrtDeterminant = sqrt(determinant); float y1 = ((b - pos.x + pos.z) + sqrtDeterminant) / 2, y2 = ((b - pos.x + pos.z) - sqrtDeterminant) / 2; float x1 = b - y1, x2 = b - y2; if (x1 >= (startX > endX ? endX : startX) && x1 < (startX > endX ? startX : endX)) return true; else if (x2 >= (startX > endX ? endX : startX) && x2 < (startX > endX ? startX : endX)) return true; } } else { //��̷���� º�ä� ��浹 �˻� ù߻. float startX = targetPos.x, endX = targetPos.x + (sqrt(pow(range, 2) / 2)) * (targetDirection.x); //���� Ǽ ��. (b+a`+b`)^2 - 2(b^2 + 2a`b + a`^2 + b`^2 - r^2) float b = targetPos.z - targetPos.x; float determinant = pow((b + pos.x + pos.z), 2) - 2 * (pow(b, 2) + 2 * pos.x * b + pow(pos.x, 2) + pow(pos.z, 2) - pow(radius, 2)); if (determinant < 0) //걳�� ̾�. �� ��� �ʾҴ. return false; else if (determinant == 0) {//ٱ��� ��ϳ��. float y = (b + pos.x + pos.z) / 2; float x = y - b; if (x >= (startX > endX ? endX : startX) && x < (startX > endX ? startX : endX)) // ٵ�� �¾Ҵ پ���. ��׾�. return true; } else {//���� ̵ΰ��. float sqrtDeterminant = sqrt(determinant); float y1 = ((b + pos.x + pos.z) + sqrtDeterminant) / 2, y2 = ((b + pos.x + pos.z) - sqrtDeterminant) / 2; float x1 = y1 - b, x2 = y2 - b; if (x1 >= (startX > endX ? endX : startX) && x1 < (startX > endX ? startX : endX)) return true; else if (x2 >= (startX > endX ? endX : startX) && x2 < (startX > endX ? startX : endX)) return true; } } return false; } bool PhysicalFunctions::CheckCollision(const float3& targetPos, const float3& direction, float height, float width, ObjectData& objData) { float3 tmpDir = direction; if (CheckCollision(targetPos, direction, height, objData)) return true; if (tmpDir == Constants::DirectionF::Up) { if (CheckCollision(targetPos + Constants::DirectionF::Right * width, tmpDir, height, objData)) return true; } else if (tmpDir == Constants::DirectionF::RightUp) { if (CheckCollision(targetPos + Constants::DirectionF::RightDown * width, tmpDir, height, objData)) return true; } else if (tmpDir == Constants::DirectionF::Right) { if (CheckCollision(targetPos + Constants::DirectionF::Down * width, tmpDir, height, objData)) return true; } else if (tmpDir == Constants::DirectionF::RightDown) { if (CheckCollision(targetPos + Constants::DirectionF::LeftDown * width, tmpDir, height, objData)) return true; } else if (tmpDir == Constants::DirectionF::Down) { if (CheckCollision(targetPos + Constants::DirectionF::Left * width, tmpDir, height, objData)) return true; } else if (tmpDir == Constants::DirectionF::LeftDown) { if (CheckCollision(targetPos + Constants::DirectionF::LeftUp * width, tmpDir, height, objData)) return true; } else if (tmpDir == Constants::DirectionF::Left) { if (CheckCollision(targetPos + Constants::DirectionF::Up * width, tmpDir, height, objData)) return true; } else if (tmpDir == Constants::DirectionF::LeftUp) { if (CheckCollision(targetPos + Constants::DirectionF::RightUp * width, tmpDir, height, objData)) return true; } float3 pos = objData.Position - targetPos; float3 spinnedPos = pos; if (tmpDir == Constants::DirectionF::RightUp) { spinnedPos = PhysicalFunctions::RotatePosition(pos, 45); } else if (tmpDir == Constants::DirectionF::Right) { spinnedPos.x = -pos.z; spinnedPos.z = pos.x; } else if (tmpDir == Constants::DirectionF::RightDown) { spinnedPos = PhysicalFunctions::RotatePosition(pos, 135); } else if (tmpDir == Constants::DirectionF::Down) { spinnedPos.x = -pos.x; spinnedPos.z = -pos.z; } else if (tmpDir == Constants::DirectionF::LeftDown) { spinnedPos = PhysicalFunctions::RotatePosition(pos, 225); } else if (tmpDir == Constants::DirectionF::Left) { spinnedPos.x = pos.z; spinnedPos.z = -pos.x; } else if (tmpDir == Constants::DirectionF::LeftUp) { spinnedPos = PhysicalFunctions::RotatePosition(pos, 315); } if (spinnedPos.x >= 0 && spinnedPos.x <= width && spinnedPos.z >= 0 && spinnedPos.z <= height) return true; return false; } bool PhysicalFunctions::CheckCollision(const float3& targetPos, const float3& targetDirection, float range, float startAngle, float endAngle, ObjectData& objData) { float3 pos = objData.Position; float radius = objData.Radius; float x = pos.x - targetPos.x; float y = pos.z - targetPos.z; float b = abs(x); float a = sqrt(pow(x, 2) + pow(y, 2)); float targetAngle = Math::RadToDeg<float>(acos(b / a)); if (x > 0 && y >= 0) targetAngle = 90 - targetAngle; else if (x > 0 && y <= 0) targetAngle += 90; else if (x < 0 && y <= 0) targetAngle = 270 - targetAngle; else if (x < 0 && y >= 0) targetAngle += 270; float sAngle = startAngle, eAngle = endAngle; if (targetDirection.x > 0 && targetDirection.z > 0) {//45 sAngle += 45.0f; eAngle += 45.0f; } else if (targetDirection.x > 0 && targetDirection.z == 0) {//90 sAngle += 90.0f; eAngle += 90.0f; } else if (targetDirection.x > 0 && targetDirection.z < 0) {//135 sAngle += 135.0f; eAngle += 135.0f; } else if (targetDirection.x == 0 && targetDirection.z < 0) {//180 sAngle += 180.0f; eAngle += 180.0f; } else if (targetDirection.x < 0 && targetDirection.z < 0) {//225 sAngle += 225.0f; eAngle += 225.0f; } else if (targetDirection.x < 0 && targetDirection.z == 0) {//270 sAngle += 270.0f; eAngle += 270.0f; } else if (targetDirection.x < 0 && targetDirection.z > 0) {//315 sAngle += 315.0f; eAngle += 315.0f; } sAngle = sAngle >= 360 ? sAngle - 360 : sAngle; eAngle = eAngle >= 360 ? eAngle - 360 : eAngle; if (sAngle < eAngle) { if (targetAngle >= sAngle && targetAngle <= eAngle) { if (a <= range + radius) return true; } else { } } else if (sAngle >= eAngle) if (targetAngle >= sAngle || targetAngle <= eAngle) if (a <= range + radius) return true; return false; } bool IsAbleToJoinStage(StageLicense target, const std::vector<StageLicense>& myLicenses) { std::vector<StageLicense>::const_iterator itr = std::find_if(myLicenses.begin(), myLicenses.end(), StageLocation::FinderOnlyStageGroupHash(target.StageGroupHash)); if (itr == myLicenses.end()) return false; if ((*itr).Level >= target.Level) return true; return false; } void PvpRoomInfo::BattleGroundInfoType::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::PvpRoomInfo::BattleGroundInfoType"); out.Write(L"GoalKillCount", GoalKillCount); out.Write(L"LimitPlayTime", LimitPlayTime); } void PvpRoomInfo::BattleGroundInfoType::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::PvpRoomInfo::BattleGroundInfoType"); in.Read(L"GoalKillCount", GoalKillCount); in.Read(L"LimitPlayTime", LimitPlayTime); } void PvpRoomInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::PvpRoomInfo"); out.Write(L"Id", Id); out.Write(L"Title", Title); out.WriteEnum(L"RoomStatus", RoomStatus); out.WriteEnum(L"GameType", GameType); out.Write(L"Map", Map); out.Write(L"Owner", Owner); out.Write(L"IsPrivateRoom", IsPrivateRoom); out.Write(L"IsRandomTeam", IsRandomTeam); out.Write(L"IsEquipSetRewardDisable", IsEquipSetRewardDisable); out.Write(L"IsPetNotUsable", IsPetNotUsable); out.Write(L"IsRebirthSkillDisable", IsRebirthSkillDisable); out.Write(L"IsInvincibleAfterRevive", IsInvincibleAfterRevive); out.Write(L"StatusLimit", StatusLimit); //out.Write(L"RandomMap", RandomMap); out.Write(L"MaxNumberOfMembersPerTeam", MaxNumberOfMembersPerTeam); out.Write(L"MaxNumberOfSpectator", MaxNumberOfSpectator); out.Write(L"BattleGroundInfo", BattleGroundInfo); } void PvpRoomInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::PvpRoomInfo"); in.Read(L"Id", Id); in.Read(L"Title", Title); in.ReadEnum(L"RoomStatus", RoomStatus); in.ReadEnum(L"GameType", GameType); in.Read(L"Map", Map); in.Read(L"Owner", Owner); in.Read(L"IsPrivateRoom", IsPrivateRoom); in.Read(L"IsRandomTeam", IsRandomTeam); in.Read(L"IsEquipSetRewardDisable", IsEquipSetRewardDisable); in.Read(L"IsPetNotUsable", IsPetNotUsable); in.Read(L"IsRebirthSkillDisable", IsRebirthSkillDisable); in.Read(L"IsInvincibleAfterRevive", IsInvincibleAfterRevive); in.Read(L"StatusLimit", StatusLimit); //in.Read(L"RandomMap", RandomMap); in.Read(L"MaxNumberOfMembersPerTeam", MaxNumberOfMembersPerTeam); in.Read(L"MaxNumberOfSpectator", MaxNumberOfSpectator); in.Read(L"BattleGroundInfo", BattleGroundInfo); } void PvpChannelInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::PvpChannelInfo"); out.Write(L"Name", Name); out.Write(L"MinLevel", MinLevel); out.Write(L"MaxLevel", MaxLevel); out.WriteEnum(L"Status", Status); } void PvpChannelInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::PvpChannelInfo"); in.Read(L"Name", Name); in.Read(L"MinLevel", MinLevel); in.Read(L"MaxLevel", MaxLevel); in.ReadEnum(L"Status", Status); } StylePointProcess::StylePointProcess(int minusScore, int minusTime, float startGab) : currentPoint(0), nowProcess(false), timerData(0.f), maxPoint(0), minusStartTime(0.f), stopCount(0), playerCount(1) { processMinusScore = minusScore; processMinusTime = minusTime; processStartGab = startGab; } StylePointProcess::~StylePointProcess() { } void StylePointProcess::Start(int startScore, int maxScroe) { timerData = static_cast<float>(processMinusTime); nowProcess = true; currentPoint = startScore; maxPoint = maxScroe; minusStartTime = processStartGab; stopCount = 0; } bool StylePointProcess::ReStart() { if (nowProcess == true) return false; --stopCount; if (stopCount > 0) return false; nowProcess = true; timerData = static_cast<float>(processMinusTime); minusStartTime = 10.f; stopCount = 0; return true; } bool StylePointProcess::Stop() { ++stopCount; if (nowProcess == false) return false; if (stopCount > 1) return false; nowProcess = false; return true; } bool StylePointProcess::Process(float dt) { if (nowProcess == false) return false; if (currentPoint <= 0) return false; if (minusStartTime > 0.f) { minusStartTime -= dt; return false; } if (timerData <= 0.f) { currentPoint -= processMinusScore; timerData += processMinusTime; if (currentPoint <= 0) currentPoint = 0; } else { timerData -= dt; } return true; } int StylePointProcess::AddStylePoint(int addValue) { int realAddPoint = 0; if (nowProcess) { switch (playerCount) { case 3: realAddPoint = static_cast<int>(static_cast<float>(addValue) * 0.9f); break; case 2: realAddPoint = static_cast<int>(static_cast<float>(addValue) * 0.8f); break; case 1: realAddPoint = static_cast<int>(static_cast<float>(addValue) * 0.7f); break; default: realAddPoint = addValue; } currentPoint += realAddPoint; if (currentPoint >= maxPoint) currentPoint = maxPoint; } return realAddPoint; } void StylePointProcess::SetCurrentStylePoint(int point) { currentPoint = point; } float StylePointProcess::GetGaguePercentage() { if (currentPoint != 0) return static_cast<float>(currentPoint) / static_cast<float>(maxPoint); else return 0; } const float Pet::ExpUpPerSec = 1.0; const float Pet::MaxFull = 100000.0f; const float Pet::MaxOverFull = 1000000.0f; const float Pet::AddEffectStateTime = 60.0f; const float Pet::Feeling::Border::OverFull = 0.90f; const float Pet::Feeling::Border::UnderFull_OverGood = 0.75f; const float Pet::Feeling::Border::UnderGood_OverSoso = 0.50f; const float Pet::Feeling::Border::UnderSoso_OverNotGood = 0.25f; const float Pet::Feeling::Border::UnderNotGood_OverHungry = 0.03f; const float Pet::Feeling::Border::UnderHungry_OverStarving = 0.00f; const float Pet::TiredFactorRelatedWithFull::Full = 1.6f; const float Pet::TiredFactorRelatedWithFull::Good = 1.2f; const float Pet::TiredFactorRelatedWithFull::Soso_NotGood = 0.8f; const float Pet::TiredFactorRelatedWithFull::Hungry_Starving = 0.4f; const float Pet::RareProbabilityFactorRelatedWithFull::Full_Good = 1.0f; const float Pet::RareProbabilityFactorRelatedWithFull::Soso = 0.7f; const float Pet::RareProbabilityFactorRelatedWithFull::NotGood = 0.5f; const float Pet::RareProbabilityFactorRelatedWithFull::Hungry_Starving = 0.3f; const float Pet::RelatedWithPresentNFull::PresentLimitFull = 1.00f; // L const float Pet::RelatedWithPresentNFull::Constant_C = 4000000.0f; // C const float Pet::RelatedWithPresentNFull::Constant_A = 10.0f; // A PetCaredBySchool::PetCaredBySchool() : ExpFactor(0.0f), Start(0, 0, 0, 0, 0, 0), End(0, 0, 0, 0, 0, 0) { } void PetCaredBySchool::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"PetCaredBySchool"); out.Write(L"PetItemHash", PetItemHash); out.Write(L"PetItemSerial", PetItemSerial); out.Write(L"PetItemInstanceEx", PetItemInstanceEx); out.Write(L"PetItemCount", PetItemCount); out.Write(L"ExpFactor", ExpFactor); out.Write(L"Start", Start); out.Write(L"End", End); } void PetCaredBySchool::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"PetCaredBySchool"); in.Read(L"PetItemHash", PetItemHash); in.Read(L"PetItemSerial", PetItemSerial); in.Read(L"PetItemInstanceEx", PetItemInstanceEx); in.Read(L"PetItemCount", PetItemCount); in.Read(L"ExpFactor", ExpFactor); in.Read(L"Start", Start); in.Read(L"End", End); } void PetToolTipInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::PetToolTipInfo"); out.Write(L"IsRarePet", IsRarePet); out.Write(L"PetName", PetName); out.Write(L"Level", Level); out.Write(L"Exp", Exp); out.Write(L"RareProbability", RareProbability); out.Write(L"EnchantSerial", EnchantSerial); } void PetToolTipInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::PetToolTipInfo"); in.Read(L"IsRarePet", IsRarePet); in.Read(L"PetName", PetName); in.Read(L"Level", Level); in.Read(L"Exp", Exp); in.Read(L"RareProbability", RareProbability); in.Read(L"EnchantSerial", EnchantSerial); } Pet::Pet() : PetSerial(0), PetHash(0), Level(0), Exp(0), Appear(false), Full(0.0f), PrevFull(0.0f), TiredFactor(1.0f), ExpFactor(1.0f), EffectStateDelayTime(0.0f), EffectStateDelayTimeForDisplay(0.0f), EmotionDelay(0.0f), RareProbability(0.0f), FullSum(0.0f), LevelUpPeriod(0.0f), NextLevelExp(0), IsRarePet(false), Equipments(Constants::Equipment::MaxPetEquipCnt) , EnchantSerial(0) { Equipments.reserve(3); PetName.reserve(50); } void Pet::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Pet"); out.Write(L"IsRarePet", IsRarePet); out.Write(L"PetSerial", PetSerial); out.Write(L"PetName", PetName); out.Write(L"PetHash", PetHash); out.Write(L"Level", Level); out.Write(L"Exp", Exp); out.Write(L"NextLevelExp", NextLevelExp); out.Write(L"Appear", Appear); out.Write(L"Full", Full); out.Write(L"TiredFactor", TiredFactor); out.Write(L"ExpFactor", ExpFactor); out.Write(L"EffectStateDelayTime", EffectStateDelayTime); out.Write(L"EmotionDelay", EmotionDelay); out.Write(L"RareProbability", RareProbability); out.Write(L"FullSum", FullSum); out.Write(L"LevelUpPeriod", LevelUpPeriod); out.Write(L"EnchantSerial", EnchantSerial); } void Pet::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Pet"); in.Read(L"IsRarePet", IsRarePet); in.Read(L"PetSerial", PetSerial); in.Read(L"PetName", PetName); in.Read(L"PetHash", PetHash); in.Read(L"Level", Level); in.Read(L"Exp", Exp); in.Read(L"NextLevelExp", NextLevelExp); in.Read(L"Appear", Appear); in.Read(L"Full", Full); in.Read(L"TiredFactor", TiredFactor); in.Read(L"ExpFactor", ExpFactor); in.Read(L"EffectStateDelayTime", EffectStateDelayTime); EffectStateDelayTimeForDisplay = EffectStateDelayTime; //�Ŭ���̾�Ʈ ����ȭ�� �� ��߰��. in.Read(L"EmotionDelay", EmotionDelay); in.Read(L"RareProbability", RareProbability); in.Read(L"FullSum", FullSum); in.Read(L"LevelUpPeriod", LevelUpPeriod); in.Read(L"EnchantSerial", EnchantSerial); } void Pet::Equipment(uint32 itemHash, int64 instance, Constants::Equipment position) { int pos = static_cast<int>(position) - static_cast<int>(XRated::Constants::Equipment::Pet_Mask); if ((Constants::Equipment::MaxPetEquipCnt > pos) && (pos >= 0)) { Equipments.at(pos).Id = itemHash; Equipments.at(pos).InstanceEx = instance; return; } Logger::GetInstance().Info("invalid pet equipment position : {0}", position); throw(fmt::format(L"invalid pet equipment position : {0}", position)); } void Pet::UnEquipment(Constants::Equipment position) { int pos = static_cast<int>(position) - static_cast<int>(XRated::Constants::Equipment::Pet_Mask); if ((Constants::Equipment::MaxPetEquipCnt > pos) && (pos >= 0)) { Equipments.at(pos).Id = 0; Equipments.at(pos).InstanceEx = 0; return; } Logger::GetInstance().Info("invalid pet equipment position : {0}", position); throw(fmt::format(L"invalid pet equipment position : {0}", position)); } void Pet::AllUnEquipment() { size_t max = Equipments.size(); for (size_t i = 0; i < max; ++i) { Equipments.at(i).Id = 0; } } const Item* Pet::GetEquipment(Constants::Equipment position) { int pos = static_cast<int>(position) - static_cast<int>(XRated::Constants::Equipment::Pet_Mask); if ((Constants::Equipment::MaxPetEquipCnt > pos) && (pos >= 0)) { if (Equipments.at(pos).Id != 0) { return &Equipments.at(pos); } return NULL; } Logger::GetInstance().Info("invalid pet equipment position : {0}", position); throw(fmt::format(L"invalid pet equipment position : {0}", position)); } bool Pet::operator!=(const Pet& in) const { if (PetSerial != in.PetSerial) return true; return false; } float Pet::GetFullChangeByPresent(uint32 sellPrice, uint32 count) const { float l = RelatedWithPresentNFull::PresentLimitFull * 100.0f; float c = RelatedWithPresentNFull::Constant_C; float a = RelatedWithPresentNFull::Constant_A; float x = sqrt(static_cast<float>(sellPrice)) * static_cast<float>(count) * 30.0f; float p = GetFullRatio() * 100.0f; return ((l - (c * l / (((c * p) / (l - p)) + a * l * x + c)) - p) / 100.0f) * Pet::MaxFull; } void Pet::Feed(uint32 amount, uint32 count, bool overFeed) { Full += static_cast<float>(amount * count); if (overFeed) { if (Full > Pet::MaxOverFull) { Full = Pet::MaxOverFull; } } else { if (Full > Pet::MaxFull) { Full = Pet::MaxFull; } } } void Pet::Give(uint32 sellPrice, uint32 count) { const static float MaxPercentByGive = 0.8f; Full += GetFullChangeByPresent(sellPrice, count); if (Full > Pet::MaxFull) Full = Pet::MaxFull; if (GetFullRatio() > MaxPercentByGive) { Full = Pet::MaxFull * MaxPercentByGive; } } int Pet::GetFeedableFoodCount(uint32 foodAmount) const { float feedableAmount = Pet::MaxFull - Full; if (feedableAmount < 0.0f) { return -1; } return static_cast<int>(feedableAmount / static_cast<float>(foodAmount)); } int Pet::GetOverFeedableFoodCount(uint32 foodAmount) const { float feedableAmount = Pet::MaxFull - Full; if (feedableAmount < 0.0f) { return -1; } return static_cast<int>(feedableAmount / static_cast<float>(foodAmount)); } bool Pet::Update(float dt) { if (PetName != L"") { FullSum += (GetFullRatio() * dt); LevelUpPeriod += dt; } if (Appear == true) { Exp += (dt * ExpUpPerSec * ExpFactor); Full -= static_cast<float>((dt * TiredFactor * GetTiredFactorRelatedWithFull())); if (Full < 0.0f) { Full = 0.0f; return false; } EffectStateDelayTime += dt; EffectStateDelayTimeForDisplay += dt; if (EffectStateDelayTimeForDisplay > AddEffectStateTime)// Լ����� ǵ���ȭ ��� 5�� ����� ΰ���Ѵ. { EffectStateDelayTimeForDisplay = 0.0f; } if (EmotionDelay > 0.0f) EmotionDelay -= dt; return true; } return false; } void Pet::UpdateByPetSchool(float dt, float schoolExpFactor) { if (Appear == true) { return; } else { Exp += dt * ExpUpPerSec * (ExpFactor + schoolExpFactor); } } int Pet::GetBuffIndex() const { switch (GetFeeling()) { case Feeling::State::Full: case Feeling::State::Good: return 3; case Feeling::State::Soso: return 2; case Feeling::State::NotGood: return 1; case Feeling::Hungry: case Feeling::Starving: return 0; } return 0; } double Pet::GetTiredFactorRelatedWithFull() const { switch (GetFeeling()) { case Feeling::State::Full: case Feeling::State::Good: return TiredFactorRelatedWithFull::Full; case Feeling::State::Soso: return TiredFactorRelatedWithFull::Good; case Feeling::State::NotGood: return TiredFactorRelatedWithFull::Soso_NotGood; case Feeling::Hungry: case Feeling::Starving: return TiredFactorRelatedWithFull::Hungry_Starving; } return 0.0; } float Pet::GetAddedRareProbability(double fullRate, float maxRareProbability, float rareProbabilityAddPerLevel, uint32 level) const { float m = maxRareProbability; float d = rareProbabilityAddPerLevel; float t = static_cast<float>(Pet::MaxLevel); float lv = static_cast<float>(level); float f = 0.0f; if (lv < 1.0f) return 0.0f; if (fullRate > 1.0f) fullRate = 1.0f; if (fullRate >= Feeling::Border::UnderFull_OverGood) f = RareProbabilityFactorRelatedWithFull::Full_Good; else if (fullRate >= Feeling::Border::UnderGood_OverSoso) f = RareProbabilityFactorRelatedWithFull::Soso; else if (fullRate >= Feeling::Border::UnderSoso_OverNotGood) f = RareProbabilityFactorRelatedWithFull::NotGood; else f = RareProbabilityFactorRelatedWithFull::Hungry_Starving; return ((m / (t - 1.0f) - (t - 2.0f) * d / 2 + (lv - 1.0f) * d) * f); } float Pet::GetFullRatio() const { return Full / Pet::MaxFull; } float Pet::GetPrevFullRatio() const { return PrevFull / Pet::MaxFull; } Pet::Feeling::State Pet::GetFeeling() const { float fullRatio = GetFullRatio(); if (fullRatio > Feeling::Border::OverFull) return Feeling::State::Full; else if (fullRatio > Feeling::Border::UnderFull_OverGood) return Feeling::State::Good; else if (fullRatio > Feeling::Border::UnderGood_OverSoso) return Feeling::State::Soso; else if (fullRatio > Feeling::Border::UnderSoso_OverNotGood) return Feeling::State::NotGood; else if (fullRatio > Feeling::Border::UnderNotGood_OverHungry) return Feeling::Hungry; return Feeling::Starving; } Pet::Feeling::State Pet::GetPrevFeeling() const { float fullRatio = GetPrevFullRatio(); if (fullRatio > Feeling::Border::OverFull) return Feeling::State::Full; else if (fullRatio > Feeling::Border::UnderFull_OverGood) return Feeling::State::Good; else if (fullRatio > Feeling::Border::UnderGood_OverSoso) return Feeling::State::Soso; else if (fullRatio > Feeling::Border::UnderSoso_OverNotGood) return Feeling::State::NotGood; else if (fullRatio > Feeling::Border::UnderNotGood_OverHungry) return Feeling::Hungry; return Feeling::Starving; } bool Pet::IsValidPetNameSize(const std::wstring& name) { std::string tmp = StringUtil::To<std::string>(name); if (tmp.size() <= MaxPetNameSize) { return true; } return false; } PetItemSlot::PetItemSlot() : Position(0), ItemHash(0), InstanceEx(0), Type(PositionType::Invaild), Stacked(0) { } PetItemSlot::PetItemSlot(const PositionType& Type, const uint8& position, const uint32& itemHash, const XRated::InstanceEx& instance, const uint16& stacked) : Position(position), ItemHash(itemHash), InstanceEx(instance), Type(Type), Stacked(stacked) { } void PetItemSlot::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::PetItemSlot"); out.WriteEnum(L"Type", Type); out.Write(L"Position", Position); out.Write(L"ItemHash", ItemHash); out.Write(L"Stacked", Stacked); out.Write(L"instanceEx", InstanceEx); } void PetItemSlot::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::PetItemSlot"); in.ReadEnum(L"Type", Type); in.Read(L"Position", Position); in.Read(L"ItemHash", ItemHash); in.Read(L"Stacked", Stacked); in.Read(L"instanceEx", InstanceEx); } void PetDataWithItemPos::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::PetDataWithItemPos"); out.Write(L"Pet", Pet); out.Write(L"PetItemPosition", PetItemPosition); } void PetDataWithItemPos::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::PetDataWithItemPos"); in.Read(L"Pet", Pet); in.Read(L"PetItemPosition", PetItemPosition); } bool StoreSlotForPet::operator ==(const StoreSlot& rhs) const { return (ItemHash == rhs.ItemHash && StackedCount == rhs.StackedCount && this->InstanceEx== rhs.InstanceEx && SellPrice == rhs.SellPrice); } void StoreSlotForPet::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::StoreSlotForPet"); out.Write(L"ItemHash", ItemHash); out.Write(L"StackedCount", StackedCount); out.Write(L"instanceEx", InstanceEx); out.Write(L"SellPrice", SellPrice); out.Write(L"PetData", PetData); } void StoreSlotForPet::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::StoreSlotForPet"); in.Read(L"ItemHash", ItemHash); in.Read(L"StackedCount", StackedCount); in.Read(L"instanceEx", InstanceEx); in.Read(L"SellPrice", SellPrice); in.Read(L"PetData", PetData); } void ConfirmTradeInfo::TradeItem::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::ConfirmTradeInfo::TradeItem"); out.Write(L"hash", hash); out.Write(L"instanceEx", InstanceEx); out.Write(L"count", count); out.Write(L"isPetItem", isPetItem); if (isPetItem) out.Write(L"pet", pet); } void ConfirmTradeInfo::TradeItem::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::ConfirmTradeInfo::TradeItem"); in.Read(L"hash", hash); in.Read(L"instanceEx", InstanceEx); in.Read(L"count", count); in.Read(L"isPetItem", isPetItem); if (isPetItem) in.Read(L"pet", pet); } void ConfirmTradeInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::ConfirmTradeInfo"); out.Write(L"playerSerial", playerSerial); out.Write(L"playerName", playerName); out.Write(L"items", items); out.Write(L"money", money); } void ConfirmTradeInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::ConfirmTradeInfo"); in.Read(L"playerSerial", playerSerial); in.Read(L"playerName", playerName); in.Read(L"items", items); in.Read(L"money", money); } const int Constants::SecurityCard::MaxRow = 10; const int Constants::SecurityCard::MaxColumn = 8; const int Constants::SecurityCard::QuestionCount = 3; /*String Constants::SecurityCard::GetSecurityCodeString(int row, int col) { return StringUtil::ToUnicode(StringUtil::Format("%c%d", (65 + col), row)); }*/ void Family::Info::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Family::Info"); out.Write(L"Serial", Serial); out.Write(L"CreatedTime", CreatedTime); } void Family::Info::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Family::Info"); in.Read(L"Serial", Serial); in.Read(L"CreatedTime", CreatedTime); } void Family::MemberInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Family::MemberInfo"); out.Write(L"MemberSerial", MemberSerial); out.Write(L"CharacterName", CharacterName); out.WriteEnum(L"Class", Class); out.Write(L"StageLevel", StageLevel); out.Write(L"PvpLevel", PvpLevel); out.Write(L"IsGuest", IsGuest); out.Write(L"IsOnline", IsOnline); out.Write(L"PlayTime", PlayTime); out.Write(L"JoinedDate", JoinedDate); out.Write(L"LastLoggedDate", LastLoggedDate); } void Family::MemberInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Family::MemberInfo"); in.Read(L"MemberSerial", MemberSerial); in.Read(L"CharacterName", CharacterName); in.ReadEnum(L"Class", Class); in.Read(L"StageLevel", StageLevel); in.Read(L"PvpLevel", PvpLevel); in.Read(L"IsGuest", IsGuest); in.Read(L"IsOnline", IsOnline); in.Read(L"PlayTime", PlayTime); in.Read(L"JoinedDate", JoinedDate); in.Read(L"LastLoggedDate", LastLoggedDate); } void Family::RewardCondition::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Family::RewardCondition"); out.Write(L"NextPlayTimeForPersonalPlay", NextPlayTimeForPersonalPlay); out.Write(L"ReceivedDateGroupPlay", ReceivedDateGroupPlay); out.Write(L"MemorialDay", MemorialDay); } void Family::RewardCondition::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Family::RewardCondition"); in.Read(L"NextPlayTimeForPersonalPlay", NextPlayTimeForPersonalPlay); in.Read(L"ReceivedDateGroupPlay", ReceivedDateGroupPlay); in.Read(L"MemorialDay", MemorialDay); } void OpenMarket::ProductInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::OpenMarket::ProductInfo"); out.Write(L"RegistrationNumber", RegistrationNumber); out.WriteEnum(L"RegistrationGrade", Grade); out.Write(L"ItemHash", ItemHash); out.Write(L"instanceEx", InstanceEx); out.Write(L"StackedCount", StackedCount); out.Write(L"Seller", Seller); out.Write(L"ExpirationDate", ExpirationDate); out.Write(L"Price", Price); out.Write(L"IsPetProduct", IsPetProduct); if (IsPetProduct) { out.Write(L"Pet", Pet); } } void OpenMarket::ProductInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::OpenMarket::ProductInfo"); in.Read(L"RegistrationNumber", RegistrationNumber); in.ReadEnum(L"RegistrationGrade", Grade); in.Read(L"ItemHash", ItemHash); in.Read(L"instanceEx", InstanceEx); in.Read(L"StackedCount", StackedCount); in.Read(L"Seller", Seller); in.Read(L"ExpirationDate", ExpirationDate); in.Read(L"Price", Price); in.Read(L"IsPetProduct", IsPetProduct); if (IsPetProduct) { in.Read(L"Pet", Pet); } } void UnidentifiedItemInfo::ProbabilityTable::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Database::Info::UnidentifiedItemInfo::ProbabilityTable"); out.Write(L"Id", Id); out.Write(L"StackedCount", StackedCount); out.Write(L"Probability", Probability); out.Write(L"ExpireMin", static_cast<uint32>(ExpireMin)); out.Write(L"ExpireDue", static_cast<uint32>(ExpireDue)); out.Write(L"ExpireDate", ExpireDate); out.Write(L"CashEnchant1Index", CashEnchant1Index); out.Write(L"CashEnchant2Index", CashEnchant2Index); out.Write(L"CashEnchant3Index", CashEnchant3Index); out.Write(L"CashEnchant4Index", CashEnchant4Index); out.Write(L"InstanceEx", InstanceEx.Instance); std::wstring temp(L"0"); if (InstanceEx.ExpireDate == InstanceEx::NoExpiration) temp = L"0"; else temp = InstanceEx.ExpireDate.ToString(); out.Write(L"InstanceEx.ExpireDate", temp); } void UnidentifiedItemInfo::ProbabilityTable::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Database::Info::UnidentifiedItemInfo::ProbabilityTable"); in.Read(L"Id", Id); in.Read(L"StackedCount", StackedCount, static_cast<uint16>(1)); in.Read(L"Probability", Probability, float(0)); in.Read(L"ExpireMin", ExpireMin, static_cast<uint32>(0)); in.Read(L"ExpireDue", ExpireDue, static_cast<uint32>(0)); in.Read(L"ExpireDate", ExpireDate, std::wstring()); in.Read(L"CashEnchant1Index", CashEnchant1Index, static_cast<uint16>(0)); in.Read(L"CashEnchant2Index", CashEnchant2Index, static_cast<uint16>(0)); in.Read(L"CashEnchant3Index", CashEnchant3Index, static_cast<uint16>(0)); in.Read(L"CashEnchant4Index", CashEnchant4Index, static_cast<uint16>(0)); in.Read(L"InstanceEx", InstanceEx.Instance, int64(0)); std::wstring temp(L"0"); in.Read(L"InstanceEx.ExpireDate", temp, std::wstring(L"0")); if (temp == L"0") InstanceEx.ExpireDate = InstanceEx::NoExpiration; else InstanceEx.ExpireDate.Parse(temp); /* in.Read(L"Instance", Instance, uint64(0)); in.Read(L"InstanceExpireDate", InstanceExpireDate, std::wstring(L"0")); */ } void UnidentifiedItemInfo::EnchantProbabilityList::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Database::Info::UnidentifiedItemInfo::EnchantProbabilityList"); out.Write(L"ReinforcementProbabilitys", ReinforcementProbabilitys); out.Write(L"LightReinforcementProbabilitys", LightReinforcementProbabilitys); } void UnidentifiedItemInfo::EnchantProbabilityList::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Database::Info::UnidentifiedItemInfo::EnchantProbabilityList"); in.Read(L"ReinforcementProbabilitys", ReinforcementProbabilitys, std::vector< float >()); in.Read(L"LightReinforcementProbabilitys", LightReinforcementProbabilitys, std::vector< float >()); } void UnidentifiedItemInfo::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Database::Info::UnidentifiedItemInfo"); out.Write(L"Id", Id); out.Write(L"AutomaticIdentify", static_cast<int32>(AutomaticIdentify)); out.Write(L"ProbabilityTablesPerLevelList", probabilityTablesPerLevelList); out.Write(L"ClassSpecializedRate", ClassSpecializedRate); out.Write(L"MajorStatSpecializedRate", MajorStatSpecializedRate); out.Write(L"EnchantProbabilitys", EnchantProbabilitys); } void UnidentifiedItemInfo::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Database::Info::UnidentifiedItemInfo"); in.Read(L"Id", Id); in.Read(L"AutomaticIdentify", reinterpret_cast<int32&>(AutomaticIdentify), 0); in.Read(L"ProbabilityTablesPerLevelList", probabilityTablesPerLevelList); in.Read(L"ClassSpecializedRate", ClassSpecializedRate, 0.f); in.Read(L"MajorStatSpecializedRate", MajorStatSpecializedRate, 0.f); in.Read(L"EnchantProbabilitys", EnchantProbabilitys, EnchantProbabilityList()); } void UnidentifiedItemInfo::Sort() { } void UnidentifiedItemInfo::ProbabilityTableListPerLevel::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"XRated::Database::Info::UnidentifiedItemInfo::ProbabilityTableListPerLevel"); out.Write(L"Level", Level); out.Write(L"ProbabilityTableList", Table); } void UnidentifiedItemInfo::ProbabilityTableListPerLevel::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"XRated::Database::Info::UnidentifiedItemInfo::ProbabilityTableListPerLevel"); in.Read(L"Level", Level); in.Read(L"ProbabilityTableList", Table); } const UnidentifiedItemInfo::ProbabilityTableList* UnidentifiedItemInfo::GetProbabilityTable(uint32 level) const { int i = static_cast<int>(probabilityTablesPerLevelList.size()) - 1; for (; i >= 0; --i) { if (probabilityTablesPerLevelList[i].Level <= level) { return &(probabilityTablesPerLevelList[i].Table); } } return NULL; } UnidentifiedItemInfo::ProbabilityTableList* UnidentifiedItemInfo::GetProbabilityTableForModify(uint32 level) { int i = static_cast<int>(probabilityTablesPerLevelList.size()) - 1; for (; i >= 0; --i) { if (probabilityTablesPerLevelList[i].Level == level) { return &(probabilityTablesPerLevelList[i].Table); } } return NULL; } const DateTime InstanceEx::NoExpiration(L"2050-12-31 00:00:00"); const DateTime InstanceEx::Expired(L"2000-01-01 00:00:00"); bool InstanceEx::IsExpired(const DateTime& now) const { if (ExpireDate == NoExpiration) return false; if (ExpireDate.GetDate().GetYear(0) == 0) return false; if (ExpireDate > now) return false; return true; } void InstanceEx::ForceExpiration() { DateTime newExpireDate(DateTime::Now()); newExpireDate.GetDate().SetYear(newExpireDate.GetDate().GetYear() - 1); ExpireDate = newExpireDate; } void InstanceEx::MakeUnlimitedPeriod() { ExpireDate = NoExpiration; } DateTime InstanceEx::GetExpiredDate() const { return ExpireDate; } DateTime InstanceEx::ExtensionExpiredDay(uint32 day) { if (*this == NoExpiration) return DateTime::Infinite; this->ExpireDate.Add(DateTime::Unit::Day, day); return this->ExpireDate; } std::wstring InstanceEx::ToString() const { return fmt::format(L"({},{})", Instance, ExpireDate.ToString()); } void InstanceEx::Serialize(Serializer::IStreamWriter& out) const { out.Begin(L"InstanceEx"); out.Write(L"Instance", Instance); ExpireDateFormat tmp; tmp.Year = ExpireDate.GetDate().GetYear(); tmp.Month = ExpireDate.GetDate().GetMonth(); tmp.Day = ExpireDate.GetDate().GetDay(); tmp.Hour = ExpireDate.GetTime().GetHour(); tmp.Minute = ExpireDate.GetTime().GetMinute(); out.Write(L"ExpireDate", reinterpret_cast<const uint32&>(tmp)); } void InstanceEx::Deserialize(Serializer::IStreamReader& in) { in.Begin(L"InstanceEx"); in.Read(L"Instance", Instance); ExpireDateFormat tmp; in.Read(L"ExpireDate", reinterpret_cast<uint32&>(tmp)); if (reinterpret_cast<uint32&>(tmp) == 0) ExpireDate = DateTime::Infinite; else ExpireDate = DateTime(tmp.Year, tmp.Month, tmp.Day, tmp.Hour, tmp.Minute, 0); } void to_json(json& j, const InstanceEx& o) { j = json{ {"instance", o.Instance}, {"expireDate", o.ExpireDate} }; } void from_json(const json& j, InstanceEx& o) { j.at("instance").get_to(o.Instance); j.at("expireDate").get_to(o.ExpireDate); } } }
<reponame>atlassian/marathon /** @jsx React.DOM */ define([ "React" ], function(React) { return React.createClass({ getDefaultProps: function() { return { isActive: false }; }, render: function() { var className = this.props.isActive ? "tab-pane active" : "tab-pane"; return ( <div className={className}> {this.props.children} </div> ); } }); });
<reponame>ibuttimer/VehiclesAPI<gh_stars>0 package com.udacity.vehicles.client.maps; public interface IAddress { String getAddress(); void setAddress(String address); String getCity(); void setCity(String city); String getState(); void setState(String state); String getZip(); void setZip(String zip); default void setFrom(IAddress address) { setAddress(address.getAddress()); setCity(address.getCity()); setState(address.getState()); setZip(address.getZip()); } }
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.jamsimulator.jams.mips.label; import net.jamsimulator.jams.utils.Validate; import java.util.*; import java.util.function.Consumer; public class Label { private final String key; private final int address; private final String originFile; private final int originLine; private final boolean global; private final Set<LabelReference> references; public Label(String key, int address, String originFile, int originLine, boolean global) { Validate.notNull(key, "Key cannot be null!"); Validate.notNull(originFile, "Origin file cannot be null!"); this.key = key; this.address = address; this.originFile = originFile; this.originLine = originLine; this.references = new HashSet<>(); this.global = global; } public Label(String key, int address, String originFile, int originLine, boolean global, Collection<LabelReference> references) { Validate.notNull(key, "Key cannot be null!"); Validate.notNull(originFile, "Origin file cannot be null!"); this.key = key; this.address = address; this.originFile = originFile; this.originLine = originLine; this.global = global; this.references = new HashSet<>(references); } public String getKey() { return key; } public int getAddress() { return address; } public String getOriginFile() { return originFile; } public int getOriginLine() { return originLine; } public boolean isGlobal() { return global; } public Set<LabelReference> getReferences() { return Collections.unmodifiableSet(references); } public boolean addReference(LabelReference reference) { return references.add(reference); } public boolean removeReference(LabelReference reference) { return references.remove(reference); } public void forEachReference(Consumer<LabelReference> consumer) { references.forEach(consumer); } public Label copyAsGlobal() { return new Label(key, address, originFile, originLine, true, references); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Label label = (Label) o; return key.equals(label.key) && originFile.equals(label.originFile); } @Override public int hashCode() { return Objects.hash(key, originFile); } }
package com.javatest.javassist; public class Rectangle { }
import { getHeroBranding } from '@/api/heroBranding' const state = { heroBranding: { title: '', description: '', button_title: '', button_href: '', background_img: '' } } const mutations = { UPDATE_HERO_BRANDING: (state, { title, description, button_title, button_href, background_img }) => { state.heroBranding.title = title state.heroBranding.description = description state.heroBranding.button_title = button_title state.heroBranding.button_href = button_href state.heroBranding.background_img = background_img } } const actions = { getHeroBranding({ commit }) { getHeroBranding().then(response => { commit('UPDATE_HERO_BRANDING', response.data.data) }) } } export default { namespaced: true, state, mutations, actions }
<gh_stars>0 /** * hub-detect * * Copyright (C) 2018 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.blackducksoftware.integration.hub.detect.workflow; import java.util.Optional; import org.springframework.util.Assert; import com.blackducksoftware.integration.hub.detect.hub.HubServiceManager; public class ConnectivityManager { private final boolean isDetectOnline; private final HubServiceManager hubServiceManager; private ConnectivityManager(boolean isDetectOnline, final HubServiceManager hubServiceManager) { this.isDetectOnline = isDetectOnline; this.hubServiceManager = hubServiceManager; } public static ConnectivityManager offline() { return new ConnectivityManager(false, null); } public static ConnectivityManager online(HubServiceManager hubServiceManager) { Assert.notNull(hubServiceManager, "Online detect needs a valid hub services manager."); return new ConnectivityManager(true, hubServiceManager); } public boolean isDetectOnline() { return isDetectOnline; } public Optional<HubServiceManager> getHubServiceManager() { return Optional.ofNullable(hubServiceManager); } }
import { Weights } from '../Weights'; import { Params as RndWeightParams } from './create-rnd-weight'; export declare type Params = { leftUnitsQty: number; rightUnitsQty: number; rndWeightParams?: RndWeightParams; }; declare const createRndWeights: (params: Params) => Weights | null; export default createRndWeights;
#!/bin/bash ############################################################################### # Use DB2 recommended settings for DB, DBM, WLM # # Copyright 2017, IBM Corporation # # 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. ############################################################################### dbname=$1 cd /tmp db2 connect to ${dbname?} db2 "call SYSPROC.ADMIN_CMD( 'AUTOCONFIGURE USING MEM_PERCENT 80 APPLY NONE' )" > autoconfig_sysproc.out recvalues=`cat autoconfig_sysproc.out | sed '/.*LEVEL NAME.*/d' | sed '/.*Result set.*/d' | sed '/.*Return Status.*/d' | sed '/.*record(s) selected.*/d' | sed '/^\s*$/d' | sed 's/^.*-----//' | awk {'print $1":"$2":"$3":"$4'}` for line in ${recvalues?} do type=`echo ${line?} | cut -d: -f1` name=`echo ${line?} | cut -d: -f2` curval=`echo ${line?} | cut -d: -f3` recval=`echo ${line?} | cut -d: -f4` if [ "${type?}" == "DB" ] && [ "${curval?}" != "${recval?}" ] then if [ "${name?}" == "{logfilsiz?}" ] then recval=$((${recval?} * 4)) fi if [ "${name?}" == "logprimary" ] || [ "${name?}" == "logsecond" ] then recval=$((${recval?} * 2)) fi echo "Updating ${type?} CFG ${name?} - Current value (${curval?}); new value (${recval?})" >> set_rec_values.out db2 update db cfg using ${name?} ${recval?} fi done # Restart DBM to take effect for non-dynamic settings db2 connect reset db2stop db2start
#!/bin/sh # # Vivado(TM) # runme.sh: a Vivado-generated Runs Script for UNIX # Copyright 1986-2016 Xilinx, Inc. All Rights Reserved. # echo "This script was generated under a different operating system." echo "Please update the PATH and LD_LIBRARY_PATH variables below, before executing this script" exit if [ -z "$PATH" ]; then PATH=C:/Xilinx/Vivado/2016.4/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2016.4/ids_lite/ISE/lib/nt64:C:/Xilinx/Vivado/2016.4/bin else PATH=C:/Xilinx/Vivado/2016.4/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2016.4/ids_lite/ISE/lib/nt64:C:/Xilinx/Vivado/2016.4/bin:$PATH fi export PATH if [ -z "$LD_LIBRARY_PATH" ]; then LD_LIBRARY_PATH= else LD_LIBRARY_PATH=:$LD_LIBRARY_PATH fi export LD_LIBRARY_PATH HD_PWD='C:/Users/carlo/Downloads/project_5_3/project_5_3.runs/synth_1' cd "$HD_PWD" HD_LOG=runme.log /bin/touch $HD_LOG ISEStep="./ISEWrap.sh" EAStep() { $ISEStep $HD_LOG "$@" >> $HD_LOG 2>&1 if [ $? -ne 0 ] then exit fi } EAStep vivado -log BMEM_GCD_SPI_Wrapper.vds -m64 -product Vivado -mode batch -messageDb vivado.pb -notrace -source BMEM_GCD_SPI_Wrapper.tcl
package mindustry.entities.bullet; import arc.audio.*; import arc.math.*; import arc.util.Tmp; import arc.z.util.ISOUtils; import arc.z.util.ZonesAnnotate.ZField; import mindustry.content.*; import mindustry.ctype.*; import mindustry.entities.*; import mindustry.entities.Effects.*; import mindustry.entities.effect.*; import mindustry.entities.traits.*; import mindustry.entities.type.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.*; import static mindustry.Vars.tilesize; import static z.debug.ZDebug.enable_isoInput; /** * 弹药类型 * */ public abstract class BulletType extends Content{ /** 存活时间*/ public float lifetime; /** 速度*/ public float speed; /** 伤害*/ public float damage; /** 碰撞尺寸*/ public float hitSize = enable_isoInput ? 4f / tilesize : 4; /** 绘制尺寸*/ public float drawSize = 40f; /** 子弹阻力(value 0-1, no continue)*/ public float drag = 0f; /** 是否可穿透目标*/ public boolean pierce; /** 撞击效果*/ public Effect hitEffect, /**销毁效果*/despawnEffect; /** 射击效果.<p/>Effect created when shooting. */ public Effect shootEffect = Fx.shootSmall; /** 烟雾效果.<p/>Extra smoke effect created when shooting. */ public Effect smokeEffect = Fx.shootSmallSmoke; /** 撞击音频.<p/>Sound made when hitting something or getting removed.*/ public Sound hitSound = Sounds.none; /** 射击误差.<p/>Extra inaccuracy when firing. */ public float inaccuracy = 0f; /** (物品提供弹药子弹数量)弹药子弹数量.<p/>How many bullets get created per ammo item/liquid. */ public float ammoMultiplier = 2f; /** 装填速度倍数.<p/>Multiplied by turret reload speed to get final shoot speed. */ public float reloadMultiplier = 1f; /** 反作用力.<p/>Recoil from shooter entities. */ public float recoil; /** 是否在开枪时杀死射击者.为自杀式炸弹袭击者.<p/>Whether to kill the shooter when this is shot. For suicide bombers. */ public boolean killShooter; /** 是否立即使子弹消失.<p/>Whether to instantly make the bullet disappear. */ public boolean instantDisappear; /** 溅射伤害,值0禁用.<p/>Damage dealt in splash. 0 to disable.*/ public float splashDamage = 0f; /** 减速速度.<p/>Knockback in velocity. */ public float knockback; /** 子弹是否击中瓦砾.<p/>Whether this bullet hits tiles. */ public boolean hitTiles = true; /** 撞击状态效果.<p/>Status effect applied on hit. */ public StatusEffect status = StatusEffects.none; /** 状态持续时间.<p/>Intensity of applied status effect in terms of duration. */ public float statusDuration = 60 * 10f; /** 子弹是否可与瓦砾发生碰撞.<p/>Whether this bullet type collides with tiles. */ public boolean collidesTiles = true; /** 子弹是否可与相同队伍瓦砾发生碰撞.<p/>Whether this bullet type collides with tiles that are of the same team. */ public boolean collidesTeam = false; /** 这颗子弹是否与空气单位相撞.<p/>Whether this bullet type collides with air units. */ public boolean collidesAir = true; /** 这颗子弹是否完全与任何东西碰撞.<p/>Whether this bullet types collides with anything at all. */ public boolean collides = true; /** 速度是否从枪手继承.<p/>Whether velocity is inherited from the shooter. */ public boolean keepVelocity = true; // 附加效果. additional effects public int fragBullets = 9; /***/ public float fragVelocityMin = 0.2f, fragVelocityMax = 1f; /** 溅射弹片子弹*/ public BulletType fragBullet = null; /** 使用负值来禁用飞溅伤害.<p/>Use a negative value to disable splash damage. */ public float splashDamageRadius = -1f; /** 燃烧数量*/ public int incendAmount = 0; /** 燃烧扩散值(燃烧范围)*/ public float incendSpread = 8f; /** 燃烧几率*/ public float incendChance = 1f; /** 自导能力*/ public float homingPower = 0f; /** 自导半径*/ public float homingRange = 50f; /** 亮度*/ public int lightining; /** 亮度长度*/ public int lightningLength = 5; /** 撞击抖动*/ public float hitShake = 0f; // zones add begon /** 攻击距离扩展使用(主要适用于近战单位, 通过配置文件初始化, !禁止在代码中初始化)*/ @ZField public float range; // zones add end public BulletType(float speed, float damage){ this.speed = speed; this.damage = damage; lifetime = 40f; hitEffect = Fx.hitBulletSmall; despawnEffect = Fx.hitBulletSmall; } /** 子弹最大移动距离.<p/>Returns maximum distance the bullet this bullet type has can travel. */ public float range(){ return speed * lifetime * (1f - drag); } /** 碰撞检测*/ public boolean collides(Bullet bullet, Tile tile){ return true; } /** 撞击瓦砾*/ public void hitTile(Bullet b, Tile tile){ hit(b); } /** 撞击事件*/ public void hit(Bullet b){ hit(b, b.x, b.y); } /** 撞击事件*/ public void hit(Bullet b, float x, float y){ Effects.effect(hitEffect, x, y, b.rot()); if (enable_isoInput) { hitSound.at(Tmp.v11.set(ISOUtils.tileToWorldCoords(b))); } else { hitSound.at(b); } Effects.shake(hitShake, hitShake, b); if(fragBullet != null){ for(int i = 0; i < fragBullets; i++){ float len = Mathf.random(1f, 7f); float a = Mathf.random(360f); Bullet.create(fragBullet, b, x + Angles.trnsx(a, len), y + Angles.trnsy(a, len), a, Mathf.random(fragVelocityMin, fragVelocityMax)); } } if(Mathf.chance(incendChance)){ Damage.createIncend(x, y, incendSpread, incendAmount); } if(splashDamageRadius > 0){ Damage.damage(b.getTeam(), x, y, splashDamageRadius, splashDamage * b.damageMultiplier()); } } /** 销毁*/ public void despawned(Bullet b){ Effects.effect(despawnEffect, b.x, b.y, b.rot()); hitSound.at(b); if(fragBullet != null || splashDamageRadius > 0){ hit(b); } for(int i = 0; i < lightining; i++){ Lightning.createLighting(Lightning.nextSeed(), b.getTeam(), Pal.surge, damage, b.x, b.y, Mathf.random(360f), lightningLength); } } /** 绘制*/ public void draw(Bullet b){ } /** 初始化*/ public void init(Bullet b){ if(killShooter && b.getOwner() instanceof HealthTrait){ ((HealthTrait)b.getOwner()).kill(); } if(instantDisappear){ b.time(lifetime); } } /** 更新*/ public void update(Bullet b){ if(homingPower > 0.0001f){ TargetTrait target = Units.closestTarget(b.getTeam(), b.x, b.y, homingRange, e -> !e.isFlying() || collidesAir); if(target != null){ b.velocity().setAngle(Mathf.slerpDelta(b.velocity().angle(), b.angleTo(target), 0.08f)); } } } @Override public ContentType getContentType(){ return ContentType.bullet; } }
import java.util.*; class PrintArrayNumber { public static void main(String[] args) { int arrayLength = 0; int [] arr; int value = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter Length of Arra"); arrayLength = sc.nextInt(); if(arrayLength != 0){ arr = new int[arrayLength]; System.out.println("Enter A Arrya Element"); for (int i =0;i< arrayLength ; i++ ) { arr[i] = sc.nextInt(); } PrintArrayNumber.printNumber(arr); } else { System.out.println("Array Length should not be 0"); } } public static void printNumber(int [] num){ System.out.println(Arrays.toString(num)); } }
#!/bin/bash # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 # This script drives the experimental Yosys synthesis flow. More details can be found in README.md set -e set -o pipefail error () { echo >&2 "$@" exit 1 } teelog () { tee "$LR_SYNTH_OUT_DIR/log/$1.log" } if [ ! -f syn_setup.sh ]; then error "No syn_setup.sh file: see README.md for instructions" fi #------------------------------------------------------------------------- # setup flow variables #------------------------------------------------------------------------- source syn_setup.sh #------------------------------------------------------------------------- # prepare output folders #------------------------------------------------------------------------- mkdir -p "$LR_SYNTH_OUT_DIR/generated" mkdir -p "$LR_SYNTH_OUT_DIR/log" mkdir -p "$LR_SYNTH_OUT_DIR/reports/timing" rm -f syn_out/latest ln -s "${LR_SYNTH_OUT_DIR#syn_out/}" syn_out/latest #------------------------------------------------------------------------- # use sv2v to convert all SystemVerilog files to Verilog #------------------------------------------------------------------------- export LR_SYNTH_SRC_DIR="../../$LR_SYNTH_IP_NAME" # Get OpenTitan dependency sources. OT_DEP_SOURCES=( "$LR_SYNTH_SRC_DIR"/../tlul/rtl/tlul_adapter_reg.sv "$LR_SYNTH_SRC_DIR"/../tlul/rtl/tlul_err.sv "$LR_SYNTH_SRC_DIR"/../tlul/rtl/tlul_cmd_intg_chk.sv "$LR_SYNTH_SRC_DIR"/../tlul/rtl/tlul_rsp_intg_gen.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_secded_64_57_dec.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_secded_64_57_enc.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_subreg.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_subreg_ext.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_subreg_shadow.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_subreg_arb.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_alert_sender.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_diff_decode.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_lc_sync.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_sync_reqack_data.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_sync_reqack.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_packer_fifo.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/prim_lfsr.sv "$LR_SYNTH_SRC_DIR"/../prim_generic/rtl/prim_generic_flop_2sync.sv "$LR_SYNTH_SRC_DIR"/../prim_xilinx/rtl/prim_xilinx_flop.sv "$LR_SYNTH_SRC_DIR"/../prim_xilinx/rtl/prim_xilinx_flop_en.sv "$LR_SYNTH_SRC_DIR"/../prim_xilinx/rtl/prim_xilinx_buf.sv "$LR_SYNTH_SRC_DIR"/../prim_xilinx/rtl/prim_xilinx_xor2.sv ) # Get OpenTitan dependency packages. OT_DEP_PACKAGES=( "$LR_SYNTH_SRC_DIR"/../../top_earlgrey/rtl/*_pkg.sv "$LR_SYNTH_SRC_DIR"/../edn/rtl/*_pkg.sv "$LR_SYNTH_SRC_DIR"/../entropy_src/rtl/*_pkg.sv "$LR_SYNTH_SRC_DIR"/../lc_ctrl/rtl/*_pkg.sv "$LR_SYNTH_SRC_DIR"/../tlul/rtl/*_pkg.sv "$LR_SYNTH_SRC_DIR"/../prim/rtl/*_pkg.sv ) # Convert OpenTitan dependency sources. for file in ${OT_DEP_SOURCES[@]}; do module=`basename -s .sv $file` # Skip packages if echo "$module" | grep -q '_pkg$'; then continue fi sv2v \ --define=SYNTHESIS --define=YOSYS \ "${OT_DEP_PACKAGES[@]}" \ -I"$LR_SYNTH_SRC_DIR"/../prim/rtl \ $file \ > $LR_SYNTH_OUT_DIR/generated/${module}.v # Make sure auto-generated primitives are resolved to generic or Xilinx-specific primitives # where available. sed -i 's/prim_flop_2sync/prim_generic_flop_2sync/g' $LR_SYNTH_OUT_DIR/generated/${module}.v sed -i 's/prim_flop/prim_xilinx_flop/g' $LR_SYNTH_OUT_DIR/generated/${module}.v sed -i 's/prim_buf/prim_xilinx_buf/g' $LR_SYNTH_OUT_DIR/generated/${module}.v sed -i 's/prim_xor2/prim_xilinx_xor2/g' $LR_SYNTH_OUT_DIR/generated/${module}.v done # Get and convert core sources. for file in "$LR_SYNTH_SRC_DIR"/rtl/*.sv; do module=`basename -s .sv $file` # Skip packages if echo "$module" | grep -q '_pkg$'; then continue fi sv2v \ --define=SYNTHESIS \ "${OT_DEP_PACKAGES[@]}" \ "$LR_SYNTH_SRC_DIR"/rtl/*_pkg.sv \ -I"$LR_SYNTH_SRC_DIR"/../prim/rtl \ $file \ > $LR_SYNTH_OUT_DIR/generated/${module}.v # Make sure auto-generated primitives are resolved to generic or Xilinx-specific primitives # where available. sed -i 's/prim_flop_2sync/prim_generic_flop_2sync/g' $LR_SYNTH_OUT_DIR/generated/${module}.v sed -i 's/prim_flop/prim_xilinx_flop/g' $LR_SYNTH_OUT_DIR/generated/${module}.v sed -i 's/prim_buf/prim_xilinx_buf/g' $LR_SYNTH_OUT_DIR/generated/${module}.v sed -i 's/prim_xor2/prim_xilinx_xor2/g' $LR_SYNTH_OUT_DIR/generated/${module}.v done #------------------------------------------------------------------------- # run Yosys synthesis #------------------------------------------------------------------------- yosys -c ./tcl/yosys_run_synth.tcl |& teelog syn || { error "Failed to synthesize RTL with Yosys" } #------------------------------------------------------------------------- # run static timing analysis #------------------------------------------------------------------------- if [[ $LR_SYNTH_TIMING_RUN == 1 ]] ; then sta ./tcl/sta_run_reports.tcl |& teelog sta || { error "Failed to run static timing analysis" } ./translate_timing_rpts.sh fi #------------------------------------------------------------------------- # report kGE number #------------------------------------------------------------------------- python/get_kge.py $LR_SYNTH_CELL_LIBRARY_PATH $LR_SYNTH_OUT_DIR/reports/area.rpt
<reponame>puresauce21/ride_laravel app.service('fileUploadService', function ($http, $q) { this.uploadFileToUrl = function (file, uploadUrl, data) { //FormData, object of key/value pair for form fields and values var fileFormData = new FormData(); fileFormData.append('file', file); if(data){ $.each(data, function(i, v){ fileFormData.append(i, v); }) } var deffered = $q.defer(); var getProgressListener = function(deffered) { return function(event) { eventLoaded = event.loaded; eventTotal = event.total; percentageLoaded = ((eventLoaded/eventTotal)*100); deffered.notify(Math.round(percentageLoaded)); }; }; $.ajax({ type: 'POST', url: uploadUrl, data: fileFormData, cache: false, contentType: false, processData: false, headers: { 'X-CSRF-Token': $('input[name="_token"]').val() }, success: function(response, textStatus, jqXHR) { deffered.resolve(response); }, error: function(jqXHR, textStatus, errorThrown) { deffered.reject(errorThrown); }, xhr: function() { var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { myXhr.upload.addEventListener( 'progress', getProgressListener(deffered), false); } return myXhr; } }); return deffered.promise; } }); app.controller('user', ['$scope', '$http', '$compile','fileUploadService', function($scope, $http, $compile, fileUploadService) { $scope.selectFile = function(){ $("#file").click(); } $scope.select_image = function() { $("#file").click(); } $scope.fileNameChanged = function(element) { files = element.files; if(files) { file = files[0]; if(file) { $('.profile_update-loader').addClass('loading'); url = APP_URL+'/'+'profile_upload'; upload = fileUploadService.uploadFileToUrl(file, url); upload.then( function(response){ if(response.success == 'true') { $('.profile_picture').attr('src',response.profile_url); $('.flash-container').html('<div class="alert alert-success text-center col-ssm-12" style="background: #2ec5e1 !important;border-color: #2ec5e1 !important;color: #fff !important;" >' + response.status_message + '</div>'); $(".flash-container").fadeIn(3000); $(".flash-container").fadeOut(3000); $('.profile_update-loader').removeClass('loading'); } else { $('.flash-container').html('<div class="alert alert-danger text-center col-ssm-12" >' + response.status_message + '</div>'); $(".flash-container").fadeIn(3000); $(".flash-container").fadeOut(3000); $('.profile_update-loader').removeClass('loading'); } } ); } } } initAutocomplete(); // Call Google Autocomplete Initialize Function // Google Place Autocomplete Code $scope.location_found = false; $scope.autocomplete_used = false; var autocomplete; function initAutocomplete() { var home_address = document.getElementById('home_address'); if(!home_address) { return false; } autocomplete = new google.maps.places.Autocomplete(home_address); autocomplete.addListener('place_changed', fillInAddress); } function fillInAddress() { $scope.autocomplete_used = true; fetchMapAddress(autocomplete.getPlace()); } function fetchMapAddress(data) { if(data['types'] == 'street_address') $scope.location_found = true; var componentForm = { street_number: 'short_name', route: 'long_name', sublocality_level_1: 'long_name', sublocality: 'long_name', locality: 'long_name', administrative_area_level_1: 'long_name', country: 'short_name', postal_code: 'short_name' }; $('#address_line1').val(''); $('#address_line2').val(''); $('#city').val(''); $('#state').val(''); $('#postal_code').val(''); var place = data; $scope.street_number = ''; for (var i = 0; i < place.address_components.length; i++) { var addressType = place.address_components[i].types[0]; if (componentForm[addressType]) { var val = place.address_components[i][componentForm[addressType]]; if(addressType == 'street_number') $scope.street_number = val; if(addressType == 'route') var street_address = $scope.street_number+' '+val; $('#address_line1').val($.trim(street_address)); if(addressType == 'sublocality_level_1') $('#address_line2').val(val); if(addressType == 'postal_code') $('#postal_code').val(val); if(addressType == 'locality') $('#city').val(val); if(addressType == 'administrative_area_level_1') $('#state').val(val); if(addressType == 'country') $('#country').val(val); } } var latitude = place.geometry.location.lat(); var longitude = place.geometry.location.lng(); $('#latitude').val(latitude); $('#longitude').val(longitude); } $('#mobile_country').click(function() { $('#select-title-stage').text($(this).find(':selected').attr('data-value')); }); $('.singin_rider').click(function(){ var data_params = {}; var type = $(this).attr('data-type'); data_params['type'] = type; if($('#email_phone').val() == '') { $('.email-error').removeClass('hide'); $('.email-error').text($scope.invalid_email); return false; } if(type == 'email') data_params['email_phone'] = $('#email_phone').val(); else if(type == 'password') { data_params['password'] = $('#password').val(); data_params['email'] = $('#email_phone').val(); } data_params['user_type'] = $('#user_type').val(); var data = JSON.stringify(data_params); $http.post('login', { data:data }).then(function(response) { if(response.data.status == 'false') { $('.email-error').removeClass('hide'); $('.email-error').text(response.data.error); } if(response.data.status == 'true') { if(response.data.user_detail != '') { $('.email_or_phone').text(response.data.user_detail); } if(response.data.success == 'true') { if($('#user_type').val() == 'Driver') window.location.href = "driver_profile"; else if($('#user_type').val() == 'Company') window.location.href = "company/dashboard"; else window.location.href = "profile"; } else { $('.email-error').addClass("hide"); $('.email_phone-sec').addClass('hide'); $('.password-sec').removeClass('hide'); $('.password_btn').focus(); $('.email_phone-sec-1').attr('data-type','password'); } } }); }) }]); $('.btn-switch').click(function(){ if($('.btn-switch').hasClass('on')) { $('#is_deaf').val('Yes'); } else { $('#is_deaf').val('No'); } }) $('#click_image').click(function() { $('#profile_image').trigger('click'); }); $('#click_image_driver').click(function() { $('#profile_image_driver').trigger('click'); });
import { Component, OnInit } from '@angular/core'; import {Router} from "@angular/router"; import { UserService } from '../../../user.service'; import { Lightbox } from 'ngx-lightbox'; import { AlertsService } from '@jaspero/ng2-alerts'; @Component({ selector: 'app-sold-product', templateUrl: './sold-product.component.html', styleUrls: ['./sold-product.component.scss'] }) export class SoldProductComponent implements OnInit { soldProduct = ''; id = ''; _album = []; constructor( public userService:UserService, private router: Router, private _lightbox: Lightbox, private _alert: AlertsService ) { } ngOnInit() { this.soldProductInfo(); } soldProductInfo(){ this.userService.soldProductList().subscribe((data) => { this.soldProduct = data.data; // let message = data.message; // const type = 'success'; // this._alert.create(type, message); }, err => { let error; let message; error = JSON.parse(err._body); message = error.message; const type = 'error'; this._alert.create(type, message); } ); } editProduct(id) { this.router.navigate(['theme/edit-product/', id]); // this.userService.getProductByID(id).subscribe((data) => { // this.product = data.data; // }, // err => { // } // ); }; open(index): void { if(this._album.length>0){ this._album.length = 0; } const album = { src: index }; this._album.push(album); this._lightbox.open(this._album); } close(): void { // close lightbox programmatically this._lightbox.close(); } /*navigating to edit-sale view*/ editSale(id) { this.router.navigate(['theme/edit-sale/', id]); }; /*navigating to edit-sale view*/ }
#!/bin/bash set -e mv /tmp/SampleMavenTomcatApp.war /usr/share/tomcat/webapps
#!/bin/sh # # Vivado(TM) # runme.sh: a Vivado-generated Runs Script for UNIX # Copyright 1986-2017 Xilinx, Inc. All Rights Reserved. # echo "This script was generated under a different operating system." echo "Please update the PATH and LD_LIBRARY_PATH variables below, before executing this script" exit if [ -z "$PATH" ]; then PATH=D:/Xilinx/SDK/2017.4/bin;D:/Xilinx/Vivado/2017.4/ids_lite/ISE/bin/nt64;D:/Xilinx/Vivado/2017.4/ids_lite/ISE/lib/nt64:D:/Xilinx/Vivado/2017.4/bin else PATH=D:/Xilinx/SDK/2017.4/bin;D:/Xilinx/Vivado/2017.4/ids_lite/ISE/bin/nt64;D:/Xilinx/Vivado/2017.4/ids_lite/ISE/lib/nt64:D:/Xilinx/Vivado/2017.4/bin:$PATH fi export PATH if [ -z "$LD_LIBRARY_PATH" ]; then LD_LIBRARY_PATH= else LD_LIBRARY_PATH=:$LD_LIBRARY_PATH fi export LD_LIBRARY_PATH HD_PWD='E:/Proj_ZYNQ/CAM_VGA/CAM_VGA.runs/impl_1' cd "$HD_PWD" HD_LOG=runme.log /bin/touch $HD_LOG ISEStep="./ISEWrap.sh" EAStep() { $ISEStep $HD_LOG "$@" >> $HD_LOG 2>&1 if [ $? -ne 0 ] then exit fi } # pre-commands: /bin/touch .init_design.begin.rst EAStep vivado -log CAM_PS_Configure_wrapper.vdi -applog -m64 -product Vivado -messageDb vivado.pb -mode batch -source CAM_PS_Configure_wrapper.tcl -notrace
# include <iostream> int main() { char ch = 'A'; std::cout << int(ch); return 0; }
def remove_duplicates(arr): seen = [] new_arr = [] for num in arr: if num not in seen: seen.append(num) new_arr.append(num) return new_arr remove_duplicates(arr) // [10, 20, 30, 15, 25]
<gh_stars>0 """Script to run image capture screenshots for state data pages. """ from argparse import ArgumentParser, RawDescriptionHelpFormatter from datetime import datetime import io import os from pytz import timezone import sys import time import boto3 from loguru import logger from captive_browser import CaptiveBrowser from url_source import load_one_source parser = ArgumentParser( description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument( '--temp-dir', default='/tmp/public-cache', help='Local temp dir for snapshots') parser.add_argument( '--s3-bucket', default='covid-data-archive', help='S3 bucket name') parser.add_argument('--states', default='', help='Comma-separated list of state 2-letter names. If present, will only screenshot those.') parser.add_argument('--public-only', action='store_true', default=False, help='If present, will only snapshot public website and not state pages') parser.add_argument('--push-to-s3', dest='push_to_s3', action='store_true', default=False, help='Push screenshots to S3') parser.add_argument('--replace-most-recent-snapshot', action='store_true', default=False, help='If present, will first delete the most recent snapshot for the state before saving ' 'new screenshot to S3') _PUBLIC_STATE_URL = 'https://covidtracking.com/data/' _STATES_LARGER_WINDOWS = ['DE', 'IN', 'MA', 'NC', 'OK'] class S3Backup(): def __init__(self, bucket_name: str): self.s3 = boto3.resource('s3') self.bucket_name = bucket_name self.bucket = self.s3.Bucket(self.bucket_name) # for now just uploads image (PNG) file with specified name def upload_file(self, local_path: str, s3_path: str): self.s3.meta.client.upload_file( local_path, self.bucket_name, s3_path, ExtraArgs={'ContentType': 'image/png'}) def delete_most_recent_snapshot(self, state: str): state_file_keys = [file.key for file in self.bucket.objects.all() if state in file.key] most_recent_state_key = sorted(state_file_keys, reverse=True)[0] self.s3.Object(self.bucket_name, most_recent_state_key).delete() # saves screenshot of data_url to specified path. takes 5 sec. can throw exception on load fail def screenshot_to_path(data_url, path, browser): logger.info(f" 1. get content from {data_url}") if not browser.navigate(data_url): logger.error(" get timed out -> skip") return logger.info(f" 2. wait for 5 seconds") time.sleep(5) logger.info(f" 3. save screenshot to {path}") browser.screenshot(path) def screenshot(state, data_url, args, s3, browser): logger.info(f"Screenshotting {state} from {data_url}") timestamp = datetime.now(timezone('US/Eastern')).strftime("%Y%m%d-%H%M%S") filename = "%s-%s.png" % (state, timestamp) local_path = os.path.join(args.temp_dir, filename) try: screenshot_to_path(data_url, local_path, browser) except Exception as exc: logger.error(f" Failed to screenshot {state}!") raise exc if args.push_to_s3: s3_path = os.path.join('state_screenshots', state, filename) if args.replace_most_recent_snapshot: logger.info(f" 3a. first delete the most recent snapshot") s3.delete_most_recent_snapshot(state) logger.info(f" 4. push to s3 at {s3_path}") s3.upload_file(local_path, s3_path) def main(args_list=None): if args_list is None: args_list = sys.argv[1:] args = parser.parse_args(args_list) browser = CaptiveBrowser() s3 = S3Backup(bucket_name=args.s3_bucket) # get states info from API src = load_one_source("google-states-csv") state_info_df = src.df failed_states = [] def screenshot_with_size_handling(state, data_url): # hack: if state needs to be bigger, capture that too. public site is huge. current_size = browser.driver.get_window_size() if state in _STATES_LARGER_WINDOWS: logger.info("temporarily resize browser to capture longer state pages") browser.driver.set_window_size(current_size["width"], current_size["height"] * 2) elif state == 'public': logger.info("temporarily resize browser to capture longer public page") browser.driver.set_window_size(current_size["width"], current_size["height"] * 4) try: screenshot(state, data_url, args, s3, browser) except Exception: failed_states.append(state) finally: logger.info("reset browser to original size") browser.driver.set_window_size(current_size["width"], current_size["height"]) # screenshot public state site screenshot_with_size_handling('public', _PUBLIC_STATE_URL) if args.public_only: logger.info("Not snapshotting state pages, was asked for --public-only") return # screenshot state images if args.states: states = args.states.split(',') for state in states: data_url = state_info_df.loc[state_info_df.state == state].head(1).data_page.values[0] screenshot_with_size_handling(state, data_url) else: for idx, r in state_info_df.iterrows(): # if idx > 1: # break state = r["location"] data_url = r["data_page"] screenshot_with_size_handling(state, data_url) if failed_states: logger.error(f"Failed states for this run: {','.join(failed_states)}") if __name__ == "__main__": main()
FactoryGirl.define do factory :product_nfe_processo_referencia, class: BrNfe::Product::Nfe::ProcessoReferencia do numero_processo 'DUO33161107BR' indicador 1 end end
#!/bin/bash FN="MeSH.Eco.55989.eg.db_1.13.0.tar.gz" URLS=( "https://bioconductor.org/packages/3.10/data/annotation/src/contrib/MeSH.Eco.55989.eg.db_1.13.0.tar.gz" "https://bioarchive.galaxyproject.org/MeSH.Eco.55989.eg.db_1.13.0.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-mesh.eco.55989.eg.db/bioconductor-mesh.eco.55989.eg.db_1.13.0_src_all.tar.gz" ) MD5="37249fa8652fe39cb7f9dbdea8205c67" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
newBudget Allow User Abort [ Off ] Set Error Capture [ On ] Go to Field [ ] If [ Get (LastError) = 509 ] Go to Field [ budget::name ] Exit Script [ ] End If New Record/Request Set Field [ budget::name; "test" ] Set Variable [ $budget; Value:budget::_Lbudget ] Go to Layout [ “target” (outTarget) ] New Record/Request Set Field [ outTarget::kbudget; $budget ] Go to Layout [ “budget” (budget) ] Set Field [ budget::name; "" ] Go to Field [ budget::name ] January 8, 平成26 18:48:30 Budget Research.fp7 - newBudget -1-
@Override public void onBindViewHolder(ServiceViewHolder holder, int position) { String service = getItem(position); holder.bind(service); }
const appRoot = require('app-root-path'); const dotenv = require('dotenv'); dotenv.config(); const express = require('express'); const bodyParser = require('body-parser'); const authRoute = require(`${appRoot}/api/routes/authRoute`); const logger = require(`${appRoot}/config/winston`); const swaggerUi = require('swagger-ui-express'); require(`${appRoot}/config/dbConnection`); const router = express.Router(); const app = express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); // views folder app.set('views', './public/view'); // specify template engine app.set('view engine', 'pug'); // configure swagger ui const swaggerDocument = require(`${appRoot}/doc/api-spec.json`); router.use('/', swaggerUi.serve); router.get('/api-docs', swaggerUi.setup(swaggerDocument)); // configure routes authRoute(router); app.use(router); const port = process.env.PORT || 3000; app.listen(3000, () => { logger.info(`listening at port ${port}`); });
#!/bin/sh ldd $1 | while read a b c d; do echo $b | grep -q '=>' || continue [ $(expr "$c" : "(0x") -eq 3 ] && continue echo $c [ -n "$d" ] && $0 $c; done
#!/bin/sh # # @author Heiko.Braun@jboss.com # @version $Id: wsconsume.sh 7513 2008-06-13 07:42:03Z richard.opalka@jboss.com $ # DIRNAME=`dirname $0` PROGNAME=`basename $0` # OS specific support (must be 'true' or 'false'). cygwin=false; case "`uname`" in CYGWIN*) cygwin=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched if $cygwin ; then [ -n "$JBOSS_HOME" ] && JBOSS_HOME=`cygpath --unix "$JBOSS_HOME"` [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Setup JBOSS_HOME if [ "x$JBOSS_HOME" = "x" ]; then # get the full path (without any relative bits) JBOSS_HOME=`cd $DIRNAME/..; pwd` fi export JBOSS_HOME # Setup the JVM if [ "x$JAVA" = "x" ]; then if [ "x$JAVA_HOME" != "x" ]; then JAVA="$JAVA_HOME/bin/java" else JAVA="java" fi fi #JPDA options. Uncomment and modify as appropriate to enable remote debugging . #JAVA_OPTS="-classic -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y $JAVA_OPTS" # Setup JBoss sepecific properties JAVA_OPTS="$JAVA_OPTS" # Setup the java endorsed dirs JBOSS_ENDORSED_DIRS="$JBOSS_HOME/lib/endorsed" ### # Setup the LIBDIR # This script maybe used form within the jbossws distribution # or installed under JBOSS_HOME/bin ### PARENT=`cd $DIRNAME/..; pwd` if [ -d $PARENT/client ]; then LIBDIR=$JBOSS_HOME/client else LIBDIR=$PARENT/lib fi ### # Setup the wsconsume classpath ### # shared libs WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$JAVA_HOME/lib/tools.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/activation.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/getopt.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/wstx.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossall-client.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/log4j.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/mail.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-spi.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-common.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-framework.jar" # shared jaxws libs WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jaxws-tools.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jaxws-rt.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/stax-api.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jaxb-api.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jaxb-impl.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jaxb-xjc.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/streambuffer.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/stax-ex.jar" ### # Stack specific dependencies ### WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/javassist.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jboss-xml-binding.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-native-client.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-native-core.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-native-jaxws.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-native-jaxws-ext.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-native-jaxrpc.jar" WSCONSUME_CLASSPATH="$WSCONSUME_CLASSPATH:$LIBDIR/jbossws-native-saaj.jar" ### # Execute the JVM ### # For Cygwin, switch paths to Windows format before running java if $cygwin; then JBOSS_HOME=`cygpath --path --windows "$JBOSS_HOME"` JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` WSCONSUME_CLASSPATH=`cygpath --path --windows "$WSCONSUME_CLASSPATH"` JBOSS_ENDORSED_DIRS=`cygpath --path --windows "$JBOSS_ENDORSED_DIRS"` fi "$JAVA" $JAVA_OPTS \ -Djava.endorsed.dirs="$JBOSS_ENDORSED_DIRS" \ -Dlog4j.configuration=wstools-log4j.xml \ -classpath "$WSCONSUME_CLASSPATH" \ org.jboss.wsf.spi.tools.cmd.WSConsume "$@"
def capitalize_words(string): words = string.split(' ') capitalized = [word.capitalize() for word in words] return ' '.join(capitalized)
package com.solvd.carfactory.sax; import java.util.Arrays; import java.util.Locale; import java.util.stream.Collectors; public class StringUtils { public static String camelToSnake(String camel) { if (camel.length() <= 1){ return camel.toLowerCase(); } return camel.substring(0, 1).toLowerCase(Locale.ROOT) + camel.substring(1).codePoints() .mapToObj(c -> String.valueOf((char) c)) .map(c -> c.equals(c.toUpperCase()) ? "_" + c.toLowerCase() : c) .collect(Collectors.joining()); } public static String snakeToCamel (String snake){ return Arrays.stream(snake.split("_")) .map(s -> s.substring(0,1).toUpperCase() + s.substring(1)) .collect(Collectors.joining()); } }
class Race < ApplicationRecord validates_with RaceValidator ABANDON_TIME = 1.hour.freeze belongs_to :user belongs_to :game, optional: true belongs_to :category, optional: true enum visibility: {public: 0, invite_only: 1, secret: 2}, _suffix: true belongs_to :owner, foreign_key: :user_id, class_name: 'User' has_many :entries, dependent: :destroy has_many :runners, through: :entries has_many :chat_messages, dependent: :destroy has_many_attached :attachments has_secure_token :join_token scope :started, -> { where.not(started_at: nil) } scope :unstarted, -> { where(started_at: nil) } scope :ongoing, -> { started.unfinished } after_create { entries.create(runner: owner, creator: owner) } def self.unfinished # Distinct call will not return races with no entries, so union all races with 0 entries joins(:entries).where(entries: {finished_at: nil, forfeited_at: nil}).distinct.union( left_outer_joins(:entries).where(entries: {id: nil}) ) end def self.finished where.not(id: unfinished) end # unabandoned returns races that have had activity (e.g. creation, new entry, etc.) in the last hour # or have more than 2 entries. this includes races that have finished def self.unabandoned where('races.updated_at > ?', ABANDON_TIME.ago) end # active returns all non-finished unabandoned races def self.active unabandoned.unfinished end def self.friendly_find!(slug) raise ActiveRecord::RecordNotFound if slug.nil? race = where('LEFT(races.id::text, ?) = ?', slug.length, slug).order(created_at: :asc).first raise ActiveRecord::RecordNotFound if race.nil? race end # with_ends modifies the returned Races to have an ended_at field, which represents the timestamp at which the last # entry finished or forfeited, or null if at least one entry has neither finished nor forfeited. def self.with_ends select('races.*, case when bool_or(entries.finished_at is null and entries.forfeited_at is null) then null else greatest(max(entries.finished_at), max(entries.forfeited_at)) end as ended_at '.squish).left_outer_joins(:entries).group(:id) end def to_s "#{game} #{category} #{title}".presence || 'Untitled race' end def abandoned? updated_at < ABANDON_TIME.ago && entries.count < 2 end def started? started_at.present? end def in_progress? started? && !finished? end def finished? started? && entries.where(finished_at: nil, forfeited_at: nil).none? end def finished_at [ entries.where.not(finished_at: nil).maximum(:finished_at), entries.where.not(forfeited_at: nil).maximum(:forfeited_at) ].compact.max end # Races are "locked" 30 minutes after they end to stop new messages coming in def locked? finished? && Time.now.utc > finished_at + 30.minutes end # potentially starts the race if all entries are now ready def maybe_start! return if started? || entries.where(readied_at: nil).any? || entries.count < 2 update(started_at: Time.now.utc + 20.seconds) # Schedule ghost splits and finishes entries.ghosts.find_each do |entry| entry.update(finished_at: started_at + (entry.run.duration(Run::REAL).to_sec)) Api::V4::RaceBroadcastJob.set(wait_until: started_at + entry.run.duration(Run::REAL).to_sec).perform_later( self, 'race_entries_updated', 'A ghost has finished' ) entry.run.segments.with_ends.each do |segment| Api::V4::RaceBroadcastJob.set(wait_until: started_at + segment.end(Run::REAL).to_sec).perform_later( self, 'race_entries_updated', 'A ghost has split' ) end end # Schedule cleanup job for a started race that was abandoned RaceCleanupJob.set(wait_until: started_at + 48.hours).perform_later(self) Api::V4::RaceBroadcastJob.perform_later(self, 'race_start_scheduled', 'The race is starting soon') Api::V4::GlobalRaceUpdateJob.perform_later(self, 'race_start_scheduled', 'A race is starting soon') end # potentially send race end broadcast if all entries are finished # note: this can potentially send multiple ending messages if called on an already finished race def maybe_end! return if !started? || entries.where(finished_at: nil, forfeited_at: nil).any? Api::V4::RaceBroadcastJob.perform_later(self, 'race_ended', 'The race has ended') Api::V4::GlobalRaceUpdateJob.perform_later(self, 'race_ended', 'A race has ended') end # checks if a given user should be able to act on a given race, returning true if any of the following pass # the user is an entrant in the race or is the race creator, or # the race visibility is not public and the provided token is correct, or # the race is public def joinable?(user: nil, token: nil) result = false result = true if entries.find_for(user).present? || belongs_to?(user) result = true if (invite_only_visibility? || secret_visibility?) && token == join_token result = true if public_visibility? result end # belongs_to? returns true if the given user owns this race, or false otherwise. Use this method instead of direct # comparison to prevent nil users from editing races without owners (e.g. logged-out users & races whose owners # deleted their accounts). def belongs_to?(user) return nil if user.nil? owner == user end def to_param (0..id.length).each do |length| return id[0..length] if self.class.where('LEFT(id::text, ?) = ?', length + 1, id[0..length]).count == 1 end end def title notes.try(:lines).try(:first) end def duration return Duration.new((finished_at - started_at) * 1000) if finished_at.present? return Duration.new((Time.now.utc - started_at) * 1000) if in_progress? Duration.new(nil) end end
module.exports = ['Mujer', 'Masculino'];
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ // THIS IS A GENERATED FILE. DO NOT MODIFY MANUALLY. @see scripts/compile-icons.js import * as React from 'react'; interface SVGRProps { title?: string; titleId?: string; } const EuiIconLogoCode = ({ title, titleId, ...props }: React.SVGProps<SVGSVGElement> & SVGRProps) => ( <svg xmlns="http://www.w3.org/2000/svg" width={32} height={32} viewBox="0 0 32 32" aria-labelledby={titleId} {...props} > {title ? <title id={titleId}>{title}</title> : null} <path className="euiIcon__fillNegative" d="M9.75 12L16 32h10l-3.4-10.88A13 13 0 0010.19 12h-.44z" /> <path fill="#22A7F3" d="M25.725 11.93A17 17 0 009.5 0H6l3.75 12h.44a13 13 0 0112.41 9.12L26 32h6l-6.275-20.07z" /> <path fill="#0377CA" d="M7.91 16.175L0 32h12.855z" /> </svg> ); export const icon = EuiIconLogoCode;
package proto; import static io.grpc.MethodDescriptor.generateFullMethodName; import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; import static io.grpc.stub.ClientCalls.asyncUnaryCall; import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; import static io.grpc.stub.ClientCalls.blockingUnaryCall; import static io.grpc.stub.ClientCalls.futureUnaryCall; import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; /** */ @javax.annotation.Generated( value = "by gRPC proto compiler (version 1.15.0)", comments = "Source: car.proto") public final class CarServiceGrpc { private CarServiceGrpc() {} public static final String SERVICE_NAME = "proto.CarService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<proto.CreateCarRequest, proto.CreateCarResponse> getCreateCarMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateCar", requestType = proto.CreateCarRequest.class, responseType = proto.CreateCarResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<proto.CreateCarRequest, proto.CreateCarResponse> getCreateCarMethod() { io.grpc.MethodDescriptor<proto.CreateCarRequest, proto.CreateCarResponse> getCreateCarMethod; if ((getCreateCarMethod = CarServiceGrpc.getCreateCarMethod) == null) { synchronized (CarServiceGrpc.class) { if ((getCreateCarMethod = CarServiceGrpc.getCreateCarMethod) == null) { CarServiceGrpc.getCreateCarMethod = getCreateCarMethod = io.grpc.MethodDescriptor.<proto.CreateCarRequest, proto.CreateCarResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "proto.CarService", "CreateCar")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.CreateCarRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.CreateCarResponse.getDefaultInstance())) .setSchemaDescriptor(new CarServiceMethodDescriptorSupplier("CreateCar")) .build(); } } } return getCreateCarMethod; } private static volatile io.grpc.MethodDescriptor<proto.DeleteCarRequest, proto.DeleteCarResponse> getDeleteCarMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "DeleteCar", requestType = proto.DeleteCarRequest.class, responseType = proto.DeleteCarResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<proto.DeleteCarRequest, proto.DeleteCarResponse> getDeleteCarMethod() { io.grpc.MethodDescriptor<proto.DeleteCarRequest, proto.DeleteCarResponse> getDeleteCarMethod; if ((getDeleteCarMethod = CarServiceGrpc.getDeleteCarMethod) == null) { synchronized (CarServiceGrpc.class) { if ((getDeleteCarMethod = CarServiceGrpc.getDeleteCarMethod) == null) { CarServiceGrpc.getDeleteCarMethod = getDeleteCarMethod = io.grpc.MethodDescriptor.<proto.DeleteCarRequest, proto.DeleteCarResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "proto.CarService", "DeleteCar")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.DeleteCarRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.DeleteCarResponse.getDefaultInstance())) .setSchemaDescriptor(new CarServiceMethodDescriptorSupplier("DeleteCar")) .build(); } } } return getDeleteCarMethod; } private static volatile io.grpc.MethodDescriptor<proto.GetCarRequest, proto.GetCarResponse> getGetCarMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetCar", requestType = proto.GetCarRequest.class, responseType = proto.GetCarResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<proto.GetCarRequest, proto.GetCarResponse> getGetCarMethod() { io.grpc.MethodDescriptor<proto.GetCarRequest, proto.GetCarResponse> getGetCarMethod; if ((getGetCarMethod = CarServiceGrpc.getGetCarMethod) == null) { synchronized (CarServiceGrpc.class) { if ((getGetCarMethod = CarServiceGrpc.getGetCarMethod) == null) { CarServiceGrpc.getGetCarMethod = getGetCarMethod = io.grpc.MethodDescriptor.<proto.GetCarRequest, proto.GetCarResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "proto.CarService", "GetCar")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.GetCarRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.GetCarResponse.getDefaultInstance())) .setSchemaDescriptor(new CarServiceMethodDescriptorSupplier("GetCar")) .build(); } } } return getGetCarMethod; } private static volatile io.grpc.MethodDescriptor<proto.ListCarRequest, proto.ListCarResponse> getListCarMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListCar", requestType = proto.ListCarRequest.class, responseType = proto.ListCarResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<proto.ListCarRequest, proto.ListCarResponse> getListCarMethod() { io.grpc.MethodDescriptor<proto.ListCarRequest, proto.ListCarResponse> getListCarMethod; if ((getListCarMethod = CarServiceGrpc.getListCarMethod) == null) { synchronized (CarServiceGrpc.class) { if ((getListCarMethod = CarServiceGrpc.getListCarMethod) == null) { CarServiceGrpc.getListCarMethod = getListCarMethod = io.grpc.MethodDescriptor.<proto.ListCarRequest, proto.ListCarResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "proto.CarService", "ListCar")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.ListCarRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.ListCarResponse.getDefaultInstance())) .setSchemaDescriptor(new CarServiceMethodDescriptorSupplier("ListCar")) .build(); } } } return getListCarMethod; } private static volatile io.grpc.MethodDescriptor<proto.UpdateCarRequest, proto.UpdateCarResponse> getUpdateCarMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UpdateCar", requestType = proto.UpdateCarRequest.class, responseType = proto.UpdateCarResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<proto.UpdateCarRequest, proto.UpdateCarResponse> getUpdateCarMethod() { io.grpc.MethodDescriptor<proto.UpdateCarRequest, proto.UpdateCarResponse> getUpdateCarMethod; if ((getUpdateCarMethod = CarServiceGrpc.getUpdateCarMethod) == null) { synchronized (CarServiceGrpc.class) { if ((getUpdateCarMethod = CarServiceGrpc.getUpdateCarMethod) == null) { CarServiceGrpc.getUpdateCarMethod = getUpdateCarMethod = io.grpc.MethodDescriptor.<proto.UpdateCarRequest, proto.UpdateCarResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "proto.CarService", "UpdateCar")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.UpdateCarRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( proto.UpdateCarResponse.getDefaultInstance())) .setSchemaDescriptor(new CarServiceMethodDescriptorSupplier("UpdateCar")) .build(); } } } return getUpdateCarMethod; } /** * Creates a new async stub that supports all call types for the service */ public static CarServiceStub newStub(io.grpc.Channel channel) { return new CarServiceStub(channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static CarServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { return new CarServiceBlockingStub(channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static CarServiceFutureStub newFutureStub( io.grpc.Channel channel) { return new CarServiceFutureStub(channel); } /** */ public static abstract class CarServiceImplBase implements io.grpc.BindableService { /** */ public void createCar(proto.CreateCarRequest request, io.grpc.stub.StreamObserver<proto.CreateCarResponse> responseObserver) { asyncUnimplementedUnaryCall(getCreateCarMethod(), responseObserver); } /** */ public void deleteCar(proto.DeleteCarRequest request, io.grpc.stub.StreamObserver<proto.DeleteCarResponse> responseObserver) { asyncUnimplementedUnaryCall(getDeleteCarMethod(), responseObserver); } /** */ public void getCar(proto.GetCarRequest request, io.grpc.stub.StreamObserver<proto.GetCarResponse> responseObserver) { asyncUnimplementedUnaryCall(getGetCarMethod(), responseObserver); } /** */ public void listCar(proto.ListCarRequest request, io.grpc.stub.StreamObserver<proto.ListCarResponse> responseObserver) { asyncUnimplementedUnaryCall(getListCarMethod(), responseObserver); } /** */ public void updateCar(proto.UpdateCarRequest request, io.grpc.stub.StreamObserver<proto.UpdateCarResponse> responseObserver) { asyncUnimplementedUnaryCall(getUpdateCarMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getCreateCarMethod(), asyncUnaryCall( new MethodHandlers< proto.CreateCarRequest, proto.CreateCarResponse>( this, METHODID_CREATE_CAR))) .addMethod( getDeleteCarMethod(), asyncUnaryCall( new MethodHandlers< proto.DeleteCarRequest, proto.DeleteCarResponse>( this, METHODID_DELETE_CAR))) .addMethod( getGetCarMethod(), asyncUnaryCall( new MethodHandlers< proto.GetCarRequest, proto.GetCarResponse>( this, METHODID_GET_CAR))) .addMethod( getListCarMethod(), asyncUnaryCall( new MethodHandlers< proto.ListCarRequest, proto.ListCarResponse>( this, METHODID_LIST_CAR))) .addMethod( getUpdateCarMethod(), asyncUnaryCall( new MethodHandlers< proto.UpdateCarRequest, proto.UpdateCarResponse>( this, METHODID_UPDATE_CAR))) .build(); } } /** */ public static final class CarServiceStub extends io.grpc.stub.AbstractStub<CarServiceStub> { private CarServiceStub(io.grpc.Channel channel) { super(channel); } private CarServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CarServiceStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CarServiceStub(channel, callOptions); } /** */ public void createCar(proto.CreateCarRequest request, io.grpc.stub.StreamObserver<proto.CreateCarResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getCreateCarMethod(), getCallOptions()), request, responseObserver); } /** */ public void deleteCar(proto.DeleteCarRequest request, io.grpc.stub.StreamObserver<proto.DeleteCarResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getDeleteCarMethod(), getCallOptions()), request, responseObserver); } /** */ public void getCar(proto.GetCarRequest request, io.grpc.stub.StreamObserver<proto.GetCarResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getGetCarMethod(), getCallOptions()), request, responseObserver); } /** */ public void listCar(proto.ListCarRequest request, io.grpc.stub.StreamObserver<proto.ListCarResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getListCarMethod(), getCallOptions()), request, responseObserver); } /** */ public void updateCar(proto.UpdateCarRequest request, io.grpc.stub.StreamObserver<proto.UpdateCarResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getUpdateCarMethod(), getCallOptions()), request, responseObserver); } } /** */ public static final class CarServiceBlockingStub extends io.grpc.stub.AbstractStub<CarServiceBlockingStub> { private CarServiceBlockingStub(io.grpc.Channel channel) { super(channel); } private CarServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CarServiceBlockingStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CarServiceBlockingStub(channel, callOptions); } /** */ public proto.CreateCarResponse createCar(proto.CreateCarRequest request) { return blockingUnaryCall( getChannel(), getCreateCarMethod(), getCallOptions(), request); } /** */ public proto.DeleteCarResponse deleteCar(proto.DeleteCarRequest request) { return blockingUnaryCall( getChannel(), getDeleteCarMethod(), getCallOptions(), request); } /** */ public proto.GetCarResponse getCar(proto.GetCarRequest request) { return blockingUnaryCall( getChannel(), getGetCarMethod(), getCallOptions(), request); } /** */ public proto.ListCarResponse listCar(proto.ListCarRequest request) { return blockingUnaryCall( getChannel(), getListCarMethod(), getCallOptions(), request); } /** */ public proto.UpdateCarResponse updateCar(proto.UpdateCarRequest request) { return blockingUnaryCall( getChannel(), getUpdateCarMethod(), getCallOptions(), request); } } /** */ public static final class CarServiceFutureStub extends io.grpc.stub.AbstractStub<CarServiceFutureStub> { private CarServiceFutureStub(io.grpc.Channel channel) { super(channel); } private CarServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CarServiceFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CarServiceFutureStub(channel, callOptions); } /** */ public com.google.common.util.concurrent.ListenableFuture<proto.CreateCarResponse> createCar( proto.CreateCarRequest request) { return futureUnaryCall( getChannel().newCall(getCreateCarMethod(), getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<proto.DeleteCarResponse> deleteCar( proto.DeleteCarRequest request) { return futureUnaryCall( getChannel().newCall(getDeleteCarMethod(), getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<proto.GetCarResponse> getCar( proto.GetCarRequest request) { return futureUnaryCall( getChannel().newCall(getGetCarMethod(), getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<proto.ListCarResponse> listCar( proto.ListCarRequest request) { return futureUnaryCall( getChannel().newCall(getListCarMethod(), getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<proto.UpdateCarResponse> updateCar( proto.UpdateCarRequest request) { return futureUnaryCall( getChannel().newCall(getUpdateCarMethod(), getCallOptions()), request); } } private static final int METHODID_CREATE_CAR = 0; private static final int METHODID_DELETE_CAR = 1; private static final int METHODID_GET_CAR = 2; private static final int METHODID_LIST_CAR = 3; private static final int METHODID_UPDATE_CAR = 4; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final CarServiceImplBase serviceImpl; private final int methodId; MethodHandlers(CarServiceImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_CREATE_CAR: serviceImpl.createCar((proto.CreateCarRequest) request, (io.grpc.stub.StreamObserver<proto.CreateCarResponse>) responseObserver); break; case METHODID_DELETE_CAR: serviceImpl.deleteCar((proto.DeleteCarRequest) request, (io.grpc.stub.StreamObserver<proto.DeleteCarResponse>) responseObserver); break; case METHODID_GET_CAR: serviceImpl.getCar((proto.GetCarRequest) request, (io.grpc.stub.StreamObserver<proto.GetCarResponse>) responseObserver); break; case METHODID_LIST_CAR: serviceImpl.listCar((proto.ListCarRequest) request, (io.grpc.stub.StreamObserver<proto.ListCarResponse>) responseObserver); break; case METHODID_UPDATE_CAR: serviceImpl.updateCar((proto.UpdateCarRequest) request, (io.grpc.stub.StreamObserver<proto.UpdateCarResponse>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static abstract class CarServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { CarServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return proto.CarOuterClass.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("CarService"); } } private static final class CarServiceFileDescriptorSupplier extends CarServiceBaseDescriptorSupplier { CarServiceFileDescriptorSupplier() {} } private static final class CarServiceMethodDescriptorSupplier extends CarServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; CarServiceMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (CarServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new CarServiceFileDescriptorSupplier()) .addMethod(getCreateCarMethod()) .addMethod(getDeleteCarMethod()) .addMethod(getGetCarMethod()) .addMethod(getListCarMethod()) .addMethod(getUpdateCarMethod()) .build(); } } } return result; } }
#include "Yaml.h" namespace execHelper::yaml { Yaml::Yaml(const execHelper::config::Path& file) : m_yaml(file) { ; } Yaml::Yaml(const std::string& yamlConfig) : m_yaml(yamlConfig) { ; } } // namespace execHelper::yaml
def remove_duplicates(input_list): unique_elements = [] seen = set() for element in input_list: if element not in seen: unique_elements.append(element) seen.add(element) return unique_elements
/** * This class was created by <ArekkuusuJerii>. It's distributed as * part of Stratoprism. Get the Source Code in github: * https://github.com/ArekkuusuJerii/Stratoprism * * Stratoprism is Open Source and distributed under the * MIT Licence: https://github.com/ArekkuusuJerii/Stratoprism/blob/master/LICENSE */ package arekkuusu.stratoprism.api.item.capability; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; import javax.annotation.Nullable; public class VastatioProvider implements ICapabilityProvider, INBTSerializable<NBTTagCompound> { @CapabilityInject(IVastatioCapability.class) public static final Capability<IVastatioCapability> VASTATIO_CAPABILITY = null; private IVastatioCapability vCapability = null; public VastatioProvider(){ vCapability = new DefaultVastatioCapability(); } public VastatioProvider(IVastatioCapability vCapability){ this.vCapability = vCapability; } @Override public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { return VASTATIO_CAPABILITY == capability; } @Override public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) { if (VASTATIO_CAPABILITY != null && capability == VASTATIO_CAPABILITY) return (T)vCapability; return null; } public static IVastatioCapability get(ItemStack stack) { return stack != null && stack.hasCapability(VASTATIO_CAPABILITY, null)? stack.getCapability(VASTATIO_CAPABILITY, null): null; } @Override public NBTTagCompound serializeNBT() { return vCapability.saveNBTData(); } @Override public void deserializeNBT(NBTTagCompound nbt) { vCapability.loadNBTData(nbt); } }
use std::sync::mpsc; #[derive(Debug)] enum Events { GunFired, SoundPlayed, } struct EventProcessor { gun_fired_event: mpsc::Receiver<Events>, event_sender: mpsc::Sender<Events>, } impl EventProcessor { fn process_events(&self) -> Result<(), mpsc::SendError<Events>> { if let Ok(gun_fired) = self.gun_fired_event.try_recv() { // play the sound dbg!(gun_fired); self.event_sender.send(Events::SoundPlayed)?; } Ok(()) } }
from __future__ import annotations from abc import ABC, abstractmethod from ctypes import sizeof, c_void_p,pointer import pyglet from random import random import glm from pyglet.gl import * import tinyobjloader from .mesh import Mesh, ModelMesh,RawMesh,TexturedMesh vaos = [] vbos = [] def createVAO(): vao_id = GLuint() glGenVertexArrays(1,vao_id) glBindVertexArray(vao_id) vaos.append(vao_id) #print("vao -> ",vao_id) return vao_id def unbindVAO(): #glBindVertexArray(0) pass def cleanup(): for vao in vaos: glDeleteVertexArrays(1,vao) for vbo in vbos: glDeleteVertexArrays(1,vbo) def createVBO(): vbo_id = GLuint() glGenBuffers(1,vbo_id) vbos.append(vbo_id) #print("vbo -> ",vbo_id) return vbo_id def storeDataInVBO(pos,size,data): buffer = (GLfloat * len(data))(*data) vboID = createVBO() #print(f"VBO[{pos} | {vboID}] = {data[:10]} ({sizeof(buffer)})") glBindBuffer(GL_ARRAY_BUFFER,vboID) glBufferData(GL_ARRAY_BUFFER,sizeof(buffer),buffer,GL_STATIC_DRAW) glEnableVertexAttribArray(pos) glVertexAttribPointer(pos,size,GL_FLOAT,GL_FALSE,0,0) #glEnableVertexAttribArray(pos) glBindBuffer(GL_ARRAY_BUFFER,0) def bindIndicesToBuffer(indices): vboID = createVBO() glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,vboID) buffer =(GLuint * len(indices))(*indices) #print(f"bindIndicesToBuffer({sizeof(buffer)}|{vboID}) -> {indices}") glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(buffer),buffer,GL_STATIC_DRAW) class Model: def vao_from_RawMesh(self, mesh: RawMesh): vaoID = createVAO() bindIndicesToBuffer([i for i in range(len(mesh.vertices))]) storeDataInVBO(0, 3, mesh.vertices) storeDataInVBO(1, 3, mesh.normals) unbindVAO() Mesh.registry[id(mesh)] = [mesh,vaoID] self.vaos.append(vaoID) def __init__(self): self.mesh_data: ModelMesh self.vaos = [] @staticmethod def model_from_mesh(model_mesh: ModelMesh): model = Model() model.mesh_data = model_mesh return model def load(self): for mesh in self.mesh_data.mesh_list: method_name = str(type(mesh)).split(".")[-1].split("'")[0] getattr(self, 'vao_from_'+method_name)(mesh) def get_mesh_info(self): pass #for mesh in self.mesh_data.mesh_list: def draw(self, shader): for i, vao in enumerate(self.vaos): glBindVertexArray(self.vaos[i]) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glEnableVertexAttribArray(2) #print(len(self.mesh_data.mesh_list[i].vertices)) glDrawElements(GL_TRIANGLES, int(len(self.mesh_data.mesh_list[i].vertices)), GL_UNSIGNED_INT, 0) glDisableVertexAttribArray(2) glDisableVertexAttribArray(1) glDisableVertexAttribArray(0) glBindVertexArray(0)
import { createStore, compose } from "redux"; import rootReducer from "./reducers"; export default createStore( rootReducer, compose( window.devToolsExtension ? window.devToolsExtension() : f => f ) );
package com.nolanlawson.keepscore.data; import java.util.Date; import com.nolanlawson.keepscore.R; import com.nolanlawson.keepscore.util.CollectionUtil.Function; import com.nolanlawson.keepscore.util.Functions; /** * Basic measures of time to use for organizing games in the LoadGameActivity, * e.g. "Today," "Yesterday," "Last," etc. * @author nolan * */ public enum TimePeriod { Today (R.string.title_today, Functions.TODAY_START, Functions.NOW), Yesterday (R.string.title_yesterday, Functions.YESTERDAY_START, Functions.TODAY_START), DayBeforeYesterday (R.string.title_two_days_ago, Functions.DAY_BEFORE_YESTERDAY_START, Functions.YESTERDAY_START), LastWeek (R.string.title_last_week, Functions.ONE_WEEK_AGO_START, Functions.DAY_BEFORE_YESTERDAY_START), LastMonth (R.string.title_last_month, Functions.ONE_MONTH_AGO_START, Functions.ONE_WEEK_AGO_START), LastYear (R.string.title_last_year, Functions.ONE_YEAR_AGO_START, Functions.ONE_MONTH_AGO_START), Older (R.string.title_older, Functions.THE_EPOCH, Functions.ONE_YEAR_AGO_START), ; private int titleResId; private Function<Date, Date> startDateFunction; private Function<Date, Date> endDateFunction; private TimePeriod(int titleResId, Function<Date, Date> startDateFunction, Function<Date, Date> endDateFunction) { this.titleResId = titleResId; this.startDateFunction = startDateFunction; this.endDateFunction = endDateFunction; } public int getTitleResId() { return titleResId; } public Function<Date, Date> getStartDateFunction() { return startDateFunction; } public Function<Date, Date> getEndDateFunction() { return endDateFunction; } }
#!/usr/bin/env bash # initialize submodules recursively git submodule update --init --force --recursive # update monero-project cd ./external/monero-project git checkout master git pull --ff-only origin master cd ../../
<reponame>jplealj/protractor-workshop<gh_stars>0 import { $, browser, ElementFinder, ExpectedConditions, } from 'protractor'; export class ProductAddedModalPage { private proceedToCheckoutButton: ElementFinder; constructor() { this.proceedToCheckoutButton = $('[title="Proceed to checkout"]'); } public async goToOrderSummaryMenu(): Promise<void> { await browser.wait(ExpectedConditions.elementToBeClickable(this.proceedToCheckoutButton), 3000); await this.proceedToCheckoutButton.click(); } }
package chat import ( "context" "fmt" "log" "strings" "sync" "time" "github.com/davecgh/go-spew/spew" lru "github.com/hashicorp/golang-lru" "github.com/keybase/client/go/chat/globals" "github.com/keybase/client/go/chat/storage" "github.com/keybase/client/go/chat/types" "github.com/keybase/client/go/chat/utils" "github.com/keybase/client/go/encrypteddb" "github.com/keybase/client/go/libkb" "github.com/keybase/client/go/protocol/chat1" "github.com/keybase/client/go/protocol/gregor1" "github.com/keybase/client/go/protocol/keybase1" ) // JourneyCardManager handles user switching and proxies to the active JourneyCardManagerSingleUser. type JourneyCardManager struct { globals.Contextified utils.DebugLabeler switchLock sync.Mutex m *JourneyCardManagerSingleUser } var _ (types.JourneyCardManager) = (*JourneyCardManager)(nil) func NewJourneyCardManager(g *globals.Context) *JourneyCardManager { return &JourneyCardManager{ Contextified: globals.NewContextified(g), DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "JourneyCardManager", false), } } func (j *JourneyCardManager) get(ctx context.Context, uid gregor1.UID) (*JourneyCardManagerSingleUser, error) { if uid.IsNil() { return nil, fmt.Errorf("missing uid") } err := libkb.AcquireWithContextAndTimeout(ctx, &j.switchLock, 10*time.Second) if err != nil { return nil, fmt.Errorf("JourneyCardManager switchLock error: %v", err) } defer j.switchLock.Unlock() if j.m != nil && !j.m.uid.Eq(uid) { j.m = nil } if j.m == nil { j.m = NewJourneyCardManagerSingleUser(j.G(), uid) j.Debug(ctx, "switched to uid:%v", uid) } return j.m, nil } func (j *JourneyCardManager) PickCard(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID, convLocalOptional *chat1.ConversationLocal, thread *chat1.ThreadView, ) (*chat1.MessageUnboxedJourneycard, error) { start := j.G().GetClock().Now() defer func() { duration := j.G().GetClock().Since(start) if duration > time.Millisecond*200 { j.Debug(ctx, "PickCard took %s", duration) } }() js, err := j.get(ctx, uid) if err != nil { return nil, err } return js.PickCard(ctx, convID, convLocalOptional, thread) } func (j *JourneyCardManager) TimeTravel(ctx context.Context, uid gregor1.UID, duration time.Duration) (err error) { js, err := j.get(ctx, uid) if err != nil { return err } return js.TimeTravel(ctx, duration) } func (j *JourneyCardManager) ResetAllConvs(ctx context.Context, uid gregor1.UID) (err error) { js, err := j.get(ctx, uid) if err != nil { return err } return js.ResetAllConvs(ctx) } func (j *JourneyCardManager) DebugState(ctx context.Context, uid gregor1.UID, teamID keybase1.TeamID) (summary string, err error) { js, err := j.get(ctx, uid) if err != nil { return "", err } return js.DebugState(ctx, teamID) } func (j *JourneyCardManager) SentMessage(ctx context.Context, uid gregor1.UID, teamID keybase1.TeamID, convID chat1.ConversationID) { js, err := j.get(ctx, uid) if err != nil { j.Debug(ctx, "SentMessage error: %v", err) return } js.SentMessage(ctx, teamID, convID) } func (j *JourneyCardManager) Dismiss(ctx context.Context, uid gregor1.UID, teamID keybase1.TeamID, convID chat1.ConversationID, jcType chat1.JourneycardType) { js, err := j.get(ctx, uid) if err != nil { j.Debug(ctx, "SentMessage error: %v", err) return } js.Dismiss(ctx, teamID, convID, jcType) } func (j *JourneyCardManager) OnDbNuke(mctx libkb.MetaContext) error { return j.clear(mctx.Ctx()) } func (j *JourneyCardManager) Start(ctx context.Context, uid gregor1.UID) { var err error defer j.G().CTrace(ctx, "JourneyCardManager.Start", func() error { return nil })() _, err = j.get(ctx, uid) _ = err // ignore error } func (j *JourneyCardManager) Stop(ctx context.Context) chan struct{} { var err error defer j.G().CTrace(ctx, "JourneyCardManager.Stop", func() error { return nil })() err = j.clear(ctx) _ = err // ignore error ch := make(chan struct{}) close(ch) return ch } func (j *JourneyCardManager) clear(ctx context.Context) error { err := libkb.AcquireWithContextAndTimeout(ctx, &j.switchLock, 10*time.Second) if err != nil { return fmt.Errorf("JourneyCardManager switchLock error: %v", err) } defer j.switchLock.Unlock() j.m = nil return nil } type JourneyCardManagerSingleUser struct { globals.Contextified utils.DebugLabeler uid gregor1.UID // Each instance of JourneyCardManagerSingleUser works only for a single fixed uid. storageLock sync.Mutex lru *lru.Cache encryptedDB *encrypteddb.EncryptedDB } type logFn func(ctx context.Context, format string, args ...interface{}) func NewJourneyCardManagerSingleUser(g *globals.Context, uid gregor1.UID) *JourneyCardManagerSingleUser { lru, err := lru.New(200) if err != nil { // lru.New only panics if size <= 0 log.Panicf("Could not create lru cache: %v", err) } dbFn := func(g *libkb.GlobalContext) *libkb.JSONLocalDb { return g.LocalChatDb } keyFn := func(ctx context.Context) ([32]byte, error) { return storage.GetSecretBoxKeyWithUID(ctx, g.ExternalG(), uid) } return &JourneyCardManagerSingleUser{ Contextified: globals.NewContextified(g), DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "JourneyCardManager", false), uid: uid, lru: lru, encryptedDB: encrypteddb.New(g.ExternalG(), dbFn, keyFn), } } func (cc *JourneyCardManagerSingleUser) checkFeature(ctx context.Context) bool { if cc.G().GetEnv().GetDebugJourneycard() { return true } if cc.G().Env.GetFeatureFlags().HasFeature(libkb.FeatureJourneycardPreview) { return true } ogCtx := ctx // G.FeatureFlags seems like the kind of system that might hang on a bad network. // PickCard is supposed to be lightning fast, so impose a timeout on FeatureFlags. ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() enabled, err := cc.G().FeatureFlags.EnabledWithError(cc.MetaContext(ctx), libkb.FeatureJourneycardPreview) if err != nil { // Send one out in a goroutine to get the goods for next time. ctx, cancel2 := context.WithTimeout(globals.BackgroundChatCtx(ogCtx, cc.G()), 10*time.Second) defer cancel2() go cc.G().FeatureFlags.Enabled(cc.MetaContext(ctx), libkb.FeatureJourneycardPreview) return false } return enabled } // Choose a journey card to show in the conversation. // Called by postProcessThread so keep it snappy. func (cc *JourneyCardManagerSingleUser) PickCard(ctx context.Context, convID chat1.ConversationID, convLocalOptional *chat1.ConversationLocal, thread *chat1.ThreadView, ) (*chat1.MessageUnboxedJourneycard, error) { debug := cc.checkFeature(ctx) if !debug { // Journey cards are gated by either client-side flag KEYBASE_DEBUG_JOURNEYCARD or server-driven flag 'journeycard_preview'. return nil, nil } debugDebug := func(ctx context.Context, format string, args ...interface{}) { if debug { cc.Debug(ctx, format, args...) } } var convInner convForJourneycardInner var untrustedTeamRole keybase1.TeamRole var tlfID chat1.TLFID var welcomeEligible bool var cannotWrite bool if convLocalOptional != nil { convInner = convLocalOptional tlfID = convLocalOptional.Info.Triple.Tlfid untrustedTeamRole = convLocalOptional.ReaderInfo.UntrustedTeamRole if convLocalOptional.ReaderInfo.Journeycard != nil { welcomeEligible = convLocalOptional.ReaderInfo.Journeycard.WelcomeEligible if convInner.GetTopicName() == globals.DefaultTeamTopic { debugDebug(ctx, "welcomeEligible: convLocalOptional has ReaderInfo.Journeycard: %v", welcomeEligible) } } cannotWrite = convLocalOptional.CannotWrite() } else { convFromCache, err := utils.GetUnverifiedConv(ctx, cc.G(), cc.uid, convID, types.InboxSourceDataSourceLocalOnly) if err != nil { return nil, err } if convFromCache.LocalMetadata == nil { // LocalMetadata is needed to get topicName. return nil, fmt.Errorf("conv LocalMetadata not found") } convInner = convFromCache tlfID = convFromCache.Conv.Metadata.IdTriple.Tlfid if convFromCache.Conv.ReaderInfo != nil { untrustedTeamRole = convFromCache.Conv.ReaderInfo.UntrustedTeamRole if convFromCache.Conv.ReaderInfo.Journeycard != nil { welcomeEligible = convFromCache.Conv.ReaderInfo.Journeycard.WelcomeEligible if convInner.GetTopicName() == globals.DefaultTeamTopic { debugDebug(ctx, "welcomeEligible: convFromCache has ReaderInfo.Journeycard: %v", welcomeEligible) } } if convFromCache.Conv.ConvSettings != nil && convFromCache.Conv.ConvSettings.MinWriterRoleInfo != nil { cannotWrite = untrustedTeamRole.IsOrAbove(convFromCache.Conv.ConvSettings.MinWriterRoleInfo.Role) } } } conv := convForJourneycard{ convForJourneycardInner: convInner, ConvID: convID, IsGeneralChannel: convInner.GetTopicName() == globals.DefaultTeamTopic, UntrustedTeamRole: untrustedTeamRole, TlfID: tlfID, // TeamID is filled a little later on WelcomeEligible: welcomeEligible, CannotWrite: cannotWrite, } if !(conv.GetTopicType() == chat1.TopicType_CHAT && conv.GetMembersType() == chat1.ConversationMembersType_TEAM) { // Cards only exist in team chats. cc.Debug(ctx, "conv not eligible for card: topicType:%v membersType:%v general:%v", conv.GetTopicType(), conv.GetMembersType(), conv.GetTopicName() == globals.DefaultTeamTopic) return nil, nil } teamID, err := keybase1.TeamIDFromString(tlfID.String()) if err != nil { return nil, err } conv.TeamID = teamID if len(thread.Messages) == 0 { cc.Debug(ctx, "skipping empty page") return nil, nil } jcd, err := cc.getTeamData(ctx, teamID) if err != nil { return nil, err } makeCard := func(cardType chat1.JourneycardType, highlightMsgID chat1.MessageID, preferSavedPosition bool) (*chat1.MessageUnboxedJourneycard, error) { // preferSavedPosition : If true, the card stays in the position it was previously seen. If false, the card goes at the bottom. var pos *journeyCardPosition if preferSavedPosition { pos = jcd.Convs[convID.String()].Positions[cardType] } if pos == nil { // Pick a message to use as the base for a frontend ordinal. prevID := conv.MaxVisibleMsgID() if prevID == 0 { cc.Debug(ctx, "no message found to use as base for ordinal") return nil, nil } pos = &journeyCardPosition{ PrevID: prevID, } go cc.savePosition(globals.BackgroundChatCtx(ctx, cc.G()), teamID, convID, cardType, *pos) } else { var foundPrev bool for _, msg := range thread.Messages { if msg.GetMessageID() == pos.PrevID { foundPrev = true break } } // If the message that is being used as a prev is not found, omit the card. // So that the card isn't presented at the edge of a far away page. if !foundPrev { cc.Debug(ctx, "omitting card missing prev: %v %v", pos.PrevID, cardType) return nil, nil } } ordinal := 1 // Won't conflict with outbox messages since they are all <= outboxOrdinalStart. cc.Debug(ctx, "makeCard -> prevID:%v cardType:%v jcdCtime:%v", pos.PrevID, cardType, jcd.Ctime.Time()) res := chat1.MessageUnboxedJourneycard{ PrevID: pos.PrevID, Ordinal: ordinal, CardType: cardType, HighlightMsgID: highlightMsgID, } if cardType == chat1.JourneycardType_ADD_PEOPLE { res.OpenTeam, err = cc.isOpenTeam(ctx, conv) if err != nil { cc.Debug(ctx, "isOpenTeam error: %v", err) } } return &res, nil } if debug { // for testing, do special stuff based on channel name: switch conv.GetTopicName() { case "kb_cards_0_kb": return makeCard(chat1.JourneycardType_WELCOME, 0, false) case "kb_cards_1_kb": return makeCard(chat1.JourneycardType_POPULAR_CHANNELS, 0, false) case "kb_cards_2_kb": return makeCard(chat1.JourneycardType_ADD_PEOPLE, 0, false) case "kb_cards_3_kb": return makeCard(chat1.JourneycardType_CREATE_CHANNELS, 0, false) case "kb_cards_4_kb": return makeCard(chat1.JourneycardType_MSG_ATTENTION, 3, false) case "kb_cards_6_kb": return makeCard(chat1.JourneycardType_CHANNEL_INACTIVE, 0, false) case "kb_cards_7_kb": return makeCard(chat1.JourneycardType_MSG_NO_ANSWER, 0, false) } } linearCardOrder := []chat1.JourneycardType{ chat1.JourneycardType_WELCOME, // 1 on design chat1.JourneycardType_POPULAR_CHANNELS, // 2 on design chat1.JourneycardType_ADD_PEOPLE, // 3 on design chat1.JourneycardType_CREATE_CHANNELS, // 4 on design chat1.JourneycardType_MSG_ATTENTION, // 5 on design } looseCardOrder := []chat1.JourneycardType{ chat1.JourneycardType_CHANNEL_INACTIVE, // B on design chat1.JourneycardType_MSG_NO_ANSWER, // C on design } type cardCondition func(context.Context) bool cardConditionTODO := func(ctx context.Context) bool { return false } cardConditions := map[chat1.JourneycardType]cardCondition{ chat1.JourneycardType_WELCOME: func(ctx context.Context) bool { return cc.cardWelcome(ctx, convID, conv, jcd, debugDebug) }, chat1.JourneycardType_POPULAR_CHANNELS: func(ctx context.Context) bool { return cc.cardPopularChannels(ctx, conv, jcd, debugDebug) }, chat1.JourneycardType_ADD_PEOPLE: func(ctx context.Context) bool { return cc.cardAddPeople(ctx, conv, jcd, debugDebug) }, chat1.JourneycardType_CREATE_CHANNELS: func(ctx context.Context) bool { return cc.cardCreateChannels(ctx, conv, jcd) }, chat1.JourneycardType_MSG_ATTENTION: cardConditionTODO, chat1.JourneycardType_CHANNEL_INACTIVE: func(ctx context.Context) bool { return cc.cardChannelInactive(ctx, conv, jcd, thread, debugDebug) }, chat1.JourneycardType_MSG_NO_ANSWER: func(ctx context.Context) bool { return cc.cardMsgNoAnswer(ctx, conv, jcd, thread, debugDebug) }, } // Prefer showing cards later in the order. checkForNeverBeforeSeenCards := func(ctx context.Context, types []chat1.JourneycardType, breakOnShown bool) *chat1.JourneycardType { for i := len(types) - 1; i >= 0; i-- { cardType := types[i] if jcd.hasShownOrDismissedOrLockout(convID, cardType) { if breakOnShown { break } else { continue } } if cond, ok := cardConditions[cardType]; ok && cond(ctx) { cc.Debug(ctx, "selected new card: %v", cardType) return &cardType } } return nil } var latestPage bool if len(thread.Messages) > 0 && conv.MaxVisibleMsgID() > 0 { end1 := thread.Messages[0].GetMessageID() end2 := thread.Messages[len(thread.Messages)-1].GetMessageID() leeway := chat1.MessageID(4) // Some fudge factor in case latest messages are not visible. latestPage = (end1+leeway) >= conv.MaxVisibleMsgID() || (end2+leeway) >= conv.MaxVisibleMsgID() if !latestPage { cc.Debug(ctx, "non-latest page maxvis:%v end1:%v end2:%v", conv.MaxVisibleMsgID(), end1, end2) } } // One might expect thread.Pagination.FirstPage() to be used instead of latestPage. // But FirstPage seems to return false often when latestPage is true. if latestPage { // Prefer showing new "linear" cards. Do not show cards that are prior to one that has been shown. if cardType := checkForNeverBeforeSeenCards(ctx, linearCardOrder, true); cardType != nil { return makeCard(*cardType, 0, true) } // Show any new loose cards. It's fine to show A even if C has already been seen. if cardType := checkForNeverBeforeSeenCards(ctx, looseCardOrder, false); cardType != nil { return makeCard(*cardType, 0, true) } } // TODO card type: MSG_ATTENTION (5 on design) // Gist: "One of your messages is getting a lot of attention! <pointer to message>" // Condition: The logged-in user's message gets a lot of reacjis // Condition: That message is above the fold. // No new cards selected. Pick the already-shown card with the most recent prev message ID. debugDebug(ctx, "no new cards selected") var mostRecentCardType chat1.JourneycardType var mostRecentPrev chat1.MessageID for cardType, savedPos := range jcd.Convs[convID.String()].Positions { if savedPos == nil || jcd.hasDismissed(convID, cardType) { continue } // Break ties in PrevID using cardType's arbitrary enum value. if savedPos.PrevID >= mostRecentPrev && (savedPos.PrevID != mostRecentPrev || cardType > mostRecentCardType) { mostRecentCardType = cardType mostRecentPrev = savedPos.PrevID } } if mostRecentPrev != 0 { switch mostRecentCardType { case chat1.JourneycardType_CHANNEL_INACTIVE, chat1.JourneycardType_MSG_NO_ANSWER: // Special case for these card types. These cards are pointing out a lack of activity // in a conv. Subsequent activity in the conv should dismiss them. if cc.messageSince(ctx, mostRecentPrev, conv, thread, debugDebug) { debugDebug(ctx, "dismissing most recent saved card: %v", mostRecentCardType) go cc.Dismiss(globals.BackgroundChatCtx(ctx, cc.G()), teamID, convID, mostRecentCardType) } else { debugDebug(ctx, "selected most recent saved card: %v", mostRecentCardType) return makeCard(mostRecentCardType, 0, true) } default: debugDebug(ctx, "selected most recent saved card: %v", mostRecentCardType) return makeCard(mostRecentCardType, 0, true) } } debugDebug(ctx, "no card at end of checks") return nil, nil } // Card type: WELCOME (1 on design) // Condition: Only in #general channel func (cc *JourneyCardManagerSingleUser) cardWelcome(ctx context.Context, convID chat1.ConversationID, conv convForJourneycard, jcd journeycardData, debugDebug logFn) bool { // TODO PICNIC-593 Welcome's interaction with existing system message // Welcome cards show not show for all pre-existing teams when a client upgrades to first support journey cards. That would be a bad transition. // The server gates whether welcome cards are allowed for a conv. After MarkAsRead-ing a conv, welcome cards are banned. if !conv.IsGeneralChannel { return false } debugDebug(ctx, "cardWelcome: welcomeEligible: %v", conv.WelcomeEligible) return conv.IsGeneralChannel && conv.WelcomeEligible } // Card type: POPULAR_CHANNELS (2 on design) // Gist: "You are in #general. Other popular channels in this team: diplomacy, sportsball" // Condition: Only in #general channel // Condition: The team has channels besides general that the user could join. // Condition: User has sent a first message OR a few days have passed since they joined the channel. func (cc *JourneyCardManagerSingleUser) cardPopularChannels(ctx context.Context, conv convForJourneycard, jcd journeycardData, debugDebug logFn) bool { otherChannelsExist := conv.GetTeamType() == chat1.TeamType_COMPLEX simpleQualified := conv.IsGeneralChannel && otherChannelsExist && (jcd.Convs[conv.ConvID.String()].SentMessage || cc.timeSinceJoined(ctx, conv.TeamID, conv.ConvID, jcd, time.Hour*24*2)) if !simpleQualified { return false } // Figure out whether there are other channels that the user is not in. // Don't get the actual names, since for NEVER_JOINED convs LocalMetadata, // which has the name, is not generally available. The gui will fetch the names async. topicType := chat1.TopicType_CHAT joinableStatuses := []chat1.ConversationMemberStatus{ // keep in sync with cards/team-journey/container.tsx chat1.ConversationMemberStatus_REMOVED, chat1.ConversationMemberStatus_LEFT, chat1.ConversationMemberStatus_RESET, chat1.ConversationMemberStatus_NEVER_JOINED, } inbox, err := cc.G().InboxSource.ReadUnverified(ctx, cc.uid, types.InboxSourceDataSourceLocalOnly, &chat1.GetInboxQuery{ TlfID: &conv.TlfID, TopicType: &topicType, MemberStatus: joinableStatuses, MembersTypes: []chat1.ConversationMembersType{chat1.ConversationMembersType_TEAM}, SummarizeMaxMsgs: true, SkipBgLoads: true, AllowUnseenQuery: true, // Make an effort, it's ok if convs are missed. }) if err != nil { debugDebug(ctx, "cardPopularChannels ReadUnverified error: %v", err) return false } debugDebug(ctx, "cardPopularChannels ReadUnverified found %v convs", len(inbox.ConvsUnverified)) for _, convOther := range inbox.ConvsUnverified { if !convOther.GetConvID().Eq(conv.ConvID) { debugDebug(ctx, "cardPopularChannels ReadUnverified found alternate conv: %v", convOther.GetConvID()) return true } } return false } // Card type: ADD_PEOPLE (3 on design) // Gist: "Do you know people interested in joining?" // Condition: User is an admin. // Condition: User has sent messages OR joined channels. // Condition: A few days on top of POPULAR_CHANNELS have passed since the user joined the channel. In order to space it out from POPULAR_CHANNELS. func (cc *JourneyCardManagerSingleUser) cardAddPeople(ctx context.Context, conv convForJourneycard, jcd journeycardData, debugDebug logFn) bool { if !conv.IsGeneralChannel || !conv.UntrustedTeamRole.IsAdminOrAbove() { return false } if !cc.timeSinceJoined(ctx, conv.TeamID, conv.ConvID, jcd, time.Hour*24*4) { return false } if jcd.Convs[conv.ConvID.String()].SentMessage { return true } // Figure whether the user is in other channels. topicType := chat1.TopicType_CHAT inbox, err := cc.G().InboxSource.ReadUnverified(ctx, cc.uid, types.InboxSourceDataSourceLocalOnly, &chat1.GetInboxQuery{ TlfID: &conv.TlfID, TopicType: &topicType, MemberStatus: []chat1.ConversationMemberStatus{ chat1.ConversationMemberStatus_ACTIVE, chat1.ConversationMemberStatus_REMOVED, chat1.ConversationMemberStatus_LEFT, chat1.ConversationMemberStatus_PREVIEW, }, MembersTypes: []chat1.ConversationMembersType{chat1.ConversationMembersType_TEAM}, SummarizeMaxMsgs: true, SkipBgLoads: true, AllowUnseenQuery: true, // Make an effort, it's ok if convs are missed. }) if err != nil { debugDebug(ctx, "ReadUnverified error: %v", err) return false } debugDebug(ctx, "ReadUnverified found %v convs", len(inbox.ConvsUnverified)) for _, convOther := range inbox.ConvsUnverified { if !convOther.GetConvID().Eq(conv.ConvID) { debugDebug(ctx, "ReadUnverified found alternate conv: %v", convOther.GetConvID()) return true } } return false } // Card type: CREATE_CHANNELS (4 on design) // Gist: "Go ahead and create #channels around topics you think are missing." // Condition: User is at least a writer. // Condition: A few weeks have passed. // Condition: User has sent a message. func (cc *JourneyCardManagerSingleUser) cardCreateChannels(ctx context.Context, conv convForJourneycard, jcd journeycardData) bool { if !conv.UntrustedTeamRole.IsWriterOrAbove() { return false } return jcd.Convs[conv.ConvID.String()].SentMessage && cc.timeSinceJoined(ctx, conv.TeamID, conv.ConvID, jcd, time.Hour*24*14) } // Card type: MSG_NO_ANSWER (C) // Gist: "People haven't been talkative in a while. Perhaps post in another channel? <list of channels>" // Condition: In a channel besides general. // Condition: The last visible message is old, was sent by the logged-in user, and was a long text message, and has not been reacted to. func (cc *JourneyCardManagerSingleUser) cardMsgNoAnswer(ctx context.Context, conv convForJourneycard, jcd journeycardData, thread *chat1.ThreadView, debugDebug logFn) bool { if conv.IsGeneralChannel { return false } // If the latest message is eligible then show the card. var eligibleMsg chat1.MessageID // maximum eligible msg var preventerMsg chat1.MessageID // maximum preventer msg save := func(msgID chat1.MessageID, eligible bool) { if eligible { if msgID > eligibleMsg { eligibleMsg = msgID } } else { if msgID > preventerMsg { preventerMsg = msgID } } } for _, msg := range thread.Messages { state, err := msg.State() if err != nil { continue } switch state { case chat1.MessageUnboxedState_VALID: eligible := func() bool { if !msg.IsValidFull() { return false } if !msg.Valid().ClientHeader.Sender.Eq(cc.uid) { return false } switch msg.GetMessageType() { case chat1.MessageType_TEXT: const howLongIsLong = 40 const howOldIsOld = time.Hour * 24 * 3 isLong := (len(msg.Valid().MessageBody.Text().Body) >= howLongIsLong) isOld := (cc.G().GetClock().Since(msg.Valid().ServerHeader.Ctime.Time()) >= howOldIsOld) hasNoReactions := len(msg.Valid().Reactions.Reactions) == 0 answer := isLong && isOld && hasNoReactions return answer default: return false } } if eligible() { save(msg.GetMessageID(), true) } else { save(msg.GetMessageID(), false) } case chat1.MessageUnboxedState_ERROR: save(msg.Error().MessageID, false) case chat1.MessageUnboxedState_OUTBOX: // If there's something in the outbox, don't show this card. return false case chat1.MessageUnboxedState_PLACEHOLDER: save(msg.Placeholder().MessageID, false) case chat1.MessageUnboxedState_JOURNEYCARD: save(msg.Journeycard().PrevID, false) default: debugDebug(ctx, "unrecognized message state: %v", state) continue } } result := eligibleMsg != 0 && eligibleMsg >= preventerMsg if result { debugDebug(ctx, "cardMsgNoAnswer result:%v eligible:%v preventer:%v n:%v", result, eligibleMsg, preventerMsg, len(thread.Messages)) } return result } // Card type: CHANNEL_INACTIVE (B on design) // Gist: "Zzz... This channel hasn't been very active... Revive it?" // Condition: User can write in the channel. // Condition: The last visible message is old. func (cc *JourneyCardManagerSingleUser) cardChannelInactive(ctx context.Context, conv convForJourneycard, jcd journeycardData, thread *chat1.ThreadView, debugDebug logFn) bool { if conv.CannotWrite { return false } // If the latest message is eligible then show the card. var eligibleMsg chat1.MessageID // maximum eligible msg var preventerMsg chat1.MessageID // maximum preventer msg save := func(msgID chat1.MessageID, eligible bool) { if eligible { if msgID > eligibleMsg { eligibleMsg = msgID } } else { if msgID > preventerMsg { preventerMsg = msgID } } } for _, msg := range thread.Messages { state, err := msg.State() if err != nil { continue } switch state { case chat1.MessageUnboxedState_VALID: eligible := func() bool { if !msg.IsValidFull() { return false } const howOldIsOld = time.Hour * 24 * 8 isOld := (cc.G().GetClock().Since(msg.Valid().ServerHeader.Ctime.Time()) >= howOldIsOld) return isOld } if eligible() { save(msg.GetMessageID(), true) } else { save(msg.GetMessageID(), false) } case chat1.MessageUnboxedState_ERROR: save(msg.Error().MessageID, false) case chat1.MessageUnboxedState_OUTBOX: // If there's something in the outbox, don't show this card. return false case chat1.MessageUnboxedState_PLACEHOLDER: save(msg.Placeholder().MessageID, false) case chat1.MessageUnboxedState_JOURNEYCARD: save(msg.Journeycard().PrevID, false) default: cc.Debug(ctx, "unrecognized message state: %v", state) continue } } result := eligibleMsg != 0 && eligibleMsg >= preventerMsg if result { debugDebug(ctx, "cardChannelInactive result:%v eligible:%v preventer:%v n:%v", result, eligibleMsg, preventerMsg, len(thread.Messages)) } return result } func (cc *JourneyCardManagerSingleUser) timeSinceJoined(ctx context.Context, teamID keybase1.TeamID, convID chat1.ConversationID, jcd journeycardData, duration time.Duration) bool { joinedTime := jcd.Convs[convID.String()].JoinedTime if joinedTime == nil { go cc.saveJoinedTime(globals.BackgroundChatCtx(ctx, cc.G()), teamID, convID, cc.G().GetClock().Now()) return false } return cc.G().GetClock().Since(joinedTime.Time()) >= duration } func (cc *JourneyCardManagerSingleUser) messageSince(ctx context.Context, msgID chat1.MessageID, conv convForJourneycard, thread *chat1.ThreadView, debugDebug logFn) bool { for _, msg := range thread.Messages { state, err := msg.State() if err != nil { continue } switch state { case chat1.MessageUnboxedState_VALID, chat1.MessageUnboxedState_ERROR, chat1.MessageUnboxedState_PLACEHOLDER: if msg.GetMessageID() > msgID { return true } case chat1.MessageUnboxedState_OUTBOX: return true case chat1.MessageUnboxedState_JOURNEYCARD: default: debugDebug(ctx, "unrecognized message state: %v", state) continue } } return false } // The user has sent a message. func (cc *JourneyCardManagerSingleUser) SentMessage(ctx context.Context, teamID keybase1.TeamID, convID chat1.ConversationID) { err := libkb.AcquireWithContextAndTimeout(ctx, &cc.storageLock, 10*time.Second) if err != nil { cc.Debug(ctx, "SentMessage storageLock error: %v", err) return } defer cc.storageLock.Unlock() if teamID.IsNil() || convID.IsNil() { return } jcd, err := cc.getTeamDataWithLock(ctx, teamID) if err != nil { cc.Debug(ctx, "storage get error: %v", err) return } if jcd.Convs[convID.String()].SentMessage { return } jcd = jcd.MutateConv(convID, func(conv journeycardConvData) journeycardConvData { conv.SentMessage = true return conv }) cc.lru.Add(teamID.String(), jcd) err = cc.encryptedDB.Put(ctx, cc.dbKey(teamID), jcd) if err != nil { cc.Debug(ctx, "storage put error: %v", err) } cc.saveJoinedTimeWithLock(globals.BackgroundChatCtx(ctx, cc.G()), teamID, convID, cc.G().GetClock().Now()) } func (cc *JourneyCardManagerSingleUser) Dismiss(ctx context.Context, teamID keybase1.TeamID, convID chat1.ConversationID, cardType chat1.JourneycardType) { err := libkb.AcquireWithContextAndTimeout(ctx, &cc.storageLock, 10*time.Second) if err != nil { cc.Debug(ctx, "Dismiss storageLock error: %v", err) return } defer cc.storageLock.Unlock() if convID.IsNil() { return } jcd, err := cc.getTeamDataWithLock(ctx, teamID) if err != nil { cc.Debug(ctx, "storage get error: %v", err) return } if jcd.Convs[convID.String()].Dismissals[cardType] { return } jcd = jcd.MutateConv(convID, func(conv journeycardConvData) journeycardConvData { conv = conv.PrepareToMutateDismissals() // clone Dismissals to avoid modifying shared conv. conv.Dismissals[cardType] = true return conv }) cc.lru.Add(teamID.String(), jcd) err = cc.encryptedDB.Put(ctx, cc.dbKey(teamID), jcd) if err != nil { cc.Debug(ctx, "storage put error: %v", err) } } func (cc *JourneyCardManagerSingleUser) dbKey(teamID keybase1.TeamID) libkb.DbKey { return libkb.DbKey{ Typ: libkb.DBChatJourney, // Key: fmt.Sprintf("jc|uid:%s|convID:%s", cc.uid, convID), // used with DiskVersion 1 Key: fmt.Sprintf("jc|uid:%s|teamID:%s", cc.uid, teamID), } } // Get info about a team and its conversations. // Note the return value may share internal structure with other threads. Do not deeply modify. func (cc *JourneyCardManagerSingleUser) getTeamData(ctx context.Context, teamID keybase1.TeamID) (res journeycardData, err error) { err = libkb.AcquireWithContextAndTimeout(ctx, &cc.storageLock, 10*time.Second) if err != nil { return res, fmt.Errorf("getTeamData storageLock error: %v", err) } defer cc.storageLock.Unlock() return cc.getTeamDataWithLock(ctx, teamID) } func (cc *JourneyCardManagerSingleUser) getTeamDataWithLock(ctx context.Context, teamID keybase1.TeamID) (res journeycardData, err error) { if teamID.IsNil() { return res, fmt.Errorf("missing teamID") } untyped, ok := cc.lru.Get(teamID.String()) if ok { res, ok = untyped.(journeycardData) if !ok { return res, fmt.Errorf("JourneyCardManager.getConvData got unexpected type: %T", untyped) } return res, nil } // Fetch from persistent storage. found, err := cc.encryptedDB.Get(ctx, cc.dbKey(teamID), &res) if err != nil { // This could be something like a "msgpack decode error" due to a severe change to the storage schema. // If care is taken when changing storage schema, this shouldn't happen. But just in case, // better to start over than to remain stuck. cc.Debug(ctx, "db error: %v", err) found = false } if found { switch res.DiskVersion { case 1: // Version 1 is obsolete. Ignore it. res = newJourneycardData() case journeycardDiskVersion: // good default: cc.Debug(ctx, "converting jcd version %v -> %v", res.DiskVersion, journeycardDiskVersion) // Accept any subset of the data that was deserialized. } } else { res = newJourneycardData() } cc.lru.Add(teamID.String(), res) return res, nil } func (cc *JourneyCardManagerSingleUser) savePosition(ctx context.Context, teamID keybase1.TeamID, convID chat1.ConversationID, cardType chat1.JourneycardType, pos journeyCardPosition) { err := libkb.AcquireWithContextAndTimeout(ctx, &cc.storageLock, 10*time.Second) if err != nil { cc.Debug(ctx, "savePosition storageLock error: %v", err) return } defer cc.storageLock.Unlock() if teamID.IsNil() || convID.IsNil() { return } jcd, err := cc.getTeamDataWithLock(ctx, teamID) if err != nil { cc.Debug(ctx, "storage get error: %v", err) return } if conv, ok := jcd.Convs[convID.String()]; ok { if existing, ok := conv.Positions[cardType]; ok && existing != nil && *existing == pos { if !journeycardTypeOncePerTeam[cardType] || jcd.Lockin[cardType].Eq(convID) { // no change return } } } jcd = jcd.MutateConv(convID, func(conv journeycardConvData) journeycardConvData { conv = conv.PrepareToMutatePositions() // clone Positions to avoid modifying shared conv. conv.Positions[cardType] = &pos return conv }) if journeycardTypeOncePerTeam[cardType] { jcd = jcd.SetLockin(cardType, convID) } cc.lru.Add(teamID.String(), jcd) err = cc.encryptedDB.Put(ctx, cc.dbKey(teamID), jcd) if err != nil { cc.Debug(ctx, "storage put error: %v", err) } } // Save the time the user joined. Discards value if one is already saved. func (cc *JourneyCardManagerSingleUser) saveJoinedTime(ctx context.Context, teamID keybase1.TeamID, convID chat1.ConversationID, t time.Time) { err := libkb.AcquireWithContextAndTimeout(ctx, &cc.storageLock, 10*time.Second) if err != nil { cc.Debug(ctx, "saveJoinedTime storageLock error: %v", err) return } defer cc.storageLock.Unlock() cc.saveJoinedTimeWithLock(ctx, teamID, convID, t) } func (cc *JourneyCardManagerSingleUser) saveJoinedTimeWithLock(ctx context.Context, teamID keybase1.TeamID, convID chat1.ConversationID, t time.Time) { cc.saveJoinedTimeWithLockInner(ctx, teamID, convID, t, false) } func (cc *JourneyCardManagerSingleUser) saveJoinedTimeWithLockInner(ctx context.Context, teamID keybase1.TeamID, convID chat1.ConversationID, t time.Time, acceptUpdate bool) { if teamID.IsNil() || convID.IsNil() { return } jcd, err := cc.getTeamDataWithLock(ctx, teamID) if err != nil { cc.Debug(ctx, "storage get error: %v", err) return } if jcd.Convs[convID.String()].JoinedTime != nil && !acceptUpdate { return } t2 := gregor1.ToTime(t) jcd = jcd.MutateConv(convID, func(conv journeycardConvData) journeycardConvData { conv.JoinedTime = &t2 return conv }) cc.lru.Add(teamID.String(), jcd) err = cc.encryptedDB.Put(ctx, cc.dbKey(teamID), jcd) if err != nil { cc.Debug(ctx, "storage put error: %v", err) } } func (cc *JourneyCardManagerSingleUser) isOpenTeam(ctx context.Context, conv convForJourneycard) (open bool, err error) { teamID, err := keybase1.TeamIDFromString(conv.TlfID.String()) if err != nil { return false, err } return cc.G().GetTeamLoader().IsOpenCached(ctx, teamID) } // TimeTravel simulates moving all known conversations forward in time. // For use simulating a user experience without the need to wait hours for cards to appear. func (cc *JourneyCardManagerSingleUser) TimeTravel(ctx context.Context, duration time.Duration) (err error) { err = libkb.AcquireWithContextAndTimeout(ctx, &cc.storageLock, 10*time.Second) if err != nil { return err } defer cc.storageLock.Unlock() teamIDs, err := cc.getKnownTeamsForDebuggingWithLock(ctx) if err != nil { return err } for _, teamID := range teamIDs { jcd, err := cc.getTeamDataWithLock(ctx, teamID) if err != nil { return fmt.Errorf("teamID:%v err:%v", teamID, err) } for convIDStr, conv := range jcd.Convs { if conv.JoinedTime != nil { convID, err := chat1.MakeConvID(convIDStr) if err != nil { return fmt.Errorf("teamID:%v convID:%v err:%v", teamID, convIDStr, err) } cc.Debug(ctx, "time travel teamID:%v convID:%v", teamID, convID) cc.saveJoinedTimeWithLockInner(ctx, teamID, convID, jcd.Convs[convID.String()].JoinedTime.Time().Add(-duration), true) } } } return nil } // ResetAllConvs deletes storage for all conversations. // For use simulating a fresh user experience without the need to switch accounts. func (cc *JourneyCardManagerSingleUser) ResetAllConvs(ctx context.Context) (err error) { err = libkb.AcquireWithContextAndTimeout(ctx, &cc.storageLock, 10*time.Second) if err != nil { return err } defer cc.storageLock.Unlock() teamIDs, err := cc.getKnownTeamsForDebuggingWithLock(ctx) if err != nil { return err } cc.lru.Purge() for _, teamID := range teamIDs { err = cc.encryptedDB.Delete(ctx, cc.dbKey(teamID)) if err != nil { return fmt.Errorf("teamID:%v err:%v", teamID, err) } } return nil } func (cc *JourneyCardManagerSingleUser) DebugState(ctx context.Context, teamID keybase1.TeamID) (summary string, err error) { jcd, err := cc.getTeamData(ctx, teamID) if err != nil { return "", err } convs := jcd.Convs jcd.Convs = nil // Blank out convs for the first spew. They will be shown separately. summary = spew.Sdump(jcd) for convIDStr, conv := range convs { summary += fmt.Sprintf("\n%v:\n%v", convIDStr, spew.Sdump(conv)) if conv.JoinedTime != nil { since := cc.G().GetClock().Since(conv.JoinedTime.Time()) summary += fmt.Sprintf("Since joined: %v (%.1f days)", since, float64(since)/float64(time.Hour*24)) } } return summary, nil } func (cc *JourneyCardManagerSingleUser) getKnownTeamsForDebuggingWithLock(ctx context.Context) (teams []keybase1.TeamID, err error) { levelDbTableKv := "kv" innerKeyPrefix := fmt.Sprintf("jc|uid:%s|teamID:", cc.uid) prefix := libkb.DbKey{ Typ: libkb.DBChatJourney, Key: innerKeyPrefix, }.ToBytes(levelDbTableKv) leveldb, ok := cc.G().LocalChatDb.GetEngine().(*libkb.LevelDb) if !ok { return nil, fmt.Errorf("could not get leveldb") } dbKeys, err := leveldb.KeysWithPrefixes(prefix) if err != nil { return nil, err } for dbKey := range dbKeys { if dbKey.Typ == libkb.DBChatJourney && strings.HasPrefix(dbKey.Key, innerKeyPrefix) { teamID, err := keybase1.TeamIDFromString(dbKey.Key[len(innerKeyPrefix):]) if err != nil { return nil, err } teams = append(teams, teamID) } } return teams, nil } type journeyCardPosition struct { PrevID chat1.MessageID `codec:"p,omitempty" json:"p,omitempty"` } const journeycardDiskVersion int = 2 // Storage for a single team's journey cards. // Bump journeycardDiskVersion when making incompatible changes. type journeycardData struct { DiskVersion int `codec:"v,omitempty" json:"v,omitempty"` Convs map[string] /*keyed by chat1.ConversationID.String()*/ journeycardConvData `codec:"cv,omitempty" json:"cv,omitempty"` // Some card types can only appear once. This map locks a type into a particular conv. Lockin map[chat1.JourneycardType]chat1.ConversationID `codec:"l,omitempty" json:"l,omitempty"` // When this data was first saved. For debugging unexpected data loss. Ctime gregor1.Time `codec:"c,omitempty" json:"c,omitempty"` } type journeycardConvData struct { Positions map[chat1.JourneycardType]*journeyCardPosition `codec:"p,omitempty" json:"p,omitempty"` Dismissals map[chat1.JourneycardType]bool `codec:"d,omitempty" json:"d,omitempty"` // Whether the user has sent a message in this channel. SentMessage bool `codec:"sm,omitempty" json:"sm,omitempty"` // When the user joined the channel (that's the idea, really it's some time when they saw the conv) JoinedTime *gregor1.Time `codec:"jt,omitempty" json:"jt,omitempty"` } func newJourneycardData() journeycardData { return journeycardData{ DiskVersion: journeycardDiskVersion, Convs: make(map[string]journeycardConvData), Lockin: make(map[chat1.JourneycardType]chat1.ConversationID), Ctime: gregor1.ToTime(time.Now()), } } func newJourneycardConvData() journeycardConvData { return journeycardConvData{ Positions: make(map[chat1.JourneycardType]*journeyCardPosition), Dismissals: make(map[chat1.JourneycardType]bool), } } // Return a new instance where the conv entry has been mutated. // Without modifying the receiver itself. // The caller should take that `apply` does not deeply mutate its argument. // If the conversation did not exist, a new entry is created. func (j *journeycardData) MutateConv(convID chat1.ConversationID, apply func(journeycardConvData) journeycardConvData) journeycardData { selectedConvIDStr := convID.String() updatedConvs := make(map[string]journeycardConvData) for convIDStr, conv := range j.Convs { if convIDStr == selectedConvIDStr { updatedConvs[convIDStr] = apply(conv) } else { updatedConvs[convIDStr] = conv } } if _, found := updatedConvs[selectedConvIDStr]; !found { updatedConvs[selectedConvIDStr] = apply(newJourneycardConvData()) } res := *j // Copy so that Convs can be assigned without aliasing. res.Convs = updatedConvs return res } // Return a new instance where Lockin has been modified. // Without modifying the receiver itself. func (j *journeycardData) SetLockin(cardType chat1.JourneycardType, convID chat1.ConversationID) (res journeycardData) { res = *j res.Lockin = make(map[chat1.JourneycardType]chat1.ConversationID) for k, v := range j.Lockin { res.Lockin[k] = v } res.Lockin[cardType] = convID return res } // Whether this card type has one of: // - already been shown (conv) // - been dismissed (conv) // - lockin to a different conv (team wide) func (j *journeycardData) hasShownOrDismissedOrLockout(convID chat1.ConversationID, cardType chat1.JourneycardType) bool { if lockinConvID, found := j.Lockin[cardType]; found { if !lockinConvID.Eq(convID) { return false } } if c, found := j.Convs[convID.String()]; found { return c.Positions[cardType] != nil || c.Dismissals[cardType] } return false } // Whether this card type has been dismissed. func (j *journeycardData) hasDismissed(convID chat1.ConversationID, cardType chat1.JourneycardType) bool { return j.Convs[convID.String()].Dismissals[cardType] } func (j *journeycardConvData) PrepareToMutatePositions() (res journeycardConvData) { res = *j res.Positions = make(map[chat1.JourneycardType]*journeyCardPosition) for k, v := range j.Positions { res.Positions[k] = v } return res } func (j *journeycardConvData) PrepareToMutateDismissals() (res journeycardConvData) { res = *j res.Dismissals = make(map[chat1.JourneycardType]bool) for k, v := range j.Dismissals { res.Dismissals[k] = v } return res } type convForJourneycardInner interface { GetMembersType() chat1.ConversationMembersType GetTopicType() chat1.TopicType GetTopicName() string GetTeamType() chat1.TeamType MaxVisibleMsgID() chat1.MessageID } type convForJourneycard struct { convForJourneycardInner ConvID chat1.ConversationID IsGeneralChannel bool UntrustedTeamRole keybase1.TeamRole TlfID chat1.TLFID TeamID keybase1.TeamID WelcomeEligible bool CannotWrite bool } var journeycardTypeOncePerTeam = map[chat1.JourneycardType]bool{ chat1.JourneycardType_WELCOME: true, chat1.JourneycardType_POPULAR_CHANNELS: true, chat1.JourneycardType_ADD_PEOPLE: true, chat1.JourneycardType_CREATE_CHANNELS: true, } var journeycardShouldNotRunOnReason = map[chat1.GetThreadReason]bool{ chat1.GetThreadReason_BACKGROUNDCONVLOAD: true, chat1.GetThreadReason_FIXRETRY: true, chat1.GetThreadReason_PREPARE: true, chat1.GetThreadReason_SEARCHER: true, chat1.GetThreadReason_INDEXED_SEARCH: true, chat1.GetThreadReason_KBFSFILEACTIVITY: true, chat1.GetThreadReason_COINFLIP: true, chat1.GetThreadReason_BOTCOMMANDS: true, }
# Complete the ImageFolderPublisher class with additional functionalities class ImageFolderPublisher: def __init__(self): # Initialize the application name self.__app_name = "image_folder_publisher" # Create CvBridge instances for left and right images self._cv_bridge_left = CvBridge() self._cv_bridge_right = CvBridge() # Set the topic names for left and right images using parameters self._topic_name_left = rospy.get_param('~topic_name_left', '/image_raw_left') self._topic_name_right = rospy.get_param('~topic_name_right', '/image_raw_right') def publish_images_from_folder(self, left_image_path, right_image_path): # Implement functionality to publish left and right images from the specified folder # Use self._cv_bridge_left and self._cv_bridge_right to convert and publish images # Use self._topic_name_left and self._topic_name_right to publish images to the respective topics pass def stop_publishing(self): # Implement functionality to stop publishing images and perform necessary cleanup pass # Add any other required functionalities based on the specific use case # ...
#!/bin/bash set -e set -o verbose set -o xtrace export SHELLOPTS echo "SHELLOPTS=${SHELLOPTS}" SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" # shellcheck disable=SC1090 # In newer shellcheck than 0.6.0, pass: "-P SCRIPTDIR" (literally) source "$SCRIPTDIR"/build.sh "$SCRIPTDIR/.plume-scripts/git-clone-related" eisop guava cd ../guava ./typecheck.sh lock
def is_order_valid(order): #Validate the length of ID if len(str(order['ID'])) != 4: return False #Validate the items in the order for item in order['Items']: if item not in item_list: # item_list is pre-defined list of items return False #Validate the total amount if order['Total'] != sum(item_prices[item] for item in order['Items']): # item_prices is pre-defined dictionary of item-price return False return True
<filename>test/actors/UserActorTest.java //package actors; // //import Actors.UserActor; //import akka.actor.ActorRef; //import akka.actor.ActorSystem; //import akka.actor.Props; //import akka.testkit.javadsl.TestKit; //import controllers.Assets; //import org.junit.Assert; //import org.junit.Before; //import org.junit.Test; // //public class UserActorTest { //// //// static ActorSystem system; //// //// @Before //// public void setUp(){ //// system = ActorSystem.create(); //// } //// //// @Test //// public void test(){ //// final TestKit testKit = new TestKit(system); //// ActorRef user = system.actorOf(UserActor.props()); //// user.tell(new UserActor.RegisterSuperMsg(), testKit.getRef()); //// //// UserActor userActor = testKit.expectMsgClass(UserActor.class); //// Assert.assertNotNull(userActor); //// } //}
function generateRandom(min, max) { return Math.floor(Math.random() * (max - min) + min); } let randomNumber = generateRandom(1, 10); console.log(randomNumber);
void LaShellAssignLabels::KeyPressEventHandler(vtkObject* obj, unsigned long eventId, void* clientdata, void* vtkNotUsed(calldata)){ /* Remember you are marking your pick position with sphere. First step is to pick and then to place a sphere in the cell you have picked_pointidarray The code below picks a cell, and you mark one of the cell's vertex with a sphere */ double screenX, screenY; // where in the screen you wil be clicking vtkIdType cellID, pointID=-1; // to store cellID of the picked cell LaShellAssignLabels* this_class_obj = reinterpret_cast<LaShellAssignLabels*>(clientdata); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkRenderWindowInteractor::SafeDownCast(obj); vtkSmartPointer<vtkRenderWindow> renderWin = iren->GetRenderWindow(); vtkSmartPointer<vtkRendererCollection> rendererCollection = renderWin->GetRenderers(); vtkSmartPointer<vtkRenderer> renderer = rendererCollection->GetFirstRenderer(); vtkSmartPointer<vtkPolyData> poly_data = vtkSmartPointer<vtkPolyData>::New(); poly_data = this_class_obj->GetSourcePolyData(); char keypressed = iren->GetKeyCode(); bool isLV = keypressed =='l' || keypressed=='L'; bool isRV = keypressed =='r' || keypressed=='R'; bool isBa = keypressed =='b' || keypressed=='B'; bool isAp = keypressed =='a' || keypressed=='A'; bool isEpi = keypressed=='L' || keypressed=='R'; int sectionCode; if(isLV) sectionCode = 2; else if(isRV) sectionCode = 3; else if(isAp) sectionCode = 5; else if(isBa) sectionCode = 7; sectionCode += isEpi ? 10 : 0; // x is for picking any points - saves: pointID, label if (iren->GetKeyCode()=='x'){ double *pick_position = new double[3]; // get the x and y co-ordinates on the screen where you have hit 'x' screenX = iren->GetEventPosition()[0]; screenY = iren->GetEventPosition()[1]; vtkSmartPointer<vtkCellPicker> cell_picker = this_class_obj->_cell_picker; cell_picker->Pick(screenX, screenY, 0.0, renderer); cellID = cell_picker->GetCellId(); cell_picker->GetPickPosition(pick_position); pointID = LaShellAssignLabels::GetFirstCellVertex(poly_data, cellID, pick_position); double picked_scalar = poly_data->GetPointData()->GetScalars()->GetTuple1(pointID); cout << "Point id picked = " << pointID << " with value:" << picked_scalar << " and co-ordinates of its position = " << pick_position[0] << ", " << pick_position[1] << "," << pick_position[2] << ")\n"; LaShellAssignLabels::CreateSphere(renderer, 3.5, pick_position); iren->Render(); delete[] pick_position; } else if (isLV || isRV || isAp || isBa){ char key = iren->GetKeyCode(); double *pick_position = new double[3]; // get the x and y co-ordinates on the screen where you have hit 'x' screenX = iren->GetEventPosition()[0]; screenY = iren->GetEventPosition()[1]; vtkSmartPointer<vtkCellPicker> cell_picker = this_class_obj->_cell_picker; cell_picker->Pick(screenX, screenY, 0.0, renderer); cellID = cell_picker->GetCellId(); cell_picker->GetPickPosition(pick_position); pointID = LaShellAssignLabels::GetFirstCellVertex(poly_data, cellID, pick_position); double picked_scalar = poly_data->GetPointData()->GetScalars()->GetTuple1(pointID); this_class_obj->_pointidarray.push_back(pointID); this_class_obj->_assignedlabels.push_back(picked_scalar); this_class_obj->_labelsAssigned.at(picked_scalar-0) = 1; this_class_obj->_codearray.push_back(sectionCode); cout << "Key pressed = [" << key << "] with label: " << picked_scalar << " and code:" << sectionCode << "\n"; LaShellAssignLabels::CreateSphere(renderer, 3.5, pick_position); iren->Render(); delete[] pick_position; } else if (iren->GetKeyCode()=='s'){ ofstream out_ID, out_CSV; stringstream ss_ID, ss_CSV; int lim = this_class_obj->_pointidarray.size(); ss_ID << "pointsIDlist.txt"; ss_CSV << "labelsNcodeslist.txt"; out_ID.open(ss_ID.str().c_str(), std::ios_base::trunc); out_CSV.open(ss_CSV.str().c_str(), std::ios_base::trunc); for(int ix=0;ix<lim;ix++){ out_ID << this_class_obj->_pointidarray[ix] << endl; out_CSV << this_class_obj->_assignedlabels[ix] << "," << this_class_obj->_codearray[ix] << endl; } out_ID.close(); out_CSV.close(); cout << "File: pointIDList.txt created. You can exit the application." << endl; } else if(iren->GetKeyCode()=='m'){ //look for missing labels int N = this_class_obj->_labelsinmesh.size(); for(int ix=0; ix<N; ix++){ cout << this_class_obj->_labelsinmesh[ix] << " " << this_class_obj->_labelsAssigned[ix]; } } //delete [] pick_position; }
package io.opensphere.core.order.impl.config.v1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; /** Configuration for an order category. */ @XmlRootElement(name = "OrderCategory") @XmlAccessorType(XmlAccessType.NONE) public class OrderCategoryConfig { /** The id of this category. */ @XmlAttribute(name = "categoryId") private String myCategoryId; /** The maximum of the allowable order range for this category. */ @XmlAttribute(name = "rangeMax") private int myRangeMax; /** The minimum of the allowable order range for this category. */ @XmlAttribute(name = "rangeMin") private int myRangeMin; /** * Constructor. * * @param categoryId The id of this category. * @param rangeMax The maximum of the allowable order range for this * category. * @param rangeMin The minimum of the allowable order range for this * category. */ public OrderCategoryConfig(String categoryId, int rangeMax, int rangeMin) { myCategoryId = categoryId; myRangeMax = rangeMax; myRangeMin = rangeMin; } /** Default constructor. */ protected OrderCategoryConfig() { } /** * Get the category id. * * @return The category id. */ public String getCategoryId() { return myCategoryId; } /** * Get the maximum of the allowable order range for this category. * * @return The maximum. */ public int getRangeMax() { return myRangeMax; } /** * Get the minimum of the allowable order range for this category. * * @return The minimum. */ public int getRangeMin() { return myRangeMin; } }
# compile and pack the new chaincode GO111MODULE=on go mod vendor cd ../../test-network export PATH=${PWD}/../bin:$PATH export FABRIC_CFG_PATH=$PWD/../config/ peer version peer lifecycle chaincode package basicuser.tar.gz --path ../user-basic/chaincode-go/ --lang golang --label basicuser_1.0
/* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable @typescript-eslint/prefer-namespace-keyword */ /* spellchecker: disable */ import { vec4 as vec4_glm, ReadonlyVec4, ReadonlyVec3 } from 'gl-matrix'; export declare type vec4 = vec4_glm; import { logArrayAsMatrix, matrixStringFromArray } from './matrixstring'; /* spellchecker: enable */ /** * A vec4 placeholder to overcome the gl-matrix out interface. */ export function v4(): vec4_glm { return vec4_glm.create(); } module vec4_ext { /** * Creates a new four-component vector with random values. * ``` * let a: vec4 = vec4.random(-1.0, +1.0); * ``` * @param min - Lower bound for the random value range. * @param max - Upper bound for the random value range. * @returns - Vector with value randomized in [min, max]. */ export function random(min: number = 0.0, max: number = 1.0): vec4 { return Float32Array.from({ length: 4 }, () => ( Math.random() * (max - min) + min)) as vec4; } /** * Constrain a four-component vector to lie between two further four-component vectors. * ``` * let a: vec4 = vec4.fromValues(2, 2, 2, 2); * vec4.clamp(a, a, [0, 0, 0, 0], [1, 1, 1, 1]); * ``` * @param out - The receiving vector. * @param x - The vector to clamp. * @param min - Minimum vector operand. * @param max - Maximum vector operand. * @returns - Vector constrained to [min,max]. */ export function clamp(out: vec4, x: ReadonlyVec4 | number[], min: ReadonlyVec4 | number[], max: ReadonlyVec4 | number[]): vec4 { out[0] = Math.max(min[0], Math.min(max[0], x[0])); out[1] = Math.max(min[1], Math.min(max[1], x[1])); out[2] = Math.max(min[2], Math.min(max[2], x[2])); out[3] = Math.max(min[3], Math.min(max[3], x[3])); return out; } /** * Derive the absolute values of each of the four vector components. * ``` * let a: vec4 = vec4.fromValues(-2, 2, -1, 1); * vec4.abs(a, a); // should result in [2,2,1,1] * ``` * @param out - The receiving vector. * @param x - The vector to apply abs to. * @returns - Vector with each component as absolute value. */ export function abs(out: vec4, x: ReadonlyVec4): vec4 { out[0] = Math.abs(x[0]); out[1] = Math.abs(x[1]); out[2] = Math.abs(x[2]); out[3] = Math.abs(x[3]); return out; } /** * Parses a vec4 from a string. * @param v4str - String in the format '<number>, <number>, <number>, <number>', e.g., '1.0, 0.0, 0.0, 0.0'. * @returns - Vec4 if string was parsed successfully, undefined else. */ export function parse(v4str: string | undefined): vec4 | undefined { if (v4str === undefined || v4str === '') { return undefined; } let numbers = []; try { numbers = JSON.parse(`[${v4str}]`); } catch (error) { return undefined; } return numbers.length !== 4 || isNaN(numbers[0]) || isNaN(numbers[1]) || isNaN(numbers[2]) || isNaN(numbers[3]) ? undefined : vec4_glm.clone(numbers); } export function log(a: ReadonlyVec4, digits: number = 4): void { logArrayAsMatrix(a as Float32Array, 1, digits); } export function toMatrixString(a: ReadonlyVec4, digits: number = 4): string { return matrixStringFromArray(a as Float32Array, 1, digits); } /** * Constructs a vec4 from a vec3 by appending 1.0 as the w component. * ``` * const v3: vec3 = vec3.fromValues(2, 4, 6); * const v4: vec4 = fromVec3(v3); // v3 is [2, 4, 6, 1] * ``` * @param x - The vector to be transformed to a vec4. * @returns - Four component vector based on x. */ export function fromVec3(x: ReadonlyVec3): vec4 { return vec4_glm.fromValues(x[0], x[1], x[2], 1.0); } /** * Packs a 32bit unsigned int into a four component byte vector. * ``` * let uint8x4: vec4 = vec4.create(); * vec4.encode_uint24_in_rgb8(uint8x4, 250285); // should result in [ 173, 209, 3, 0 ] * ``` * @param out - byte (uint8) vector with packed uint32 data * @param x - uint32 number * @returns - Three component byte vector with x packed. */ export function encode_uint32_to_rgba8(out: vec4, x: number): vec4 { out[0] = (x >>> 0) & 0xFF; out[1] = (x >>> 8) & 0xFF; out[2] = (x >>> 16) & 0xFF; out[3] = (x >>> 24) & 0xFF; return out; } /** * Unpacks a 32bit unsigned int from a four component byte vector. * ``` * let uint8x4: vec4 = vec4.fromValues(173, 209, 3, 23); * vec4.decode_uint24_from_rgba8(uint8x4); // should return xxx * ``` * @param x - byte (uint8) vector with packed uint32 data * @returns - Unpacked 32bit unsigned int. */ export function decode_uint32_from_rgba8(x: ReadonlyVec4): number { return x[0] + (x[1] << 8) + (x[2] << 16) + (x[3] << 24) >>> 0; } } export const vec4 = { ...vec4_glm, ...vec4_ext }
package com.wxh.sdk.view; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.widget.TextView; import com.wxh.sdk.R; public class LoadingDialog extends Dialog { private TextView tips_loading_msg; private CharSequence message = "加载中"; public LoadingDialog(Context context) { super(context,R.style.FullDialog); } public LoadingDialog(Context context, String message) { super(context); this.message = message; } public LoadingDialog(Context context, int theme, String message) { super(context, theme); this.message = message; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.v_loadingdialog); tips_loading_msg = (TextView) findViewById(R.id.tips_loading_msg); tips_loading_msg.setText(this.message); } public void setMessage(CharSequence message) { this.message = message; } public void setMessage(int resId) { setMessage(getContext().getResources().getString(resId)); } }
#!/usr/bin/env bash # # solana-cli integration sanity test # set -e cd "$(dirname "$0")"/.. # shellcheck source=multinode-demo/common.sh source multinode-demo/common.sh if [[ -z $1 ]]; then # no network argument, use localhost by default args=(--url http://127.0.0.1:8899) else args=("$@") fi keypair="target/wallet-sanity-keypair.json" $solana_keygen new --no-passphrase -sf -o $keypair args+=(--keypair "$keypair") node_readiness=false timeout=60 while [[ $timeout -gt 0 ]]; do output=$($solana_cli "${args[@]}" transaction-count) if [[ -n $output ]]; then node_readiness=true break fi sleep 2 (( timeout=timeout-2 )) done if ! "$node_readiness"; then echo "Timed out waiting for cluster to start" exit 1 fi ( set -x $solana_cli "${args[@]}" address $solana_cli "${args[@]}" airdrop 0.01 $solana_cli "${args[@]}" balance --lamports $solana_cli "${args[@]}" ping --count 5 --interval 0 $solana_cli "${args[@]}" balance --lamports ) rm $keypair echo PASS exit 0
<filename>imagenet-classification/utils.py # Copyright (c) 2019 Sony Corporation. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import nnabla as nn import nnabla.communicators as C import nnabla.monitor as M import nnabla.solvers as S import numpy as np from tqdm import trange def create_float_context(ctx): from nnabla.ext_utils import get_extension_context ctx_float = get_extension_context(ctx.backend[0].split(':')[ 0], device_id=ctx.device_id) return ctx_float def ceil_to_multiple(x, mul): ''' Get a minimum integer >= x of a multiple of ``mul``. ''' return (x + mul - 1) // mul class CommunicatorWrapper(object): def __init__(self, ctx): try: comm = C.MultiProcessDataParallelCommunicator(ctx) except Exception as e: print(e) print('No communicator found. Running with a single process. If you run this with MPI processes, all processes will perform totally same.') self.n_procs = 1 self.rank = 0 self.ctx = ctx self.ctx_float = create_float_context(ctx) self.comm = None return comm.init() self.n_procs = comm.size self.rank = comm.rank self.ctx = ctx self.ctx.device_id = str(self.rank) self.ctx_float = create_float_context(self.ctx) self.comm = comm def all_reduce(self, params, division, inplace): if self.n_procs == 1: # skip all reduce since no processes have to be all-reduced return self.comm.all_reduce(params, division=division, inplace=inplace) class LearningRateScheduler(object): '''Learning rate decay scheduler. ''' def __init__(self, base_lr, decay_at=[30, 60, 80], decay_rate=0.1, warmup_epochs=5): self.base_learning_rate = base_lr self.decay_at = np.asarray(decay_at, dtype=np.int) self.decay_rate = decay_rate self.warmup_epochs = warmup_epochs def __call__(self, epoch): lr = self.base_learning_rate if epoch < self.warmup_epochs: lr = lr * (epoch + 1) / (self.warmup_epochs + 1) return lr p = np.sum(self.decay_at <= epoch) return lr * (self.decay_rate ** p) class MomentumNoWeightDecayBn(object): '''Momentum solver with disabling weight decay for BN scales and biases (beta and gamma). ''' def __init__(self, learning_rate, momentum=0.9): self.solver = S.Momentum(learning_rate, momentum) self.solver_bn = S.Momentum(learning_rate, momentum) def set_parameters(self, params): params_bn = {k: v for k, v in params.items() if k.endswith( '/gamma') or k.endswith('/beta')} params = {k: v for k, v in params.items() if not ( k.endswith('/gamma') or k.endswith('/beta'))} self.solver_bn.set_parameters(params_bn) self.solver.set_parameters(params) def weight_decay(self, wd): # Weight decay is not performed for BN scales and biases self.solver.weight_decay(wd) def update(self): self.solver.update() self.solver_bn.update() def zero_grad(self): self.solver.zero_grad() self.solver_bn.zero_grad() def learning_rate(self): return self.solver.learning_rate() def set_learning_rate(self, lr): self.solver.set_learning_rate(lr) self.solver_bn.set_learning_rate(lr) class EpochReporter(object): def __init__(self, name, monitor, comm, loss, error, batch_size, time=True, flush_interval=10): self.name = name self.comm = comm self.epoch_loss = 0.0 self.epoch_error = 0 self.batch_counter = 0 self.loss = loss self.error = error self.batch_size = batch_size if self.comm.rank == 0: self.monitor_loss = M.MonitorSeries( "%s loss" % name, monitor, interval=1) self.monitor_err = M.MonitorSeries( "%s error" % name, monitor, interval=1) self.monitor_time = None if time: self.monitor_time = M.MonitorTimeElapsed( "Epoch time", monitor, interval=1) self.flush_interval = flush_interval def reset_buff(self): for b in self.buff: b.zero() def reset(self, epoch, pbar): self.epoch = epoch self.epoch_loss = 0.0 self.epoch_error = 0 self.batch_counter = 0 self.pbar = pbar self.buff = [nn.NdArray(), nn.NdArray()] self.reset_buff() self.flush = True def flush_buff(self): error_per_iter = int(np.round(self.buff[0].get_data('r'))) loss_per_iter = float(self.buff[1].get_data('r')) self.reset_buff() self.epoch_error += error_per_iter self.epoch_loss += loss_per_iter def update(self): with nn.context_scope(self.comm.ctx_float): self.buff[0] += self.error.data self.buff[1] += self.loss.data self.batch_counter += 1 self.flush = False def __call__(self, lr=0, force=False): if not force and ( self.batch_counter == 0 or self.batch_counter % self.flush_interval != 0): return self.flush_buff() self.pbar.set_description( '{} epoch {} (lr={:.2e}): loss={:.4} error={:.4}'.format( self.name, self.epoch, lr, self.epoch_loss / self.batch_counter, self.epoch_error / (self.batch_counter * self.batch_size))) def on_epoch_end(self): if not self.flush: self.flush_buff() epoch_loss = nn.NdArray.from_numpy_array( np.asarray(self.epoch_loss / self.batch_counter, dtype=np.float32)) epoch_error = nn.NdArray.from_numpy_array( np.asarray(float(self.epoch_error) / (self.batch_counter * self.batch_size), dtype=np.float32)) self.comm.all_reduce(epoch_loss, division=True, inplace=True) self.comm.all_reduce(epoch_error, division=True, inplace=True) if self.comm.rank == 0: self.monitor_loss.add(self.epoch, epoch_loss.data.copy()) self.monitor_err.add(self.epoch, epoch_error.data.copy()) if self.monitor_time is not None: self.monitor_time.add(self.epoch) class EpochTrainer(object): def __init__(self, model, solver, learning_rate_scheduler, data, comm, monitor, loss_scaling, weight_decay, stream_event_handler): batch_size = model.image.shape[0] self.model = model self.solver = solver self.data = data self.comm = comm self.learning_rate_scheduler = learning_rate_scheduler self.batch_size = batch_size self.loss_scaling = loss_scaling self.weight_decay = weight_decay self.stream_event_handler = stream_event_handler self.num_iter_per_epoch = ceil_to_multiple(data.size, batch_size) self.reporter = EpochReporter( 'Train', monitor, comm, model.loss, model.error, batch_size) def _update_learning_rate(self, epoch): # Set scheduled learning rate lr = self.learning_rate_scheduler(epoch) self.solver.set_learning_rate(lr) return lr def run(self, epoch): lr = self._update_learning_rate(epoch) # Training loop epoch_loss = 0.0 epoch_error = 0 pbar = trange(self.num_iter_per_epoch, desc='Train at epoch %d' % epoch, disable=self.comm.rank > 0) # pbar = range(self.num_iter_per_epoch) self.reporter.reset(epoch, pbar) for i in pbar: # nvtx.range_push("train_{}".format(i)) # wait here until back-prop has been finished self.stream_event_handler.event_synchronize() next_image, next_label = self.data.next() self.model.image.data = next_image self.model.label.data = next_label # Synchronizing null-stream and host here makes update faster. I'm not sure why. self.stream_event_handler.default_stream_synchronize() self.reporter(lr * self.loss_scaling) nn.forward_all([self.model.loss, self.model.error], clear_no_need_grad=True) # self.model.loss.forward(clear_no_need_grad=True, function_pre_hook=None) comm_callback = None if self.comm.n_procs > 1: params = [x.grad for x in nn.get_parameters().values()] comm_callback = self.comm.comm.all_reduce_callback( params, 1024 * 1024 * 2) self.solver.zero_grad() self.model.loss.backward( self.loss_scaling, clear_buffer=True, communicator_callbacks=comm_callback ) # Subscript event self.stream_event_handler.add_default_stream_event() # # Update self.solver.weight_decay(self.weight_decay) self.solver.update() self.reporter.update() # if i == 10: # import sys # nvtx.range_pop() self.reporter(lr * self.loss_scaling, force=True) self.reporter.on_epoch_end() class EpochValidator(object): def __init__(self, model, data, comm, monitor, stream_event_handler): batch_size = model.image.shape[0] self.model = model self.data = data self.comm = comm self.stream_event_handler = stream_event_handler self.batch_size = batch_size self.num_iter_per_epoch = ceil_to_multiple(self.data.size, batch_size) self.reporter = EpochReporter( 'Validation', monitor, comm, model.loss, model.error, batch_size, time=False) def run(self, epoch): epoch_loss = 0.0 epoch_error = 0 pbar = trange(self.num_iter_per_epoch, desc='Val at epoch %d' % epoch, disable=self.comm.rank > 0) self.reporter.reset(epoch, pbar) for i in pbar: # wait here until forward-prop has been finished self.stream_event_handler.event_synchronize() next_image, next_label = self.data.next() self.reporter(0) self.model.image.data = next_image self.model.label.data = next_label nn.forward_all([self.model.loss, self.model.error], clear_buffer=True) self.stream_event_handler.add_default_stream_event() self.reporter.update() self.reporter(0, force=True) self.reporter.on_epoch_end()
package com.example.yizu.location.demo; import com.baidu.location.BDAbstractLocationListener; import com.baidu.location.BDLocation; import com.example.yizu.R; import com.example.yizu.location.service.LocationService; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class IsHotWifiActivity extends Activity{ private LocationService locService; private TextView res; private Button startBtn; private MyLocationListener listener; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.hotwifi); res = (TextView)findViewById(R.id.hotwifiResult); startBtn = (Button)findViewById(R.id.start); locService = ((LocationApplication) getApplication()).locationService; //LocationClientOption mOption = locService.getDefaultLocationClientOption(); //mOption.setLocationMode(LocationClientOption.LocationMode.Battery_Saving); //mOption.setCoorType("bd09ll"); //locService.setLocationOption(mOption); listener = new MyLocationListener(); locService.registerListener(listener); locService.start(); startBtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub boolean b = locService.requestHotSpotState(); res.setText(""); Log.i("lxm", b+""); } }); } /*** * 定位结果回调,在此方法中处理定位结果 */ class MyLocationListener extends BDAbstractLocationListener { @Override public void onConnectHotSpotMessage(String s, int i) { // TODO Auto-generated method stub Log.i("lxm", i+" "+s); String resText = ""; if(i == 0){ resText = "不是wifi热点, wifi:"+s; } else if(i == 1){ resText = "是wifi热点, wifi:"+s; } else if (i == -1){ resText = "未连接wifi"; } res.setText(resText); } @Override public void onReceiveLocation(BDLocation arg0) { // TODO Auto-generated method stub } } @Override protected void onDestroy() { super.onDestroy(); // 在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理 // WriteLog.getInstance().close(); locService.unregisterListener(listener); locService.stop(); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } }
class TextEditor: def __init__(self): self.lines = [""] self.current_line = 0 def type(self, text): while len(text) > 80: self.lines[self.current_line] += text[:80] text = text[80:] self.lines.append("") self.current_line += 1 self.lines[self.current_line] += text if len(self.lines[self.current_line]) > 80: self.lines.append(self.lines[self.current_line][80:]) self.lines[self.current_line] = self.lines[self.current_line][:80] self.current_line += 1 def backspace(self): if len(self.lines[self.current_line]) == 0 and self.current_line > 0: self.current_line -= 1 self.lines[self.current_line] += self.lines.pop() else: self.lines[self.current_line] = self.lines[self.current_line][:-1] def moveUp(self): if self.current_line > 0: self.current_line -= 1 def moveDown(self): if self.current_line < len(self.lines) - 1: self.current_line += 1 def getCurrentLine(self): return self.lines[self.current_line]
def duplicate_words(string): """ Find a list of words that appear more than once in a string Parameters: string (str): a string Return: list: a list of duplicate words """ word_list = string.split() duplicate_words = [] for word in word_list: if word_list.count(word) > 1 and word not in duplicate_words: duplicate_words.append(word) return duplicate_words if __name__ == '__main__': string = "This this is a a sample sample string" print(duplicate_words(string))
#!/usr/bin/env bash ./node_modules/.bin/babel-node index.js
#!/bin/sh DIR="$( cd "$( dirname "$0" )" && pwd )" set -x make -C $DIR/maru eval gceval tpeg.l $DIR/maru/gceval -b $DIR/maru/boot.l -L $DIR/maru/ $DIR/nile-compiler.l \ $DIR c $@
#!/bin/bash source /opt/vyatta/etc/functions/script-template configure set system conntrack modules ftp disable set system conntrack modules gre disable set system conntrack modules h323 disable set system conntrack modules pptp disable set system conntrack modules sip disable set system conntrack modules tftp disable set system conntrack timeout tcp close 10 set system conntrack timeout tcp close-wait 10 set system conntrack timeout tcp established 86400 set system conntrack timeout tcp fin-wait 10 set system conntrack timeout tcp last-ack 10 set system conntrack timeout tcp syn-recv 5 set system conntrack timeout tcp syn-sent 5 set system conntrack timeout tcp time-wait 10 set system conntrack timeout udp other 30 set system conntrack timeout udp stream 180 set system offload hwnat enable set system host-name bastion set system name-server 8.8.8.8 set system name-server 8.8.4.4 set system time-zone Europe/Madrid commit save exit
def insertBits(N, M, i, j): # Create a mask to clear bits i through j in N allOnes = ~0 left = allOnes << (j + 1) right = (1 << i) - 1 mask = left | right # Clear bits i through j in N clearedN = N & mask # Shift M so that it lines up with bits i through j shiftedM = M << i # Merge M into N result = clearedN | shiftedM return result
pod package YMTCloudClassroom.podspec --force --no-mangle --exclude-deps --spec-sources=ssh://gerrit.ymfd.corp:29418/YMSpecs,https://github.com/CocoaPods/Specs.gitow
#!/bin/bash BP=$SP_DIR/backports mkdir $BP cp $RECIPE_DIR/__init__.py $BP/ $PYTHON -c "import backports"