text
stringlengths
1
1.05M
<gh_stars>0 /* https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups Use capture groups in reRegex to match numbers that are repeated only three times in a string, each separated by a space. (01) Your regex should use the shorthand character class for digits. (02) Your regex should reuse a capture group twice. (03) Your regex should have two spaces separating the three numbers. (04) Your regex should match "42 42 42". (05) Your regex should match "100 100 100". (06) Your regex should not match "42 42 42 42". (07) Your regex should not match "42 42". (08) Your regex should not match "101 102 103". (09) Your regex should not match "1 2 3". (10) Your regex should match "10 10 10". */ let repeatNum = "42 42 42"; let reRegex = /^(\d+)\s\1\s\1$/; // Change this line let result = reRegex.test(repeatNum); console.log(result);
class Pybind11 < Formula desc "Seamless operability between C++11 and Python" homepage "https://github.com/pybind/pybind11" url "https://github.com/pybind/pybind11/archive/v2.6.1.tar.gz" sha256 "cdbe326d357f18b83d10322ba202d69f11b2f49e2d87ade0dc2be0c5c34f8e2a" license "BSD-3-Clause" bottle do cellar :any_skip_relocation sha256 "2f8d6a8a4ec4e2d35ed5926f56d49e0a3c1a3a853f16f1fe266e4cb25673a2c9" => :big_sur sha256 "a65ec879104470206955784e0715d9188fd2f3848dcd88714e094313ab8305de" => :catalina sha256 "122967134526009627cf8648d4181f4a7e06688d5b74ffa0a2767abeeb54e091" => :mojave sha256 "2128187d3a45fbb3dfe2426b8e974ad15a07942a17ae07c09a52f07482b11bdf" => :high_sierra sha256 "8f6291fa8fa9b0a3285c4dd70f96c2d9f1214496ea228f410acd9036259468a1" => :x86_64_linux end depends_on "cmake" => :build depends_on "python@3.9" => :test def install system "cmake", "-S", ".", "-B", "build", "-DPYBIND11_TEST=OFF", "-DPYBIND11_NOPYTHON=ON", *std_cmake_args system "cmake", "--install", "build" end test do (testpath/"example.cpp").write <<~EOS #include <pybind11/pybind11.h> int add(int i, int j) { return i + j; } namespace py = pybind11; PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example plugin"; m.def("add", &add, "A function which adds two numbers"); } EOS (testpath/"example.py").write <<~EOS import example example.add(1,2) EOS python_flags = `#{Formula["python@3.9"].opt_bin}/python3-config --cflags --ldflags --embed`.split(" ") system ENV.cxx, "-O3", "-shared", "-std=c++11", *python_flags, *("-fPIC" unless OS.mac?), "example.cpp", "-o", "example.so" system Formula["python@3.9"].opt_bin/"python3", "example.py" end end
package postgres import ( "hash/fnv" "io" ) const ( manifestAdvisoryLock = `SELECT pg_try_advisory_xact_lock($1);` ) func crushkey(key string) int64 { h := fnv.New64a() io.WriteString(h, key) return int64(h.Sum64()) }
#!/bin/sh if [[ "$(whoami)" == "kristijan" ]]; then REPO_DIR=/home/kristijan/phd/pose/learnable-triangulation-pytorch/ else REPO_DIR=/home/dbojanic/pose/learnable-triangulation-pytorch/ fi echo ${REPO_DIR} docker run --rm --gpus all --name kbartol-triangulation -it \ -v ${REPO_DIR}:/learnable-triangulation/ learnable-triangulation
def sum(a, b): result = a + b print(result) sum(10, 20)
import { PresentationNode } from '@daign/2d-pipeline'; import { StyleSelectorChain } from '@daign/style-sheets'; import { TwoPointRectangle } from '@daign/2d-graphics'; import { TikzRenderer } from '../tikzRenderer'; import { TikzRenderModule } from '../tikzRenderModule'; export const twoPointRectangleModule = new TikzRenderModule( TwoPointRectangle, ( currentNode: PresentationNode, selectorChain: StyleSelectorChain, renderer: TikzRenderer ): string => { const rectangle = currentNode.sourceNode as TwoPointRectangle; selectorChain.addSelector( rectangle.styleSelector ); const startPoint = rectangle.getStartTransformed( currentNode.projectNodeToView ) .round( renderer.precision ); const endPoint = rectangle.getEndTransformed( currentNode.projectNodeToView ) .round( renderer.precision ); const tikzShape = `(${startPoint.x},${startPoint.y}) rectangle (${endPoint.x},${endPoint.y})`; const tikzCommand = renderer.applyStyle( tikzShape, selectorChain ); return tikzCommand; } );
#!/bin/sh set -e export LANG=C export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" export TZ=America/New_York OVERRIDE_SCRIPT="/etc/apache2/override.sh" # update ClientID if [ -z "$CLIENTID" ] ; then export CLIENTID='none' fi # update ClientSecret if [ -z "$CLIENTSECRET" ] ; then export CLIENTSECRET='none' fi # update REMOTE_USER_CLAIM if [ -z "$REMOTE_USER_CLAIM" ] ; then export REMOTE_USER_CLAIM=email fi # update SERVER_ADMIN if [ -z "$SERVER_ADMIN" ] ; then export SERVER_ADMIN=webmaster@example.org fi # update SERVER_NAME if [ -z "$SERVER_NAME" ] ; then export SERVER_NAME=localhost fi # update AUTH_REQUIRE if [ -z "$AUTH_REQUIRE" ] ; then # backward compatibility for OIDC_CLAIM if [ -n "$OIDC_CLAIM" ] ; then export AUTH_REQUIRE="${OIDC_CLAIM}" else export AUTH_REQUIRE='Require all granted' fi elif [ "$AUTH_REQUIRE" = '(none)' ]; then export AUTH_REQUIRE= fi # update AUTH_REQUIRE2 if [ -z "$AUTH_REQUIRE2" ] ; then # backward compatibility for OIDC_CLAIM2 if [ -n "$OIDC_CLAIM2" ] ; then export AUTH_REQUIRE2="${OIDC_CLAIM2}" else export AUTH_REQUIRE2='Require valid-user' fi elif [ "$AUTH_REQUIRE2" = '(none)' ]; then export AUTH_REQUIRE2= fi # update AUTH_TYPE if [ -z "$AUTH_TYPE" ] ; then export AUTH_TYPE='AuthType None' fi # update AUTH_TYPE2 if [ -z "$AUTH_TYPE2" ] ; then export AUTH_TYPE2='AuthType oauth20' fi # update CALLBACK_URI if [ -z "$CALLBACK_URI" ] ; then export CALLBACK_URI="https://${SERVER_NAME}/oauth2callback" fi # update CALLBACK_PATH if [ -z "$CALLBACK_PATH" ] ; then # shellcheck disable=SC2006 CALLBACK_PATH=/`echo $CALLBACK_URI | rev | cut -d/ -f1 | rev` export CALLBACK_PATH fi # set httpd port if [ -z "$HTTPD_PORT" ] ; then export HTTPD_PORT=80 fi # update LOG_LEVEL if [ -z "$LOG_LEVEL" ] ; then export LOG_LEVEL=warn fi # update OIDC_COOKIE if [ -z "$OIDC_COOKIE" ] ; then export OIDC_COOKIE='prometheus_session' fi # update PROXY_PATH if [ -z "$PROXY_PATH" ] ; then export PROXY_PATH=/ fi # update PROXY_PATH2 if [ -z "$PROXY_PATH2" ] ; then export PROXY_PATH2=/api fi # update PROXY_TIMEOUT if [ -z "$PROXY_TIMEOUT" ] ; then export PROXY_TIMEOUT='300' fi # update PROXY_URL if [ -z "$PROXY_URL" ] ; then export PROXY_URL=http://app:8080/ fi # update PROXY_URL2 if [ -z "$PROXY_URL2" ] ; then export PROXY_URL2=http://app:8080/api fi # update OIDC_PROVIDER_METADATA_URL if [ -z "$OIDC_PROVIDER_METADATA_URL" ] ; then export OIDC_PROVIDER_METADATA_URL='https://accounts.google.com/.well-known/openid-configuration' fi # update OIDC_SCOPES if [ -z "$OIDC_SCOPES" ] ; then export OIDC_SCOPES='openid email profile' fi # set httpd ssl port if [ -z "$SSL_HTTPD_PORT" ] ; then export SSL_HTTPD_PORT=443 fi # set SSL protocol if [ -z "$SSL_PROTOCOL" ] ; then export SSL_PROTOCOL='-SSLv3 -TLSv1 -TLSv1.1 +TLSv1.2' fi # set the SSL Cipher Suite if [ -z "$SSL_CIPHER_SUITE" ] ; then export SSL_CIPHER_SUITE='ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-ES256-SHA:!3DES:!ADH:!DES:!DH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!EXPORT:!KRB5-DES-CBC3-SHA:!MD5:!PSK:!RC4:!aECDH:!aNULL:!eNULL' fi ### Common modules to enable ### ENABLE_TCELL="${ENABLE_TCELL:-no}" if [ "$ENABLE_TCELL" = 'yes' ]; then a2enmod agenttcell fi ENABLE_WEBSOCKET="${ENABLE_WEBSOCKET:-no}" if [ "$ENABLE_WEBSOCKET" = 'yes' ]; then a2enmod proxy_wstunnel fi # Instead setting values via environment variables you can put them in the following file # Location of environment variable settings: ENVFILE="${ENVFILE:-/etc/apache2/env-override}" # If there is an override script, pull it in if [ -f "$ENVFILE" ]; then # shellcheck disable=SC1090 . $ENVFILE fi # If there is an override script, pull it in if [ -f "${OVERRIDE_SCRIPT}" ]; then # shellcheck disable=SC1090 . $OVERRIDE_SCRIPT fi # Apache gets grumpy about PID files pre-existing rm -f /var/run/apache2/apache2.pid exec /usr/sbin/apachectl -DNO_DETACH -DFOREGROUND 2>&1
package com.kakaopay.dto; import lombok.Data; /** * 결제 응답 * * @author kjy * @since Create : 2020. 4. 17. * @version 1.0 */ @Data public class CardInfo { private String cardNo; private String extMmYy; private String cvcNo; public CardInfo(String cardInfoStr) { String tempStr = (cardInfoStr); String tempCdNo = tempStr.split("\\|")[0]; this.extMmYy = tempStr.split("\\|")[1]; this.cvcNo = tempStr.split("\\|")[2]; this.cardNo = getCardNoMaskStr(tempCdNo); } public String getCardNoMaskStr(String tempCdNo) { String rtnStr = ""; int cardLen = tempCdNo.length(); int tempLen = 0; int cardFrontLen = 6; //앞6자리 int cardMidLen = 0; //가운데 자리수 int cardLastLen = 3; //뒤3자리 tempLen = cardLen - cardFrontLen; cardMidLen = tempLen - cardLastLen; String frontStr = tempCdNo.substring(0,cardFrontLen); // String midStr = tempCdNo.substring(cardFrontLen, cardFrontLen+cardMidLen); String lastStr = tempCdNo.substring(cardFrontLen+cardMidLen, cardLen); String midStr = ""; for(int i=0; i<cardMidLen; i++) { midStr += "*"; } rtnStr = frontStr + midStr + lastStr; return rtnStr; } }
const element = require('../../index'); const { storage, blockchain, primaryKeypair, recoveryKeypair, } = require('../__tests__/__fixtures__'); describe('operationsToTransaction', () => { it('should batch and anchor operations to blockchain', async () => { const encodedPayload = element.func.encodeJson({ '@context': 'https://w3id.org/did/v1', publicKey: [ { id: '#primary', type: 'Secp256k1VerificationKey2018', publicKeyHex: primaryKeypair.publicKey, }, { id: '#recovery', type: 'Secp256k1VerificationKey2018', publicKeyHex: recoveryKeypair.publicKey, }, ], }); const signature = element.func.signEncodedPayload(encodedPayload, primaryKeypair.privateKey); const requestBody = { header: { operation: 'create', kid: '#primary', alg: 'ES256K', }, payload: encodedPayload, signature, }; const encodedOperation = element.func.requestBodyToEncodedOperation({ ...requestBody, }); const txn = await element.func.operationsToTransaction({ operations: [encodedOperation], storage, blockchain, }); expect(txn).toEqual({ anchorFileHash: 'QmXtnsawdNkTMBUWEBR1kTTP1gefcQiWG6aJQVq9pgrqNy', transactionNumber: 15, transactionTime: 53, transactionTimeHash: '0xa6dd7120730ddccf4788a082b0b5607fd1f39dbb80ebc170678551878b90b835', }); }); });
#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by <NAME> on 2010-12-23. Copyright (c) 2010 """ __author__ = '<NAME>' __copyright__ = 'Copyright (c) 2011, <NAME>' __credits__ = ['<NAME>', 'Brant Faircloth'] __license__ = 'http://www.opensource.org/licenses/BSD-3-Clause' __version__ = '1.0' __maintainer__ = '<NAME>' __email__ = 'ngcrawford _at_ gmail *dot* com' __status__ = 'testing' from core import *
<reponame>sadjy/devnet-wallet import { Colors } from "./colors"; import { Base58 } from "./crypto/base58"; import { ED25519 } from "./crypto/ed25519"; import { IKeyPair } from "./models/IKeyPair"; import { ITransaction } from "./models/ITransaction"; /** * Class to help with transactions. */ export class Transaction { /** * Sign a transaction. * @param keyPair The key pair to sign with. * @param buffer The data to sign. * @returns The signature. */ public static sign(keyPair: IKeyPair, buffer: Buffer): Buffer { return ED25519.privateSign(keyPair, buffer); } /** * Get the index of the MINT output. * @param outputs The ouputs of the transaction. * @returns The index of the MINT output. */ public static mintIndex(outputs: { [address: string]: {color: string; value: bigint }[] }): number { let mintOutput = ""; let mintAddress = ""; let mintOutputIndex = 0; const bufferOutputs: Buffer[] = []; for (const address in outputs) { const outputType = Buffer.alloc(1); outputType.writeUInt8(1); const balancesCount = Buffer.alloc(4); balancesCount.writeUInt32LE(outputs[address].length); const bufferColors: Buffer[] = []; for (const balance of outputs[address]) { const color = balance.color === Colors.IOTA_NAME ? Colors.IOTA_BUFFER : Base58.decode(balance.color); if (balance.color === Colors.MINT) { mintAddress = address; } const colorValueBuffer = Buffer.alloc(8); colorValueBuffer.writeBigUInt64LE(balance.value); bufferColors.push(Buffer.concat([color, colorValueBuffer])); } bufferColors.sort((a, b) => a.compare(b)); const decodedAddress = Base58.decode(address); const output = Buffer.concat([outputType, balancesCount, Buffer.concat(bufferColors), decodedAddress]); bufferOutputs.push(output); if (mintAddress === address) { mintOutput = output.toString("hex"); } } bufferOutputs.sort((a, b) => a.compare(b)); let i = 0; for (const index in bufferOutputs) { if (bufferOutputs[index].toString("hex") === mintOutput) { mintOutputIndex = i; } i += 1; } return mintOutputIndex; } /** * Get the essence for a transaction. * @param tx The tx to get the essence for. * @returns The essence of the transaction. */ public static essence(tx: ITransaction): Buffer { const buffers: Buffer[] = []; // version const version = Buffer.alloc(1); version.writeUInt8(tx.version); buffers.push(version); // timestamp const timestamp = Buffer.alloc(8); timestamp.writeBigInt64LE(tx.timestamp); buffers.push(timestamp); // aManaPledge buffers.push(Base58.decode(tx.aManaPledge)); // cManaPledge buffers.push(Base58.decode(tx.cManaPledge)); // Input Size const inputsCount = Buffer.alloc(2); inputsCount.writeUInt16LE(tx.inputs.length); buffers.push(inputsCount); // Inputs for (const input of tx.inputs) { const inputType = Buffer.alloc(1); inputType.writeUInt8(0); buffers.push(inputType); const decodedInput = Base58.decode(input); buffers.push(decodedInput); } // Output count const outputsCount = Buffer.alloc(2); outputsCount.writeUInt16LE(Object.keys(tx.outputs).length); buffers.push(outputsCount); // Outputs const bufferOutputs: Buffer[] = []; for (const address in tx.outputs) { const outputType = Buffer.alloc(1); outputType.writeUInt8(1); const balancesCount = Buffer.alloc(4); balancesCount.writeUInt32LE(tx.outputs[address].length); const bufferColors: Buffer[] = []; for (const balance of tx.outputs[address]) { const color = balance.color === Colors.IOTA_NAME ? Colors.IOTA_BUFFER : Base58.decode(balance.color); const colorValueBuffer = Buffer.alloc(8); colorValueBuffer.writeBigUInt64LE(balance.value); bufferColors.push(Buffer.concat([color, colorValueBuffer])); } bufferColors.sort((a, b) => a.compare(b)); const decodedAddress = Base58.decode(address); const output = Buffer.concat([outputType, balancesCount, Buffer.concat(bufferColors), decodedAddress]); bufferOutputs.push(output); } bufferOutputs.sort((a, b) => a.compare(b)); buffers.push(Buffer.concat(bufferOutputs)); // dataPayload size const dataPayloadSize = Buffer.alloc(4); dataPayloadSize.writeUInt32LE(0); buffers.push(dataPayloadSize); return Buffer.concat(buffers); } /** * Get the bytes for a transaction. * @param tx The tx to get the bytes for. * @param essence Existing essence. * @returns The bytes of the transaction. */ public static bytes(tx: ITransaction, essence?: Buffer): Buffer { const buffers: Buffer[] = []; const payloadType = Buffer.alloc(4); payloadType.writeUInt32LE(1337); buffers.push(payloadType); const essenceBytes = Transaction.essence(tx); buffers.push(essenceBytes); const unlockBlocksCount = Buffer.alloc(2); unlockBlocksCount.writeUInt16LE(tx.unlockBlocks.length); buffers.push(unlockBlocksCount); for (const index in tx.unlockBlocks) { const ubType = tx.unlockBlocks[index].type; const unlockBlockType = Buffer.alloc(1); unlockBlockType.writeUInt8(ubType); buffers.push(unlockBlockType); if (ubType === 0){ const ED25519Type = Buffer.alloc(1); ED25519Type.writeUInt8(0); buffers.push(ED25519Type); buffers.push(tx.unlockBlocks[index].publicKey); buffers.push(tx.unlockBlocks[index].signature); continue; } const referencedIndex = Buffer.alloc(2); referencedIndex.writeUInt16LE(tx.unlockBlocks[index].referenceIndex); buffers.push(referencedIndex); } const payloadSize = Buffer.concat(buffers).length; const payloadSizeBuffer = Buffer.alloc(4); payloadSizeBuffer.writeUInt32LE(payloadSize); buffers.unshift(payloadSizeBuffer); return Buffer.concat(buffers); } }
from flask import Flask, render_template, request import requests app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/search', methods=['POST']) def search(): // Get the search query from the form search_query = request.form['search-query'] // Make the API request endpoint = 'https://api.themoviedb.org/3/search/movie' parameters = { 'api_key': 'YOUR_API_KEY', 'query': search_query } response = requests.get(endpoint, parameters) data = response.json() // Get the results results = data['results'] // Pass the results to the template return render_template( 'results.html', query=search_query, results=results ) if __name__ == '__main__': app.run()
import os import numpy as np dir = '/home/gzx/data/Dataset/image_caption/coco/x152_grid_320x500' files = os.listdir(dir) # for f in files: # # print(f) # # data = np.load(os.path.join(dir, f))['feat'] # # print(data.shape) # # break # np.savez(os.path.join('/home/gzx/data/Dataset/image_caption/coco/', f), feat=data) f1 = np.load(os.path.join(dir, '371800.npz'))['feat'] print(f1.shape) f2 = np.load(os.path.join('/home/gzx/data/Dataset/image_caption/coco/x152_box_feature', '371800.npz'))['feat'] print(f2.shape)
class Node: def __init__(self, data): self.data = data self.next = None def insert_node(head, value): node = Node(value) if head is None: return node temp = head while temp.next: temp = temp.next temp.next = node return head head = Node(3) head.next = Node(7) head.next.next = Node(10) head.next.next.next = Node(12) print(insert_node(head, 4))
package main; import java.util.Scanner; public class HeatWaterEnergy { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the amount of water in kilograms: "); double waterWeightInKilograms = input.nextDouble(); System.out.print("Enter the initial temperature: "); double initialTemperatureInDegreeCelsius = input.nextDouble(); System.out.print("Enter the final temperature: "); double finalTemperatureInDegreeCelsius = input.nextDouble(); double energyToHeatWaterInJoules = waterWeightInKilograms * (finalTemperatureInDegreeCelsius - initialTemperatureInDegreeCelsius) * 4184; System.out.println("The energy needed is " + energyToHeatWaterInJoules); input.close(); } }
var ExampleBlock = function(config) { this.container = config.container; this.callbacks = config.callbacks || {}; this.codeblock = this.container.querySelector(".codeblock"); this.type = this.container.getAttribute("data-type"); this.fn = this.codeblock.getAttribute("data-fn"); this.autoexec = this.codeblock.getAttribute("data-autoexec") || false; this.executable = this.codeblock.getAttribute("data-executable") == "0" ? 0 : 1; this.container.setAttribute("data-executable", this.executable); this.livetimer = null; this.dcc = null; }; ExampleBlock.prototype.trigger = function(task, data) { data = data || {}; data.instance = this; if(typeof this.callbacks[task] == "undefined") return data; return this.callbacks[task](data); }; ExampleBlock.prototype.init = function() { var self = this; this.trigger("onPreInit"); this.dcc = new DynamicCodeContainer({ container: this.codeblock, callbacks : { onFieldChange: function() { self.onFieldChange(); }, onBeforeLoadNewCode : function(data) { data.code = codehighlighter.highlightCode(data.code); return data; }, onBeforeHTMLAppended : function(data) { data.code = codehighlighter.prepareCode(data.code) return data; }, onHTMLAppended : function(data) { codehighlighter.addCodePeeker(data.container); data.container.className += " hljs"; return data; } } }); console.log(this.fn); this.dcc.loadNewCode(window[this.fn].toString()); this.registerHandlers(); this.trigger("onInit"); }; ExampleBlock.prototype.registerHandlers = function() { var self = this; var execute = this.container.querySelector("button[name='execute']"); var autoexec = this.container.querySelector("input[name='live_update']"); execute.addEventListener("click", function() { self.execute(); }); autoexec.addEventListener("change", function() { self.setAutoexec(this.checked); }); }; ExampleBlock.prototype.setAutoexec = function(autoexec) { this.autoexec = autoexec; }; ExampleBlock.prototype.onFieldChange = function(field) { if(this.autoexec) this.execute(); }; ExampleBlock.prototype.execute = function() { if(!this.executable) return; var code; try { code = this.dcc.prepareCustomCode(); } catch(e) { console.error("Invalid Value"); throw e; return; } this.executeCode(code); }; ExampleBlock.prototype.executeCode = function(fn) { if(false === this.trigger("onExecuteCode", {fn: fn})) return; fn(); };
package neutron const LB_ROUND_ROBIN_ALGORITHM = "ROUND_ROBIN" const LB_SOURCE_IP_ALGORITHM = "SOURCE_IP" type OpenStackObject struct { Id string `json:"id,omitempty"` Name string `json:"name,omitempty"` TenantId string `json:"tenant_id,omitempty"` } type FixIP struct { SubnetId string `json:"subnet_id"` IpAddress string `json:"ip_address"` } type OpenStackPort struct { OpenStackObject Status string `json:"status,omitempty"` DnsName string `json:"dns_name,omitempty"` NetworkId string `json:"network_id,omitempty"` MacAddress string `json:"mac_address,omitempty"` FixedIPS []FixIP `json:"fixed_ips,omitempty"` AdminStateUp bool `json:"admin_state_up,omitempty"` SecurityGroupIds []string `json:"security_groups,omitempty"` BindingHost string `json:"binding:host_id,omitempty"` DeviceOwner string `json:"device_owner,omitempty"` DeviceId string `json:"device_id,omitempty"` } type PortsResponse struct { Ports []OpenStackPort `json:"ports"` } type OpenStackSubnet struct { OpenStackObject NetworkId string `json:"network_id"` GatewayIp string `json:"gateway_ip"` Cidr string `json:"cidr"` } type SubnetResponse struct { Subnet OpenStackSubnet `json:"subnet"` } type LbObject struct { ProvisionStatus string `json:"provisioning_status,omitempty"` OperatingStatus string `json:"operating_status,omitempty"` } type LoadBalancer struct { OpenStackObject LbObject VipAddress string `json:"vip_address,omitempty"` VipSubnetId string `json:"vip_subnet_id,omitempty"` Listeners []Listener `json:"listeners,omitempty"` Description string `json:"description,omitempty"` Pools []Pool `json:"pools,omitempty"` } type LoadBalancersResponse struct { Lbs []LoadBalancer `json:"loadbalancers"` } type LoadBalancerResponse struct { LoadBalanacerBody LoadBalancer `json:"loadbalancer"` } type Member struct { OpenStackObject LbObject Address string `json:"address"` ProtocolPort int32 `json:"protocol_port"` SubnetId string `json:"subnet_id"` PoolId string `json:"pool_id,omitempty"` Weight int `json:"weight"` } type MemberResponse struct { MemberBody Member `json:"member"` } type SesssionPersistence struct { Type string `json:"type,omitempty"` } type Pool struct { OpenStackObject LbObject Members []Member `json:"members,omitempty"` LbAlgorithm string `json:"lb_algorithm,omitempty"` SessionPersistence SesssionPersistence `json:"session_persistence,omitempty"` ListenerId string `json:"listener_id,omitempty"` LoadBalancerId string `json:"loadbalancer_id,omitempty"` Protocol string `json:"protocol"` } type PoolResponse struct { PoolBody Pool `json:"pool,omitempty"` } type Vip struct { OpenStackObject } type Listener struct { OpenStackObject LbObject Pools []Pool `json:"pools,omitempty"` ProtocolPort int32 `json:"protocol_port"` Protocol string `json:"protocol"` LoadBalancerId string `json:"loadbalancer_id"` } type ListenerResponse struct { ListenerBody Listener `json:"listener"` } type LoadBalancerStatusResponse struct { Statuses LbStatusWrapper `json:"statuses"` } type LbStatusWrapper struct { Lb LoadBalancer `json:"loadbalancer"` }
import java.util.List; public class LargestNumber { public static int getLargestNumber(List<Integer> list) { int largest = Integer.MIN_VALUE; for (int num : list) { if (num > largest) { largest = num; } } return largest; } public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); System.out.println("Largest number in List: " + getLargestNumber(list)); } }
#!/bin/sh #SBATCH --nodes=7 #SBATCH --ntasks-per-node=20 #SBATCH --mem=64000 #SBATCH --time=23:59:00 source ~/.bashrc time mpiexec nemo PS_S18d_f220_202006.yml -M -n
import pygame import time, sys, random from wordsearchGenerator import returnWordPuzzle # Initialize the program. pygame.init() # Define initial variable values. SIZE = 15 MARGIN = 40 WIN_WIDTH = MARGIN + SIZE*40 + MARGIN + MARGIN*2 WIN_HEIGHT = MARGIN + SIZE*40 + 50 notRunning = False linesToDraw = [] wsArray, wordKey, wordArray = returnWordPuzzle(SIZE) print(wordKey) # Set the Pygame display values. screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) backgroundColour = (255, 255, 255) screen.fill(backgroundColour) pygame.display.set_caption('Word Search') start_time = time.time() clock = pygame.time.Clock() def drawText(labelText, xPos, yPos, thisType): sizeFnt = 25 if thisType == "Input": thisColor = (52, 72, 97)#(117, 58, 14) elif thisType == "Back": thisColor = (0, 0, 0) elif thisType == "Red": thisColor = (132, 21, 0)#(245, 57, 12) elif thisType == "Timer": thisColor = (148, 163, 183) elif thisType == "Key": thisColor = (148, 163, 183) sizeFnt = 14 font = pygame.font.Font('freesansbold.ttf', sizeFnt) text = font.render(labelText, True, thisColor) textRect = text.get_rect() textRect.center = (xPos, yPos+3) return screen.blit(text, textRect) def drawTimer(): global timeElapsed, start_time, wordKey elapsed_time = time.time() - start_time #time.strftime("%H:%M:%S", time.gmtime(elapsed_time)) #pygame.draw.rect(screen, (200,150,70), (140, 20, 120, 120)) drawText(str(time.strftime("%M:%S", time.gmtime(elapsed_time))), 60, WIN_HEIGHT - 37, "Timer") for let in range(len(wordArray)): drawText(wordArray[let], WIN_WIDTH - 70, MARGIN +(let*40), "Key") def drawArray(): yMarg = 0 for line in range(SIZE+1): pygame.draw.line(screen, (0, 0, 0), (20 + (line*40), 20 + yMarg), (20 + (line*40), (MARGIN/2 + SIZE*40) + yMarg)) pygame.draw.line(screen, (0, 0, 0), (20, 20 + (line*40) + yMarg), ((MARGIN/2 + SIZE*40), 20 + (line*40) + yMarg)) drawLines() for row in range(SIZE): for col in range(SIZE): drawText(str(wsArray[row][col]), col*40 + MARGIN,row*40 + MARGIN + yMarg, "Back") def drawLines(): lineColor = (119, 189, 255) lineSize = 10 mouseX, mouseY = pygame.mouse.get_pos() howManyLines = 0 if len(linesToDraw)%2 == 0: howManyLines = len(linesToDraw) else: howManyLines = len(linesToDraw)-1 for l in range(0, howManyLines, 2): if len(linesToDraw) > 1: x1, x2 = linesToDraw[l][0], linesToDraw[l+1][0] y1, y2 = linesToDraw[l][1], linesToDraw[l+1][1] pygame.draw.line(screen, lineColor, (x1, y1), (x2, y2), lineSize) else: break # if the length is even, draw it to mouseX if len(linesToDraw)%2 != 0: # pygame.draw.circle(screen, lineColor, (linesToDraw[len(linesToDraw)-1][0], linesToDraw[len(linesToDraw)-1][1]), 10, 1) # pygame.draw.circle(screen, lineColor, (mouseX, mouseY), 15, 1) pygame.draw.line(screen, lineColor, (linesToDraw[len(linesToDraw)-1][0], linesToDraw[len(linesToDraw)-1][1]), (mouseX, mouseY), lineSize) def restartGame(): global notRunning global wsArray global wordKey global start_time global SIZE notRunning = False start_time = time.time() wsArray, wordKey, wordArray = returnWordPuzzle(SIZE) updateDisplay() # Main loop to continuously draw objects and process user input. def updateDisplay(): timeTracker = 0 global notRunning, linesToDraw while not notRunning: mouseX, mouseY = pygame.mouse.get_pos() screen.fill(backgroundColour) for event in pygame.event.get(): keyPressed = pygame.key.get_pressed() if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() sys.exit() elif event.type == pygame.KEYUP: if event.key == pygame.K_g: returnWordPuzzle() elif event.key == pygame.K_z and keyPressed[pygame.K_LSHIFT]: if len(linesToDraw)%2 == 0 and len(linesToDraw) > 1: linesToDraw.pop(len(linesToDraw)-1) linesToDraw.pop(len(linesToDraw)-1) if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: linesToDraw.append([mouseX, mouseY]) if event.type == pygame.MOUSEBUTTONUP and event.button == 1: linesToDraw.append([mouseX, mouseY]) drawArray() drawTimer() pygame.display.update() clock.tick(60) finishTime = time.time() - start_time #Stop processing coverField, wait for user to restart the game. while notRunning: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: restartGame() # HERE, reset startime variable screen.fill(backgroundColour) drawArray() thisRectW = 280 pygame.draw.rect(screen, (239, 255, 234), (WIN_WIDTH/2 - thisRectW/2, (WIN_HEIGHT - 50)/2 - 30/2, thisRectW, 30)) drawText("Press space to restart.", WIN_WIDTH/2, (WIN_HEIGHT - 50)/2, "Back") drawText(("Completed in: " + str(time.strftime("%M:%S", time.gmtime(finishTime)))), WIN_WIDTH/2, WIN_HEIGHT - 37, "Timer") pygame.display.flip() clock.tick(60) updateDisplay()
public int maxPathSum(int[][] triangle) { for(int i=triangle.length-2; i>=0; i--) { for(int j=0; j<=i; j++) { triangle[i][j] += Math.max(triangle[i+1][j], triangle[i+1][j+1]); } } return triangle[0][0]; }
<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cassette = void 0; var cassette = { "viewBox": "0 0 64 64", "children": [{ "name": "g", "attribs": { "id": "CASSETTE" }, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "path", "attribs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M61,9H3c-1.657,0-3,1.343-3,3v40c0,1.657,1.343,3,3,3h8.369l4.846-12.114\r\n\t\t\tl0.004,0.002C16.661,41.783,17.737,41,19,41h26c1.263,0,2.339,0.782,2.781,1.887l0.004-0.002L52.631,55H61c1.657,0,3-1.343,3-3V12\r\n\t\t\tC64,10.343,62.657,9,61,9z M16,32c-2.209,0-4-1.791-4-4c0-2.209,1.791-4,4-4c2.209,0,4,1.791,4,4C20,30.209,18.209,32,16,32z\r\n\t\t\t M40,32H24v-8h16V32z M48,32c-2.209,0-4-1.791-4-4c0-2.209,1.791-4,4-4s4,1.791,4,4C52,30.209,50.209,32,48,32z M45.834,46.056\r\n\t\t\tC45.436,44.865,44.325,44,43,44H21c-1.296,0-2.391,0.827-2.81,1.978l-0.01-0.004L14.899,55h33.93l-2.983-8.949L45.834,46.056z" }, "children": [{ "name": "path", "attribs": { "fill-rule": "evenodd", "clip-rule": "evenodd", "d": "M61,9H3c-1.657,0-3,1.343-3,3v40c0,1.657,1.343,3,3,3h8.369l4.846-12.114\r\n\t\t\tl0.004,0.002C16.661,41.783,17.737,41,19,41h26c1.263,0,2.339,0.782,2.781,1.887l0.004-0.002L52.631,55H61c1.657,0,3-1.343,3-3V12\r\n\t\t\tC64,10.343,62.657,9,61,9z M16,32c-2.209,0-4-1.791-4-4c0-2.209,1.791-4,4-4c2.209,0,4,1.791,4,4C20,30.209,18.209,32,16,32z\r\n\t\t\t M40,32H24v-8h16V32z M48,32c-2.209,0-4-1.791-4-4c0-2.209,1.791-4,4-4s4,1.791,4,4C52,30.209,50.209,32,48,32z M45.834,46.056\r\n\t\t\tC45.436,44.865,44.325,44,43,44H21c-1.296,0-2.391,0.827-2.81,1.978l-0.01-0.004L14.899,55h33.93l-2.983-8.949L45.834,46.056z" }, "children": [] }] }] }] }] }] }; exports.cassette = cassette;
import fade from '../../internal/fade'; import colors from '../../settings/colors'; export default { root: { color: 'currentColor', fontSize: '12px', lineHeight: '12px', textAlign: 'right', padding: '0 0 0 10px', opacity: '.75' }, edited: { marginRight: '4px' }, image: { padding: '4px', borderRadius: '4px 0 4px', backgroundColor: fade(colors.black, 0.55), position: 'absolute', bottom: '12px', right: '12px', color: colors.white, opacity: 1 } };
import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression # load the dataset data = pd.read_csv("house_data.csv") # create feature and target arrays X = data[['sqft_living', 'sqft_lot', 'grade', 'bedrooms', 'bathrooms']] y = data['price'] # create and fit the model model = LinearRegression().fit(X, y) # makepredictions predictions = model.predict(X) print("predictions:", predictions)
gcc /vagrant/mirai/reports/main.c -o reports
<reponame>mayankmanj/acl2<gh_stars>100-1000 #!/usr/bin/env ruby # VL Verilog Toolkit # Copyright (C) 2008-2014 Centaur Technology # # Contact: # Centaur Technology Formal Verification Group # 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. # http://www.centtech.com/ # # License: (An MIT/X11-style license) # # 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. # # Original author: <NAME> <<EMAIL>> require 'require_relative' if RUBY_VERSION =~ /1\.8/ require_relative '../utils' outlaw_bad_warnings() outlaw_warning_global("VL-PROGRAMMING-ERROR") def find_major_extension_warning(substring) raise "No warnings for top" unless WARNINGS.has_key?(:top) wlist = WARNINGS[:top] wlist.each do |w| if ((w[:type].include?("VL-WARN-EXTENSION")) and (not w[:type].include?("MINOR")) and (w[:text].include?(substring))) return w end end return false end def find_minor_extension_warning(substring) raise "No warnings for top" unless WARNINGS.has_key?(:top) wlist = WARNINGS[:top] wlist.each do |w| if ((w[:type].include?("VL-WARN-EXTENSION")) and (w[:type].include?("MINOR")) and (w[:text].include?(substring))) return w end end return false end def major(substring) major = find_major_extension_warning(substring) if (major) puts "OK: #{substring}: found major extension warning: #{major[:type]}" else raise "FAIL: #{substring}: no major extension warning" end minor = find_minor_extension_warning(substring) if (minor) raise "FAIL: extension warning for #{substring} is minor instead of major:\n #{minor[:type]} -- #{minor[:text]}" else puts "OK: #{substring}: no minor extension warning" end end def normal(substring) major = find_major_extension_warning(substring) if (major) raise "FAIL: #{substring}: unexpected major extension warning:\n #{major[:type]} -- #{major[:text]}" else puts "OK: #{substring}: no major extension warnings" end minor = find_minor_extension_warning(substring) if (minor) raise "FAIL: #{substring}: unexpected minor extension warning:\n #{minor[:type]} -- #{minor[:text]}" else puts "OK: #{substring}: no minor extension warnings" end end def minor(substring) major = find_major_extension_warning(substring) if (major) raise "FAIL: #{substring}: unexpected major extension warning:\n #{major[:type]} -- #{major[:text]}" else puts "OK: #{substring}: no major extension warnings" end minor = find_minor_extension_warning(substring) if (minor) puts "OK: #{substring}: found minor extension warning: #{minor[:type]}" else raise "FAIL: #{substring}: no minor extension warning" end end normal("as_normal1") normal("as_normal2") normal("as_normal3") normal("as_normal4") normal("as_normal5") normal("as_normal6") major("as_warn1") major("as_warn2") major("as_warn3") test_passed()
/** * Copyright 2014 isandlaTech * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psem2m.isolates.services.conf.beans; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.psem2m.isolates.services.conf.IIsolateDescr; /** * Description of an isolate * * @author <NAME> */ public class IsolateDescription implements Serializable { /** Serializable version */ private static final long serialVersionUID = 1L; /** Isolate bundles (can't be null) */ private final Set<BundleDescription> pBundles = new LinkedHashSet<BundleDescription>(); /** The isolate VM class path (mainly for Java) */ private final List<String> pClasspath = new LinkedList<String>(); /** The isolate process environment variables */ private final Map<String, String> pEnvironment = new HashMap<String, String>(); /** Isolate kind, must never be null */ private String pIsolateKind = ""; /** Isolate name */ private String pIsolateName; /** Isolate ID */ private String pIsolateUID; /** The node hosting the isolate */ private String pNode; /** The OSGi framework JAR file path, if any */ private String pOsgiFramework; /** The isolate signals port */ private int pPort; /** Isolate Java VM arguments (can't be null, must be ordered) */ private final List<String> pVmArguments = new ArrayList<String>(); /** * Default constructor */ public IsolateDescription() { // Do nothing } /** * Sets up the description according to the given map * * @param aDescriptionMap * An isolate description map */ public IsolateDescription(final Map<String, Object> aDescriptionMap) { // Standard fields pIsolateUID = (String) aDescriptionMap.get(IIsolateDescr.ISOLATE_UID); pIsolateName = (String) aDescriptionMap.get(IIsolateDescr.ISOLATE_NAME); pNode = (String) aDescriptionMap.get(IIsolateDescr.ISOLATE_NODE); pPort = (Integer) aDescriptionMap .get(IIsolateDescr.ISOLATE_SIGNALS_PORT); pOsgiFramework = (String) aDescriptionMap .get(IIsolateDescr.ISOLATE_OSGI_FRAMEWORK); // "Special" fields setKind((String) aDescriptionMap.get(IIsolateDescr.ISOLATE_KIND)); // Class path fillStringCollection(pClasspath, aDescriptionMap.get(IIsolateDescr.ISOLATE_CLASSPATH), true); // VM Arguments fillStringCollection(pVmArguments, aDescriptionMap.get(IIsolateDescr.ISOLATE_VM_ARGS), true); // Bundles if (aDescriptionMap.get(IIsolateDescr.ISOLATE_BUNDLES) instanceof Collection) { final Collection<?> args = (Collection<?>) aDescriptionMap .get(IIsolateDescr.ISOLATE_VM_ARGS); for (final Object arg : args) { if (arg instanceof Map) { @SuppressWarnings("unchecked") final Map<String, Object> mapArg = (Map<String, Object>) arg; pBundles.add(new BundleDescription(mapArg)); } } } // Environment if (aDescriptionMap.get(IIsolateDescr.ISOLATE_ENVIRONMENT) instanceof Map) { final Map<?, ?> mapEnv = (Map<?, ?>) aDescriptionMap .get(IIsolateDescr.ISOLATE_ENVIRONMENT); for (final Entry<?, ?> entry : mapEnv.entrySet()) { final String key = (String) entry.getKey(); if (key == null || key.isEmpty()) { // Ignore empty keys continue; } final String value = (String) entry.getValue(); if (value == null) { // Ignore null values continue; } pEnvironment.put(key, value); } } } /** * Sets up the isolate description * * @param aIsolateId */ public IsolateDescription(final String aIsolateId) { pIsolateUID = aIsolateId; } /** * Fills the given collection with the given object, if it is a collection * * @param aFilledCollection * The collection to fill * @param aSourceObject * The source collection (untyped) * @param aAvoidNull * If True, null values are ignored */ protected void fillStringCollection( final Collection<String> aFilledCollection, final Object aSourceObject, final boolean aAvoidNull) { if (aFilledCollection == null) { // Nothing to fill return; } if (!(aSourceObject instanceof Collection)) { // No content aFilledCollection.clear(); return; } final Collection<?> collection = (Collection<?>) aSourceObject; for (final Object obj : collection) { if (obj == null && aAvoidNull) { continue; } aFilledCollection.add((String) obj); } } /** * Retrieves the list of bundles described in the isolate configuration * * @return The isolate bundles */ public Set<BundleDescription> getBundles() { return pBundles; } /** * Retrieves the isolate VM class path (Java) * * @return the isolate class path */ public List<String> getClasspath() { return pClasspath; } /** * Retrieves the isolate process environment * * @return the isolate process environment */ public Map<String, String> getEnvironment() { return pEnvironment; } /** * Retrieves the kind of this isolate * * @return the isolate kind */ public String getKind() { return pIsolateKind; } /** * @return the isolateName */ public String getName() { return pIsolateName; } /** * Retrieves the isolate node name * * @return the node name */ public String getNode() { return pNode; } /** * The path to the OSGi framework JAR file * * @return the path to the OSGi framework */ public String getOsgiFramework() { return pOsgiFramework; } /** * The port to access the isolate signal receiver * * @return the signal receiver port */ public int getPort() { return pPort; } /** * Retrieves the ID of this isolate * * @return The isolate ID */ public String getUID() { return pIsolateUID; } /** * Retrieves the list of VM / interpreter arguments for this isolate * * @return The list of VM arguments */ public List<String> getVmArgs() { return pVmArguments; } /** * Sets the isolate bundles * * @param aBundles * the isolate bundles */ public void setBundles(final Set<BundleDescription> aBundles) { pBundles.clear(); if (aBundles != null) { pBundles.addAll(aBundles); } } /** * @param aClasspath * the classpath to set */ public void setClasspath(final List<String> aClasspath) { pClasspath.clear(); if (aClasspath != null) { pClasspath.addAll(aClasspath); } } /** * @param aEnvironment * the environment to set */ public void setEnvironment(final Map<String, String> aEnvironment) { pEnvironment.clear(); if (aEnvironment != null) { pEnvironment.putAll(aEnvironment); } } /** * Sets the kind of isolate * * @param aKind * The kind of the isolate * * @see IIsolateDescr#getKind() */ public void setKind(final String aKind) { if (aKind != null) { pIsolateKind = aKind; } else { pIsolateKind = ""; } } /** * @param aIsolateName * the isolateName to set */ public void setName(final String aIsolateName) { pIsolateName = aIsolateName; } /** * Sets up the isolate node name * * @param aNode * the node */ public void setNode(final String aNode) { pNode = aNode; } /** * @param aOsgiFramework * the osgiFramework to set */ public void setOsgiFramework(final String aOsgiFramework) { pOsgiFramework = aOsgiFramework; } /** * @param aPort * the port to set */ public void setPort(final int aPort) { pPort = aPort; } /** * Sets the isolate ID * * @param aIsolateId * the isolate ID */ public void setUID(final String aIsolateId) { pIsolateUID = aIsolateId; } /** * Sets the Java virtual machine arguments * * @param aVmArgs * the VM arguments */ public void setVMArgs(final List<String> aVmArgs) { pVmArguments.clear(); if (aVmArgs != null) { pVmArguments.addAll(aVmArgs); } } /** * Converts this description into its map representation * * @return The map representation of this object */ public Map<String, Object> toMap() { final Map<String, Object> map = new HashMap<String, Object>(); map.put(IIsolateDescr.ISOLATE_CLASSPATH, pClasspath); map.put(IIsolateDescr.ISOLATE_ENVIRONMENT, pEnvironment); map.put(IIsolateDescr.ISOLATE_UID, pIsolateUID); map.put(IIsolateDescr.ISOLATE_KIND, pIsolateKind); map.put(IIsolateDescr.ISOLATE_OSGI_FRAMEWORK, pOsgiFramework); map.put(IIsolateDescr.ISOLATE_NODE, pNode); map.put(IIsolateDescr.ISOLATE_SIGNALS_PORT, pPort); map.put(IIsolateDescr.ISOLATE_VM_ARGS, pVmArguments); // Bundles, converted to maps final List<Map<String, Object>> bundlesMap = new ArrayList<Map<String, Object>>(); for (final BundleDescription bundle : pBundles) { bundlesMap.add(bundle.toMap()); } map.put(IIsolateDescr.ISOLATE_BUNDLES, bundlesMap); return map; } }
public class Boss{ public String weapon; public int bossHealth; public int damage; public Boss(String weapon, int bossHealth, int damage){ this.weapon = weapon; this.bossHealth = bossHealth; this.damage = damage; } }
#!/bin/bash # (Creates python callable GRPC logic from the .proto file) # You can run this script from anywhere, # and it will generate the new files in the protobuf folder in this script's directory THIS_SCRIPTS_DIR="`dirname \"$0\"`" cd "$THIS_SCRIPTS_DIR" || (echo "Couldn't cd into $THIS_SCRIPTS_DIR" && exit) python3 -m grpc_tools.protoc \ -I protobuf \ --python_out protobuf \ --grpc_python_out protobuf \ protobuf/population_server.proto
#!/bin/sh ./gradlew --console plain --no-daemon -q tank-server:run
#!/bin/bash # This will read in a .gfg format and convert it to the atoms/diameters in PDMS cat ~/ranger_home/materials/PDMS/gfg/PDMS_1.gfg | sed -e "s/0.023000/0.023000\tWhite\tH/" \ | sed -e "s/0.198000/0.198000\tGray\tSi/" \ | sed -e "s/0.062000/0.062000\tBlack\tC/" \ | sed -e "s/0.080000/0.080000\tRed\tO/" \ | sed -e "s/0.008000/0.008000\tWhite\tH/" > 1.gfgci
SELECT SUM(quantity) FROM orders WHERE product = '<product_name>' AND created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
<gh_stars>0 module.exports = function(grunt) { grunt.initConfig({ // Sets up the watch on the above tasks watch: { file: { files: ['packages/**/*.coffee', 'packages/**/*.less', 'packages/**/*.css', 'packages/**/*.js'], tasks: ['shell'] } }, shell: { assets: { options: { stdout: true }, command: 'php artisan vendor:publish --force' } } }); grunt.loadNpmTasks('grunt-shell'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['watch']); }
<filename>thread/2/main.c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> //线程函数 void *test(void *ptr) { int i; for(i=0;i<8;i++) { printf("the pthread running ,count: %d\n",i); sleep(1); } } int main(void) { pthread_t pId; int i,ret; //创建子线程,线程id为pId ret = pthread_create(&pId,NULL,test,NULL); if(ret != 0) { printf("create pthread error!\n"); exit(1); } for(i=0;i < 5;i++) { printf("main thread running ,count : %d\n",i); sleep(1); } printf("main thread will exit when pthread is over\n"); //等待线程pId的完成 pthread_join(pId,NULL); printf("main thread exit\n"); return 0; }
set -e -x gcc \ -o wayland \ wayland.c \ -lwayland-client \ -lwayland-server \ -Wl,-Map=wayland.map sudo mount -o remount,rw / sudo cp wayland /usr/share/click/preinstalled/.click/users/@all/com.ubuntu.camera/camera-app ls -l /usr/share/click/preinstalled/.click/users/@all/com.ubuntu.camera/camera-app echo >/home/phablet/.cache/upstart/application-click-com.ubuntu.camera_camera_3.1.3.log tail -f /home/phablet/.cache/upstart/application-click-com.ubuntu.camera_camera_3.1.3.log
import java.io.{FileWriter, IOException} import org.jsoup.select.Elements import org.jsoup.{HttpStatusException, Jsoup} import scala.text.Document import scala.util.matching.Regex import play.api.libs.json._ /** * Fetches airport data from flightradar24.com. * No access tokens needed. */ object FR24AirportDataScraper { // Path of the file data should be written in val outputFile = "airports.csv" def main (args: Array[String]) { val countries = fetchPage("https://www.flightradar24.com/data/airports") .select("#tbl-datatable tbody tr td a") val airportUrls = new Regex("href=\"[a-zA-Z0-9.\\/:\\-]*\"") .findAllIn(countries.toString) .map { case (s: String) => s.subSequence(6, s.length-1) } .toStream .distinct val iataCodes = airportUrls .flatMap( url => { val airports = fetchPage(url.toString) .select("#tbl-datatable tbody tr td a") new Regex("data-iata=\"[A-Z0-9]*\"") .findAllIn(airports.toString) .map { case (s: String) => s.substring(11, s.length-1) } } ) .distinct val fw = new FileWriter(outputFile) fw.write("iata,icao,name,latitude,longitude,altitude,country,city,ratings_avg,ratings_total,reviews_count,reviews_evaluation\n") var i = 1 iataCodes .foreach( iata => { println(i + " " + iata) try { val json = fetchPage( String.format( "https://api.flightradar24.com/common/v1/airport.json?code=%s&plugin[]=&plugin-setting[schedule][mode]=&plugin-setting[schedule][timestamp]=%s&page=1&limit=25&token=", iata.toLowerCase, (System.currentTimeMillis / 1000).toString ) ) .text() val parsed = Json.parse(json) val icao = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "details" \ "code" \ "icao").get val name = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "details" \ "name").get val latitude = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "details" \ "position" \ "latitude").getOrElse(JsNull) val longitude = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "details" \ "position" \ "longitude").getOrElse(JsNull) val altitude = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "weather" \ "elevation" \ "m").getOrElse(JsNull) val country = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "details" \ "position" \ "country" \ "name").getOrElse(JsNull) val city = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "details" \ "position" \ "region" \ "city").getOrElse(JsNull) val ratingsAvg = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "flightdiary" \ "ratings" \ "avg").getOrElse(JsNull) val ratingsTotal = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "flightdiary" \ "ratings" \ "total").getOrElse(JsNull) val reviewsCount = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "flightdiary" \ "reviews").getOrElse(JsNull) val reviewsEvaluation = (parsed \ "result" \ "response" \ "airport" \ "pluginData" \ "flightdiary" \ "evaluation").getOrElse(JsNull) fw.write(iata + "," + icao + "," + name + "," + latitude + "," + longitude + "," + altitude + "," + country + "," + city + "," + ratingsAvg + "," + ratingsTotal + "," + reviewsCount + "," + reviewsEvaluation + "\n") } catch { case e: HttpStatusException => println(e) } i += 1 } ) fw.close() } private def fetchPage(url: String): org.jsoup.nodes.Document = { try { Jsoup .connect(url) .ignoreContentType(true) .timeout(100000) .userAgent( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36") .get() } catch { case e: Exception => { println(e) println("pause and retry..") Thread.sleep(10000) fetchPage(url) } } } }
#!/usr/bin/env node /* * Copyright 2018 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ 'use strict'; /** * @fileoverview * * Build the graal native compiler image for the current OS. * Intended to be run with a working directory of the intended package. */ const fs = require('fs'); const path = require('path'); const { GRAAL_OS, GRAAL_FOLDER, GRAAL_VERSION, GRAAL_PACKAGE_SUFFIX, GRAAL_URL } = require('./graal-env'); const TEMP_PATH = path.resolve(__dirname, '../temp'); const runCommand = require('./run-command'); // This script should catch and handle all rejected promises. // If it ever fails to do so, report that and exit immediately. process.on('unhandledRejection', error => { console.error(error); process.exit(1); }); // Build graal from source if (!fs.existsSync(TEMP_PATH)) { fs.mkdirSync(TEMP_PATH); } const NATIVE_IMAGE_BUILD_ARGS = [ '-H:+JNI', '--no-server', '-H:+ReportUnsupportedElementsAtRuntime', '-H:IncludeResourceBundles=com.google.javascript.rhino.Messages', '-H:IncludeResourceBundles=org.kohsuke.args4j.Messages', '-H:IncludeResourceBundles=org.kohsuke.args4j.spi.Messages', '-H:IncludeResourceBundles=com.google.javascript.jscomp.parsing.ParserConfig', `-H:ReflectionConfigurationFiles=${path.resolve(__dirname, 'reflection-config.json')}`, '-H:IncludeResources=(externs.zip)|(.*(js|txt))'.replace(/[\|\(\)]/g, (match) => { if (GRAAL_OS === 'windows') { // Escape the '|' character in a windows batch command // See https://stackoverflow.com/a/16018942/1211524 if (match === '|') { return '%PIPE%'; } return `^${match}`; } return '|'; }), '-H:+ReportExceptionStackTraces', '--initialize-at-build-time', '-jar', path.resolve(process.cwd(), 'compiler.jar') ]; let buildSteps = Promise.resolve(); // Download Graal const GRAAL_ARCHIVE_FILE = `${GRAAL_FOLDER}.${GRAAL_PACKAGE_SUFFIX}`; // Build the compiler native image. let pathParts = [TEMP_PATH, `graalvm-ce-java8-${GRAAL_VERSION}`]; if (GRAAL_OS === 'darwin') { pathParts.push('Contents', 'Home', 'bin'); } else { pathParts.push('bin'); } const GRAAL_BIN_FOLDER = path.resolve.apply(null, pathParts); if (!fs.existsSync(path.resolve(TEMP_PATH, GRAAL_FOLDER))) { const GRAAL_GU_PATH = path.resolve(GRAAL_BIN_FOLDER, `gu${GRAAL_OS === 'windows' ? '.cmd' : ''}`); buildSteps = buildSteps .then(() => { // Download graal and extract the contents if (!fs.existsSync(path.resolve(TEMP_PATH, GRAAL_ARCHIVE_FILE))) { process.stdout.write(`Downloading graal from ${GRAAL_URL}\n`); return runCommand( `curl --fail --show-error --location --progress-bar --output ${GRAAL_ARCHIVE_FILE} ${GRAAL_URL}`, {cwd: TEMP_PATH}); } }) .then(() => { if (GRAAL_PACKAGE_SUFFIX === 'tar.gz') { return runCommand(`tar -xzf ${GRAAL_ARCHIVE_FILE}`, {cwd: TEMP_PATH}); } return runCommand(`7z x -y ${GRAAL_ARCHIVE_FILE}`, {cwd: TEMP_PATH}); }) .then(() => runCommand(`${GRAAL_GU_PATH} install native-image`)); } // Build the compiler native image. const GRAAL_NATIVE_IMAGE_PATH = path.resolve( GRAAL_BIN_FOLDER, `native-image${GRAAL_OS === 'windows' ? '.cmd' : ''}`); buildSteps .then(() => runCommand(GRAAL_NATIVE_IMAGE_PATH, NATIVE_IMAGE_BUILD_ARGS)) .catch(e => { console.error(e); process.exit(1); });
def createFromXML(filename): try: # Initialize an empty dictionary to store the extracted parameters params = dict() # Import the necessary modules for XML parsing import amanzi_xml.utils.io import amanzi_xml.utils.search as search # Parse the XML file and extract the low coordinates of the box xml = amanzi_xml.utils.io.fromFile(filename) xyz = search.find_tag_path(xml, ["amanzi_input", "mesh", "generate", "box"]).get("low_coordinates") # Extract the x and z coordinates from the low coordinates string and store them in the params dictionary params["x_0"] = float(xyz.split(',')[0]) params["z_0"] = float(xyz.split(',')[2]) return params # Return the extracted parameters except FileNotFoundError: print("Error: The specified XML file was not found.") except KeyError: print("Error: The required tag or attribute was not found in the XML structure.") except ValueError: print("Error: Unable to convert the extracted coordinates to floating-point numbers.") except Exception as e: print("An unexpected error occurred:", e) # Example usage filename = "simulation_input.xml" extracted_params = createFromXML(filename) print(extracted_params)
#!/bin/bash set -eo pipefail SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd) PROJECT_DIR=$1 shift "$@" ./src/play/play \ w \ "${SCRIPT_DIR}/tiles.txt" \ "${PROJECT_DIR}/boards/scrabble.txt" \ --game=scrabble
package cn.lts.common.domain; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.time.LocalDateTime; /** * author: huanghaiping * created on 16-7-13. */ public class BaseEntity extends Entity { private static final long serialVersionUID = 1L; protected DataStatus dataStatus; protected LocalDateTime createTime; protected LocalDateTime lastUpdateTime; public long getId() { return id; } public void setId(long id) { this.id = id; } public DataStatus getDataStatus() { return dataStatus; } public void setDataStatus(DataStatus dataStatus) { this.dataStatus = dataStatus; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(LocalDateTime lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (Long.hashCode(getId())); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseEntity other = (BaseEntity) obj; if (getId() != other.getId()) return false; return true; } /** 由需要的编码字段的实体去覆盖 */ protected StringBuilder getOrigendFiled() { return null; } public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.JSON_STYLE); } }
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-N-VB-fill/7-model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-N-VB-fill/7-512+0+512-N-IP-1 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function replace_all_but_nouns_first_half_full --eval_function last_element_eval
var l = window.location; var url = 'ws://' + l.host + '/chat' + l.pathname; var ws = new WebSocket(url); function byId(id) { return document.getElementById(id); }; var out = byId('out'); var inp = byId('inp'); inp.onkeyup = function (e) { if (e.ctrlKey && e.keyCode == 13) { ws.send(inp.value); inp.value = ""; } }; function time() { return new Date().toLocaleTimeString(); //("ru", { hour: 'numeric', minute: 'numeric', seconds: 'numeric' }); }; ws.onmessage = function (e) { console.log(e) out.insertAdjacentHTML('afterbegin', time() + " " + e.data); }
public class GkTuple<T> : IComparable { private T v; public GkTuple(T value) { v = value; } public int CompareTo(object obj) { if (obj == null) return 1; GkTuple<T> other = obj as GkTuple<T>; if (other == null) throw new ArgumentException("Object is not a GkTuple"); return Comparer<T>.Default.Compare(v, other.v); } }
<gh_stars>0 /* * Copyright © 2008-2011 <NAME> * Copyright © 2010-2011 Intel Corporation * * Permission to use, copy, modify, distribute, and sell this * software and its documentation for any purpose is hereby granted * without fee, provided that\n the above copyright notice appear in * all copies and that both that copyright notice and this permission * notice appear in supporting documentation, and that the name of * the copyright holders not be used in advertising or publicity * pertaining to distribution of the software without specific, * written prior permission. The copyright holders make no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied * warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ #include <stdlib.h> #include <stdint.h> #include "ozone/wayland/protocol/wayland-drm-protocol.h" extern const struct wl_interface wl_buffer_interface; extern const struct wl_interface wl_buffer_interface; extern const struct wl_interface wl_buffer_interface; static const struct wl_interface *types[] = { NULL, &wl_buffer_interface, NULL, NULL, NULL, NULL, NULL, &wl_buffer_interface, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &wl_buffer_interface, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; static const struct wl_message wl_drm_requests[] = { { "authenticate", "u", types + 0 }, { "create_buffer", "nuiiuu", types + 1 }, { "create_planar_buffer", "nuiiuiiiiii", types + 7 }, { "create_prime_buffer", "nhiiuiiiiii", types + 18 }, }; static const struct wl_message wl_drm_events[] = { { "device", "s", types + 0 }, { "format", "u", types + 0 }, { "authenticated", "", types + 0 }, { "capabilities", "u", types + 0 }, }; WL_EXPORT const struct wl_interface wl_drm_interface = { "wl_drm", 2, 4, wl_drm_requests, 4, wl_drm_events, };
import React from 'react'; import logo from './logo.svg'; import Hi from './components/Hi'; import MediaCard from './components/MediaCard'; import Gate from './components/Gate'; import Room from './components/Room'; import Temp from './components/Temp'; import Reddit from './components/Reddit'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> <Hi name='Megan!' /> <MediaCard title='Operation moon eye' body='let it begin op moon eye' imgUrl={logo} /> <Gate isOpen={true}/> <Gate isOpen={false}/> <Room/> <Temp/> <Reddit/> </header> </div> ); } export default App;
<filename>src/components/WorkOrder/AssignTechnicianFields.js import React, { Component } from "react"; import Select from "react-select"; import { FIELDS } from "./formConfig"; import api from "../../queries/api"; export default class AssignTechnicianFields extends Component { _isMounted = false; constructor(props) { super(props); this.state = { technicianOptions: [], }; } componentDidMount() { this._isMounted = true; this.getTechnicianOptions(); } componentWillUnmount() { this._isMounted = false; } getTechnicianOptions = () => { api .workOrder() .technicians() .then(res => { const technicianOptions = res.data.records.map(item => { return { label: item.identifier, value: item.id }; }); this._isMounted && this.setState({ technicianOptions }); }); }; getSupportTechnicianDefaultValue = () => { let data = this.props.data[FIELDS.SUPPORT_TECHNICIANS]; let rawData = this.props.data[`${FIELDS.SUPPORT_TECHNICIANS}_raw`]; let currentData = rawData ? rawData : data; // handle no assigned Technicians currentData = currentData === "" ? currentData : currentData.map(item => ({ value: item.id, label: item.identifier, })); return currentData; }; render() { return ( <> {this.props.data[FIELDS.ASSIGN_TO_SELF] === "No" && ( <div className="form-group"> <label htmlFor={FIELDS.LEAD_TECHNICIAN}>Lead Technician</label> <Select className="basic-single" classNamePrefix="select" defaultValue={this.props.data[FIELDS.LEAD_TECHNICIAN]} isClearable isSearchable name={FIELDS.LEAD_TECHNICIAN} options={this.state.technicianOptions} onChange={e => this.props.handleLeadTechnicianFieldChange( FIELDS.LEAD_TECHNICIAN, e ) } /> </div> )} <div className="form-group"> <label htmlFor={FIELDS.SUPPORT_TECHNICIANS}> Support Technician(s) </label> <Select className="basic-multi-select" classNamePrefix="select" isMulti defaultValue={this.getSupportTechnicianDefaultValue()} name={FIELDS.SUPPORT_TECHNICIANS} options={this.state.technicianOptions} onChange={this.props.handleSupportTechniciansFieldChange.bind( this, FIELDS.SUPPORT_TECHNICIANS )} /> </div> </> ); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ic_more = void 0; var ic_more = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M0 0h24v24H0z", "fill": "none" }, "children": [] }, { "name": "path", "attribs": { "d": "M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.97.89 1.66.89H22c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 13.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm5 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm5 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" }, "children": [] }] }; exports.ic_more = ic_more;
#!/bin/bash set -e # usage: ./generate.sh [versions] # ie: ./generate.sh # to update all Dockerfiles in this directory # or: ./generate.sh debian-jessie # to only update debian-jessie/Dockerfile # or: ./generate.sh debian-newversion # to create a new folder and a Dockerfile within it cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" versions=( "$@" ) if [ ${#versions[@]} -eq 0 ]; then versions=( */ ) fi versions=( "${versions[@]%/}" ) for version in "${versions[@]}"; do distro="${version%-*}" suite="${version##*-}" from="${distro}:${suite}" mkdir -p "$version" echo "$version -> FROM $from" cat > "$version/Dockerfile" <<-EOF # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM $from EOF case "$from" in debian:wheezy) # add -backports, like our users have to echo "RUN echo deb http://http.debian.net/debian $suite-backports main > /etc/apt/sources.list.d/$suite-backports.list" >> "$version/Dockerfile" ;; esac echo >> "$version/Dockerfile" extraBuildTags= # this list is sorted alphabetically; please keep it that way packages=( bash-completion # for bash-completion debhelper integration btrfs-tools # for "btrfs/ioctl.h" (and "version.h" if possible) build-essential # "essential for building Debian packages" curl ca-certificates # for downloading Go debhelper # for easy ".deb" building dh-apparmor # for apparmor debhelper dh-systemd # for systemd debhelper integration git # for "git commit" info in "docker -v" libapparmor-dev # for "sys/apparmor.h" libdevmapper-dev # for "libdevmapper.h" libsqlite3-dev # for "sqlite3.h" ) if [ "$suite" = 'precise' ]; then # precise has a few package issues # - dh-systemd doesn't exist at all packages=( "${packages[@]/dh-systemd}" ) # - libdevmapper-dev is missing critical structs (too old) packages=( "${packages[@]/libdevmapper-dev}" ) extraBuildTags+=' exclude_graphdriver_devicemapper' # - btrfs-tools is missing "ioctl.h" (too old), so it's useless # (since kernels on precise are old too, just skip btrfs entirely) packages=( "${packages[@]/btrfs-tools}" ) extraBuildTags+=' exclude_graphdriver_btrfs' fi echo "RUN apt-get update && apt-get install -y ${packages[*]} --no-install-recommends && rm -rf /var/lib/apt/lists/*" >> "$version/Dockerfile" echo >> "$version/Dockerfile" awk '$1 == "ENV" && $2 == "GO_VERSION" { print; exit }' ../../../Dockerfile >> "$version/Dockerfile" echo 'RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local' >> "$version/Dockerfile" echo 'ENV PATH $PATH:/usr/local/go/bin' >> "$version/Dockerfile" echo >> "$version/Dockerfile" echo 'ENV AUTO_GOPATH 1' >> "$version/Dockerfile" awk '$1 == "ENV" && $2 == "DOCKER_BUILDTAGS" { print $0 "'"$extraBuildTags"'"; exit }' ../../../Dockerfile >> "$version/Dockerfile" done
<reponame>madjake/node-mud-server class GameMap { constructor(width, height) { this.width = width; this.height = height; this.map = {}; } moveObject(obj, x, y) { const oldHash = this.hashPoint(obj.x, obj.y); const newHash = this.hashPoint(x, y); if (oldHash === newHash) { return true; } if (this.map[oldHash] && this.map[oldHash][obj.id]) { delete this.map[oldHash][old.id]; if (Object.keys(this.map[oldHash]) === 0) { delete this.map[oldHash]; } } if (!this.map[newHash]) { this.map[newHash] = {}; } this.map[newHash][obj.id] = obj.id; return true; } hashPoint(x, y) { return `${x},${y}`; } } module.exports = GameMap;
class JwsToken { protected?: string; constructor(protected?: string) { this.protected = protected; } validateAndExtractHeader(): string | null { if (!this.protected) { return null; } try { const decodedHeader = base64urlDecode(this.protected); if (typeof decodedHeader === 'object' && decodedHeader !== null && decodedHeader.hasOwnProperty('alg')) { return decodedHeader['alg']; } } catch (error) { return null; } return null; } } function base64urlDecode(input: string): object { // Implementation of base64url decoding // ... }
#!/bin/sh runFormula() { echoColor "green" "Output global config template." outputGlobalTemplate } outputGlobalTemplate(){ if [[ ! -s $VKPR_GLOBAL ]]; then echoColor "red" "Doesnt have any values in global config file." else $VKPR_YQ eval $VKPR_GLOBAL fi }
import { Component, OnInit } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/auth'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Router } from '@angular/router'; import { NgForm } from '@angular/forms'; import { auth } from 'firebase/app'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit { type: string; icon: string = 'visibility'; constructor( private auth: AngularFireAuth, private snackbar: MatSnackBar, private router: Router ) {} ngOnInit(): void { this.type = 'password'; } onsignup(form: NgForm) { this.auth .signInWithEmailAndPassword(form.value.email, form.value.password) .then((re) => { console.log(re, 'Success'); this.snackbar.open('Login Successfully !!', 'Dismiss', { duration: 3000, }); this.router.navigate(['/login']); }) .catch((err) => { console.log(err.message); this.snackbar.open(err.message, 'Dismiss', { duration: 3000, }); }); } googleSignIn() { this.auth .signInWithPopup(new auth.GoogleAuthProvider()) .then((re) => { console.log(re); this.snackbar.open('Login Successfully !!', 'Dismiss', { duration: 3000, }); this.router.navigate(['/login']); }) .catch((err) => { console.log('failed'); this.snackbar.open(err.message, 'Dismiss', { duration: 3000, }); }); } RecoveryPassword() { console.log('Password Reset'); } show(type: string) { if (type === 'password') { this.type = 'text'; this.icon = 'visibility_off'; } else { this.type = 'password'; this.icon = 'visibility'; } } }
package edu.rosehulman.goistjt; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; import java.util.Iterator; public class JoinReducer extends Reducer<TaggedText, Text, Text, Text> { @Override protected void reduce(TaggedText key, Iterable<Text> values, Context context) throws IOException, InterruptedException { Iterator<Text> iterator = values.iterator(); String courseName = iterator.next().toString(); String[] details; while (iterator.hasNext()) { details = iterator.next().toString().split(","); Text outKey = new Text(String.format("%s\t%s", details[0], key.getCourseNum().toString())); Text outVal = new Text(String.format("%s\t%s", courseName, details[1])); context.write(outKey, outVal); } } }
package org.apache.skywalking.testcase.undertow; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Copyright @ 2018/8/11 * * @author cloudgc */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
#!/bin/sh # ----------------------------------------------------------------------------- # # 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. # # build.sh - build script for rasterizer task # # $Id: build.sh # -------------------------------------------------------------------------- # ----- Verify and Set Required Environment Variables ------------------------- if [ "$ANT_HOME" = "" ] ; then ANT_HOME=../.. fi if [ "$JAVA_HOME" = "" ] ; then echo You must set JAVA_HOME to point at your Java Development Kit installation exit 1 fi BATIK_HOME=../.. # ----- Set up classpath --------------------------------------------------- # CP=$JAVA_HOME/lib/tools.jar:$ANT_HOME/lib/build/ant_1_4_1.jar:$BATIK_HOME/lib/build/crimson-ant.jar:$BATIK_HOME/lib/build/jaxp.jar CP=$JAVA_HOME/lib/tools.jar; CP=$CP:../../ant.jar; CP=$CP:../../ant-launcher.jar; CP=$CP:../../build/xercesImpl-2.11.0.jar; CP=$CP:../../xml-api-1.4.01.jar; CP=$CP:../../batik-all-svn1576673.jar; CP=$CP:$BATIK_HOME/classes # ----- Execute The Requested Build ------------------------------------------- TARGET=$1; if [ $# != 0 ] ; then shift 1 fi $JAVA_HOME/bin/java $ANT_OPTS -classpath $CP org.apache.tools.ant.Main -Dant.home=$ANT_HOME $TARGET -Dargs="$*" # ----- Cleanup the environment -------------------------------------------- BATIK_HOME= CP=
<reponame>BearerPipelineTest/buf // Copyright 2020-2022 Buf Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.0 // protoc (unknown) // source: buf/alpha/registry/v1alpha1/push.proto package registryv1alpha1 import ( v1alpha1 "github.com/bufbuild/buf/private/gen/proto/go/buf/alpha/module/v1alpha1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type PushRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"` Repository string `protobuf:"bytes,2,opt,name=repository,proto3" json:"repository,omitempty"` Branch string `protobuf:"bytes,3,opt,name=branch,proto3" json:"branch,omitempty"` Module *v1alpha1.Module `protobuf:"bytes,4,opt,name=module,proto3" json:"module,omitempty"` // Optional; if provided, the provided tags // are created for the pushed commit. Tags []string `protobuf:"bytes,5,rep,name=tags,proto3" json:"tags,omitempty"` // Optional; if provided, the pushed commit // will be appended to these tracks. If the // tracks do not exist, they will be created. Tracks []string `protobuf:"bytes,6,rep,name=tracks,proto3" json:"tracks,omitempty"` } func (x *PushRequest) Reset() { *x = PushRequest{} if protoimpl.UnsafeEnabled { mi := &file_buf_alpha_registry_v1alpha1_push_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PushRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*PushRequest) ProtoMessage() {} func (x *PushRequest) ProtoReflect() protoreflect.Message { mi := &file_buf_alpha_registry_v1alpha1_push_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PushRequest.ProtoReflect.Descriptor instead. func (*PushRequest) Descriptor() ([]byte, []int) { return file_buf_alpha_registry_v1alpha1_push_proto_rawDescGZIP(), []int{0} } func (x *PushRequest) GetOwner() string { if x != nil { return x.Owner } return "" } func (x *PushRequest) GetRepository() string { if x != nil { return x.Repository } return "" } func (x *PushRequest) GetBranch() string { if x != nil { return x.Branch } return "" } func (x *PushRequest) GetModule() *v1alpha1.Module { if x != nil { return x.Module } return nil } func (x *PushRequest) GetTags() []string { if x != nil { return x.Tags } return nil } func (x *PushRequest) GetTracks() []string { if x != nil { return x.Tracks } return nil } type PushResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields LocalModulePin *LocalModulePin `protobuf:"bytes,5,opt,name=local_module_pin,json=localModulePin,proto3" json:"local_module_pin,omitempty"` } func (x *PushResponse) Reset() { *x = PushResponse{} if protoimpl.UnsafeEnabled { mi := &file_buf_alpha_registry_v1alpha1_push_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *PushResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*PushResponse) ProtoMessage() {} func (x *PushResponse) ProtoReflect() protoreflect.Message { mi := &file_buf_alpha_registry_v1alpha1_push_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PushResponse.ProtoReflect.Descriptor instead. func (*PushResponse) Descriptor() ([]byte, []int) { return file_buf_alpha_registry_v1alpha1_push_proto_rawDescGZIP(), []int{1} } func (x *PushResponse) GetLocalModulePin() *LocalModulePin { if x != nil { return x.LocalModulePin } return nil } var File_buf_alpha_registry_v1alpha1_push_proto protoreflect.FileDescriptor var file_buf_alpha_registry_v1alpha1_push_proto_rawDesc = []byte{ 0x0a, 0x26, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2f, 0x70, 0x75, 0x73, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1b, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x1a, 0x26, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x28, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xc2, 0x01, 0x0a, 0x0b, 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x12, 0x1e, 0x0a, 0x0a, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x62, 0x72, 0x61, 0x6e, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x62, 0x72, 0x61, 0x6e, 0x63, 0x68, 0x12, 0x39, 0x0a, 0x06, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x52, 0x06, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x61, 0x67, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x09, 0x52, 0x04, 0x74, 0x61, 0x67, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x74, 0x72, 0x61, 0x63, 0x6b, 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x74, 0x72, 0x61, 0x63, 0x6b, 0x73, 0x22, 0x65, 0x0a, 0x0c, 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x55, 0x0a, 0x10, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x5f, 0x70, 0x69, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x4c, 0x6f, 0x63, 0x61, 0x6c, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x50, 0x69, 0x6e, 0x52, 0x0e, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x50, 0x69, 0x6e, 0x32, 0x6a, 0x0a, 0x0b, 0x50, 0x75, 0x73, 0x68, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x5b, 0x0a, 0x04, 0x50, 0x75, 0x73, 0x68, 0x12, 0x28, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x29, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x96, 0x02, 0x0a, 0x1f, 0x63, 0x6f, 0x6d, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x42, 0x09, 0x50, 0x75, 0x73, 0x68, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x59, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x75, 0x66, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x2f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x2f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x3b, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0xa2, 0x02, 0x03, 0x42, 0x41, 0x52, 0xaa, 0x02, 0x1b, 0x42, 0x75, 0x66, 0x2e, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x56, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0xca, 0x02, 0x1b, 0x42, 0x75, 0x66, 0x5c, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x5c, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5c, 0x56, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0xe2, 0x02, 0x27, 0x42, 0x75, 0x66, 0x5c, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x5c, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5c, 0x56, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x1e, 0x42, 0x75, 0x66, 0x3a, 0x3a, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x3a, 0x3a, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x3a, 0x3a, 0x56, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_buf_alpha_registry_v1alpha1_push_proto_rawDescOnce sync.Once file_buf_alpha_registry_v1alpha1_push_proto_rawDescData = file_buf_alpha_registry_v1alpha1_push_proto_rawDesc ) func file_buf_alpha_registry_v1alpha1_push_proto_rawDescGZIP() []byte { file_buf_alpha_registry_v1alpha1_push_proto_rawDescOnce.Do(func() { file_buf_alpha_registry_v1alpha1_push_proto_rawDescData = protoimpl.X.CompressGZIP(file_buf_alpha_registry_v1alpha1_push_proto_rawDescData) }) return file_buf_alpha_registry_v1alpha1_push_proto_rawDescData } var file_buf_alpha_registry_v1alpha1_push_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_buf_alpha_registry_v1alpha1_push_proto_goTypes = []interface{}{ (*PushRequest)(nil), // 0: buf.alpha.registry.v1alpha1.PushRequest (*PushResponse)(nil), // 1: buf.alpha.registry.v1alpha1.PushResponse (*v1alpha1.Module)(nil), // 2: buf.alpha.module.v1alpha1.Module (*LocalModulePin)(nil), // 3: buf.alpha.registry.v1alpha1.LocalModulePin } var file_buf_alpha_registry_v1alpha1_push_proto_depIdxs = []int32{ 2, // 0: buf.alpha.registry.v1alpha1.PushRequest.module:type_name -> buf.alpha.module.v1alpha1.Module 3, // 1: buf.alpha.registry.v1alpha1.PushResponse.local_module_pin:type_name -> buf.alpha.registry.v1alpha1.LocalModulePin 0, // 2: buf.alpha.registry.v1alpha1.PushService.Push:input_type -> buf.alpha.registry.v1alpha1.PushRequest 1, // 3: buf.alpha.registry.v1alpha1.PushService.Push:output_type -> buf.alpha.registry.v1alpha1.PushResponse 3, // [3:4] is the sub-list for method output_type 2, // [2:3] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_buf_alpha_registry_v1alpha1_push_proto_init() } func file_buf_alpha_registry_v1alpha1_push_proto_init() { if File_buf_alpha_registry_v1alpha1_push_proto != nil { return } file_buf_alpha_registry_v1alpha1_module_proto_init() if !protoimpl.UnsafeEnabled { file_buf_alpha_registry_v1alpha1_push_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PushRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_buf_alpha_registry_v1alpha1_push_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*PushResponse); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_buf_alpha_registry_v1alpha1_push_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 1, }, GoTypes: file_buf_alpha_registry_v1alpha1_push_proto_goTypes, DependencyIndexes: file_buf_alpha_registry_v1alpha1_push_proto_depIdxs, MessageInfos: file_buf_alpha_registry_v1alpha1_push_proto_msgTypes, }.Build() File_buf_alpha_registry_v1alpha1_push_proto = out.File file_buf_alpha_registry_v1alpha1_push_proto_rawDesc = nil file_buf_alpha_registry_v1alpha1_push_proto_goTypes = nil file_buf_alpha_registry_v1alpha1_push_proto_depIdxs = nil }
<filename>vtStorManaged/RunTimeDll.cpp<gh_stars>1-10 /* <License> Copyright 2015 Virtium Technology 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. </License> */ #include "RunTimeDll.h" namespace vtStor { namespace Managed { cRunTimeDll::cRunTimeDll(HMODULE Module, System::String^ ModulePath) { m_Module = Module; m_ModulePath = ModulePath; } cRunTimeDll::~cRunTimeDll() { this->!cRunTimeDll(); } cRunTimeDll::!cRunTimeDll() { if (!FreeLibrary(m_Module)) { throw gcnew System::Exception(System::String::Format("FreeLibrary failed to free '{0}'. Error code 0x{1:x}.", m_ModulePath, GetLastError())); } } FARPROC cRunTimeDll::GetFunction(LPCSTR name) { FARPROC function = GetProcAddress(m_Module, name); if (NULL == function) { throw gcnew System::Exception(System::String::Format("Failed to get '{0}' function. Error code 0x{1:x}.", gcnew System::String(name), GetLastError())); } return function; } } }
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class PrintQueue { private final Lock queueLock = new ReentrantLock(); public void printJob(String jobName) { queueLock.lock(); try { System.out.println("Printing " + jobName + "..."); Thread.sleep(1000); // Simulating the printing process } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.println(jobName + " has been printed."); queueLock.unlock(); } } } class Job implements Runnable { private PrintQueue printQueue; public Job(PrintQueue printQueue) { this.printQueue = printQueue; } @Override public void run() { for (int i = 0; i < 3; i++) { // Simulating multiple jobs per thread int priority = (int) (Math.random() * 10); // Generating random priority String jobName = Thread.currentThread().getName() + " - Job " + i + " (Priority " + priority + ")"; System.out.println("Adding " + jobName + " to the print queue."); printQueue.printJob(jobName); } } } public class Main { public static void main(String[] args) { PrintQueue printQueue = new PrintQueue(); Thread[] thread = new Thread[10]; for (int i = 0; i < 10; i++) { thread[i] = new Thread(new Job(printQueue), "Thread " + i); } for (int i = 0; i < 10; i++) { thread[i].start(); } } }
<filename>fastly/response_object_test.go package fastly import "testing" func TestClient_ResponseObjects(t *testing.T) { t.Parallel() var err error var tv *Version record(t, "response_objects/version", func(c *Client) { tv = testVersion(t, c) }) // Create var ro *ResponseObject record(t, "response_objects/create", func(c *Client) { ro, err = c.CreateResponseObject(&CreateResponseObjectInput{ ServiceID: testServiceID, ServiceVersion: tv.Number, Name: "test-response-object", Status: 200, Response: "Ok", Content: "abcd", ContentType: "text/plain", }) }) if err != nil { t.Fatal(err) } // Ensure deleted defer func() { record(t, "response_objects/cleanup", func(c *Client) { c.DeleteResponseObject(&DeleteResponseObjectInput{ ServiceID: testServiceID, ServiceVersion: tv.Number, Name: "test-response-object", }) c.DeleteResponseObject(&DeleteResponseObjectInput{ ServiceID: testServiceID, ServiceVersion: tv.Number, Name: "new-test-response-object", }) }) }() if ro.Name != "test-response-object" { t.Errorf("bad name: %q", ro.Name) } if ro.Status != 200 { t.Errorf("bad status: %q", ro.Status) } if ro.Response != "Ok" { t.Errorf("bad response: %q", ro.Response) } if ro.Content != "abcd" { t.Errorf("bad content: %q", ro.Content) } if ro.ContentType != "text/plain" { t.Errorf("bad content_type: %q", ro.ContentType) } // List var ros []*ResponseObject record(t, "response_objects/list", func(c *Client) { ros, err = c.ListResponseObjects(&ListResponseObjectsInput{ ServiceID: testServiceID, ServiceVersion: tv.Number, }) }) if err != nil { t.Fatal(err) } if len(ros) < 1 { t.Errorf("bad response objects: %v", ros) } // Get var nro *ResponseObject record(t, "response_objects/get", func(c *Client) { nro, err = c.GetResponseObject(&GetResponseObjectInput{ ServiceID: testServiceID, ServiceVersion: tv.Number, Name: "test-response-object", }) }) if err != nil { t.Fatal(err) } if ro.Name != nro.Name { t.Errorf("bad name: %q", ro.Name) } if ro.Status != nro.Status { t.Errorf("bad status: %q", ro.Status) } if ro.Response != nro.Response { t.Errorf("bad response: %q", ro.Response) } if ro.Content != nro.Content { t.Errorf("bad content: %q", ro.Content) } if ro.ContentType != nro.ContentType { t.Errorf("bad content_type: %q", ro.ContentType) } // Update var uro *ResponseObject record(t, "response_objects/update", func(c *Client) { uro, err = c.UpdateResponseObject(&UpdateResponseObjectInput{ ServiceID: testServiceID, ServiceVersion: tv.Number, Name: "test-response-object", NewName: String("new-test-response-object"), }) }) if err != nil { t.Fatal(err) } if uro.Name != "new-test-response-object" { t.Errorf("bad name: %q", uro.Name) } // Delete record(t, "response_objects/delete", func(c *Client) { err = c.DeleteResponseObject(&DeleteResponseObjectInput{ ServiceID: testServiceID, ServiceVersion: tv.Number, Name: "new-test-response-object", }) }) if err != nil { t.Fatal(err) } } func TestClient_ListResponseObjects_validation(t *testing.T) { var err error _, err = testClient.ListResponseObjects(&ListResponseObjectsInput{ ServiceID: "", }) if err != ErrMissingServiceID { t.Errorf("bad error: %s", err) } _, err = testClient.ListResponseObjects(&ListResponseObjectsInput{ ServiceID: "foo", ServiceVersion: 0, }) if err != ErrMissingServiceVersion { t.Errorf("bad error: %s", err) } } func TestClient_CreateResponseObject_validation(t *testing.T) { var err error _, err = testClient.CreateResponseObject(&CreateResponseObjectInput{ ServiceID: "", }) if err != ErrMissingServiceID { t.Errorf("bad error: %s", err) } _, err = testClient.CreateResponseObject(&CreateResponseObjectInput{ ServiceID: "foo", ServiceVersion: 0, }) if err != ErrMissingServiceVersion { t.Errorf("bad error: %s", err) } } func TestClient_GetResponseObject_validation(t *testing.T) { var err error _, err = testClient.GetResponseObject(&GetResponseObjectInput{ ServiceID: "", }) if err != ErrMissingServiceID { t.Errorf("bad error: %s", err) } _, err = testClient.GetResponseObject(&GetResponseObjectInput{ ServiceID: "foo", ServiceVersion: 0, }) if err != ErrMissingServiceVersion { t.Errorf("bad error: %s", err) } _, err = testClient.GetResponseObject(&GetResponseObjectInput{ ServiceID: "foo", ServiceVersion: 1, Name: "", }) if err != ErrMissingName { t.Errorf("bad error: %s", err) } } func TestClient_UpdateResponseObject_validation(t *testing.T) { var err error _, err = testClient.UpdateResponseObject(&UpdateResponseObjectInput{ ServiceID: "", }) if err != ErrMissingServiceID { t.Errorf("bad error: %s", err) } _, err = testClient.UpdateResponseObject(&UpdateResponseObjectInput{ ServiceID: "foo", ServiceVersion: 0, }) if err != ErrMissingServiceVersion { t.Errorf("bad error: %s", err) } _, err = testClient.UpdateResponseObject(&UpdateResponseObjectInput{ ServiceID: "foo", ServiceVersion: 1, Name: "", }) if err != ErrMissingName { t.Errorf("bad error: %s", err) } } func TestClient_DeleteResponseObject_validation(t *testing.T) { var err error err = testClient.DeleteResponseObject(&DeleteResponseObjectInput{ ServiceID: "", }) if err != ErrMissingServiceID { t.Errorf("bad error: %s", err) } err = testClient.DeleteResponseObject(&DeleteResponseObjectInput{ ServiceID: "foo", ServiceVersion: 0, }) if err != ErrMissingServiceVersion { t.Errorf("bad error: %s", err) } err = testClient.DeleteResponseObject(&DeleteResponseObjectInput{ ServiceID: "foo", ServiceVersion: 1, Name: "", }) if err != ErrMissingName { t.Errorf("bad error: %s", err) } }
import tkinter as tk from tkinter import ttk def reset_body_position(): # Implement the logic to reset the robot's body position pass def egg_wave(): # Implement the logic for the wave Easter egg action pass def egg_shake(): # Implement the logic for the shake Easter egg action pass def egg_twerk(): # Implement the logic for the twerk Easter egg action pass def egg_madison(): # Implement the logic for the Madison dance Easter egg action pass # Create the main window main_window = tk.Tk() main_window.title("Robot Control Panel") # Create tab for body parameters tab_body_params = ttk.Notebook(main_window) tab_body_params.pack() # Create scales for setting the target x, y, and z positions of the robot's body body_xpos = tk.Scale(tab_body_params, from_=-0.2, to_=0.3, resolution=0.01, orient='horizontal', label="Target x :") body_ypos = tk.Scale(tab_body_params, from_=-0.2, to_=0.3, resolution=0.01, orient='horizontal', label="Target y :") body_zpos = tk.Scale(tab_body_params, from_=-0.2, to_=0.3, resolution=0.01, orient='horizontal', label="Target z :") # Create a button to reset the robot's body position body_reset = ttk.Button(tab_body_params, text="Reset position", command=lambda: reset_body_position()) # Create tab for Easter egg actions tab_easter_eggs = ttk.Notebook(main_window) tab_easter_eggs.pack() # Add buttons for triggering Easter egg actions hello_button = ttk.Button(tab_easter_eggs, text='Wave', command=lambda: egg_wave()) shake_button = ttk.Button(tab_easter_eggs, text='Shake', command=lambda: egg_shake()) twerk_button = ttk.Button(tab_easter_eggs, text='Twerk', command=lambda: egg_twerk()) madison_button = ttk.Button(tab_easter_eggs, text='Madison Dance !', command=lambda: egg_madison()) # Create a labeled frame for displaying robot statistics robot_stats_group = tk.LabelFrame(main_window, text="Robot Statistics", relief='sunken', padx=5, pady=5) rob_stat_mode_text = tk.StringVar() rob_stat_mode_label = ttk.Label(robot_stats_group, textvariable=rob_stat_mode_text) # Pack the widgets tab_body_params.add(body_xpos, text="X Position") tab_body_params.add(body_ypos, text="Y Position") tab_body_params.add(body_zpos, text="Z Position") tab_body_params.add(body_reset, text="Reset Position") tab_easter_eggs.add(hello_button, text="Wave") tab_easter_eggs.add(shake_button, text="Shake") tab_easter_eggs.add(twerk_button, text="Twerk") tab_easter_eggs.add(madison_button, text="Madison Dance") rob_stat_mode_label.pack() robot_stats_group.pack() # Start the main loop main_window.mainloop()
def is_valid_parentheses(s: str) -> bool: stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping: if not stack or mapping[char] != stack.pop(): return False return not stack
#!/bin/bash # FPGA environment setup for oneAPI # Check if we are on a supported OS # We don't want to set up any FPGA environment variables in # such cases because they can break non-FPGA targets as well DISTRO=CentOS DISTRO_STATUS=$? RELEASE=8.1.1911 RELEASE_STATUS=$? SUPPORTED_OS=0 if [ $DISTRO_STATUS == 0 ] && [ $RELEASE_STATUS == 0 ]; then if [ "$DISTRO" == "RedHatEnterpriseServer" ] || [ "$DISTRO" == "CentOS" ] && [[ $RELEASE =~ ^7.[0-9]+ ]]; then SUPPORTED_OS=1 fi if [ "$DISTRO" == "Ubuntu" ] && [ "$RELEASE" == "18.04" ]; then SUPPORTED_OS=1 fi fi # realpath is used in other oneAPI components but it is not available in RHEL6 # Using 'readlink -e' instead SCRIPTDIR=$(readlink -e $(dirname "${BASH_SOURCE[0]}")) if [ "${BASH_SOURCE[0]}" == "$0" ]; then echo "Proper usage: source fpgavars.sh" exit 1 fi icdadd() { if [ -z $OCL_ICD_FILENAMES ]; then export OCL_ICD_FILENAMES="$1" else # For non-empty, only add if not already there if [[ ":$OCL_ICD_FILENAMES:" != *":$1:"* ]]; then export OCL_ICD_FILENAMES="$1:$OCL_ICD_FILENAMES" fi fi } if [ $SUPPORTED_OS -eq 1 ]; then icdadd "libalteracl.so" icdadd "libintelocl_emu.so" export ACL_BOARD_VENDOR_PATH=/opt/Intel/OpenCLFPGA/oneAPI/Boards source ${SCRIPTDIR}/init_opencl.sh > /dev/null #Configure the PAC system for BSP in intel_a10gx_pac intel_s10sx_pac; do if [ -f ${INTEL_FPGA_ROOT}/board/${BSP}/linux64/libexec/pac_bsp_init.sh ]; then ${INTEL_FPGA_ROOT}/board/${BSP}/linux64/libexec/pac_bsp_init.sh elif [ -f ${INTELFPGAOCLSDKROOT}/board/${BSP}/linux64/libexec/pac_bsp_init.sh ]; then ${INTELFPGAOCLSDKROOT}/board/${BSP}/linux64/libexec/pac_bsp_init.sh fi done fi
export const en = { 'redpackets': { /********** * Generic * ***********/ 'red-packets': 'Red Packets', 'red-packet': 'Red Packet', 'view-all': 'View all', 'continue': 'Continue', /************* * Components * **************/ 'expired': 'Expired', 'few-minutes-left': "A few minutes left", 'n-hours-left': "{{ hours }} hours left", 'n-days-left': "{{ days }} days left", 'enter-captcha-placeholder': 'Enter the captcha to open packet', 'wrong-captcha': 'Wrong captcha, please try again', 'error-captcha-is-required': 'Please type the captcha to continue', 'not-active-yet': 'Not active yet', 'ip-rate-limitation': 'Hey, don\'t grab packets too quickly, please wait a few minutes', /******* * Home * ********/ 'public-packets': 'Public packets', 'no-public-packet': 'No public packets available at the moment', 'my-packets': 'My packets', 'create-new-packet': 'Create new packet', 'no-my-packet': 'You haven\'t created any packet yet', 'opened-packets': 'Opened packets', 'about-red-packets': 'About Red Packets', 'about-red-packets-part-1': 'Traditionally used in China to celebrate special occasions and share happiness among friends, red packets are derived from this idea in Elastos Essentials to celebrate, but also to create entertainment for crypto communities.', 'about-red-packets-part-2': 'Red packets introduce much more fun compared to “airdrops”, as luck and reactivity are involved.', /************* * New packet * **************/ 'new-red-packet-title': 'New Red Packet', 'unsupported-network-intro': 'Red packets are unsupported for this network. Please select another one.', 'quantity': 'Quantity', 'quantity-hint': 'Total number of packets that can be grabbed by others.', 'token': 'Token', 'token-hint': 'Type of token won by users when opening red packets.', 'amount': 'Amount', 'amount-hint': 'Total number of tokens that will be distributed randomly or equally.', 'distribution': 'Distribution', 'distribution-hint': 'Choose to give the same number of tokens to all users, or random amounts.', 'distribution-fixed': 'Same value in all packets', 'distribution-random': 'Random packet values', 'distribution-random-info': '* Winning users will receive random amounts of {{ token }}.', 'distribution-fixed-info': '* All winning users will receive {{ value }} {{ token }}.', 'probability': 'Probability', 'probability-hint': 'If there are remaining packets, probability to get one. After losing, a user cannot try again.', 'visibility': 'Visibility', 'visibility-hint': 'Choose to let only users with the packet link grab packets, or make your red packet public. Public red packets appear on the Essentials home screen, can be used to promote a project, but cost a bit more.', 'visibility-link-only': 'Users with link only', 'visibility-public': 'Public', 'duration': 'Duration', 'duration-hint': 'After a few days, the red packet becomes inactive and unspent funds are returned to you. Max 7 days.', 'expiration-days': 'Days', 'about-you': 'About you', 'profile-hint': 'If published, your avatar and name will be seen by others.', 'message': 'Message', 'packet-message-placeholder': 'Happy Chinese New Year to you', 'theme': 'Theme', 'theme-hint': 'Choose to customize the visual appearance of opened red packets, for special events.', 'theme-default': 'Default', 'theme-christmas': 'Christmas', 'theme-summer_holidays': 'Summer Holidays', 'theme-cny': 'Chinese New Year', 'error-invalid-number-of-packets': 'Invalid number of packets', 'error-invalid-number-of-tokens': "Invalid number of tokens to distribute", 'error-invalid-probability': "Invalid probability. Use a 0-100 value", 'error-invalid-expiration-time': "Invalid expiration time. Use 1-7 days", 'error-no-message': "Be kind with your people, send them a nice message!", 'error-packet-creation-failed': "The packet could not be created. Please try again later", 'technical-preview-title': 'Note: Technical Preview', 'technical-preview-info': 'The red packet service was recently launched and this is still a technical release. Make sure to create only red packets with small amounts of tokens.', /*********** * Settings * ************/ 'settings-title': 'Settings', 'profile-visibility': 'Profile Visibility', 'profile-visibility-hint': 'Send my Elastos DID profile when grabbing red packets', /***************** * Packet details * ******************/ 'grabbing-packet': 'Trying to grab a packet... Please wait', 'packet-is-live': 'Your packet is now live!', 'packet-is-not-live': 'Your packet is not live yet!', 'this-packet-is-not-live': 'This packet is not live yet', 'packet-is-expired': 'This packet is expired', 'error-retrieve-packet': 'Unable to retrieve red packet information, please retry later.', 'grab-me': 'Grab me!', 'grab-packet': 'Grab packet', 'anonymous-offering': 'A generous anonymous friend is offering some', 'anonymous-offered-you': 'A generous anonymous friend just offered you', 'creator-offering': '<b>{{ creator }}</b> is offering some', 'grab-lost': 'No luck this time!', 'grab-too-late': 'Too late, someone was faster at grabbing this one, no more packets...', 'grab-too-late-2': 'Too late, no more packets...', 'information': 'Information', 'distributed-packets': 'Packets', 'n-packets': '{{ packets }} packets', 'distributed-tokens': 'Tokens', 'n-tokens': '{{ tokens }} {{ symbol }}', 'distribution-model': 'Model', 'probability-to-win': 'Probability to win', 'most-recent-winners': 'Most Recent Winners', 'fetching-winners': 'Getting the winners', 'no-winner': 'All the winners will be listed here', 'complete-payment': 'Complete payment', 'date-time-at': 'at', 'creator-sent-you': '{{ creator }} sent you', 'you-grabbed': 'Congratulations, you grabbed', 'random': 'Random', 'fixed-amounts': 'Fixed amounts', 'anonymous': "Anonymous", 'packet-url-copied': "Packet URL copied to clipboard, you can now share it!", 'packet-share-title': "A red packet for you!", 'got-it': 'You\'ve grabbed a packet! Tokens will arrive in your wallet soon', 'copy-link': 'Copy link', 'share-link': 'Share link', 'no-user-wallet': 'You currently don\'t have any wallet. Please create or import a wallet in Essentials in order to grab packets or to create your own packets.', 'packet-cancelled': 'This packet has been cancelled, probably because of a payment error. Funds will be returned or have already been returned to the packet creator.', 'test-network-title': 'This is a test network!', 'test-network-info': 'This red packet was created on a test network. Tokens will be transferred but have no value. Make sure to share this packet only with testers.', /****** * Pay * *******/ 'payment-title': 'Payment', 'getting-packet-info': 'Getting packet information, please wait', 'balance-not-enough': 'Current balance of {{ currentTokens }} {{ symbol }} is not enough to pay {{ targetTokens }} {{ symbol }}', 'process': 'Process', 'step-n': 'Step {{ step }}', 'send-n-tokens': 'Send {{ amount }} {{ symbol }}', 'n-tokens-sent': '{{ amount }} {{ symbol }} sent!', 'payment-confirmation-error': 'The payment could not be confirmed. This red packet will be cancelled and refunded, please try to create another. Reason: ', 'balance-n-tokens': 'Balance: {{ amount }} {{ symbol }}', 'packet-is-live-pay': 'The Red Packet is live', 'total-symbol': 'Total {{ symbol }}', 'transaction-fees': 'Transaction fees', 'service-fees': 'Service Fees', 'public-option-fees': 'Option: public packet', 'note': 'Note', 'unspent-tokens-refunded': 'Unspent tokens and provisionning fees are returned at the expiration of the red packet.', 'view-packet': 'View packet', 'base-service-fee-info': 'Base service fee of ${{ baseFee }}, paid in {{ symbol }}.', 'public-service-fee-info': 'Additional public packet option at ${{ publicFee }}, paid in {{ symbol }}, plus {{ publicFeePercentage }}% of the total {{ packetSymbol }} in the packet.', 'transaction-fees-info': 'Transaction fees are estimated based on the number of packets the service will send to winners.' } }
/** * @description: XxxxReq为接口入参封装,XxxxVO为接口出参封装。 * 查询接口的入参,统一用XxxxCriteria * @author: <EMAIL> * @date: 2021/05/28 */ package com.tuya.iot.suite.web.model;
'use strict'; var allStores = []; var hoursOfOperation = [ '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm' ]; var totalCookiesByHour = []; //initialize totalCookiesByHour array with zeros for (let i = 0; i < hoursOfOperation.length; i++) { totalCookiesByHour.push(0); } function CookieStore(storeName, displayName, minCust, maxCust, cookiesPerSale) { this.storeName = storeName; this.displayedName = displayName; this.minCust = minCust; this.maxCust = maxCust; this.cookiesPerHour = []; this.cookiesPerSale = cookiesPerSale; this.custPerHour = []; this.totalCookies = 0; allStores.push(this); // methods follow: //generate a random number of customers per hour based on location min/max this.generateCustomerLoad = function() { let custPossible = this.maxCust - this.minCust; return Math.floor(Math.random() * (custPossible + 1)) + this.minCust; }; //generate cookies per hour based on customers per hour and hours of operation this.getCookiesPerHour = function() { for (let i = 0; i < hoursOfOperation.length; i++) { let numCookies = Math.ceil( this.generateCustomerLoad() * this.cookiesPerSale ); this.cookiesPerHour.push(numCookies); this.totalCookies += numCookies; totalCookiesByHour[i] += numCookies; } }; //add its row to the table this.render = function() { let parentTable = document.getElementById('storesTable'); let tblRow = document.createElement('tr'); modifyDom(tblRow, 'th', this.displayedName); for (let i = 0; i < hoursOfOperation.length; i++) { modifyDom(tblRow, 'td', this.cookiesPerHour[i]); } modifyDom(tblRow, 'td', this.totalCookies); parentTable.appendChild(tblRow); }; this.getCookiesPerHour(); } //end of CookieStore contstructor //instantiate the cookie stores new CookieStore('firstPike', 'First and Pike', 23, 65, 6.3); new CookieStore('seaTac', 'SeaTac Airport', 3, 24, 1.2); new CookieStore('seaCenter', 'Seattle Center', 11, 38, 3.7); new CookieStore('capHill', 'Capitol Hill', 20, 38, 2.3); new CookieStore('alki', 'Alki', 2, 16, 4.6); //helper function to add an element to the dom var modifyDom = function( parent, childType, content, tagId = null, tagClass = null ) { let parentEl = parent; let childEl = document.createElement(childType); if (tagId) { childEl.setAttribute('id', tagId); } else if (tagClass) { childEl.setAttribute('class', tagClass); } childEl.innerText = content; parentEl.appendChild(childEl); }; //helper function to toal all cookies at all locations function sumAllCookies() { let sum = 0; totalCookiesByHour.forEach(value => (sum += value)); return sum; } //function to create the table by calling functions that create the parts of the table function createTable() { createTableHeader(); allStores.forEach(item => item.render()); createTableFooter(); } //creates the table header row function createTableHeader() { let parentTable = document.getElementById('storesTable'); let tblHeader = document.createElement('thead'); modifyDom(tblHeader, 'th', 'Locations'); for (let i = 0; i < hoursOfOperation.length; i++) { modifyDom(tblHeader, 'th', hoursOfOperation[i]); } modifyDom(tblHeader, 'th', 'Totals'); parentTable.appendChild(tblHeader); } //creates footer row function createTableFooter() { let parentTable = document.getElementById('storesTable'); let tblFooter = document.createElement('tfoot'); modifyDom(tblFooter, 'th', 'Totals'); for (let i = 0; i < totalCookiesByHour.length; i++) { modifyDom(tblFooter, 'th', totalCookiesByHour[i]); } modifyDom(tblFooter, 'th', sumAllCookies()); parentTable.appendChild(tblFooter); } //Executable code// createTable(); //event handling for form let formEl = document.getElementById('storeInput'); formEl.addEventListener('submit', function(event) { event.preventDefault(); new CookieStore( event.target[1].value, event.target[2].value, Number(event.target[3].value), Number(event.target[4].value), Number(event.target[5].value) ); let tableEl = document.getElementById('storesTable'); tableEl.innerHTML = ''; document.getElementById('storeInput').reset(); createTable(); });
import re def keep_lazy_text(func): # Assume this function is provided for use pass class NodeRenderer: def __init__(self, nodelist): # Initialize the class with the given list of nodes self.nodelist = nodelist def render(self, context): # Implement the rendering logic according to the specified requirements strip_line_breaks = keep_lazy_text( lambda x: re.sub(r'[\n]+', '\n', x) ) return strip_line_breaks(self.nodelist.render(context).strip())
import React, { useCallback, useMemo } from 'react'; import { TextField } from '@/components/core/Form'; import { Stack } from '@/components/UI/Stack'; import { useFocusIdx } from '@/hooks/useFocusIdx'; import { useBlock } from '@/hooks/useBlock'; import { BasicType } from '@/constants'; import { getParentByIdx } from '@/utils/block'; export function Width() { const { focusIdx, } = useFocusIdx(); const { focusBlock, values } = useBlock(); const parentType = getParentByIdx(values, focusIdx)?.type; const validate = useCallback((val: string): string | undefined => { if (focusBlock?.type === BasicType.COLUMN && parentType === BasicType.GROUP) { return /(\d)*%/.test(val) ? undefined : 'Column inside a group must have a width in percentage, not in pixel'; } return undefined; }, [focusBlock?.type, parentType]); return useMemo(() => { return ( <Stack wrap={false}> <Stack.Item fill> <TextField validate={validate} label='Width' name={`${focusIdx}.attributes.width`} inline quickchange /> </Stack.Item> </Stack> ); }, [focusIdx, validate]); }
<reponame>wuximing/dsshop "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ellipsisLabel = exports.testLabel = exports.getLabelLength = exports.getMaxLabelWidth = void 0; var util_1 = require("@antv/util"); var text_1 = require("./text"); var ELLIPSIS_CODE = '\u2026'; var ELLIPSIS_CODE_LENGTH = 2; // 省略号的长度 /** 获取最长的 label */ function getMaxLabelWidth(labels) { var max = 0; util_1.each(labels, function (label) { var bbox = label.getBBox(); var width = bbox.width; if (max < width) { max = width; } }); return max; } exports.getMaxLabelWidth = getMaxLabelWidth; /** 获取label长度 */ function getLabelLength(isVertical, label) { var bbox = label.getCanvasBBox(); return isVertical ? bbox.width : bbox.height; } exports.getLabelLength = getLabelLength; /* label长度是否超过约束值 */ function testLabel(label, limitLength) { return label.getBBox().width < limitLength; } exports.testLabel = testLabel; /** 处理 text shape 的自动省略 */ function ellipsisLabel(isVertical, label, limitLength, position) { if (position === void 0) { position = 'tail'; } var text = label.attr('text'); var labelLength = getLabelLength(isVertical, label); var codeLength = text_1.strLen(text); var ellipsised = false; if (limitLength < labelLength) { var reseveLength = Math.floor((limitLength / labelLength) * codeLength) - ELLIPSIS_CODE_LENGTH; // 计算出来的应该保存的长度 var newText = void 0; if (reseveLength >= 0) { newText = text_1.ellipsisString(text, reseveLength, position); } else { newText = ELLIPSIS_CODE; } if (newText) { label.attr('text', newText); ellipsised = true; } } if (ellipsised) { label.set('tip', text); } else { label.set('tip', null); } return ellipsised; } exports.ellipsisLabel = ellipsisLabel; //# sourceMappingURL=label.js.map
# basics setopt AUTO_CD # if you type foo, and it isn't a command, and it is a directory in your cdpath, go there # history setopt APPEND_HISTORY # allow multiple terminal sessions to all append to one zsh command history setopt EXTENDED_HISTORY # include more information about when the command was executed, etc setopt HIST_FIND_NO_DUPS # when searching history don't display results already cycled through twice setopt HIST_IGNORE_DUPS # do not write events to history that are duplicates of previous events setopt HIST_IGNORE_ALL_DUPS # do not write events to history that are duplicates of previous events setopt HIST_IGNORE_SPACE # do not save history for commanding beginning with a space setopt HIST_REDUCE_BLANKS # remove extra blanks from each command line being added to history setopt INC_APPEND_HISTORY # add comamnds as they are typed, don't wait until shell exit # completion setopt ALWAYS_TO_END # when completing from the middle of a word, move the cursor to the end of the word setopt COMPLETE_IN_WORD # allow completion from within a word/phrase setopt LIST_PACKED # make the completion list take less lines with variable width columns # prompt setopt AUTO_MENU # automatically use menu completion after the second consecutive request for completion setopt PROMPT_SUBST # enable parameter expansion, command substitution, and arithmetic expansion in the prompt
<reponame>javifm86/hugo-site // Colors for console.log messages module.exports.COLORS = { black: '\x1b[30m', red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', blue: '\x1b[34m', magenta: '\x1b[35m', cyan: '\x1b[36m', white: '\x1b[37m' }; /** * Convert Windows backslash paths to slash paths. * @param {string} path */ module.exports.converToSlash = path => { const isExtendedLengthPath = /^\\\\\?\\/.test(path); const hasNonAscii = /[^\u0000-\u0080]+/.test(path); if (isExtendedLengthPath || hasNonAscii) { return path; } return path.replace(/\\/g, '/'); };
""" Generate a set of C++ structures to represent a list of customers, each of which contains their name, address and phone numbers """ struct Customer { string name; string addr; string phone; }; std::vector<Customer> customers;
<reponame>invinst/CPDB from rest_framework import authentication class SessionAuthentication(authentication.SessionAuthentication): def enforce_csrf(self, request): return
#!/bin/bash sudo sed -i '/^#\sdeb-src /s/^#//' /etc/apt/sources.list sudo apt-get -y build-dep linux linux-image-$(uname -r) sudo apt-get install -y git vim dpkg-dev flex bison libncurses-dev \ gawk flex dwarves bison openssl libssl-dev dkms libelf-dev libudev-dev libpci-dev libiberty-dev autoconf fakeroot
#!/bin/bash ENV=$1 NAMESPACE=$2 kubectl create configmap secondbaser-config-map --from-file=config/conf/$ENV.json -n $NAMESPACE
package sharethis // import "github.com/otremblay/sharethis" import ( "crypto/sha256" "fmt" "log" "os" "os/user" "path/filepath" "golang.org/x/crypto/ssh" ) type FileReq struct { Path string ShareCount uint Username string Hostname string ServerConn *ssh.ServerConn fileurl string httpport string remotehost string localpath string filename string IsDir bool } func NewFileReq(path, httpport, remotehost string, shareCount uint) *FileReq { return getFileReq(DefaultPrefixFn, path, httpport, remotehost, shareCount) } func (fr *FileReq) RebuildUrls() { fr = getFileReq(DefaultPrefixFn, fr.localpath, fr.httpport, fr.remotehost, fr.ShareCount) } func (fr *FileReq) String() string { if fr.IsDir { return fmt.Sprintf("%s\n%s", fr.fileurl+".tar", fr.fileurl+".zip") } else { return fmt.Sprintf(fr.fileurl) } } func getRemotePath(prefixFn func() string, path string) string { fullpath := fmt.Sprintf("%s:%s", prefixFn(), path) hashedpath := fmt.Sprintf("%x", sha256.Sum256([]byte(fullpath))) return fmt.Sprintf("%s/%s", hashedpath, filepath.Base(path)) } func getFileReq(prefixFn func() string, path string, httpport string, remotehost string, sharecount uint) *FileReq { var dir bool if fs, err := os.Stat(path); err != nil { log.Fatalln("Can't read file") } else { p, err := filepath.Abs(fs.Name()) if err != nil { log.Fatalln("Can't read file") } dir = fs.IsDir() path = p } remotepath := getRemotePath(prefixFn, path) var fileurl string if httpport == "443" { fileurl = fmt.Sprintf("https://%s/%s", remotehost, remotepath) } else if httpport == "80" { fileurl = fmt.Sprintf("http://%s/%s", remotehost, remotepath) } else { fileurl = fmt.Sprintf("http://%s:%s/%s", remotehost, httpport, remotepath) } return &FileReq{Path: remotepath, ShareCount: sharecount, fileurl: fileurl, localpath: path, IsDir: dir} } var DefaultPrefixFn = func() string { hostname, err := os.Hostname() if err != nil { fmt.Fprintln(os.Stderr, "Could not get hostname with os.Hostname()") hostname = "unknown" } var username string userobj, err := user.Current() if err != nil { fmt.Fprintln(os.Stderr, "Could not get user with user.Current()") username = "unknown" } else { username = userobj.Username } return fmt.Sprintf("%s@%s", username, hostname) }
package main; public class TwoNumbersCombinations { public static void main(String[] args) { final int MINIMUM_NUMBER = 1; final int MAXIMUM_NUMBER = 7; int totalCombinations = 0; for (int firstNumber = MINIMUM_NUMBER; firstNumber < MAXIMUM_NUMBER; firstNumber++) { for (int secondNumber = firstNumber + 1; secondNumber <= MAXIMUM_NUMBER; secondNumber++) { System.out.println(firstNumber + " " + secondNumber); totalCombinations++; } } System.out.println("Keep picking two numbers between " + MINIMUM_NUMBER + " and " + MAXIMUM_NUMBER + " yields " + totalCombinations + " combinations"); } }
(function() { 'use strict'; angular .module('app.station') .controller('StationSensorInfoDialogController', StationSensorInfoDialogController); StationSensorInfoDialogController.$inject = ['$mdDialog', 'sensor', 'StationSensorsFactory']; function StationSensorInfoDialogController($mdDialog, sensor, StationSensorsFactory) { var vm = this; vm.cancel = cancel; vm.sensor = sensor; vm.sensorGroups = []; vm.sensorParmeters = []; activate(); function activate() { getParametersBySensor() .then(function(data) { vm.sensorParameters = data; return vm.sensorParameters; }); getGroupsBySensor() .then(function(data) { vm.sensorGroups = data; return vm.sensorGroups; }); } function cancel() { $mdDialog.cancel(); }; function getGroupsBySensor() { return StationSensorsFactory.getSensorGroups(vm.sensor.sensor_id) .then(function(response) { return response.data; }); } function getParametersBySensor() { return StationSensorsFactory.getSensorParameters(vm.sensor.sensor_id) .then(function(response) { return response.data; }); } } })();
<filename>OntoSeer/src/main/java/edu/stanford/bmir/protege/examples/menu/ToolsMenu1.java package edu.stanford.bmir.protege.examples.menu; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import org.protege.editor.owl.ui.action.ProtegeOWLAction; public class ToolsMenu1 extends ProtegeOWLAction { public void initialise() throws Exception { } public void dispose() throws Exception { } public void actionPerformed(ActionEvent event) { StringBuilder message = new StringBuilder("This example menu item is under the Tools menu.\n"); message.append("The currently selected class is "); message.append(getOWLWorkspace().getOWLSelectionModel().getLastSelectedClass()); message.append("."); JOptionPane.showMessageDialog(getOWLWorkspace(), message.toString()); } }
/******************************************************************************* * 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. *******************************************************************************/ /* This file has been modified by Open Source Strategies, Inc. */ package org.ofbiz.shark.tool; import java.util.Map; import java.util.HashMap; import org.ofbiz.shark.container.SharkContainer; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.ServiceUtil; import org.ofbiz.base.util.Debug; import org.enhydra.shark.toolagent.AbstractToolAgent; import org.enhydra.shark.api.internal.toolagent.ToolAgentGeneralException; import org.enhydra.shark.api.internal.toolagent.ApplicationBusy; import org.enhydra.shark.api.internal.toolagent.ApplicationNotDefined; import org.enhydra.shark.api.internal.toolagent.ApplicationNotStarted; import org.enhydra.shark.api.internal.toolagent.AppParameter; import org.enhydra.shark.api.SharkTransaction; import org.enhydra.shark.xpdl.XPDLConstants; import org.enhydra.shark.xpdl.elements.ExtendedAttributes; /** * Shark Service Engine Agent Tool API */ public class ServiceEngineAgent extends AbstractToolAgent { public static final String module = ServiceEngineAgent.class.getName(); public void invokeApplication (SharkTransaction trans, long handle, String applicationName, String procInstId, String actInstId, AppParameter[] parameters, Integer appMode) throws ApplicationNotStarted, ApplicationNotDefined, ApplicationBusy, ToolAgentGeneralException { super.invokeApplication(trans, handle, applicationName, procInstId, actInstId, parameters, appMode); // set the status status = APP_STATUS_RUNNING; // prepare the service LocalDispatcher dispatcher = SharkContainer.getDispatcher(); Map serviceContext = new HashMap(); this.getServiceContext(parameters, serviceContext); // invoke the service Map serviceResult = null; try { serviceResult = dispatcher.runSync(appName, serviceContext); } catch (GenericServiceException e) { status = APP_STATUS_INVALID; Debug.logError(e, module); throw new ToolAgentGeneralException(e); } // process the result this.getServiceResults(parameters, serviceResult); // check for errors if (ServiceUtil.isError(serviceResult)) { status = APP_STATUS_INVALID; } else { status = APP_STATUS_FINISHED; } } private void getServiceContext(AppParameter[] params, Map context) { if (params != null && context != null) { for (int i = 1; i < params.length; i++) { if (params[i].the_mode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_IN) || params[i].the_mode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_INOUT)) { context.put(params[i].the_formal_name, params[i].the_value); } } } } private void getServiceResults(AppParameter[] params, Map result) { if (params != null && result != null) { for (int i = 1; i < params.length; i++) { if (params[i].the_mode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_OUT) || params[i].the_mode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_INOUT)) { params[i].the_value = result.get(params[i].the_formal_name); } } } } protected ExtendedAttributes readParamsFromExtAttributes (String extAttribs) throws Exception { ExtendedAttributes eas = super.readParamsFromExtAttributes(extAttribs); return eas; } }
#!/usr/bin/env bash STATE=$(nmcli networking connectivity) function tagMail { echo "Running tag additions to tag new mail" # # github # notmuch tag +github -- from:notifications@github.com AND tag:new # notmuch tag +github -- from:noreply@github.com AND tag:new notmuch tag -inbox -- tag:new AND subject:"Steam wishlist" AND from:"noreply@steampowered.com" notmuch tag -inbox -- tag:new AND tag:promotions # # CI # notmuch tag +CI -- from:builds@travis-ci.com AND tag:new # notmuch tag +CI -- from:builds@circleci.com AND tag:new # notmuch tag -inbox -- tag:CI AND subject:Passed # UCSB notmuch tag +flagged +important -- tag:new AND from:"laura reynolds" AND to:"karthik chikmagalur" notmuch tag +ucsb -- tag:new AND from:"ucsb.edu" AND to:"karthik chikmagalur" # TA stuff notmuch tag +TA -- tag:new AND '(subject:163 OR subject:ME163)' AND date:"01/01/2021".. # Mailing Lists notmuch tag +grad/ccdc -- tag:new AND from:ccdc-admin notmuch tag +list/emacs -inbox -- tag:new AND from:help-gnu-emacs-request@gnu.org notmuch tag +list/emacs -inbox -- tag:new AND to:emacs-devel@gnu.org notmuch tag +list/github -- tag:new AND from:notifications@github.com notmuch tag +list/matlab-emacs -- tag:new AND from:matlab-emacs-discuss@lists.sourceforge.net # notmuch tag +list/IPFS -inbox -- from:newsletter@ipfs.io AND tag:new # notmuch tag +list/rust -inbox -- from:twir@rust-lang.org AND tag:new # notmuch tag +list/nixos -inbox -- from:domen@enlambda.com AND tag:new # Training notmuch tag +training -important -- tag:new AND from:"swoletron@truecoach.co" # Money notmuch tag +money -important -inbox -- tag:new AND from:ealerts.bankofamerica.com AND subject:"your statement" # Sent mail is considered read notmuch tag -unread -- tag:new AND tag:sent } function untagMail { # Remove new notmuch tag -new -- tag:new } function notifyMail { gmail_new=$(notmuch count tag:inbox AND tag:new AND folder:gmail/mail) ucsb_new=$(notmuch count tag:inbox AND tag:new AND folder:ucsb/mail) if [ $gmail_new -ne 0 ]; then notify-send "Gmail: $gmail_new new emails" fi if [ $ucsb_new -ne 0 ]; then notify-send "UCSB: $ucsb_new new emails" fi } if [ $STATE = 'full' ]; then echo "Syncing ucsb" cd "$HOME/.local/share/mail/ucsb/" gmi sync echo "Syncing gmail" cd "$HOME/.local/share/mail/gmail/" gmi sync # echo "Checking school" # Non gmail email # mbsync -V school echo "Running notmuch new" notmuch new echo "Tagging mail" tagMail echo "Sending notification" notifyMail echo "Removing ~new~ tag " untagMail exit 0 fi echo "No internet connection." exit 0
let item= [] $(document).ready(function () { const urlNews = "https://www.jsonbulut.com/json/news.php"; const urlObjNews = { ref:"51152bdc1f6fcae3e24bf21c819b02f6", start:"0", } $.ajax({ type: "get", url: urlNews, data: urlObjNews, dataType: "json", success: function (response) { const items= response.News[0].Haber_Bilgileri; item=items; let html=`` for (let i = 0; i < items.length; i++) { console.log(`item`, item) html +=` <div class="col-xl-4 col-lg-4 col-md-6 col-6 card urunKart urunKartHaber" > <img src="`+items[i].picture+`" class="card-img-top" alt="img/no.jpg"> <div class="card-body"> <h5 class="card-title">`+items[i].title.slice(0,15)+`...</h5> <p class="card-text">`+items[i].s_description.slice(0,45)+"..."+`</p> <a onclick="fncClick(${i})" href="newsInfo.html" class="btn btn-dark">Detay</a> </div> </div> ` } $('#rowHaberKartlar').append(html); } }); }); function fncClick(i) { let itempage = JSON.stringify(item[i]); localStorage.removeItem("productInfo"); sessionStorage.removeItem("productInfo"); localStorage.setItem("productInfo", itempage); sessionStorage.setItem("productInfo", itempage); window.location.href = "newsInfo.html"; }
<reponame>Real-Currents/heroku-wp /* global tinymce */ tinymce.PluginManager.add( 'ecwid', function( editor ) { var toolbarActive = false; function editStore( img ) { ecwid_open_store_popup(); } function removeImage( node ) { var wrap; if ( node.nodeName === 'DIV' && editor.dom.hasClass( node, 'ecwid-store-wrap' ) ) { wrap = node; } else if ( node.nodeName === 'IMG' || node.nodeName === 'DT' || node.nodeName === 'A' ) { wrap = editor.dom.getParent( node, 'div.ecwid-store-wrap' ); } if ( wrap ) { if ( wrap.nextSibling ) { editor.selection.select( wrap.nextSibling ); } else if ( wrap.previousSibling ) { editor.selection.select( wrap.previousSibling ); } else { editor.selection.select( wrap.parentNode ); } editor.selection.collapse( true ); editor.nodeChanged(); editor.dom.remove( wrap ); } else { editor.dom.remove( node ); } removeToolbar(); editor.dom.remove(editor.dom.select('#ecwid-edit-store-button')); } function addToolbar( node ) { var rectangle, toolbarHtml, toolbar, left, dom = editor.dom; removeToolbar(node); // Don't add to other images if ( ! node || node.nodeName !== 'IMG' || node.className.indexOf('ecwid-store-editor') == -1 ) { return; } dom.setAttrib( node, 'data-ecwid-store-select', 1 ); rectangle = dom.getRect( node ); toolbarHtml = '<div class="dashicons dashicons-no-alt remove" data-mce-bogus="1"></div>'; toolbar = dom.create( 'div', { 'id': 'ecwid-store-toolbar', 'data-mce-bogus': '1', 'contenteditable': false }, toolbarHtml ); if ( editor.rtl ) { left = rectangle.x + rectangle.w - 82; } else { left = rectangle.x; } editor.getBody().appendChild( toolbar ); dom.setStyles( toolbar, { top: rectangle.y, left: left }); toolbarActive = true; } this.addToolbar = function() { addToolbar( jQuery(editor.dom.doc.body).find('.ecwid-store-editor').get(0) ); } function removeToolbar(parentNode) { if (parentNode && editor.dom.getAttrib( parentNode, 'class') == 'ecwid-store-editor' ) { var toolbar = editor.dom.get( 'wp-image-toolbar' ); if ( toolbar ) { editor.dom.remove( toolbar ); } } var toolbar = editor.dom.get( 'ecwid-store-toolbar' ); if ( toolbar ) { editor.dom.remove( toolbar ); } // also remove image toolbar editor.dom.setAttrib( editor.dom.select( 'img[data-ecwid-store-select]' ), 'data-ecwid-store-select', null ); toolbarActive = false; } editor.onInit.add(function(editor) { dom = editor.dom; dom.bind( editor.getDoc(), 'dragstart', function( event ) { var node = editor.selection.getNode(); // Prevent dragging images out of the caption elements if ( node.nodeName === 'IMG' && dom.getParent( node, '.wp-caption' ) ) { event.preventDefault(); } // Remove toolbar to avoid an orphaned toolbar when dragging an image to a new location removeToolbar(); }); }); editor.onKeyUp.add( function( editor, event ) { var node, wrap, P, spacer, selection = editor.selection, keyCode = event.keyCode, dom = editor.dom; if ( keyCode === 46 || keyCode === 8 ) { checkEcwid(); } }); editor.onKeyDown.add( function( editor, event ) { var node, wrap, P, spacer, selection = editor.selection, keyCode = event.keyCode, dom = editor.dom; if ( keyCode == 27 ) { jQuery('#ecwid-store-popup-content').removeClass('open'); return false; } if ( keyCode === 46 || keyCode === 8 ) { node = selection.getNode(); if ( node.nodeName === 'DIV' && dom.hasClass( node, 'ecwid-store-wrap' ) ) { wrap = node; } else if ( node.nodeName === 'IMG' ) { wrap = dom.getParent( node, 'div.ecwid-store-wrap' ); } if ( wrap ) { dom.events.cancel( event ); removeImage( node ); editor.dom.remove(editor.dom.select('#ecwid-edit-store-button')); return false; } removeToolbar(); } // Key presses will replace the image so we need to remove the toolbar if ( toolbarActive ) { if ( event.ctrlKey || event.metaKey || event.altKey || ( keyCode < 48 && keyCode > 90 ) || keyCode > 186 ) { return; } removeToolbar(); editor.dom.remove(editor.dom.select('#ecwid-edit-store-button')); } }); editor.onMouseDown.add( function( editor, event ) { if ( editor.dom.getParent( event.target, '#ecwid-store-toolbar' ) ) { if ( tinymce.Env.ie ) { // Stop IE > 8 from making the wrapper resizable on mousedown event.preventDefault(); } } else if ( event.target.nodeName !== 'IMG' ) { removeToolbar(); } }); editor.onMouseUp.add( function( editor, event ) { var image, node = event.target, dom = editor.dom; // Don't trigger on right-click if ( event.button && event.button > 1 ) { return; } if ( node.nodeName === 'DIV' && dom.getParent( node, '#ecwid-store-toolbar' ) ) { image = dom.select( 'img[data-ecwid-store-select]' )[0]; if ( image ) { editor.selection.select( image ); if ( dom.hasClass( node, 'remove' ) ) { removeImage( image ); } else if ( dom.hasClass( node, 'edit' ) ) { editStore( image ); } } } else if ( node.nodeName === 'IMG' && ! editor.dom.getAttrib( node, 'data-ecwid-store-select' ) ) { addToolbar( node ); } else if ( node.nodeName !== 'IMG' ) { removeToolbar(); } }); // Replace Read More/Next Page tags with images editor.onBeforeSetContent.add( function( editor, e ) { if ( e.content ) { found = ecwid_get_store_shortcode(e.content); if (!found) return; var content = e.content; var store = '<img height="200" width="100%" data-ecwid-shortcode="' + window.encodeURIComponent(found.content) + '" src="' + ecwid_store_svg + '" data-mce-placeholder="true" data-mce-resize="false" class="ecwid-store-editor mceItem">'; e.content = e.content.substr(0, found.index) + store + e.content.substr(found.index + found.content.length); } }); // Replace images with tags editor.onPostProcess.add( function( editor, e ) { if ( e.get ) { return e.content = e.content.replace( /(<img [^>]*data-ecwid-shortcode=[^>]+>)/g, function( match, image ) { var data = window.decodeURIComponent(jQuery(image).attr('data-ecwid-shortcode')); if ( data ) { return data; } return match; }); } }); });
#!/bin/bash echo "Starting entrypoint.sh ..." echo "Installing dependencies" composer install echo "Generating app key" php artisan key:generate echo "Running migrations..." php artisan migrate echo "Starting PHP FPM" php-fpm
<reponame>abramenal/abramenal.com<gh_stars>0 export { default as Copyright } from './Copyright'; export { default as Footer } from './Footer'; export { default as Header } from './Header'; export { default as Icon } from './Icon';
#!/bin/sh # Copyright 1998-2019 Lawrence Livermore National Security, LLC and other # HYPRE Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) ex=ex13 dir=`basename \`pwd\`` keys=AbjRl************ if [ "$dir" = "vis" ]; then dir=. mesh=$ex.mesh sol=$ex.sol else dir=vis mesh=vis/$ex.mesh sol=vis/$ex.sol fi if [ ! -e $mesh.000000 ] then echo "Can't find visualization data for $ex!" exit fi np=`cat $dir/$ex.data | head -n 1 | awk '{ print $2 }'` glvis -np $np -m $mesh -g $sol -k $keys
#!/bin/bash # Fetches latest files from github repo="mudpi/mudpi-core" branch="master" mudpi_dir="/etc/mudpi" webroot_dir="/var/www/html" mudpi_user="www-data" user=$(whoami) function log_error() { echo -e "\033[1;37;41mMudPi Install Error: $*\033[m" exit 1 } if [ ! -d "$mudpi_dir" ]; then sudo mkdir -p $mudpi_dir || log_error "Unable to create new core install directory" fi if [ -d "$mudpi_dir/core" ]; then sudo mv $mudpi_dir/core "$mudpi_dir/core.`date +%F_%H%M%S`" || log_error "Unable to remove old core directory" fi echo "Cloning latest core files from github" sudo rm -r /tmp/mudpi_core git clone --depth 1 https://github.com/${repo} /tmp/mudpi_core || log_error "Unable to download core files from github" sudo mv /tmp/mudpi_core $mudpi_dir/core || log_error "Unable to move Mudpi core to $mudpi_dir" sudo chown -R $mudpi_user:$mudpi_user "$mudpi_dir" || log_error "Unable to set permissions in '$mudpi_dir'" pip3 install -r $mudpi_dir/core/requirements.txt
#!/usr/bin/env sh # Terminate already running bar instances killall -q polybar # Wait until the processes have been shut down while pgrep -x polybar >/dev/null; do sleep 1; done # Launch bar1 and bar2 nohup polybar topbar > /dev/null 2>&1 & nohup polybar bottombar > /dev/null 2>&1 &
package pages import ( "net/http" "sync" "io" ) type Page struct { Request *http.Request Header http.Header Cookies []*http.Cookie Body []byte item *PageItem } var ( pagePool = sync.Pool{ New: func() interface{} { return &Page{ Cookies: make([]*http.Cookie, 0), Body: make([]byte, 0), item: NewItem(), } }, } ) func NewPage() *Page { return pagePool.Get().(*Page) } func NewPageForRes(res *http.Response) *Page { page := pagePool.Get().(*Page) page.Request = res.Request page.Header = res.Header io.Copy(page, res.Body) cookies := res.Cookies() page.Cookies = make([]*http.Cookie, len(cookies)) copy(page.Cookies, cookies) return page } func (self *Page) AddField(k, v string) { self.item.Set(k, v) } func (self *Page) Field(k string) string { return self.item.Get(k) } func (self *Page) GetItem() *PageItem { return self.item } func (self *Page) Write(p []byte) (n int, err error) { self.Body = make([]byte, len(p)) n = copy(self.Body, p) return } func (self *Page) Read(p []byte) (n int, err error) { p = make([]byte, len(self.Body)) n = copy(p, self.Body) return } func (self *Page) Free() { self.Request = nil self.Header = make(http.Header) self.Cookies = make([]*http.Cookie, 0) self.Body = make([]byte, 0) pagePool.Put(self) }
#!/bin/bash set -ex export # Enter temporary directory. pushd /tmp # Install Homebrew curl --location --output install-brew.sh "https://raw.githubusercontent.com/Homebrew/install/master/install.sh" bash install-brew.sh rm install-brew.sh # Install Node. version=14.15.4 curl --location --output node.pkg "https://nodejs.org/dist/v$version/node-v$version.pkg" sudo installer -pkg node.pkg -store -target / rm node.pkg # Install Bats. if [ "$(uname -r)" = "19.6.0" ]; then brew unlink bats fi brew install bats-core # Install Bats support. version=0.3.0 curl --location --output bats-support.tar.gz https://github.com/ztombol/bats-support/archive/v$version.tar.gz mkdir /usr/local/lib/bats-support tar --directory /usr/local/lib/bats-support --extract --file bats-support.tar.gz --strip-components 1 rm bats-support.tar.gz # Install DFINITY SDK. curl --location --output install-dfx.sh "https://sdk.dfinity.org/install.sh" bash install-dfx.sh < <(yes Y) rm install-dfx.sh # Set environment variables. BATS_SUPPORT="/usr/local/lib/bats-support" echo "BATS_SUPPORT=${BATS_SUPPORT}" >> "$GITHUB_ENV" # Exit temporary directory. popd
<filename>app/src/main/java/com/sreemenon/crypt/Lamp.java package com.sreemenon.crypt; import android.content.Context; import android.util.Base64; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.UnrecoverableEntryException; import java.security.cert.CertificateException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.util.ArrayList; import java.util.Random; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.NoSuchPaddingException; /** * Created by Sree on 18/12/2015. */ /** * Helper class for encrypting and decrypting the intermediate key */ public class Lamp { /** * * @param alias alias for pulling key from keystore * @param genie the intermediate key * * @return Decrypted ntermediate key * * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws UnrecoverableEntryException * @throws NoSuchProviderException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static String decryptGenie(String alias, String genie)throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException { KeyStoreHelper keyStoreHelper = new KeyStoreHelper("AndroidKeyStore"); RSAPrivateKey privateKey = keyStoreHelper.getPrivateKey(alias); Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); output.init(Cipher.DECRYPT_MODE, privateKey); CipherInputStream cipherInputStream = new CipherInputStream( new ByteArrayInputStream(Base64.decode(genie, Base64.DEFAULT)), output); ArrayList<Byte> values = new ArrayList<>(); int nextByte; while ((nextByte = cipherInputStream.read()) != -1) { values.add((byte)nextByte); } byte[] bytes = new byte[values.size()]; for(int i = 0; i < bytes.length; i++) { bytes[i] = values.get(i).byteValue(); } return new String(bytes, 0, bytes.length, "UTF-8"); } /** * * @param alias alias for pulling key from keystore * @param context context to create a new key pair * * @return both plain and encrypted intermediate key * @throws InvalidAlgorithmParameterException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws UnrecoverableEntryException * @throws NoSuchProviderException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static String[] encryptGenie(String alias, Context context)throws InvalidAlgorithmParameterException, KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException { KeyStoreHelper keyStoreHelper = new KeyStoreHelper("AndroidKeyStore"); RSAPublicKey publicKey = keyStoreHelper.createNewKeyPair(alias, context); String baseChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890@%+/'!#$^?:,(){}[]~-_"; StringBuilder randomBuilder = new StringBuilder(); Random random = new Random(); for(int i = 0 ; i < 100; i++){ randomBuilder.append(baseChars.charAt(random.nextInt(baseChars.length()))); } // Encrypt the text String initialText = randomBuilder.toString(); Cipher input = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); input.init(Cipher.ENCRYPT_MODE, publicKey); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream( outputStream, input); cipherOutputStream.write(initialText.getBytes("UTF-8")); cipherOutputStream.close(); byte [] vals = outputStream.toByteArray(); String result[] = new String[]{Base64.encodeToString(vals, Base64.DEFAULT), initialText}; return result; } }
#!/bin/bash cd ./Jar java -jar Client.jar -cli
package io.opensphere.wms; import java.util.Collection; import java.util.HashMap; import org.easymock.EasyMock; import io.opensphere.core.AnimationManager; import io.opensphere.core.PluginToolboxRegistry; import io.opensphere.core.TimeManager; import io.opensphere.core.Toolbox; import io.opensphere.core.control.action.ContextActionManager; import io.opensphere.core.control.ui.UIRegistry; import io.opensphere.core.event.EventManager; import io.opensphere.core.model.time.TimeSpan; import io.opensphere.core.model.time.TimeSpanList; import io.opensphere.core.order.OrderManagerRegistry; import io.opensphere.core.order.impl.OrderManagerRegistryImpl; import io.opensphere.core.util.ColorUtilities; import io.opensphere.core.util.swing.input.model.BooleanModel; import io.opensphere.mantle.MantleToolbox; import io.opensphere.mantle.controller.DataGroupController; import io.opensphere.mantle.data.DataTypeInfoPreferenceAssistant; import io.opensphere.mantle.data.PlayState; /** * The Class WFSTestToolbox. */ public final class WMSTestToolbox { /** * Setup a test toolbox for testing purposes. * * @param replay flag indicating whether to replay the mocked toolbox before * returning it * @return the toolbox */ public static Toolbox getToolbox(boolean replay) { // Add Z-Order manager to mantle toolbox. MantleToolbox mantleTb = EasyMock.createMock(MantleToolbox.class); // Add DataGroupController to mantle toolbox. DataGroupController dgCtrl = EasyMock.createNiceMock(DataGroupController.class); EasyMock.expect(mantleTb.getDataGroupController()).andReturn(dgCtrl).anyTimes(); // Add DataTypeInfo Preference Assistant to Mantle toolbox. DataTypeInfoPreferenceAssistant prefAsst = new DataTypeInfoPreferenceAssistant() { @Override public int getColorPreference(String dtiKey, int def) { return 0; } @Override public int getOpacityPreference(String dtiKey, int def) { return ColorUtilities.COLOR_COMPONENT_MAX_VALUE; } @Override public PlayState getPlayStatePreference(String dtiKey) { return PlayState.STOP; } @Override public boolean isVisiblePreference(String dtiKey) { return true; } @Override public boolean isVisiblePreference(String dtiKey, boolean def) { return true; } @Override public void removePreferences(String dtiKey) { } @Override public void removePreferences(String dtiKey, PreferenceType... typeToRemove) { } @Override public void removePreferencesForPrefix(String dtiKeyPrefix) { } @Override public void removePreferencesForPrefix(String dtiKeyPrefix, PreferenceType... typeToRemove) { } @Override public void setPlayStatePreference(String dtiKey, PlayState playState) { } @Override public void getBooleanPreference(BooleanModel property, String dtiKey) { } @Override public void setBooleanPreference(BooleanModel property, String dtiKey) { } }; EasyMock.expect(mantleTb.getDataTypeInfoPreferenceAssistant()).andReturn(prefAsst).anyTimes(); EasyMock.replay(mantleTb); // Add mantle toolbox to plugin toolbox registry. PluginToolboxRegistry pluginTb = EasyMock.createMock(PluginToolboxRegistry.class); EasyMock.expect(pluginTb.getPluginToolbox(MantleToolbox.class)).andReturn(mantleTb).anyTimes(); EasyMock.replay(pluginTb); // Create Core toolbox with test mantle toolbox. Toolbox coreToolbox = EasyMock.createMock(Toolbox.class); EasyMock.expect(coreToolbox.getPluginToolboxRegistry()).andReturn(pluginTb).anyTimes(); // Add animation manager AnimationManager animationMgr = EasyMock.createNiceMock(AnimationManager.class); EasyMock.expect(animationMgr.getCurrentPlan()).andReturn(null).anyTimes(); EasyMock.replay(animationMgr); EasyMock.expect(coreToolbox.getAnimationManager()).andReturn(animationMgr).anyTimes(); // Add event manager EventManager eventMgr = EasyMock.createNiceMock(EventManager.class); EasyMock.expect(coreToolbox.getEventManager()).andReturn(eventMgr).anyTimes(); // Add mock time manager TimeManager timeMgr = EasyMock.createNiceMock(TimeManager.class); EasyMock.expect(timeMgr.getPrimaryActiveTimeSpans()).andReturn(TimeSpanList.singleton(TimeSpan.get())).anyTimes(); EasyMock.expect(timeMgr.getSecondaryActiveTimeSpans()).andReturn(new HashMap<Object, Collection<? extends TimeSpan>>()) .anyTimes(); EasyMock.replay(timeMgr); EasyMock.expect(coreToolbox.getTimeManager()).andReturn(timeMgr).anyTimes(); // Add control action manager ContextActionManager ctrlMgr = EasyMock.createNiceMock(ContextActionManager.class); UIRegistry uiRegistry = EasyMock.createMock(UIRegistry.class); EasyMock.expect(uiRegistry.getContextActionManager()).andReturn(ctrlMgr).anyTimes(); EasyMock.replay(uiRegistry); EasyMock.expect(coreToolbox.getUIRegistry()).andReturn(uiRegistry).anyTimes(); OrderManagerRegistry orderManagerReg = new OrderManagerRegistryImpl(null); EasyMock.expect(coreToolbox.getOrderManagerRegistry()).andReturn(orderManagerReg).anyTimes(); if (replay) { EasyMock.replay(coreToolbox); } return coreToolbox; } /** Disallow instantiation of utility class. */ private WMSTestToolbox() { } }
package io.opensphere.mantle.data.geom.factory; import java.util.Collection; import java.util.Set; import io.opensphere.core.geometry.Geometry; import io.opensphere.core.geometry.renderproperties.RenderProperties; import io.opensphere.mantle.data.DataTypeInfo; /** * The Interface RenderPropertyPool. */ public interface RenderPropertyPool { /** * Adds all the unique {@link RenderProperties} owned by the provided * collection of {@link Geometry} to the pool. (Greedy) * * @param geomCollection the collection from which to get RenderProperties */ void addAllFromGeometry(Collection<Geometry> geomCollection); /** * Adds the unique {@link RenderProperties} owned by the provided collection * of {@link Geometry} to the pool. * * @param geom the {@link Geometry} */ void addFromGeometry(Geometry geom); /** * Clears all pooled RenderProperties. */ void clearPool(); /** * Gets the data type. * * @return the data type */ DataTypeInfo getDataType(); /** * Checks the pool to see if an equivalent RenderProperties is already * within the pool. If so returns the pool instance if not adds the provided * property to the pool and returns the passed in property. * * @param <T> the generic type * @param prop the {@link RenderProperties} to add to the pool. * @return the pool instance of the equivalent {@link RenderProperties} or * the now pooled version. */ <T extends RenderProperties> T getPoolInstance(T prop); /** * Removes the specified property ( or its equivalent ) from the pool if it * is in the pool. * * @param <T> the generic type * @param prop the {@link RenderProperties} to remove */ <T extends RenderProperties> void removePoolInstance(T prop); /** * Gets the number of unique properties in the pool. * * @return the int number of unique properties. */ int size(); /** * Values. * * @return the sets the */ Set<RenderProperties> values(); }
#!/bin/bash #SBATCH --job-name FHH_SU2 #SBATCH --comment "FHH Model - QH Ferromagnetism" #SBATCH --time=7-00:00:00 #SBATCH --mail-type=ALL #SBATCH --mail-user=Mert.Kurttutan@physik.uni-muenchen.de #SBATCH --chdir=/home/m/Mert.Kurttutan/Academia/Codes/Physics/Projects/qh_fm_01/codes/excs #SBATCH --output=/project/th-scratch/m/Mert.Kurttutan/slurm/DMRG.%j.%N.out #SBATCH --constraint=avx #SBATCH --ntasks=4 #SBATCH --mem=128GB #SBATCH --partition=th-cl,cluster __dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # input: Lx Ly alpha U N S(spin) PBC job source /project/theorie/s/Sam.Mardazad/Group/syten_inc.sh #python ${__dir}/run_DMRG.py $1 $2 $3 $4 $5 $6 $7 #python ${__dir}/convergence_n_arr.py $1 $2 $3 $4 $5 $6 $7 #python ${__dir}/convergence_cur_arr.py $1 $2 $3 $4 $5 $6 $7 #python ${__dir}/sCorr-func-GS.py $1 $2 $3 $4 $5 $6 $7 #python ${__dir}/nCorr-func-GS.py $1 $2 $3 $4 $5 $6 $7 #python ${__dir}/run_DMRG_pinning.py $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 python ./run_DMRG_pinning.py $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 #python ${__dir}/sCorr-func-GS.py $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 #python ./sCorr-func-GS.py $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 #python ${__dir}/nCorr-func-GS.py $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 #python ./nCorr-func-GS.py $1 $2 $3 $4 $5 $6 $7 $8 $9 $10
<reponame>jawa007/Spark-Test<gh_stars>0 package com.spark.itversity.example import org.apache.spark.streaming.{ Seconds, StreamingContext } import org.apache.spark.streaming.StreamingContext._ object WindowSparkStreaming { def main(args: Array[String]) { val ssc = new StreamingContext("local[2]", "Statefulwordcount", Seconds(10)) val lines = ssc.socketTextStream("192.168.56.101", 9999) val words = lines.flatMap(_.split(" ")) val pairs = words.map(word => (word, 1)) pairs.reduceByKeyAndWindow((x: Int, y: Int) => (x + y), Seconds(30), Seconds(10)).print() ssc.start() ssc.awaitTermination() } }
package main.support; import org.deuce.transform.Exclude; import adapters.*; import main.support.*; import java.util.ArrayList; public class Factories { // central list of factory classes for all supported data structures public static final ArrayList<TreeFactory<Integer>> factories = new ArrayList<TreeFactory<Integer>>(); static { factories.add(new VcasBatchBSTGCFactory<Integer>()); factories.add(new LockFreeBSTFactory<Integer>()); factories.add(new LockFreeChromaticFactory<Integer>()); factories.add(new LockFreeBatchBSTFactory<Integer>()); factories.add(new LockFreePBSTFactory<Integer>()); factories.add(new LockFreeBPBSTFactory<Integer>()); factories.add(new LFCAFactory<Integer>()); factories.add(new LockFreeBatchChromaticFactory<Integer>()); factories.add(new VcasBatchChromaticGCFactory<Integer>()); factories.add(new KiwiFactory<Integer>()); factories.add(new SnapTreeFactory<Integer>()); factories.add(new LockFreeKSTRQFactory<Integer>()); } // factory classes for each supported data structure @Exclude protected static class LockFreePBSTFactory<K> extends TreeFactory<K> { public SetInterface<K> newTree(final Object param) { return new LockFreePBSTAdapter(); } public String getName() { return "PBST"; } } @Exclude protected static class KiwiFactory<K> extends TreeFactory<K> { public SetInterface<K> newTree(final Object param) { return new KiwiAdapter(); } public String getName() { return "KIWI"; } } @Exclude protected static class LFCAFactory<K> extends TreeFactory<K> { public SetInterface<K> newTree(final Object param) { return new LFCAAdapter(); } public String getName() { return "LFCA"; } } @Exclude protected static class LockFreeBSTFactory<K> extends TreeFactory<K> { public SetInterface<K> newTree(final Object param) { return new LockFreeBSTAdapter(); } public String getName() { return "BST"; } } @Exclude protected static class LockFreeChromaticFactory<K> extends TreeFactory<K> { public SetInterface<K> newTree(final Object param) { return new LockFreeChromaticAdapter(); } public String getName() { return "ChromaticBST"; } } @Exclude protected static class SnapTreeFactory<K> extends TreeFactory<K> { public SetInterface<K> newTree(final Object param) { return new SnapTreeAdapter(); } public String getName() { return "SnapTree"; } } @Exclude protected static class LockFreeKSTRQFactory<K> extends TreeFactory<K> { public SetInterface<K> newTree(final Object param) { return new LockFreeKSTRQAdapter(); } public String getName() { return "KSTRQ"; } } @Exclude protected static class LockFreeBatchChromaticFactory<K> extends TreeFactory<K> { Object param; public SetInterface<K> newTree(final Object param) { this.param = param; return param.toString().isEmpty() ? new LockFreeBatchChromaticAdapter() : new LockFreeBatchChromaticAdapter(Integer.parseInt(param.toString())); } public String getName() { return "ChromaticBatchBST"; } } @Exclude protected static class VcasBatchChromaticGCFactory<K> extends TreeFactory<K> { Object param; public SetInterface<K> newTree(final Object param) { this.param = param; return param.toString().isEmpty() ? new VcasBatchChromaticGCAdapter() : new VcasBatchChromaticGCAdapter(Integer.parseInt(param.toString())); } public String getName() { return "VcasChromaticBatchBSTGC"; } } @Exclude protected static class LockFreeBatchBSTFactory<K> extends TreeFactory<K> { Object param; public SetInterface<K> newTree(final Object param) { this.param = param; return param.toString().isEmpty() ? new LockFreeBatchBSTAdapter() : new LockFreeBatchBSTAdapter(Integer.parseInt(param.toString())); } public String getName() { return "BatchBST"; } } @Exclude protected static class VcasBatchBSTGCFactory<K> extends TreeFactory<K> { Object param; public SetInterface<K> newTree(final Object param) { this.param = param; return param.toString().isEmpty() ? new VcasBatchBSTGCAdapter() : new VcasBatchBSTGCAdapter(Integer.parseInt(param.toString())); } public String getName() { return "VcasBatchBSTGC"; } } @Exclude protected static class LockFreeBPBSTFactory<K> extends TreeFactory<K> { Object param; public SetInterface<K> newTree(final Object param) { this.param = param; return param.toString().isEmpty() ? new LockFreeBPBSTAdapter() : new LockFreeBPBSTAdapter(Integer.parseInt(param.toString())); } public String getName() { return "BPBST"; } } }
<reponame>Boatdude55/staging-website /** * @fileoverview Closure Builder - Build tools * * @license Copyright 2015 Google Inc. 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. * * @author <EMAIL> (<NAME>) */ let fs = require('fs-extra'); let BuildType = require('./build/types.js'); let SnifferTools = require('./tools/sniffer.js'); /** * Build Tools. * @constructor * @struct * @final */ let BuildTools = function() {}; /** * Detects the needed compiler types. * @param {!BuildConfig} config * @return {!string} */ BuildTools.detectType = function(config) { if (config.hasSoyFiles() > 0) { if (config.hasClosureFiles() === 0) { return BuildType.SOY; } else { return BuildType.SOY_CLOSURE; } } else if (config.hasClosureFiles()) { return BuildType.CLOSURE; } else if (config.hasNodeFiles()) { return BuildType.NODEJS; } else if (config.hasJsFiles()) { return BuildType.JAVASCRIPT; } else if (config.hasClosureStylesheetsFiles()) { return BuildType.CLOSURE_STYLESHEETS; } else if (config.hasCssFiles()) { return BuildType.CSS; } else if (config.hasMarkdownFiles()) { return BuildType.MARKDOWN; } else if (config.hasResourceFiles()) { return BuildType.RESOURCES; } else { return BuildType.UNKNOWN; } }; /** * @param {!array|string} files * @param {boolean=} opt_all Show all files and folders. * @param {boolean=} opt_exclude_test Exclude test files. * @return {array} */ BuildTools.sortFiles = function(files, opt_all, opt_exclude_test) { if (!Array.isArray(files)) { files = [files]; } let fileList = []; let knownFile = {}; for (let i = files.length - 1; i >= 0; i--) { let file = files[i]; if (file.constructor === Array) { for (let i2 = file.length - 1; i2 >= 0; i2--) { let subFile = file[i2]; if (!knownFile[subFile] && (opt_all || subFile.indexOf('.') !== -1)) { fileList.push(subFile); knownFile[subFile] = true; } } } else { if (!knownFile[file] && (opt_all || file.indexOf('.') !== -1)) { fileList.push(file); knownFile[file] = true; } } } if (opt_exclude_test) { return BuildTools.filterTestFiles(fileList); } return fileList; }; /** * Returns the needed build requirements for the given config. * @param {BuildConfig} config * @return {Object} Build requirements */ BuildTools.getBuildRequirements = function(config) { let depsConfig = this.scanFiles(config.deps); let srcsConfig = this.scanFiles(config.srcs, config.name); let soyConfig = this.scanFiles(config.soy); let mdConfig = this.scanFiles(config.markdown); return { closureFiles: [].concat(depsConfig.closureFiles, srcsConfig.closureFiles), cssFiles: [].concat(srcsConfig.cssFiles), closureStylesheetsFiles: [].concat(srcsConfig.closureStylesheetsFiles), jsFiles: [].concat(depsConfig.jsFiles, srcsConfig.jsFiles), markdownFiles: [].concat(mdConfig.markdownFiles), nodeFiles: [].concat(srcsConfig.nodeFiles), soyFiles: [].concat(depsConfig.soyFiles, soyConfig.soyFiles, srcsConfig.soyFiles), entryPoint: (depsConfig.entryPoint || srcsConfig.entryPoint), requireClosureExport: (srcsConfig.requireClosureExport), requireClosureLibrary: (depsConfig.requireClosureLibrary || srcsConfig.requireClosureLibrary), requireClosureLibraryUI: (depsConfig.requireClosureLibraryUI || srcsConfig.requireClosureLibraryUI), requiredECMAVersion: [depsConfig.requiredECMAVersion, srcsConfig.requiredECMAVersion].sort().pop(), requireSoyLibrary: (depsConfig.requireSoyLibrary || srcsConfig.requireSoyLibrary || soyConfig.requireSoyLibrary), requireSoyi18n: (soyConfig.requireSoyi18n || srcsConfig.requireSoyi18n), }; }; /** * Scan files for certain file types and return list of files and requirements. * @param {!array|string} files * @param {string=} opt_entry_point * @return {Object} */ BuildTools.scanFiles = function(files, opt_entry_point) { if (!Array.isArray(files)) { files = [files]; } let closureFiles = []; let closureStylesheetsFiles = []; let cssFiles = []; let entryPoint = ''; let jsFiles = []; let markdownFiles = []; let nodeFiles = []; let requireClosureExport = false; let requireClosureLibrary = false; let requireClosureLibraryUI = false; let requireSoyLibrary = false; let requireSoyi18n = false; let requiredECMAVersion = ''; let soyFiles = []; for (let i = files.length - 1; i >= 0; i--) { let file = files[i]; // Handling soy files. if (file.endsWith('.soy')) { let soyContent = fs.readFileSync(file, 'utf8'); if (soyContent.includes('{i18n}') && soyContent.includes('{/i18n}')) { requireSoyi18n = true; } requireSoyLibrary = true; soyFiles.push(file); // Handling JavaScript files. } else if (file.endsWith('.js')) { let fileContent = fs.readFileSync(file, 'utf8'); if (fileContent.includes('goog.provide(') || fileContent.includes('goog.require(') || fileContent.includes('goog.module(')) { if (fileContent.includes(' * @export')) { requireClosureExport = true; } closureFiles.push(file); } else if (fileContent.includes('require(') && fileContent.includes('module.exports')) { nodeFiles.push(file); } else { jsFiles.push(file); } // Validating possible entry points. if (opt_entry_point) { if (fileContent.includes('goog.provide(\'' + opt_entry_point + '\'') || fileContent.includes('goog.module(\'' + opt_entry_point + '\'')) { entryPoint = opt_entry_point; } } // Require closure library ? if (fileContent.includes('goog.require(\'goog.') || fileContent.includes('goog.require("goog.')) { if (fileContent.includes('goog.require(\'goog.ui') || fileContent.includes('goog.require("goog.ui')) { requireClosureLibraryUI = true; } requireClosureLibrary = true; } // Require soy library ? if (fileContent.includes('goog.require(\'soy') || fileContent.includes('goog.require(\'soydata')) { requireSoyLibrary = true; } // Detecting min. ECMA Script version ? let ECMAScriptVersion = SnifferTools.getECMAScriptVersion(fileContent); if (ECMAScriptVersion && requiredECMAVersion) { if (ECMAScriptVersion.split('_')[1] > requiredECMAVersion.split('_')[1]) { requiredECMAVersion = ECMAScriptVersion; } } else if (ECMAScriptVersion) { requiredECMAVersion = ECMAScriptVersion; } // Handling Closure stylesheets (.gss) file. } else if (file.endsWith('.gss')) { closureStylesheetsFiles.push(file); // Handling CSS files. } else if (file.endsWith('.css')) { cssFiles.push(file); // Handling Markdown files. } else if (file.endsWith('.md')) { markdownFiles.push(file); } } return { closureFiles: closureFiles, cssFiles: cssFiles, entryPoint: entryPoint, closureStylesheetsFiles: closureStylesheetsFiles, jsFiles: jsFiles, markdownFiles: markdownFiles, nodeFiles: nodeFiles, soyFiles: soyFiles, requireClosureExport: requireClosureExport, requireClosureLibrary: requireClosureLibrary, requireClosureLibraryUI: requireClosureLibraryUI, requiredECMAVersion: requiredECMAVersion, requireSoyLibrary: requireSoyLibrary, requireSoyi18n: requireSoyi18n, }; }; /** * @param {array} files * @return {array} */ BuildTools.filterTestFiles = function(files) { for (let i = files.length - 1; i >= 0; i--) { let file = files[i]; if (file.indexOf('_test.js') !== -1 || file.indexOf('_testhelper.js') !== -1 || file.indexOf('/demos/') !== -1 || file.indexOf('/deps.js') !== -1) { files.splice(i, 1); } } return files; }; module.exports = BuildTools;
<gh_stars>1-10 import { OrderSerializer } from '../../../../shared/serializers/order-serializer'; import { RentalOrder } from '../entities/rental-order.entity'; import { Injectable, BadRequestException, NotFoundException, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { RentalOrderRepository } from '../repositories/rental-order.repository'; import { AuthorizedUser } from 'src/shared/interfaces/authorized-user.interface'; import { RentalOrderDto } from '../../../../shared/dtos/response/rental-order.dto'; import { plainToClass } from 'class-transformer'; import { ReturnOrderRepository } from '../repositories/return-order.repository'; import { PaginationDto } from 'src/shared/dtos/request/pagination.dto'; import { PaginatedDataDto } from 'src/shared/dtos/response/paginated-data.dto'; import { OrderResponseDto } from 'src/shared/dtos/response/order-response.dto'; import { ReturnOrderResponseDto } from 'src/shared/dtos/response/return-order-response.dto'; import { PaginatedSerializer } from 'src/shared/serializers/paginated-serializer'; import { RentMovieDto } from 'src/customer/dto/rent-movie.dto'; import { MoviesService } from '../../../../movies/services/movies.service'; @Injectable() export class RentalOrdersService { constructor( @InjectRepository(RentalOrderRepository) private rentalOrderRepository: RentalOrderRepository, @InjectRepository(ReturnOrderRepository) private returnOrderRepository: ReturnOrderRepository, private moviesService: MoviesService, private serializer: OrderSerializer, private paginationSerializer: PaginatedSerializer<RentalOrderDto>, ) {} async getRentalOrderById( id: number, user: AuthorizedUser, ): Promise<RentalOrderDto> { const rental = await this.rentalOrderRepository.findOne( { id, userId: user.userId }, { relations: ['movie'] }, ); if (!rental) { throw new NotFoundException(`Rental Order with ID "${id}" not found`); } const rentalOrder = plainToClass(RentalOrderDto, rental); return rentalOrder; } async rentMovie( rentMovieDto: RentMovieDto, user: AuthorizedUser, ): Promise<OrderResponseDto<RentalOrderDto>> { const { movieId, toBeReturnedAt } = rentMovieDto; const movie = await this.moviesService.findMovie(movieId); if (!movie.availability) { throw new BadRequestException( `Movie with ID "${movieId} is no longer available"`, ); } if (movie.stock === 0) { throw new BadRequestException( `Movie with ID "${movie.id}" is out of stock`, ); } const rental = await this.rentalOrderRepository.rentMovie( movie, user.userId, toBeReturnedAt, ); await movie.reload(); const rentalOrder = plainToClass(RentalOrderDto, { movie, ...rental }); return this.serializer.serialize<RentalOrderDto>(rentalOrder, movie); } async returnMovie( rentalOrderId: number, user: AuthorizedUser, ): Promise<OrderResponseDto<ReturnOrderResponseDto>> { const rental = await this.findRentalOrder(rentalOrderId, user.userId); await this.returnOrderRepository.returnMovie(rental); const returnOrder = await this.returnOrderRepository.findOne( { rentalOrderId: rental.id, }, { relations: ['rentalOrder'] }, ); await rental.movie.reload(); return this.serializer.serializeWithRentalOrder(returnOrder); } async getUserRentalOrders( userId: number, paginationDto: PaginationDto, ): Promise<PaginatedDataDto<OrderResponseDto<RentalOrderDto>[]>> { const { data, totalCount, } = await this.rentalOrderRepository.getUserRentalOrders( userId, paginationDto, ); const page = Number(paginationDto.page) || 1; const limit = Number(paginationDto.limit) || 10; const rentals: OrderResponseDto<RentalOrderDto>[] = data.map(order => { const dto = plainToClass(RentalOrderDto, order); return this.serializer.serialize<RentalOrderDto>(dto, order.movie); }); return this.paginationSerializer.serialize( rentals, totalCount, page, limit, ); } private findRentalOrder(id: number, userId: number): Promise<RentalOrder> { const rental = this.rentalOrderRepository.findOne({ id, userId }); if (!rental) { throw new NotFoundException(`Rental Order with ID "${id}" not found`); } return rental; } }
<reponame>GiantAxeWhy/skyline-vue // Copyright 2021 99cloud // // 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 { observer, inject } from 'mobx-react'; import Base from 'containers/List'; import { QoSPolicyStore } from 'stores/neutron/qos-policy'; import { getQosPolicyColumns, getQosPolicyFilters } from 'resources/qos-policy'; import { qosEndpoint } from 'client/client/constants'; import actionConfigs from './actions'; export class QoSPolicy extends Base { init() { this.store = new QoSPolicyStore(); this.downloadStore = new QoSPolicyStore(); } updateFetchParamsByPage = (params) => ({ ...params, all_projects: this.tabKey === 'allQoSPolicy' || this.isAdminPage, }); get checkEndpoint() { return true; } get endpoint() { return qosEndpoint(); } get policy() { return 'get_policy'; } get name() { return t('QoS policies'); } get actionConfigs() { if (this.isAdminPage) { return actionConfigs.actionConfigs; } return actionConfigs.consoleActions; } get isFilterByBackend() { return true; } get isSortByBackend() { return true; } get defaultSortKey() { return 'name'; } get tabKey() { const { tab } = this.props; return tab; } getColumnParamsFromTabKey() { switch (this.tabKey) { case 'projectQoSPolicy': return { self: this, all: false, shared: false, }; case 'sharedQoSPolicy': return { self: this, all: false, shared: true, }; case 'allQoSPolicy': return { self: this, all: true, shared: false, }; default: return { self: this, all: true, shared: false, }; } } getColumns() { return getQosPolicyColumns(this.getColumnParamsFromTabKey()); } get searchFilters() { return getQosPolicyFilters(this.getColumnParamsFromTabKey()); } } export default inject('rootStore')(observer(QoSPolicy));
#!/bin/bash PKG_NAME="ws-client" QHOME=$PREFIX/q mkdir -p $QHOME/packages/${PKG_NAME} cp -r ${SRC_DIR}/*.q $QHOME/packages/${PKG_NAME}/