text
stringlengths
1
1.05M
def get_even_list(list): even_list = [] for num in list: if num % 2 == 0: even_list.append(num) return even_list list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(get_even_list(list))
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v7/resources/conversion_action.proto require 'google/ads/googleads/v7/common/tag_snippet_pb' require 'google/ads/googleads/v7/enums/attribution_model_pb' require 'google/ads/googleads/v7/enums/conversion_action_category_pb' require 'google/ads/googleads/v7/enums/conversion_action_counting_type_pb' require 'google/ads/googleads/v7/enums/conversion_action_status_pb' require 'google/ads/googleads/v7/enums/conversion_action_type_pb' require 'google/ads/googleads/v7/enums/data_driven_model_status_pb' require 'google/ads/googleads/v7/enums/mobile_app_vendor_pb' require 'google/api/field_behavior_pb' require 'google/api/resource_pb' require 'google/api/annotations_pb' require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/ads/googleads/v7/resources/conversion_action.proto", :syntax => :proto3) do add_message "google.ads.googleads.v7.resources.ConversionAction" do optional :resource_name, :string, 1 proto3_optional :id, :int64, 21 proto3_optional :name, :string, 22 optional :status, :enum, 4, "google.ads.googleads.v7.enums.ConversionActionStatusEnum.ConversionActionStatus" optional :type, :enum, 5, "google.ads.googleads.v7.enums.ConversionActionTypeEnum.ConversionActionType" optional :category, :enum, 6, "google.ads.googleads.v7.enums.ConversionActionCategoryEnum.ConversionActionCategory" proto3_optional :owner_customer, :string, 23 proto3_optional :include_in_conversions_metric, :bool, 24 proto3_optional :click_through_lookback_window_days, :int64, 25 proto3_optional :view_through_lookback_window_days, :int64, 26 optional :value_settings, :message, 11, "google.ads.googleads.v7.resources.ConversionAction.ValueSettings" optional :counting_type, :enum, 12, "google.ads.googleads.v7.enums.ConversionActionCountingTypeEnum.ConversionActionCountingType" optional :attribution_model_settings, :message, 13, "google.ads.googleads.v7.resources.ConversionAction.AttributionModelSettings" repeated :tag_snippets, :message, 14, "google.ads.googleads.v7.common.TagSnippet" proto3_optional :phone_call_duration_seconds, :int64, 27 proto3_optional :app_id, :string, 28 optional :mobile_app_vendor, :enum, 17, "google.ads.googleads.v7.enums.MobileAppVendorEnum.MobileAppVendor" optional :firebase_settings, :message, 18, "google.ads.googleads.v7.resources.ConversionAction.FirebaseSettings" optional :third_party_app_analytics_settings, :message, 19, "google.ads.googleads.v7.resources.ConversionAction.ThirdPartyAppAnalyticsSettings" end add_message "google.ads.googleads.v7.resources.ConversionAction.AttributionModelSettings" do optional :attribution_model, :enum, 1, "google.ads.googleads.v7.enums.AttributionModelEnum.AttributionModel" optional :data_driven_model_status, :enum, 2, "google.ads.googleads.v7.enums.DataDrivenModelStatusEnum.DataDrivenModelStatus" end add_message "google.ads.googleads.v7.resources.ConversionAction.ValueSettings" do proto3_optional :default_value, :double, 4 proto3_optional :default_currency_code, :string, 5 proto3_optional :always_use_default_value, :bool, 6 end add_message "google.ads.googleads.v7.resources.ConversionAction.ThirdPartyAppAnalyticsSettings" do proto3_optional :event_name, :string, 2 optional :provider_name, :string, 3 end add_message "google.ads.googleads.v7.resources.ConversionAction.FirebaseSettings" do proto3_optional :event_name, :string, 3 proto3_optional :project_id, :string, 4 end end end module Google module Ads module GoogleAds module V7 module Resources ConversionAction = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.resources.ConversionAction").msgclass ConversionAction::AttributionModelSettings = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.resources.ConversionAction.AttributionModelSettings").msgclass ConversionAction::ValueSettings = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.resources.ConversionAction.ValueSettings").msgclass ConversionAction::ThirdPartyAppAnalyticsSettings = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.resources.ConversionAction.ThirdPartyAppAnalyticsSettings").msgclass ConversionAction::FirebaseSettings = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.resources.ConversionAction.FirebaseSettings").msgclass end end end end end
package com.tracy.competition.domain.entity import java.util import java.util.List import scala.beans.BeanProperty /** * @author Tracy * @date 2021/2/9 1:06 */ class Role extends Serializable { @BeanProperty var roleId: String = _ @BeanProperty var roleName: String = _ @BeanProperty var promises: util.List[Promise] = _ @BeanProperty var users: util.List[User] = _ override def toString: String = { "Role{" + "roleId='" + roleId + '\'' + ", roleName='" + roleName + '\'' + ", promises=" + promises + ", users=" + users + '}' } }
<filename>example/test/particle.cpp<gh_stars>1-10 /* MANGO Multimedia Development Platform Copyright (C) 2012-2020 Twilight Finland 3D Oy Ltd. All rights reserved. */ #include <mango/mango.hpp> #include <algorithm> #include <random> using namespace mango; // ---------------------------------------------------------------------- // helpers // ---------------------------------------------------------------------- namespace { std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<float> dist(-1.0, 1.0); inline float4 random_float4(float w) { float x = dist(mt); float y = dist(mt); float z = dist(mt); return float4(x, y, z, w); } } // namespace // ---------------------------------------------------------------------- // method1: AoS - Array of Structures // ---------------------------------------------------------------------- /* This method wastes memory bandwidth for reading data which is not needed and writing data that doesn't change. */ namespace method1 { struct Particle { float4 position; // this is the only mutable data in the transform() method float4 velocity; u32 color; float radius; float rotation; }; struct Scene { AlignedStorage<Particle> particles; Scene(int count) : particles(count) { for (auto &particle : particles) { particle.position = random_float4(1.0f); particle.velocity = random_float4(0.0f); } } void transform() { for (auto &particle : particles) { particle.position += particle.velocity; } } }; } // namespace // ---------------------------------------------------------------------- // method2: SoA - Structure of Arrays // ---------------------------------------------------------------------- /* This method is slightly better as it writes to continuous memory w/o any holes. */ namespace method2 { struct Scene { AlignedStorage<float4> positions; AlignedStorage<float4> velocities; std::vector<u32> colors; std::vector<float> radiuses; std::vector<float> rotations; Scene(int count) : positions(count) , velocities(count) , colors(count) , radiuses(count) , rotations(count) { for (auto &position : positions) { position = random_float4(1.0f); } for (auto &velocity : velocities) { velocity = random_float4(1.0f); } } void transform() { const size_t count = positions.size(); for (size_t i = 0; i < count; ++i) { positions[i] += velocities[i]; } } }; } // namespace // ---------------------------------------------------------------------- // method3: SoA w/ 100% SIMD register utilization // ---------------------------------------------------------------------- /* This method does not waste 25% of ram for storing the w-coordinate which is a constant value. It was stored in the earlier methods for alignment. */ namespace method3 { struct Scene { AlignedStorage<float4> xpositions; AlignedStorage<float4> ypositions; AlignedStorage<float4> zpositions; AlignedStorage<float4> xvelocities; AlignedStorage<float4> yvelocities; AlignedStorage<float4> zvelocities; std::vector<u32> colors; std::vector<float> radiuses; std::vector<float> rotations; Scene(int count) : xpositions(count / 4) , ypositions(count / 4) , zpositions(count / 4) , xvelocities(count / 4) , yvelocities(count / 4) , zvelocities(count / 4) , colors(count) , radiuses(count) , rotations(count) { count /= 4; for (int i = 0; i < count; ++i) { xpositions[i] = random_float4(1.0f); ypositions[i] = random_float4(1.0f); zpositions[i] = random_float4(2.0f); xvelocities[i] = random_float4(1.0f); yvelocities[i] = random_float4(2.0f); zvelocities[i] = random_float4(5.0f); } } void transform() { const int count = xpositions.size(); for (int i = 0; i < count; ++i) { xpositions[i] += xvelocities[i]; ypositions[i] += yvelocities[i]; zpositions[i] += zvelocities[i]; } } }; } // namespace // ---------------------------------------------------------------------- // method4: SoA with vector types // ---------------------------------------------------------------------- namespace method4 { // configure SIMD vector type using VectorType = float32x4; // 3-dimensional vector of VectorType using PackedVector = Vector<VectorType, 3>; constexpr int N = VectorType::VectorSize; VectorType vrandom() { VectorType v; for (int i = 0; i < N; ++i) { v[i] = dist(mt); } return v; } struct Scene { AlignedStorage<PackedVector> positions; AlignedStorage<PackedVector> velocities; std::vector<u32> colors; std::vector<float> radiuses; std::vector<float> rotations; Scene(int count) : positions(count / N) , velocities(count / N) , colors(count) , radiuses(count) , rotations(count) { count /= N; for (int i = 0; i < count; ++i) { positions[i].x = vrandom(); positions[i].y = vrandom(); positions[i].z = vrandom(); velocities[i].x = vrandom(); velocities[i].y = vrandom(); velocities[i].z = vrandom(); } } void transform() { const int count = positions.size(); for (int i = 0; i < count; ++i) { positions[i].x += velocities[i].x; positions[i].y += velocities[i].y; positions[i].z += velocities[i].z; } /* generated code with g++ 7.1 .L631: movaps (%rax), %xmm0 addq $48, %rax addq $48, %rcx addps -48(%rcx), %xmm0 movaps %xmm0, -48(%rax) movaps -32(%rax), %xmm0 addps -32(%rcx), %xmm0 movaps %xmm0, -32(%rax) movaps -16(%rax), %xmm0 addps -16(%rcx), %xmm0 movaps %xmm0, -16(%rax) cmpq %rax, %rsi jne .L631 */ } }; } // namespace // ---------------------------------------------------------------------- // main() // ---------------------------------------------------------------------- /* Timings on i7 3770K processor using AVX instructions for 1,000,000 particles and 60 frames: method1: 263 ms (228 fps) method2: 151 ms (397 fps) method3: 121 ms (495 fps) method4: 110 ms (545 fps) Conclusion: the effects of memory layout can double the performance. */ int main(int argc, const char* argv[]) { const int count = 1000 * 1000; method1::Scene scene1(count); method2::Scene scene2(count); method3::Scene scene3(count); method4::Scene scene4(count); u64 time1 = 0; u64 time2 = 0; u64 time3 = 0; u64 time4 = 0; const int frames = 60; for (int i = 0; i < frames; ++i) { u64 s0 = Time::ms(); scene1.transform(); u64 s1 = Time::ms(); scene2.transform(); u64 s2 = Time::ms(); scene3.transform(); u64 s3 = Time::ms(); scene4.transform(); u64 s4 = Time::ms(); time1 += (s1 - s0); time2 += (s2 - s1); time3 += (s3 - s2); time4 += (s4 - s3); } printf("Rendered %d frames in...\n", frames); printf("time: %d ms (%d fps)\n", int(time1), int(frames * 1000 / time1)); printf("time: %d ms (%d fps)\n", int(time2), int(frames * 1000 / time2)); printf("time: %d ms (%d fps)\n", int(time3), int(frames * 1000 / time3)); printf("time: %d ms (%d fps)\n", int(time4), int(frames * 1000 / time4)); }
import { log, loadFrequencyMap } from "./util.js"; import * as Config from "./config.js"; enum GuessOutcome { Green = "g", Yellow = "y", Grey = ".", } function guessOutcomeFromChar(char: string): GuessOutcome { switch (char) { case "g": return GuessOutcome.Green; case "y": return GuessOutcome.Yellow; case ".": return GuessOutcome.Grey; default: throw new Error(`Invalid guess outcome: ${char}`); } } type Guess = { word: string; result: GuessOutcome[]; }; class Wordler { // the dictionary is a map of words to their frequency // as words are filtered out, they are removed dictionary: Map<string, number> = loadFrequencyMap("dict/dict-with-frequencies.txt"); // the board is an array of entries for each slot // each of which is either a single letter or set of possible letters board: (Set<string> | string)[] = []; // Letters which are known to be in the word // Lote that even when we place a letter, it can still appear again somewhere else, so we leave it in the set includedLetters: Set<string> = new Set(); // hard mode is a boolean which indicates whether we must guess the same letter once we know it's in a certain slot hardMode = true; // first guess is a boolean which indicates whether we're on the first guess firstGuess = true; constructor() { // fill each board slot with the alphabet // there must be a more idiomatic way to do this const alphabet = Array<string>(26); for (let i = 0; i < 26; i++) { alphabet[i] = String.fromCharCode(65 + i); } for (let i = 0; i < Config.WordLength; i++) { this.board.push(new Set(alphabet)); } } // handle result takes a guess and a result and updates the state handleResult(guess: Guess): void { for (let i = 0; i < guess.result.length; i++) { const letter = guess.word[i]; const result = guess.result[i]; switch (result) { case GuessOutcome.Green: { this.board[i] = letter; break; } case GuessOutcome.Yellow: { this.includedLetters.add(letter); const boardElement = this.board[i]; if (boardElement instanceof Set) { boardElement.delete(letter); } break; } case GuessOutcome.Grey: { // remove letter from all sets for (let j = 0; j < this.board.length; j++) { const boardElement = this.board[j]; if (boardElement instanceof Set) { boardElement.delete(letter); } } break; } } } this.printBoard(); this.updateDictionary(); } printBoard(): void { // map first set to a string log("Board:"); log( this.board .map(function (set) { return Array.from(set).join(" "); }) .join("\n") ); log(`\nUnplaced letters: ${Array.from(this.includedLetters).join(" ")}\n`); } // does a word match the current board? wordMatchesBoard(word: string): boolean { for (let i = 0; i < word.length; i++) { const letter = word[i]; const boardElement = this.board[i]; if (boardElement instanceof Set) { if (!boardElement.has(letter)) { return false; } } else { if (boardElement !== letter) { return false; } } } return true; } // does a word include all included letters? wordIncludesAllUnplacedLetters(word: string): boolean { for (const letter of this.includedLetters) { if (!word.includes(letter)) { return false; } } return true; } // is a word valid? isValidWord(word: string): boolean { if (!this.wordIncludesAllUnplacedLetters(word)) { return false; } if (!this.wordMatchesBoard(word)) { return false; } return true; } // update dictionary based on the result of a guess updateDictionary(): void { for (const word of this.dictionary.keys()) { if (!this.isValidWord(word)) { this.dictionary.delete(word); } } log(`Dictionary size: ${this.dictionary.size}`); } } export { GuessOutcome, guessOutcomeFromChar, Wordler };
<gh_stars>0 package br.utfpr.gp.tsi.racing.util; public class Geometry { /** * * @param a first point of line * @param b second point of line * @param p point to know the side * @return -1 to left. +1 to right. 0 to center. */ public static int getSideOfTheLine(int ax, int ay, int bx, int by, int px, int py) { return (int) Math.signum( (bx-ax)*(py-ay) - (by-ay)*(px-ax) ); } public static double calcDistanceBetweenPoints(int x1, int y1, int x2, int y2) { return Math.abs( Math.sqrt( Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2) ) ); } }
#!/usr/bin/env bash # Directorios fuente para el backup. src_dir=("/home/kali" "/home/guest" "/root/.bashrc" "/root/.ssh/") # Directorio destino para guardar los backup. tgt_dir="/home/kali/Backup" # Exluir los ficheros que concuerden con el patrón. exclude=("Backup/") exclude+=("Downloads/" "mnt/" "tmp/") # Eliminar backups anteriores a 2 meses. age=$(date +%F --date='2 months ago') for i in "$tgt_dir"/* do if [[ -d $i ]] && [[ ${age//-} -ge $(echo "$i" | sed -r 's/^.*([0-9]{4})-([0-9]{2})-([0-9]{2})T.*$/\1\2\3/') ]] 2>/dev/null then rm -rf "$i" fi done # Generar una lista del array de input. src_dir=$(printf -- '"%s" ' "${src_dir[@]}") # Generamos una lista con el array de excluídos. exclude=$(printf -- "--exclude '%s' " "${exclude[@]}") # Crear el directorio de backup en caso de no existir. [[ ! -d $tgt_dir ]] && mkdir -p "$tgt_dir" # Directorio de backup actual, ej. "2020-12-05T05:02:40"; now=$(date +%FT%H:%M:%S) # Directorio de backup previo. prev=$(ls "$tgt_dir" | grep -e '^....-..-..T..:..:..$' | tail -1); make_backup() { if [[ -z $prev ]]; then # Backup inicial. eval rsync -av --delete ${exclude} ${src_dir} "$tgt_dir/$now/" else # Backup incremental. eval rsync -av --delete --link-dest="$tgt_dir/$prev/" ${exclude} ${src_dir} "$tgt_dir/$now/" fi }; make_backup > "${tgt_dir}/.backup.log" 2>&1 # Crea un log ocn unas estadísticas. echo -e "\n${now}\t$(du -hs "$tgt_dir/$now")\n" >> "${tgt_dir}/.backup.log" df -h "$tgt_dir" >> "${tgt_dir}/.backup.log" exit 0;
<gh_stars>1-10 /* eslint-disable @typescript-eslint/no-var-requires */ require('dotenv').config(); import { WebsiteCarbonCalculator, WebsiteCarbonCalculatorError } from '../src'; jest.setTimeout(60000); let websiteCarbonCalculator: null | WebsiteCarbonCalculator; describe('Website Carbon Calculator', () => { beforeEach(() => { websiteCarbonCalculator = null; }); it('Should calculate the carbon emission for a given URL', async () => { websiteCarbonCalculator = new WebsiteCarbonCalculator({ pagespeedApiKey: process.env.GOOGLE_PAGESPEED_API_KEY, }); const result = await websiteCarbonCalculator.calculateByURL( 'https://ricardodantas.me' ); expect(websiteCarbonCalculator).toBeInstanceOf(WebsiteCarbonCalculator); expect(result).toEqual( expect.objectContaining({ url: 'https://ricardodantas.me', bytesTransferred: expect.any(Number), isGreenHost: expect.any(Boolean), co2PerPageview: expect.any(Number), }) ); }); it('Should throw error due the missing Google Pagespeed API Key', () => { expect(() => { new WebsiteCarbonCalculator({ pagespeedApiKey: null }); }).toThrowError(WebsiteCarbonCalculatorError); }); it('Should throw error for a non existent website', async () => { await expect(async () => { websiteCarbonCalculator = new WebsiteCarbonCalculator({ pagespeedApiKey: process.env.GOOGLE_PAGESPEED_API_KEY, }); await websiteCarbonCalculator.calculateByURL( 'https://something.invalid.xpto' ); }).rejects.toThrowError(WebsiteCarbonCalculatorError); }); it('Should throw an error for a given invalid URL', async () => { await expect(async () => { websiteCarbonCalculator = new WebsiteCarbonCalculator({ pagespeedApiKey: process.env.GOOGLE_PAGESPEED_API_KEY, }); await websiteCarbonCalculator.calculateByURL('somethinginvalid.com'); }).rejects.toThrowError('Ops! This is an invalid URL.'); }); });
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import actionCreators from 'actions'; import {Link} from 'react-router'; import {flatButton, divStyle, center, PalanquinImage} from 'styles'; import Modal from 'react-modal'; import * as R from 'ramda'; import * as l from 'lodash-fp'; import {Motion, spring} from 'react-motion'; import {TransitionMotion} from 'react-motion'; const getStyles = function(blocks) { let configs = {}; //or blocks.keys.map blocks.map(key => { configs[key] = { opacity: spring(1, [50, 10]), height: spring(20), text: key // not interpolated }; }); return configs; } const willEnter = function(inputText) { return { opacity: 0, width: 0, height: 0, // start at 0, gradually expand text: inputText // this is really just carried around so // that interpolated values can still access the text when the key is gone // from actual `styles` }; } const willLeave = function(key, style) { return { opacity: spring(0, [100, 10]), // make opacity reach 0, after which we can kill the key text: style.text, height: spring(0, [100, 15]) }; } export const speakers = (speakers) => { return <TransitionMotion styles={getStyles(speakers)} willEnter={willEnter} willLeave={willLeave}> {interpolatedStyles => <div> {Object.keys(interpolatedStyles).map(key => { const {text, ...style} = interpolatedStyles[key]; return ( <div style={style} onClick={()=> console.log('hellow')}> {text} </div> ); })} </div> } </TransitionMotion> } const mapStateToProps = (state) => ({ poem : state.poem, routerState : state.router, poemlist : state.poemlist }); const mapDispatchToProps = (dispatch) => ({ actions : bindActionCreators(actionCreators, dispatch) }); export class HomeView2 extends React.Component { constructor(props){ super(props) this.state = {visible: false} console.log(this.state) } static propTypes = { actions : React.PropTypes.object, poem : React.PropTypes.object, poemlist : React.PropTypes.array } closeMe(){ this.setState({visible: false}); } render () { let {poemLoad} = this.props.actions; return ( <div style={{ minHeight: '100vh', flexDirection: 'column', display: 'flex', alignItems: 'center', justifyContent: 'center', alignContent: 'flex-end' }}> <div style={{alignSelf: 'flex-end', backgroundColor: 'red', display: 'flex', alignItems: 'flex-end'}}> <div style={{fontSize: 40}}> <strong>{speakers(['hello'])}</strong> </div> </div> <div style={{alignSelf: 'center', flexWrap: 'wrap', display: 'flex', justifyContent: 'center', flex: 1}}> <div style={{alignSelf: 'center', backgroundColor: 'red', fontSize: 40}}> <strong>Center</strong> </div> </div> <div style={{alignSelf: 'flex-start', backgroundColor: 'red', display: 'flex', alignItems: 'flex-end'}}> <div style={{fontSize: 40}}> <strong>Bottom</strong> </div> </div> <div style={{alignSelf: 'flex-end', backgroundColor: 'red', display: 'flex', alignItems: 'flex-end'}}> <div style={{fontSize: 40}}> <strong>Bottom</strong> </div> </div> <div style={{alignSelf: 'flex-end', backgroundColor: 'red', display: 'flex', alignItems: 'flex-end'}}> <div style={{fontSize: 40}}> <strong>Bottom</strong> </div> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(HomeView2);
<gh_stars>10-100 from uuid import uuid4 import flask from blok.http_api import api from blok.node_server import BlockChain def get_app() -> flask.Flask: app = flask.Flask(__name__) app.blockchain = BlockChain() app.node_address = uuid4().hex app.register_blueprint(api) return app
package beater import ( "fmt" "time" ldap "gopkg.in/ldap.v2" "github.com/elastic/beats/libbeat/beat" "github.com/elastic/beats/libbeat/common" "github.com/elastic/beats/libbeat/logp" "github.com/kwojcicki/ldapbeat/config" ) // Ldapbeat - struct for beater type Ldapbeat struct { done chan struct{} config config.LdapBeatConfig client beat.Client } // New - Creates Beater func New(b *beat.Beat, cfg *common.Config) (beat.Beater, error) { config := config.DefaultConfig if err := cfg.Unpack(&config); err != nil { return nil, fmt.Errorf("Error reading config file: %v", err) } bt := &Ldapbeat{ done: make(chan struct{}), config: config, } return bt, nil } func (bt *Ldapbeat) query(conn *ldap.Conn, query config.LDAPQuery) *ldap.SearchResult { searchRequest := ldap.NewSearchRequest( query.BaseDN, query.Scope, query.DeRefAliases, query.Sizelimit, query.Timelimit, query.Typesonly, query.Query, query.Attributes, nil, ) sr, err := conn.Search(searchRequest) if err != nil { logp.Warn("Couldn't query ldap server: %s", err) return nil } return sr } func (bt *Ldapbeat) connectToLDAP() (*ldap.Conn, error) { conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", bt.config.Server, bt.config.Port)) if err != nil { logp.Warn("Couldn't connect to the ldap server: %s", err) return nil, err } logp.Info("Connected") err = conn.Bind(bt.config.Username, bt.config.Password) if err != nil { logp.Warn("Couldn't bind to the ldap server: %s", err) return nil, err } return conn, nil } func (bt *Ldapbeat) publishEvent(result *ldap.SearchResult, query config.LDAPQuery) { for _, entry := range result.Entries { fields := common.MapStr{ "query": query.Query, } for _, attribute := range query.Attributes { if attribute == "dn" || attribute == "DN" { fields["dn"] = entry.DN } else { fields[attribute] = entry.GetAttributeValue(attribute) } } event := beat.Event{ Timestamp: time.Now(), Fields: fields, } bt.client.Publish(event) logp.Info("Event sent") } } // Run - basic run loop for beat func (bt *Ldapbeat) Run(b *beat.Beat) error { logp.Info("ldapbeat is running! Hit CTRL-C to stop it.") var err error bt.client, err = b.Publisher.Connect() if err != nil { return err } ticker := time.NewTicker(bt.config.Period) for { select { case <-bt.done: return nil case <-ticker.C: } func() { for _, query := range bt.config.Queries { conn, err := bt.connectToLDAP() if err != nil { continue } defer conn.Close() result := bt.query(conn, query) bt.publishEvent(result, query) } }() } } // Stop - stops beat func (bt *Ldapbeat) Stop() { bt.client.Close() close(bt.done) }
#! /bin/bash KernelBranch="base-r-oss-custom-release-uv-SLMK" IncludeFiles "${MainPath}/device/merlin-r-oss.sh" CustomUploader="Y" IncludeFiles "${MainPath}/misc/kernel.sh" "https://${GIT_SECRET}@github.com/${GIT_USERNAME}/lancelot_kernels" FolderUp="shared-file" TypeBuildTag="[SLMK][1000Mhz]" CloneKernel "--depth=1" ChangeConfigData # pullBranch "base-r-oss-custom-ALMK" "[STABLE][ALMK][1000Mhz]" # pullBranch "base-r-oss-custom-SLMK" "[TEST][SLMK][1000Mhz]" CloneZyCFifTeenClang OptimizaForPerf # DisableMsmP DisableThin EnableRELR CompileClangKernelLLVM && CleanOut
import React, { Component,PropTypes } from 'react'; import BookSearchItem from './BookSearchItem'; import styles from './BookSearch.css'; // Dumb React Component export default class BookSearch extends Component { // Expectation to render BookSearch method static propTypes = { catalog: PropTypes.array.isRequired, onBookAdd: PropTypes.func.isRequired, }; constructor() { super(); } render() { const {catalog, onBookAdd} = this.props; return ( <ul className='book--list'> {catalog.map((book, index) => <li key={index} className='book--list__list-item'> <BookSearchItem title={book.volumeInfo.title} description={book.volumeInfo.description} imageLinks={book.volumeInfo.imageLinks} addBook={onBookAdd} id={index} /> </li>)} </ul> ); } }
// Final Project Milestone 4 // CustomMade Tester program // File CustomMadeTester.cpp // Version 1.0 // Date 2019/11/16 // Author <NAME> // ///////////////////////////////////////////////////////////////// #include "CustomMade.h" using namespace ict; using namespace std; #define FileName "csMd.txt" void piv(const char* sku, const char* name, const char* price = "", const char* taxed = "", const char* qty = "", const char* qtyNd = "", const char* date = "") { cout << "Enter the following: " << endl << "Sku: " << sku << endl << "Name: " << name << endl; if (price[0]) cout << "Price: " << price << endl; if (taxed[0]) cout << "Taxed: " << taxed << endl; if (qty[0]) cout << "Quantity on hand: " << qty << endl; if (qtyNd[0]) cout << "Quantity needed: " << qtyNd << endl; if (date[0]) cout << "Delivery date: " << date << endl; cout << endl; } void dumpFile(const char* fname) { ifstream f(fname); char ch; while (!f.get(ch).fail()) { cout.put(ch); } f.clear(); f.close(); } void _pause() { cout << "****press enter to continue..."; cin.ignore(1000, '\n'); } int main() { fstream csMdfile(FileName, ios::out); CustomMade csmd; bool ok = true; cout << "--CustomMade Item test:" << endl; cout << "----Price validation test:" << endl; piv("abc", "abc", "abc"); cin >> csmd; if (cin.fail()) { cin.clear(); cin.ignore(2000, '\n'); cout << "Passed " << csmd << endl; } else { ok = false; cout << "Price validaton failed" << endl; } _pause(); if (ok) { cout << "----Taxed validation test:" << endl; piv("abc", "abc", "10", "abc"); cin >> csmd; if (cin.fail()) { cin.clear(); cin.ignore(2000, '\n'); cout << "Passed " << csmd << endl; } else { ok = false; cout << "Quantity validaton failed" << endl; } } _pause(); if (ok) { cout << "----Quantity Validation test:" << endl; piv("abc", "abc", "10", "y", "abc"); cin >> csmd; if (cin.fail()) { cin.clear(); cin.ignore(2000, '\n'); cout << "Passed " << csmd << endl; } else { ok = false; cout << "Quantity validaton failed" << endl; } } _pause(); if (ok) { cout << "----Quantity Needed Validation test:" << endl; piv("abc", "abc", "10", "n", "10", "abc"); cin >> csmd; if (cin.fail()) { cin.clear(); cin.ignore(2000, '\n'); cout << "Passed " << csmd << endl; } else { ok = false; cout << "Quantity Needed validaton failed" << endl; } } _pause(); if (ok) { cout << "----Delivery date Validation test:" << endl; piv("abc", "abc", "10", "y", "10", "10", "10/1/1"); cin >> csmd; if (cin.fail()) { cin.clear(); cout << "Passed " << csmd << endl; } else { ok = false; cout << "delivery date validaton failed" << endl; } cin.ignore(2000, '\n'); } _pause(); if (ok) { cout << "----Display test, the output of the Program and yours must match:" << endl; piv("1234", "centerpiece", "123.45", "y", "1", "15", "2017/10/12"); cin >> csmd; cin.ignore(2000, '\n'); cout << "--Linear------------" << endl; cout << "Program: 1234|centerpiece | 139.50| t | 1| 15|2017/10/12" << endl; cout << " Yours: " << csmd << endl; cout << "--Form Display------" << endl; cout << "--Program: " << endl; cout << "sku: 1234" << endl; cout << "name: centerpiece" << endl; cout << "price: 123.45" << endl; cout << "Price after tax: 139.50" << endl; cout << "Quantity On hand: 1" << endl; cout << "Quantity Needed: 15" << endl; cout << "delivery date: 2017/10/12" << endl; cout << "--Yours: " << endl; csmd.display(cout, false) << endl; } _pause(); if (ok) { cout << "----Storage and loading test, the output of the Program and yours must match:" << endl; CustomMade tcsmd; csmd.store(csMdfile); csmd.store(csMdfile); csMdfile.close(); cout << "--Store CustomMade, program: " << endl << "C,1234,centerpiece,123.45,1,1,15,2017/10/12" << endl << "C,1234,centerpiece,123.45,1,1,15,2017/10/12" << endl; cout << "--Store CustomMade, yours: " << endl; dumpFile("csmd.txt"); cout << "--Load CustomMade: " << endl; csMdfile.open("csmd.txt", ios::in); csMdfile.ignore(2); tcsmd.load(csMdfile); cout << "Program: 1234|centerpiece | 139.50| t | 1| 15|2017/10/12" << endl; cout << " Yours: " << tcsmd << endl; csMdfile.clear(); csMdfile.close(); } return 0; }
<gh_stars>0 import Vue from 'vue' import App from './App.vue' import router from './router' import './app.scss' import BootstrapVue from 'bootstrap-vue' import { formatTimestamp } from './lib/formatter' Vue.use(BootstrapVue) Vue.config.productionTip = false // Filters Vue.filter('symbolFormat', value => { return value ? 'Yes' : 'No' }) Vue.filter('dateFormat', value => { if (!value || value <= 0) { return '' } return formatTimestamp(value) }) new Vue({ router: router, render: h => h(App), }).$mount('#app')
rm /testing.txt cp /etc/resolv.conf /testing.txt sed -i s/127.0.0.11/8.8.8.8/ /testing.txt cat /testing.txt > /etc/resolv.conf cat /etc/resolv.conf
#!/bin/bash make clean M4=m4 \ CC=~/txgoto/llvm/build/bin/clang \ CFLAGS="-fsanitize=thread -fPIE -pie -g -Ofast" \ LDFLAGS="-fsanitize=thread -fPIE -pie -g -Ofast" \ make version=pthreads -j4 mv ocean_ncp ocean_ncp.gtsan.exe
#!/bin/bash if [[ $KAFKA_MANAGER_USERNAME != '' && $KAFKA_MANAGER_PASSWORD != '' ]]; then sed -i.bak '/^basicAuthentication/d' /opt/kafka-manager/conf/application.conf echo 'basicAuthentication.enabled=true' >> /opt/kafka-manager/conf/application.conf echo "basicAuthentication.username=${KAFKA_MANAGER_USERNAME}" >> /opt/kafka-manager/conf/application.conf echo "basicAuthentication.password=${KAFKA_MANAGER_PASSWORD}" >> /opt/kafka-manager/conf/application.conf echo 'basicAuthentication.realm="Kafka-Manager"' >> /opt/kafka-manager/conf/application.conf fi exec ./bin/kafka-manager -Dconfig.file=${KAFKA_MANAGER_CONFIGFILE} -Dhttp.port=9000 "${KAFKA_MANAGER_ARGS}" "${@}"
cd ~ sudo yum install -y gcc-c++ git htop iotop atop snappy snappy-devel zlib zlib-devel bzip2 bzip2-devel lz4-devel sysstat wget nano sudo mkdir /data-ebs sudo chown ec2-user:ec2-user /data-ebs wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh mv git-prompt.sh /home/ec2-user/.git-prompt.sh cat <<EOF | tee -a ~/.bashrc source ~/.git-prompt.sh PS1='\[\033[0;34m\]loadtest\[\033[0;33m\] \w\[\033[00m\]\$(__git_ps1)\n> ' alias l="ls -la" alias ..="cd .." export DATADIR=/data export DATADIREBS=/data-ebs EOF export ROCKSVERSION=5.1.4 wget https://github.com/facebook/rocksdb/archive/v$ROCKSVERSION.tar.gz tar -xzvf v$ROCKSVERSION.tar.gz cd rocksdb-$ROCKSVERSION export USE_RTTI=1 && make shared_lib sudo make install-shared sudo ldconfig # to update ld.so.cache echo "export LD_LIBRARY_PATH=/home/ec2-user/rocksdb-$ROCKSVERSION/" >> ~/.bashrc source ~/.bashrc arch="" case $(uname -m) in i386) arch="386" ;; i686) arch="386" ;; x86_64) arch="amd64" ;; arm) dpkg --print-architecture | grep -q "arm64" && arch="arm64" || arch="arm" ;; esac cd ~ wget https://storage.googleapis.com/golang/go1.13.7.linux-$arch.tar.gz sudo tar -C /usr/local -xzf go1.13.7.linux-$arch.tar.gz sudo ln -s /usr/local/go/bin/go /usr/bin/go sudo mkdir /usr/local/share/go sudo mkdir /usr/local/share/go/bin sudo chmod 777 /usr/local/share/go cd ~/badger-bench go mod init github.com/dgraph-io/badger-bench echo ' fs.file-max = 999999 net.ipv4.tcp_rmem = 4096 4096 16777216 net.ipv4.tcp_wmem = 4096 4096 16777216 ' | sudo tee -a /etc/sysctl.conf echo '1024 65535' | sudo tee /proc/sys/net/ipv4/ip_local_port_range echo ' * - nofile 999999 ' | sudo tee -a /etc/security/limits.conf echo 100 | sudo tee /proc/sys/vm/dirty_expire_centisecs echo 100 | sudo tee /proc/sys/vm/dirty_writeback_centisecs echo 50 | sudo tee /proc/sys/vm/dirty_background_ratio echo 80 | sudo tee /proc/sys/vm/dirty_ratio exit # Copy/paste this #--- sudo yum install -y git git clone https://github.com/kevburnsjr/badger-bench cd ~/badger-bench chmod +x init.sh ./init.sh sudo mkfs -t ext4 /dev/nvme0n1 sudo mkdir /data sudo mount /dev/nvme0n1 /data sudo chown ec2-user:ec2-user /data #--- # end # GCP sudo mkfs -t ext4 /dev/nvme0n1 sudo mkdir /data1 sudo mount /dev/nvme0n1 /data1 sudo chown kevburnsjr:kevburnsjr /data1 sudo mkfs -t ext4 /dev/nvme0n2 sudo mkdir /data2 sudo mount /dev/nvme0n2 /data2 sudo chown kevburnsjr:kevburnsjr /data2 sudo mkfs -t ext4 /dev/nvme0n3 sudo mkdir /data3 sudo mount /dev/nvme0n3 /data3 sudo chown kevburnsjr:kevburnsjr /data3 sudo mkfs -t ext4 /dev/nvme0n4 sudo mkdir /data4 sudo mount /dev/nvme0n4 /data4 sudo chown kevburnsjr:kevburnsjr /data4 sudo mkdir /data sudo chown kevburnsjr:kevburnsjr /data sudo mkdir /data/test ln -s /data1 /data/test/0 ln -s /data2 /data/test/1 ln -s /data3 /data/test/2 ln -s /data4 /data/test/3 #--- sudo mkfs -t ext4 /dev/sdb sudo mkdir /data sudo mount /dev/sdb /data sudo mkfs -t ext4 /dev/sdc sudo mkdir /data-nvme sudo mount /dev/sdc /data-nvme sudo mkfs -t ext4 /dev/xvdf sudo mkdir /data-ebs sudo mount /dev/xvdf /data-ebs sudo chown ec2-user:ec2-user /data-ebs sudo mkfs -t ext4 /dev/nvme1n1 sudo mkdir /data-ebs-2 sudo mount /dev/nvme1n1 /data-ebs-2 sudo chown ec2-user:ec2-user /data-ebs-2 driveletters=( f g h i j k l m n o p q r s t u ) for i in {0..15} do h=$(printf "%x" $i) d="${driveletters[$i]}" sudo umount /data/$h sudo mkfs -t ext4 /dev/xvd$d sudo mount /dev/xvd$d /data/$h sudo chown ec2-user:ec2-user /data/$h done # a1 sudo mkfs -t ext4 /dev/nvme2n1 sudo mkdir /data-ebs sudo mount /dev/nvme2n1 /data-ebs sudo chown ec2-user:ec2-user /data-ebs # i3.2xl nvme partitions sudo mkfs -t ext4 /dev/nvme0n1p1 sudo mkfs -t ext4 /dev/nvme0n1p2 sudo mkfs -t ext4 /dev/nvme0n1p3 sudo mkfs -t ext4 /dev/nvme0n1p4 sudo mkdir -p /data/0 sudo mkdir -p /data/1 sudo mkdir -p /data/2 sudo mkdir -p /data/3 sudo mount /dev/nvme0n1p1 /data/0 sudo mount /dev/nvme0n1p2 /data/1 sudo mount /dev/nvme0n1p3 /data/2 sudo mount /dev/nvme0n1p4 /data/3 sudo chown ec2-user:ec2-user /data/0 sudo chown ec2-user:ec2-user /data/1 sudo chown ec2-user:ec2-user /data/2 sudo chown ec2-user:ec2-user /data/3
package messages import ( "fmt" ) // FormatAmount formats a cent amount as dollars. func FormatAmount(v int64) string { f := "$%d.%02d" if v < 0 { v = -v f = "-" + f } return fmt.Sprintf(f, v/100, v%100) }
package org.apache.spark.hbase import org.apache.spark.{ SparkContext, TaskContext } import org.apache.spark.broadcast.Broadcast import org.apache.spark.SerializableWritable import org.apache.hadoop.conf.Configuration import org.apache.hadoop.security.Credentials import org.apache.spark.rdd.RDD import org.apache.spark.Partition import org.apache.spark.InterruptibleIterator import org.apache.hadoop.hbase.mapreduce.TableInputFormat import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil import org.apache.hadoop.hbase.client.Scan import org.apache.hadoop.hbase.mapreduce.IdentityTableMapper import org.apache.hadoop.mapreduce.Job import org.apache.hadoop.mapreduce.SparkHadoopMapReduceUtil import org.apache.spark.Logging import org.apache.hadoop.mapreduce.JobID import org.apache.hadoop.io.Writable import org.apache.hadoop.mapreduce.InputSplit import java.text.SimpleDateFormat import java.util.Date import java.util.ArrayList import org.apache.hadoop.security.UserGroupInformation import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod import org.apache.hadoop.hbase.mapreduce.IdentityTableMapper class HBaseScanRDD(sc: SparkContext, @transient tableName: String, @transient scan: Scan, configBroadcast: Broadcast[SerializableWritable[Configuration]], credentialBroadcast: Broadcast[SerializableWritable[Credentials]]) extends RDD[(Array[Byte], java.util.List[(Array[Byte], Array[Byte], Array[Byte])])](sc, Nil) with SparkHadoopMapReduceUtil with Logging { /// @transient val jobTransient = new Job(configBroadcast.value.value, "ExampleRead"); TableMapReduceUtil.initTableMapperJob( tableName, // input HBase table name scan, // Scan instance to control CF and attribute selection classOf[IdentityTableMapper], // mapper null, // mapper output key null, // mapper output value jobTransient); @transient val jobConfigurationTrans = jobTransient.getConfiguration() jobConfigurationTrans.set(TableInputFormat.INPUT_TABLE, tableName) val jobConfigBroadcast = sc.broadcast(new SerializableWritable(jobConfigurationTrans)) //// private val jobTrackerId: String = { val formatter = new SimpleDateFormat("yyyyMMddHHmm") formatter.format(new Date()) } @transient protected val jobId = new JobID(jobTrackerId, id) override def getPartitions: Array[Partition] = { addCreds val tableInputFormat = new TableInputFormat tableInputFormat.setConf(jobConfigBroadcast.value.value) val jobContext = newJobContext(jobConfigBroadcast.value.value, jobId) val rawSplits = tableInputFormat.getSplits(jobContext).toArray val result = new Array[Partition](rawSplits.size) for (i <- 0 until rawSplits.size) { result(i) = new NewHadoopPartition(id, i, rawSplits(i).asInstanceOf[InputSplit with Writable]) } result } override def compute(theSplit: Partition, context: TaskContext): InterruptibleIterator[(Array[Byte], java.util.List[(Array[Byte], Array[Byte], Array[Byte])])] = { addCreds val iter = new Iterator[(Array[Byte], java.util.List[(Array[Byte], Array[Byte], Array[Byte])])] { addCreds val split = theSplit.asInstanceOf[NewHadoopPartition] logInfo("Input split: " + split.serializableHadoopSplit) val conf = jobConfigBroadcast.value.value val attemptId = newTaskAttemptID(jobTrackerId, id, isMap = true, split.index, 0) val hadoopAttemptContext = newTaskAttemptContext(conf, attemptId) val format = new TableInputFormat format.setConf(conf) val reader = format.createRecordReader( split.serializableHadoopSplit.value, hadoopAttemptContext) reader.initialize(split.serializableHadoopSplit.value, hadoopAttemptContext) // Register an on-task-completion callback to close the input stream. context.addOnCompleteCallback(() => close()) var havePair = false var finished = false override def hasNext: Boolean = { if (!finished && !havePair) { finished = !reader.nextKeyValue havePair = !finished } !finished } override def next(): (Array[Byte], java.util.List[(Array[Byte], Array[Byte], Array[Byte])]) = { if (!hasNext) { throw new java.util.NoSuchElementException("End of stream") } havePair = false val it = reader.getCurrentValue.list().iterator() val list = new ArrayList[(Array[Byte], Array[Byte], Array[Byte])]() while (it.hasNext()) { val kv = it.next() list.add((kv.getFamily(), kv.getQualifier(), kv.getValue())) } (reader.getCurrentKey.copyBytes(), list) } private def close() { try { reader.close() } catch { case e: Exception => logWarning("Exception in RecordReader.close()", e) } } } new InterruptibleIterator(context, iter) } def addCreds { val creds = credentialBroadcast.value.value val ugi = UserGroupInformation.getCurrentUser(); ugi.addCredentials(creds) // specify that this is a proxy user ugi.setAuthenticationMethod(AuthenticationMethod.PROXY) } private[spark] class NewHadoopPartition( rddId: Int, val index: Int, @transient rawSplit: InputSplit with Writable) extends Partition { val serializableHadoopSplit = new SerializableWritable(rawSplit) override def hashCode(): Int = 41 * (41 + rddId) + index } }
<reponame>chrisdenman/rrd-monolith (function iffe() { function getDate(app) { var date = app.currentDate(); date.setHours(0) date.setMinutes(0) date.setSeconds(0) return date; } function getAllDayEventData(app, summary) { return { summary: summary, startDate: getDate(app), endDate: getDate(app), alldayEvent: true }; } let exitCode = 0; let summary="<<summary>>"; let calendarName = "<<calendarName>>"; let applicationName = "Calendar"; let app = Application.currentApplication(); app.includeStandardAdditions = true; let Calendar = Application(applicationName); try { let targetCalendar = Calendar.calendars.whose({name: calendarName})[0]; if (targetCalendar) { let event = Calendar.Event(getAllDayEventData(app, summary)); targetCalendar.events.push(event); } else { exitCode = -1 } } catch (error) { exitCode = -2 } return exitCode; })();
<gh_stars>1-10 #include "main.h" void I2C1_Setup() { //Configure I2C Pins as Digital ANSELBbits.ANSB4 = DIGITAL; //Configure I2C pins as inputs TRIS_I2C_SCK = INPUT; TRIS_I2C_SDA = INPUT; //Configure MSSP for I2C mode #ifdef _PIC16F1829_H_ SSP1ADD = 0x4F; //Calculate for ~100 KHz I2C Clock SSP1CON1bits.SSPEN = 1; //1 = Enables the serial port and configures the SDAx and SCLx pins as the source of the serial port pins(3) SSP1CON1bits.SSPM = 0b1000; //1000 = I2C Master mode, clock = FOSC / (4 * (SSPxADD+1))(4) SSP1STATbits.SMP = 1; //1 = Slew rate control disabled for standard speed mode (100 kHz and 1 MHz) SSP1STATbits.CKE = 1; //1 = Enable input logic so that thresholds are compliant with SMbus specification SSP1CON3bits.SDAHT = 1; //1 = Minimum of 300 ns hold time on SDAx after the falling edge of SCLx SSP1CON2bits.RCEN = 0; //1 = Enables Receive mode for I2C // SSPBUF 0x00; SSP1BUF = 0x00; // SSPMSK 0x00; SSP1MSK = 0x00; #endif } void I2C1_WaitIdle() { uint16_t watchdog = 15000; while( ( (!SSP1CON2bits.SEN) || (!SSP1STATbits.R_nW) || (!SSP1CON2bits.RSEN) || (!SSP1CON2bits.PEN) || (!SSP1CON2bits.ACKEN) ) && (watchdog !=0) ) { --watchdog; } #ifdef _DEBUG_UART_ UART_Debug("Error: I2C not idle!\r\n"); #endif } uint8_t I2C1_SendByte(uint8_t data) { SSP1BUF = data; I2C1_WaitIdle(); return (uint8_t)(!SSP1CON2bits.ACKSTAT); } uint8_t I2C1_ReadByte() { SSP1CON2bits.RCEN = 1; while (SSP1CON2bits.RCEN == 1); return SSP1BUF; } /** Prototype: uint8_t I2C1_ReadFrame(uint8_t i2c1SlaveAddress, uint8_t *i2c1ReadPointer, uint8_t i2c1FrameLength) Input: i2c1SlaveAddress : Address of slave sending data. *i2c1ReadPointer : Pointer to starting location in file register where data is written. i2c1FrameLength : Number of bytes to receive. Output: none Description: This function is used to read from the I2C bus and store into the file register from the starting location passed as an argument. This is a blocking function and will wait until all the data is received. Usage: I2C1_ReadFrame(i2c1SlaveAddress, (char *)i2c1ReadPointer, i2c1FrameLength); */ uint8_t I2C1_ReadFrame(uint8_t i2c1SlaveAddress, uint8_t *i2c1ReadPointer, uint8_t i2c1FrameLength) { if(SSP1STATbits.S) { return I2C1_BUS_BUSY; } // initiate start condition SSP1CON2bits.SEN = 1; while (SSP1CON2bits.SEN) { } //check for bus collision if(PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } // send slave address with Read/Write bit set SSP1BUF = i2c1SlaveAddress | 0x01; while ((SSP1STATbits.BF || SSP1STATbits.R_nW) && !PIR2bits.BCL1IF); //check for bus collision if(PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } // check for acknowledgement status if (SSP1CON2bits.ACKSTAT) { SSP1CON2bits.PEN = 1; while(SSP1CON2bits.PEN) { } return I2C1_ACK_NOT_RECEIVED; } while (i2c1FrameLength) { // receive byte of data SSP1CON2bits.RCEN = 1; while(SSP1CON2bits.RCEN) { } *i2c1ReadPointer++ = SSP1BUF; // set acknowledgement status if(i2c1FrameLength == 1) { SSP1CON2bits.ACKDT = 1; } else { SSP1CON2bits.ACKDT = 0; } // send acknowledgement SSP1CON2bits.ACKEN = 1; while (SSP1CON2bits.ACKEN) { } i2c1FrameLength--; //check for bus collision if (PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } } // initiate stop condition SSP1CON2bits.PEN = 1; while (SSP1CON2bits.PEN) { } //check for bus collision if (PIR2bits.BCL1IF) { PIR2bits.BCL1IF=0; return I2C1_BUS_COLLISION; } return I2C1_SUCCESS; } /** Prototype: uint8_t I2C1_WriteFrame(uint8_t i2c1SlaveAddress, uint8_t *i2c1WritePointer, uint8_t i2c1FrameLength) Input: i2c1SlaveAddress : Address of slave receiving data. *i2c1WritePointer : Pointer to starting location in file register from where data is read. i2c1FrameLength : Number of bytes to send. Output: none Description: This function is used to write into the I2C bus. This is a blocking function and will wait until all the data is send. Usage: I2C1_WriteFrame(i2c1SlaveAddress, (char *)i2c1WritePointer, i2c1FrameLength); */ uint8_t I2C1_WriteFrame(uint8_t i2c1SlaveAddress, uint8_t *i2c1WritePointer, uint8_t i2c1FrameLength) { if (SSP1STATbits.S) { return I2C1_BUS_BUSY; } // initiate start condition SSP1CON2bits.SEN = 1; while (SSP1CON2bits.SEN) { } //check for bus collision if (PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } //write address into the buffer SSP1BUF = i2c1SlaveAddress; while (SSP1STATbits.BF || SSP1STATbits.R_nW) { } //Check for acknowledgement status if (SSP1CON2bits.ACKSTAT ) { SSP1CON2bits.PEN = 1; while (SSP1CON2bits.PEN) { } return I2C1_ACK_NOT_RECEIVED; } while (i2c1FrameLength) { //write byte into the buffer SSP1BUF = *i2c1WritePointer++; while (SSP1STATbits.BF || SSP1STATbits.R_nW) { } //Check for acknowledgement status if ( SSP1CON2bits.ACKSTAT ) { SSP1CON2bits.PEN = 1; while (SSP1CON2bits.PEN) { } return I2C1_ACK_NOT_RECEIVED; } // check for bus collision if (PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } i2c1FrameLength-- ; } //initiate stop condition SSP1CON2bits.PEN = 1; while (SSP1CON2bits.PEN) { } //check for bus collision if(PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } return I2C1_SUCCESS; } /** Prototype: uint8_t I2C1_WriteByte(uint8_t i2c1SlaveAddress, uint8_t i2c1Data) Input: i2c1SlaveAddress : Address of slave receiving data. i2c1Data : data to be send. Output: none Description: This function is used to write into the I2C bus. This is a blocking function and will wait until the data byte is send. Usage: I2C1_WriteByte(i2c1SlaveAddress, i2c1Data); */ uint8_t I2C1_WriteByte(uint8_t i2c1SlaveAddress, uint8_t i2c1Data) { if (SSP1STATbits.S) { return I2C1_BUS_BUSY; } // initiate start condition SSP1CON2bits.SEN = 1; while (SSP1CON2bits.SEN) { } //check for bus collision if (PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } //write address into the buffer SSP1BUF = i2c1SlaveAddress; while (SSP1STATbits.BF || SSP1STATbits.R_nW) { } //Check for acknowledgement status if (SSP1CON2bits.ACKSTAT ) { SSP1CON2bits.PEN = 1; while (SSP1CON2bits.PEN) { } return I2C1_ACK_NOT_RECEIVED; } //write byte into the buffer SSP1BUF = i2c1Data; while (SSP1STATbits.BF || SSP1STATbits.R_nW) { } //Check for acknowledgement status if ( SSP1CON2bits.ACKSTAT ) { SSP1CON2bits.PEN = 1; while (SSP1CON2bits.PEN) { } return I2C1_ACK_NOT_RECEIVED; } // check for bus collision if (PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } //initiate stop condition SSP1CON2bits.PEN = 1; while (SSP1CON2bits.PEN) { } //check for bus collision if(PIR2bits.BCL1IF) { PIR2bits.BCL1IF = 0; return I2C1_BUS_COLLISION; } return I2C1_SUCCESS; }
# ---------------------------------------------------------------------------- # # Package : fluentd # Version : 1.2.2 # Source repo : https://github.com/fluent/fluentd # Tested on : ubuntu_16.04 # Script License: Apache License, Version 2 or later # Maintainer : Atul Sowani <sowania@us.ibm.com> # # Disclaimer: This script has been tested in non-root mode on given # ========== platform using the mentioned version of the package. # It may not work as expected with newer versions of the # package and/or distribution. In such case, please # contact "Maintainer" of this script. # # ---------------------------------------------------------------------------- #!/bin/bash # Install dependencies. sudo apt-get update -y sudo apt-get install -y git build-essential ruby-dev ruby gnupg2 curl # Install ruby and rvm. gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB curl -L https://get.rvm.io | bash -s stable source ~/.rvm/scripts/rvm rvm install 2.4.0 rvm use 2.4.0 --default ruby -v gem install bundler # Clone and build source. git clone https://github.com/fluent/fluentd cd fluentd bundle install --path=./vendor/bundle && bundle exec rake
#!/usr/bin/env bash #set -x target=$1 out_file=$2 threads=$3 branchname=$4 function export_home() { local home_path="" if command -v cygpath >/dev/null 2>&1; then home_path=$(cygpath -m "$2") else home_path="$2" fi export $1_HOME=$home_path # Update .bashrc file token=$1_HOME= if grep -q "$token" ~/.bashrc; then sed -i -E "s|$token.*|$token$home_path|" ~/.bashrc else echo "export $1_HOME=$home_path" >> ~/.bashrc fi } # By default, kremlin master works against F* stable. Can also be overridden. function fetch_kremlin() { if [ ! -d kremlin ]; then git clone https://github.com/FStarLang/kremlin kremlin fi cd kremlin git fetch origin local ref=$(jq -c -r '.RepoVersions["kremlin_version"]' "$rootPath/.docker/build/config.json" ) echo Switching to KreMLin $ref git reset --hard $ref cd .. export_home KREMLIN "$(pwd)/kremlin" } function fetch_and_make_kremlin() { fetch_kremlin # Default build target is minimal, unless specified otherwise local target if [[ $1 == "" ]]; then target="minimal" else target="$1" fi make -C kremlin -j $threads $target || (cd kremlin && git clean -fdx && make -j $threads $target) OTHERFLAGS='--admit_smt_queries true' make -C kremlin/kremlib -j $threads export PATH="$(pwd)/kremlin:$PATH" } function fetch_hacl() { if [ ! -d hacl-star ]; then git clone https://github.com/project-everest/hacl-star hacl-star fi cd hacl-star git fetch origin local ref=$(jq -c -r '.RepoVersions["hacl_version"]' "$rootPath/.docker/build/config.json" ) echo Switching to 'HACL*' $ref git reset --hard $ref cd .. export_home HACL "$(pwd)/hacl-star" } function fetch_and_make_hacl() { fetch_hacl make -C hacl-star/dist/gcc-compatible -j $threads make -C hacl-star/dist/gcc-compatible install-hacl-star-raw (cd hacl-star/bindings/ocaml && dune build @install && dune install) } # Nightly build: verify miTLS parsers # (necessary since miTLS builds check them with "--admit_smt_queries true") function fetch_mitls() { if [ ! -d mitls-fstar ]; then git clone https://github.com/project-everest/mitls-fstar mitls-fstar fi cd mitls-fstar git fetch origin local ref=$(jq -c -r '.RepoVersions["mitls_version"]' "$rootPath/.docker/build/config.json" ) echo Switching to miTLS $ref git reset --hard $ref cd .. export_home MITLS "$(pwd)/mitls-fstar" } function rebuild_doc () { if [[ "$OS" != "Windows_NT" ]] && [[ "$branchname" == "master" ]] then git clone git@github.com:project-everest/project-everest.github.io project-everest-github-io && rm -rf project-everest-github-io/everparse && mkdir project-everest-github-io/everparse && doc/ci.sh project-everest-github-io/everparse && pushd project-everest-github-io && { git add -A everparse && if ! git diff --exit-code HEAD > /dev/null; then git add -u && git commit -m "[CI] Refresh EverParse doc" && git push else echo No git diff for the doc, not generating a commit fi errcode=$? } && popd && return $errcode fi } function test_mitls_parsers () { fetch_and_make_kremlin && OTHERFLAGS='--admit_smt_queries true' make -j $threads quackyducky lowparse && export_home QD "$(pwd)" && fetch_mitls && make -j $threads -C $MITLS_HOME/src/parsers verify } function nightly_test_quackyducky () { test_mitls_parsers } function raise () { return $1 } function build_and_test_quackyducky() { # Rebuild the EverParse documentation and push it to project-everest.github.io rebuild_doc && # Test EverParse proper fetch_and_make_kremlin && fetch_and_make_hacl && make -j $threads -k ci && # Build incrementality test pushd tests/sample && { { echo 'let foo : FStar.UInt32.t = 42ul' >> Data.fsti && echo 'let foo : FStar.UInt32.t = Data.foo' >> Test.fst && make -j $threads && git checkout Test.fst && sed -i 's!payloads!payload!g' Test.rfc && make -j $threads && git checkout Test.rfc } err=$? popd } && if [[ "$err" -gt 0 ]] ; then return "$err" ; fi && true } function exec_build() { result_file="../result.txt" local status_file="../status.txt" echo -n false >$status_file if [[ $target == "quackyducky_nightly_test" ]] then nightly_test_quackyducky else build_and_test_quackyducky fi && { echo -n true >$status_file ; } if [[ $(cat $status_file) != "true" ]]; then echo "Build failed" echo Failure >$result_file else echo "Build succeeded" echo Success >$result_file fi } # Some environment variables we want export OCAMLRUNPARAM=b export OTHERFLAGS="--query_stats" export MAKEFLAGS="$MAKEFLAGS -Otarget" export_home FSTAR "$(pwd)/FStar" cd quackyducky rootPath=$(pwd) exec_build cd ..
<reponame>ChrisLMerrill/museide package org.museautomation.ui.ide.navigation.resources; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; import net.christophermerrill.ShadowboxFx.*; import org.controlsfx.control.*; import org.jetbrains.annotations.*; import org.museautomation.core.*; import org.museautomation.core.resource.*; import org.museautomation.core.resource.storage.*; import org.museautomation.ui.extend.actions.*; import org.museautomation.ui.extend.components.*; import org.museautomation.ui.extend.edit.*; import org.museautomation.ui.extend.glyphs.*; import org.museautomation.ui.extend.javafx.*; import org.museautomation.ui.ide.*; import org.museautomation.ui.ide.navigation.*; import org.museautomation.ui.ide.navigation.resources.actions.*; import org.museautomation.ui.ide.navigation.resources.nodes.*; import org.museautomation.ui.seideimport.*; import org.museautomation.ui.settings.*; import org.slf4j.*; import java.io.*; import java.util.*; /** * @author <NAME> (see LICENSE.txt for license details) */ public class ProjectNavigator { public ProjectNavigator(MuseProject project, ResourceEditors editors) { _project = project; _editors = editors; } public Scene getScene() { if (_scene == null) _scene = createScene(); return _scene; } private Scene createScene() { Scene scene = new Scene(getNode()); scene.getStylesheets().add(getClass().getResource("/Trees.css").toExternalForm()); return scene; } public Parent getNode() { if (_node == null) { BorderPane border_pane = new BorderPane(); _node = new NotificationPane(border_pane); ResourceTreeOperationHandler ops_handler = new ResourceTreeOperationHandler(_project, _editors, _undo, _node); _tree = new ProjectResourceTree(_project, ops_handler); border_pane.setCenter(_tree.getNode()); GridPane label_box = new GridPane(); label_box.setPadding(new Insets(0, 0, 0, 5)); Button menu_button = Buttons.createMenu(20); label_box.add(menu_button, 0, 0); menu_button.setOnAction((event -> { Menu main_item = new Menu("Organize Resources By"); for (ResourceTreeNodeFactory factory : ResourceNodeFactories.getFactories()) { CheckMenuItem item = new CheckMenuItem(factory.getName()); if (factory.getName().equals(_tree.getFactory().getName())) item.setSelected(true); else item.setOnAction(e1 -> _tree.setFactory(factory)); main_item.getItems().add(item); } ContextMenu menu = new ContextMenu(main_item); menu.show(menu_button, Side.BOTTOM, 0, 0); })); Label project_label = new Label(" " + _project.getName()); project_label.setTooltip(new Tooltip("Project location: " + ((FolderIntoMemoryResourceStorage)_project.getResourceStorage()).getBaseLocation().getAbsolutePath())); Styles.addStyle(project_label, "heading"); GridPane.setHgrow(project_label, Priority.ALWAYS); GridPane.setHalignment(project_label, HPos.LEFT); label_box.add(project_label, 1, 0); if (_project_closer != null) { Button close_button = Buttons.createCancel(20); close_button.setTooltip(new Tooltip("Close Project")); label_box.add(close_button, 2, 0); GridPane.setHgrow(close_button, Priority.NEVER); GridPane.setHalignment(close_button, HPos.RIGHT); GridPane.setMargin(close_button, new Insets(5)); close_button.setOnAction((event) -> { LOG.info("Close the project!"); _project_closer.close(); }); } GridPane button_bar = new GridPane(); createButtons(button_bar); VBox header = new VBox(); header.getChildren().add(label_box); header.getChildren().add(button_bar); border_pane.setTop(header); } return _node; } private void createButtons(GridPane button_bar) { HBox edit_buttons = new HBox(); edit_buttons.setPadding(new Insets(4, 4, 4, 4)); edit_buttons.setAlignment(Pos.TOP_LEFT); edit_buttons.setSpacing(4); button_bar.add(edit_buttons, button_bar.getChildren().size(), 0); GridPane.setHgrow(edit_buttons, Priority.ALWAYS); Button add_button = createAddResourceButton(); edit_buttons.getChildren().add(add_button); Button import_button = createImportButton(); edit_buttons.getChildren().add(import_button); for (ProjectNavigatorAdditionalButtonProvider provider : BUTTON_PROVIDERS) for (Button button : provider.getButtons(_project, getNode())) edit_buttons.getChildren().add(button); } @NotNull private Button createAddResourceButton() { Button add_button = new Button("Add", Glyphs.create("FA:PLUS")); add_button.setTooltip(new Tooltip("Add new resource to project")); add_button.setOnAction(event -> { PopupDialog popper = new PopupDialog("Create", "Create resource") { CreateResourcePanel _panel; @Override protected Node createContent() { _panel = new CreateResourcePanel(_project, _undo); return _panel.getNode(); } @Override protected boolean okPressed() { CreateResourceAction action = _panel.getAction(); if (action != null) { boolean created = action.execute(_undo); if (created) showAndEditResource(action.getToken()); else { LOG.error("Cannot create resource: " + action.getErrorMessage()); return false; } } return true; } }; popper.show(add_button); }); return add_button; } @NotNull private Button createImportButton() { Button import_button = new Button("Import", Glyphs.create("FA:SIGN_IN")); import_button.setTooltip(new Tooltip("Import a SeleniumIDE test")); import_button.setOnAction(event -> { FileChooser chooser = new FileChooser(); File initial_directory = RecentFileSettings.get().suggestRecentFolder(_project); if (initial_directory.exists()) chooser.setInitialDirectory(initial_directory); chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("SeleniumIDE Test", "*.html", "*.side")); List<File> selections = chooser.showOpenMultipleDialog(getNode().getScene().getWindow()); if (selections == null || selections.size() == 0) return; // remember this folder RecentFileSettings.get().setRecentPath(selections.get(0).getParent()); ImportCandidates candidates = ImportCandidates.build(_project, selections.toArray(new File[0])); if (candidates.size() == 0) return; ImportCandidatesPane import_pane = new ImportCandidatesPane(_project); import_pane.setCandidates(candidates); ShadowboxPane shadowbox = ShadowboxPane.findFromNode(getNode()); shadowbox.showOverlayOnShadowbox(import_pane.getNode()); import_pane.setButtonListener(new ImportCandidatesPane.ImportPaneButtonListener() { @Override public void importButtonPressed() { shadowbox.removeOverlay(); ImportSeleniumIdeTestsAction action = import_pane.getAction(); action.execute(_undo); } @Override public void cancelButtonPressed() { shadowbox.removeOverlay(); } }); }); return import_button; } private void showAndEditResource(ResourceToken<MuseResource> token) { ResourceTreeNode root = _tree.getRootNode(); ResourceTreeNode node = root.findResourceNode(token); _tree.getTreeView().getSelectionModel().clearSelection(); _tree.getTreeView().expandScrollToAndSelect(node); _editors.editResource(token, _project); } public void setProjectCloser(NavigatorView.ProjectCloser project_closer) { _project_closer = project_closer; } private final MuseProject _project; private final ResourceEditors _editors; private final UndoStack _undo = new UndoStack(); private Scene _scene; private NotificationPane _node; private ProjectResourceTree _tree; private NavigatorView.ProjectCloser _project_closer = null; private final static Logger LOG = LoggerFactory.getLogger(ProjectNavigator.class); private final static List<ProjectNavigatorAdditionalButtonProvider> BUTTON_PROVIDERS = new ArrayList<>(); @SuppressWarnings("unused") // allows additons of buttons by other projects public static void addButtonProvider(ProjectNavigatorAdditionalButtonProvider provider) { BUTTON_PROVIDERS.add(provider); } }
python run_pretraining.py \ --input_file=/tmp/tf_examples.tfrecord \ --output_dir=/tmp/pretraining_output \ --do_train=True \ --do_eval=True \ --bert_config_file=./uncased_L-12_H-768_A-12/bert_config.json \ --train_batch_size=8\ --max_seq_length=128 \ --max_predictions_per_seq=20 \ --num_train_steps=2000 \ --num_warmup_steps=10 \ --learning_rate=2e-5
#!/bin/bash set -o nounset # Starts monitoring the progress of the creation and provisioning of SNO clusters # installed with Assisted Installer. # Usage: # ./monitor-deployment.sh KUBECONFIG_FILE [INTERVAL_SECONDS] # The output of the stats will both be displayed in terminal output and saved to # csv file managedsnocluster.csv. # You can optionally supply the number of seconds between each intervals of collecting # stats. The default value is 10 seconds. # The following stats are reported: # - initialized: the number of clusterdeployment that have been created. # - booted: baremetal hosts that are provisioned; currently running discovery iso and downloading rootfs. # - discovered: rootfs has been downloaded and discovery results sent back to the hub; agent created. # - provisioning: clusterdeployment in provisioning state # - completed: clusterdeployment in completed state # - managed: managedcluster avaialble # - agents_available: managedclusteraddon avaialble if [ -z "$1" ]; then echo 'usage: ./monitor-deployment.sh KUBECONFIG_FILE [INTERVAL_SECONDS]' exit 1 fi kubeconfig_path=$1 sleep_seconds=${2:-'10'} export KUBECONFIG=$kubeconfig_path file=managedsnocluster.csv if [ ! -f ${file} ]; then echo "\ date,\ initialized,\ booted,\ discovered,\ provisioning,\ completed,\ managed,\ agents_available\ " > ${file} fi while true; do D=$(date -u +"%Y-%m-%dT%H:%M:%SZ") clusterdeployments_readyforinstallation_and_installed=$(oc get clusterdeployment -A --no-headers -o custom-columns=READY:'.status.conditions[?(@.type=="ReadyForInstallation")].reason',installed:'.spec.installed',name:'.spec.clusterName') initialized=$(echo "$clusterdeployments_readyforinstallation_and_installed" | grep -c sno | tr -d " ") booted=$(oc get bmh -A --no-headers | grep -c provisioned | tr -d " ") discovered=$(oc get agent -A --no-headers | wc -l | tr -d " ") provisioning=$(echo "$clusterdeployments_readyforinstallation_and_installed" | grep -c ClusterAlreadyInstalling | tr -d " ") completed=$(echo "$clusterdeployments_readyforinstallation_and_installed" | grep -i -c true | tr -d " ") managed=$(oc get managedcluster -A --no-headers -o custom-columns=JOINED:'.status.conditions[?(@.type=="ManagedClusterJoined")].status',AVAILABLE:'.status.conditions[?(@.type=="ManagedClusterConditionAvailable")].status' | grep -v none | grep -i true | grep -v Unknown | wc -l | tr -d " ") agents_available=$(oc get managedclusteraddon -A --no-headers -o custom-columns=AVAILABLE:'.status.conditions[?(@.type=="Available")].status',CLUSTER:'.status.addOnConfiguration.crName' | grep -i true | grep -c sno) echo "$D" echo "$D initialized: $initialized" echo "$D booted: $booted" echo "$D discovered: $discovered" echo "$D provisioning: $provisioning" echo "$D completed: $completed" echo "$D managed: $managed" echo "$D agents_available: $agents_available" echo "\ $D,\ $initialized,\ $booted,\ $discovered,\ $provisioning,\ $completed,\ $managed,\ $agents_available\ " >> ${file} sleep "$sleep_seconds" done
<filename>scripts/_listFiles.js import { resolve } from 'path' import { readdir } from 'fs/promises' export async function listFiles(dir, regexFilter) { const dirents = await readdir(dir, { withFileTypes: true }) const files = await Promise.all( dirents.map((dirent) => { const res = resolve(dir, dirent.name) return dirent.isDirectory() ? listFiles(res) : res }), ) const allFiles = Array.prototype.concat(...files) if (!regexFilter) return allFiles return allFiles.filter((f) => f.match(regexFilter)) }
docker-compose -f docker/docker-compose.yml down docker-compose -f docker/docker-compose.yml build --no-cache
<reponame>hdijkema/mmwiki // vim: ts=3 sts=3 sw=4 noet : /**************************************************************** * LICENSE CC0 1.0 Universal * (c) 2020 <NAME> * * These classes can be used with mmwiki.js to provide remedies * and links for the Materia Medica Wiki pages. *****************************************************************/ import { MMWiki, MMWiki_ImageSrc, MMWiki_IncludeProvider, MMWiki_ImageProvider, MMWiki_MetaProvider, MMWiki_LinkProvider, MMWiki_RemedyProvider } from './mmwiki.js'; import { mmwiki_images } from './images.js'; import { mmwiki_remedies } from './remedies.js'; function tr(txt) { return txt; } class MMLinkProvider { constructor() { this._context = ""; this._prefix = ""; this._old_link_prov = new MMWiki_LinkProvider(); } setContext(c) { this._context = c; } context() { return this._context; } setPrefix(p) { this._prefix = p; } mkLinkHRef(link, content, tab_target) { var c = this._context; var p = this._prefix; if (link.startsWith("wiki://")) { link = link.replace("wiki://", ""); var idx = link.lastIndexOf('/'); var page = link; if (idx >= 0) { page = link.substr(idx + 1); c = link.substr(0, idx); } else { page = link; } if (c == "_") { c = ""; } if (c != "") { c = "/" + c; } if (p != "") { p = "/" + p; } var nlink = p + c + "/" + page; link = nlink; } var target = ""; if (tab_target) { target = ' target="_blank"'; } return "<a href=\"" + link + "\"" + target + ">" + content + "</a>"; } mkLinkId(n) { return this._old_link_prov.mkLinkId(n); } } class MMRemedyProvider { constructor() { this._context = ""; this._prev_prov = new MMWiki_RemedyProvider(); } setContext(c) { this._context = c; } hasLink(uabbrev) { return true; } getLink(uabbrev) { var a = uabbrev.toLowerCase(); if (a == "con") { a = "_con"; } //return "index.php?context=" + this._context + "&page=" + a; //return "/" + this._context + "/" + a; return a; } getLatinName(uabbrev) { var ln = mmwiki_remedies[uabbrev]; if (ln) { return ln; } else { return uabbrev; } } unifyAbbrev(a) { return this._prev_prov.unifyAbbrev(a); } } class MMImageProvider { constructor() { this._context = ""; } setContext(c) { this._context = c; } getImageSrc(img) { //return "mm/" + this._context + "/" + img; return img; } getImageSrcs(uabbrev) { var abbrev = uabbrev.toLowerCase(); var imgs = mmwiki_images[abbrev]; if (imgs) { return imgs; } else { return new Array(); } } getVideoSrcs(img) { var videos = new Array(); videos.push({ link: img + ".mp4", ext: "mp4" }); videos.push({ link: img + ".webm", ext: "webm" }); videos.push({ link: img + ".ogv", ext: "ogg" }); return videos; } } class MMIncludeProvider { constructor() { this._context = ""; } setContext(c) { this._context = c; } getPage(include_page, setter, f_error) { var xhr = new XMLHttpRequest(); var url = "get_page.php?context=" + this._context + "&page=" + include_page; xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { setter(xhr.responseText); } else if (xhr.readyState ===4) { f_error(); } } xhr.send(); } } export class MMWikiMM { constructor(context) { this._mmwiki = new MMWiki(); this._rem_prov = new MMRemedyProvider(); this._link_prov = new MMLinkProvider(); this._img_prov = new MMImageProvider(); this._incl_prov = new MMIncludeProvider(); this._rem_prov.setContext(context); this._link_prov.setContext(context); this._img_prov.setContext(context); this._incl_prov.setContext(context); this._mmwiki.setLinkProvider(this._link_prov); this._mmwiki.setRemedyProvider(this._rem_prov); this._mmwiki.setImageProvider(this._img_prov); this._mmwiki.setIncludeProvider(this._incl_prov); this._context = context; this._abbrev = ""; } setPrefix(prefix) { this._mmwiki.linkProvider().setPrefix(prefix); } getLanguages(mmwiki) { return this._mmwiki.getLanguages(mmwiki); } book() { var hdr = this._mmwiki.header(); return hdr.book(); } headerHtml() { var hdr = this._mmwiki.header(); var lp = this._link_prov; var author = hdr.author().trim(); if (author != "") { author = " (" + author + ")"; } document.title = hdr.book() + author; var h_html = '<div class="mmwiki_hdr">' + '<div class="left">' + lp.mkLinkHRef("wiki://index", '<span class="index">' + tr(hdr.book() + author) + '</span>' + '<span class="mobile-index">&#x2616;</span>', false ) + '</div>' + '<div class="right">' + lp.mkLinkHRef("wiki://_/index", '<span class="home">' + tr("Main index of Materia Medica Wiki") + '</span>' + '<span class="mobile-home">&#x2617;</span>', false ) + '</div>' + '</div>'; return h_html; } toHtml(abbrev, mmwiki, one_per_line = false, language = "en") { var html = this._mmwiki.toHtml(mmwiki, one_per_line, language); var hdr = this._mmwiki.header(); var lp = this._link_prov; var rp = this._rem_prov; this._abbrev = abbrev; if (abbrev == "_con") { abbrev = "con"; } var uabbrev = rp.unifyAbbrev(abbrev); hdr.setAbbrev(uabbrev); hdr.setLatinName(rp.getLatinName(uabbrev)); var h1_html = ""; var h_meta = ""; var t_html = ""; var context = this._context; if (context.startsWith("mm_")) { if (uabbrev == "Index") { h1_html = '<h1>Index of ' + hdr.book() + '</h1>'; } else { h1_html = '<h1>' + rp.getLatinName(uabbrev) + ' (' + uabbrev + ')' + '</h1>'; } var meta = this._mmwiki.metaProvider(); h_meta = meta.getMeta(); } else { } var d_html = h1_html + h_meta + html; return d_html; } addIncludesRaw(ready_f, error_f, finish_f) { this._mmwiki.addIncludes(ready_f, error_f, finish_f); } addIncludes() { this._mmwiki.addIncludes( function(id, html) { document.getElementById(id).innerHTML = html; }, function(id, include_page) { console.log("Error including id '" + id + "', page '" + include_page + "'"); }, function() { // finish includes, does nothing here } ); } tocHtml() { var context = this._context; var page = this._abbrev.toLowerCase().trim(); if (context.startsWith("mm_")) { return ""; } else if (page == "index") { return ""; } var toc = this._mmwiki.toc(); var i; var level = -1; var t_html = ""; var lang = mmwikiLanguage(); var h = ""; if (toc.size() == 0) { return ""; } if (lang == "nl") { h = "Inhoud"; } else { h = "Contents"; } t_html += "<h3>" + h + "</h3>" for(i = 0; i < toc.size(); i++) { var lvl = toc.level(i); if (lvl > level) { while(level < lvl) { t_html += "<ul>"; level += 1; } } else if (lvl == level) { // do nothing } else { while(level > lvl) { t_html += "</ul>"; level -= 1; } } t_html += "<li><a href=\"#" + toc.tocRef(i) + "\">" + toc.tocTxt(i) + "</a></li>"; } while (level >= 0) { t_html += "</ul>"; level -= 1; } t_html = "<div class=\"toc\">" + t_html + "</div>"; return t_html; } } function mmwikiPublishAllPage(incl_provider, context, pages, page_idx, f_progress, f_ok, f_error) { if (page_idx >= pages.length) { f_ok(); } else { var page = pages[page_idx]; incl_provider.getPage(page, function(content) { f_progress(context, page, page_idx + 1, pages); mmwikiPublish(context, page, content, function() { page_idx += 1; mmwikiPublishAllPage(incl_provider, context, pages, page_idx, f_progress, f_ok, f_error); }, f_error ); }, f_error ); } } export function mmwikiPublishAll(context, f_progress, f_ok, f_error) { var xhr = new XMLHttpRequest(); var url = "get_pages.php"; var incl_provider = new MMIncludeProvider(); incl_provider.setContext(context); var url = "get_pages.php?context=" + context; xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var pages_str = xhr.responseText; var pages = pages_str.split(","); if (pages.length > 0) { var page_idx = 0; mmwikiPublishAllPage(incl_provider, context, pages, page_idx, f_progress, f_ok, f_error); } } else if (xhr.readyState ===4) { f_error(); } } xhr.send(); } export function mmwikiPublish(context, page, content, f_ok, f_error) { var m = new MMWikiMM(context); var l = m.getLanguages(content); var html = ""; var book = ""; var i; for(i = 0; i < l.length; i++) { var languages = l[i]; var lang = languages[0]; var j; var sep = ""; var cl = ""; for(j = 0; j < languages.length; j++) { cl += sep; cl += languages[j]; sep = "_"; } html += '<div id="lang_' + cl + '">'; var contents = m.toHtml(page, content, false, lang); var toc = m.tocHtml(); var header = m.headerHtml(); book = m.book(); html += '<div id="mmwiki_hdr">' + header + '</div>'; html += '<div id="mmwiki_toc"><div class="mmwiki_toc">' + toc + '</div></div>'; html += '<div id="mmwiki"><div class="mmwiki">'; html += "<!-- begin contents -->"; html += contents html += "<!-- end contents -->"; html += '</div></div>'; html += '</div>'; } m.addIncludesRaw( function(id, incl_html) { var needle = "<div id=\"" + id + "\"></div>"; html = html.replace(needle, "<!-- " + id + "--> " + incl_html); }, function(id, incl_page) { console.log("Error including page '" + incl_page + "', id '" + id + "'"); }, function() { var xhr = new XMLHttpRequest(); var url = "publish.php"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { f_ok(); } else if (xhr.readyState ===4) { f_error(); } } if (page == "con") { page = "_con"; } var obj = { "book": book, "context": context, "page": page, "content": html, "languages": l }; var data = JSON.stringify(obj); xhr.send(data); } ); } export function mmwikiGetCss(f_ok, f_error) { var incl_prov = new MMIncludeProvider(); incl_prov.getPage("custom.css", f_ok, f_error); } export function mmwikiSaveCss(css, f_ok, f_error) { mmwikiSave("css", "custom.css", css, f_ok, f_error); } export function mmwikiSave(context, page, content, f_ok, f_error) { var xhr = new XMLHttpRequest(); var url = "save.php"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { f_ok(); } else if (xhr.readyState ===4) { f_error(); } } if (page == "con") { page = "_con"; } var obj = { "context": context, "page": page, "content": content }; var data = JSON.stringify(obj); xhr.send(data); } export function mmwikiLogin(account, passwd, f_ok, f_error) { var xhr = new XMLHttpRequest(); var url = "login.php"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { f_ok(); } else if (xhr.readyState ===4) { f_error(); } } var obj = { "account": account, "passwd": <PASSWORD> }; var data = JSON.stringify(obj); xhr.send(data); } export function mmwikiPing(f_ok, f_error) { var xhr = new XMLHttpRequest(); var url = "/ping.php"; xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { f_ok(); } else if (xhr.readyState ===4) { f_error(); } } xhr.send(); } export function mmwikiLogout(f_ok, f_error) { var xhr = new XMLHttpRequest(); var url = "logout.php"; xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { f_ok(); } else if (xhr.readyState ===4) { f_error(); } } xhr.send(); } export function mmwikiUploadImage(context, page, req_name, image_file, image_name, f_ok, f_error) { var req = new XMLHttpRequest(); var formData = new FormData(); req_name = req_name.trim(); image_name = image_name.trim(); if (req_name != "") { image_name = req_name; } var url = "upload_image.php?context=" + context + "&page=" + page + "&name=" + image_name; formData.append("image", image_file); req.open("POST", url, true); req.send(formData); req.onreadystatechange = function () { if (req.readyState === 4 && req.status === 200) { f_ok(image_name); } else if (req.readyState ===4) { f_error(); } } } var mmwiki_custom_language = ""; export function mmwikiLanguage() { if (mmwiki_custom_language != "") { return mmwiki_custom_language; } else { var userLang = navigator.language || navigator.userLanguage; if (userLang) { var idx = userLang.indexOf('-'); if (idx >= 0) { userLang = userLang.substr(0, idx); } return userLang; } else { return "en"; } } } export function mmwikiSetLanguage(lang) { mmwiki_custom_language = lang.trim(); } export function mmwikiCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } export function mmwikiSetCookie(cname, val) { document.cookie = cname + '=' + val; return val; } export function mmwikiMakeMovable(id) { var mousePosition; var offset = [0,0]; var div = document.getElementById(id); var isDown = false; div.addEventListener('mousedown', function(e) { var y = event.clientY; if (y >= div.offsetTop && y <= (div.offsetTop + 30)) { isDown = true; offset = [ div.offsetLeft - e.clientX, div.offsetTop - e.clientY ]; } }, true); document.addEventListener('mouseup', function() { isDown = false; }, true); document.addEventListener('mousemove', function(event) { if (isDown) { event.preventDefault(); mousePosition = { x : event.clientX, y : event.clientY }; div.style.left = (mousePosition.x + offset[0]) + 'px'; div.style.top = (mousePosition.y + offset[1]) + 'px'; } }, true); }
<filename>test/root.js<gh_stars>0 import {test} from "zora"; test("root", assert => { assert.equal(true, true, "root test directory"); }); export default test;
import React, { useState } from 'react' import { Col, Row, Toast ,Button, Form, ToastContainer} from 'react-bootstrap' export default function Toasts() { const [showA, setShowA] = useState(true); const [showB, setShowB] = useState(true); const toggleShowA = () => setShowA(!showA); const toggleShowB = () => setShowB(!showB); const [position, setPosition] = useState('top-start'); return ( <div> <Toast> <Toast.Header> <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" /> <strong className="me-auto">Bootstrap</strong> <small>11 mins ago</small> </Toast.Header> <Toast.Body>Hello, world! This is a toast message.</Toast.Body> </Toast> <Row> <Col md={6} className="mb-2"> <Button onClick={toggleShowA} className="mb-2"> Toggle Toast <strong>with</strong> Animation </Button> <Toast show={showA} onClose={toggleShowA}> <Toast.Header> <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" /> <strong className="me-auto">Bootstrap</strong> <small>11 mins ago</small> </Toast.Header> <Toast.Body>Woohoo, you're reading this text in a Toast!</Toast.Body> </Toast> </Col> <Col md={6} className="mb-2"> <Button onClick={toggleShowB} className="mb-2"> Toggle Toast <strong>without</strong> Animation </Button> <Toast onClose={toggleShowB} show={showB} animation={false}> <Toast.Header> <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" /> <strong className="me-auto">Bootstrap</strong> <small>11 mins ago</small> </Toast.Header> <Toast.Body>Woohoo, you're reading this text in a Toast!</Toast.Body> </Toast> </Col> </Row> <> <div className="mb-3"> <label htmlFor="selectToastPlacement">Toast position</label> <Form.Select id="selectToastPlacement" className="mt-2" onChange={(e) => setPosition(e.currentTarget.value)} > {[ 'top-start', 'top-center', 'top-end', 'middle-start', 'middle-center', 'middle-end', 'bottom-start', 'bottom-center', 'bottom-end', ].map((p) => ( <option key={p} value={p}> {p} </option> ))} </Form.Select> </div> <div aria-live="polite" aria-atomic="true" className="bg-dark position-relative" style={{ minHeight: '240px' }} > <ToastContainer className="p-3" position={position}> <Toast> <Toast.Header closeButton={false}> <img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" /> <strong className="me-auto">Bootstrap</strong> <small>11 mins ago</small> </Toast.Header> <Toast.Body>Hello, world! This is a toast message.</Toast.Body> </Toast> </ToastContainer> </div> </> </div> ) }
package io.opensphere.csvcommon.detect.datetime.algorithm.deciders; import io.opensphere.core.common.configuration.date.DateFormat.Type; /** * Scores potential date columns assuming they contain just dates. * */ public class DateDecider extends SingleValueDecider { @Override protected Type getTimeType() { return Type.DATE; } }
/* * Copyright 2018-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pranavpandey.android.dynamic.support.utils; import android.Manifest; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.Settings; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import com.pranavpandey.android.dynamic.support.R; import com.pranavpandey.android.dynamic.support.intent.DynamicIntent; import com.pranavpandey.android.dynamic.support.model.DynamicPermission; /** * Helper class to work with permissions and {@link DynamicPermission}. */ public class DynamicPermissionUtils { /** * Default package scheme for the permission settings intent. */ private static final String SCHEME = "package"; /** * Open the settings activity according to the permission name. * * @param context The context to start the activity. * @param permission The permission name. * * @return {@code true} if permissions settings activity can be opened successfully. * Otherwise, {@code false}. */ public static boolean openPermissionSettings(@NonNull Context context, @NonNull String permission) { String action = getPermissionSettingsAction(permission); Intent intent = new Intent(action); if (action.equals(DynamicIntent.ACTION_OVERLAY_SETTINGS) || action.equals(DynamicIntent.ACTION_WRITE_SYSTEM_SETTINGS)) { Uri uri = Uri.fromParts(SCHEME, context.getPackageName(), null); intent.setData(uri); } try { context.startActivity(intent); return true; } catch (Exception ignored) { } return false; } /** * Launch app info by extracting the package name from the supplied context. * * @param context The context to start the activity. * * @return {@code true} if permissions settings activity can be opened successfully. * Otherwise, {@code false}. */ public static boolean launchAppInfo(@NonNull Context context) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts(SCHEME, context.getPackageName(), null); intent.setData(uri); try { context.startActivity(intent); return true; } catch (Exception ignored) { } return false; } /** * Get permission icon drawable resource according to the permission name. * * @param permission The permission name. * * @return The permission icon drawable resource. */ public static @DrawableRes int getPermissionIcon(@NonNull String permission) { switch (permission) { default: return R.drawable.ads_ic_security; case Manifest.permission.WRITE_SETTINGS: case Manifest.permission.PACKAGE_USAGE_STATS: case Manifest.permission.SYSTEM_ALERT_WINDOW: return R.drawable.ads_ic_settings; } } /** * Get permission title string resource according to the permission name. * * @param permission The permission name. * * @return The permission title string resource. */ public static @StringRes int getPermissionTitle(@NonNull String permission) { switch (permission) { case Manifest.permission.SYSTEM_ALERT_WINDOW: return R.string.ads_perm_overlay; case Manifest.permission.PACKAGE_USAGE_STATS: return R.string.ads_perm_usage_access; case Manifest.permission.WRITE_SETTINGS: return R.string.ads_perm_write_system_settings; default: return R.string.ads_perm_default; } } /** * Get permission subtitle string resource according to the permission name. * * @param permission The permission name. * * @return The permission subtitle string resource. */ public static @StringRes int getPermissionSubtitle(@NonNull String permission) { switch (permission) { case Manifest.permission.SYSTEM_ALERT_WINDOW: return R.string.ads_perm_overlay_desc; case Manifest.permission.PACKAGE_USAGE_STATS: return R.string.ads_perm_usage_access_desc; case Manifest.permission.WRITE_SETTINGS: return R.string.ads_perm_write_system_settings_desc; default: return R.string.ads_perm_default_desc; } } /** * Get permission settings action according to the permission name. * * @param permission The permission name. * * @return The permission settings action. */ public static @NonNull String getPermissionSettingsAction(@NonNull String permission) { switch (permission) { case Manifest.permission.SYSTEM_ALERT_WINDOW: return DynamicIntent.ACTION_OVERLAY_SETTINGS; case Manifest.permission.PACKAGE_USAGE_STATS: return DynamicIntent.ACTION_USAGE_ACCESS_SETTINGS; case Manifest.permission.WRITE_SETTINGS: return DynamicIntent.ACTION_WRITE_SYSTEM_SETTINGS; case Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: return DynamicIntent.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS; default: return Settings.ACTION_APPLICATION_DETAILS_SETTINGS; } } }
function isPalindrome(str) { // remove characters not in range a-z str = str.replace(/[^a-zA-Z]+/g, ""); // reverse string for comparison let reversedStr = str.split("").reverse().join(""); // compare reversedStr to str return str === reversedStr; }
import numpy as np from sklearn.model_selection import train_test_split def preprocess_data(X, y, test_size) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: scaler = StandardScaler() # Initialize the scaler object scaler.fit(X) # Fit the scaler to the dataset scaled_features = scaler.transform(X) # Standardize the features in X X_train, X_test, y_train, y_test = train_test_split(scaled_features, y, test_size=test_size) # Split the dataset into training and testing sets return X_train, X_test, y_train, y_test
<reponame>adligo/models_core.adligo.org<filename>src/org/adligo/models/core/shared/SimpleStorageInfo.java package org.adligo.models.core.shared; import org.adligo.i.util.shared.I_Immutable; public class SimpleStorageInfo implements I_StorageInfo, I_Immutable { private String storeName; public SimpleStorageInfo() { storeName = "DEFAULT"; } public SimpleStorageInfo(String name) { storeName = name; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((storeName == null) ? 0 : storeName.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SimpleStorageInfo other = (SimpleStorageInfo) obj; if (storeName == null) { if (other.storeName != null) return false; } else if (!storeName.equals(other.storeName)) return false; return true; } public Class getDetailClass() { return this.getClass(); } public I_CustomInfo toImmutable() throws ValidationException { return this; } public I_CustomInfo toMutant() throws ValidationException { return this; } public boolean isValidatable() { return false; } public String getStoreName() { return storeName; } public String getImmutableFieldName() { return "storeName"; } public void isValid() throws ValidationException { if (storeName == null) { throw new ValidationException("SimpleStorageInfo requires a store name.", I_Validateable.IS_VALID); } } public String toString() { return "SimpleStorageInfo[" + storeName + "]"; } }
#!/bin/sh DEPLOY="/home/acm" # Preferably separate commits but this ensures changes are pushed git commit -a git pull git push jekyll build --trace rsync -rcvz --delete --exclude='.git*' --exclude='.zfs' _site/ "joegen@bg3.cs.wm.edu:$DEPLOY/"
# tasks/pref.bash tasks_pref_install() { if is-macos; then _pref_install_macos_osascript _pref_install_macos_defaults fi } _pref_install_macos_osascript() { local script="$DOTFILES_RESOURCES/pref/prefs.scpt" echo "> osascript $script" osascript "$script" } _pref_install_macos_defaults() { local defaults="$DOTFILES_RESOURCES/pref/defaults.sh" echo "> $defaults" "$defaults" }
<gh_stars>1-10 import cv2 import numpy as np from matplotlib import pyplot as plt # read enhanced image from output of enhancement code img = cv2.imread('edgeG.png',0) #morphological operations kernel = np.ones((5,5),np.uint8) dilation = cv2.dilate(img,kernel,iterations = 1) closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) #Adaptive thresholding on mean and gaussian filter th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY,11,2) th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY,11,2) #Otsu's thresholding ret4,th4 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # Initialize the list Pipe_count, x_count, y_count = [], [], [] #read original image, to display the circle and center detection display = cv2.imread("claheNorm_blurM.png") image =th3 #hough transform with modified circular parameters circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 1.2,20,param1=50,param2=28,minRadius=1,maxRadius=20) #circle detection and labeling using hough transformation if circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: cv2.circle(display, (x, y), r, (0, 255, 0), 2) cv2.rectangle(display, (x - 2, y - 2), (x + 2, y + 2), (0, 128, 255),-1) Pipe_count.append(r) x_count.append(x) y_count.append(y) # show the output image cv2.imshow("gray", display) cv2.waitKey(0) #display the count of white blood cells print(len(Pipe_count)) print(Pipe_count) # Total number of radius print(x_count) # X co-ordinate of circle print(y_count) # Y co-ordinate of circle
<reponame>bopopescu/drawquest-web from django.shortcuts import get_object_or_404, Http404 from canvas.redis_models import redis from drawquest.apps.palettes.models import Color, ColorPack from drawquest.apps.palettes.forms import ColorPackForm, ColorForm from drawquest.generic import ModelFormSetView, SortableListMixin class _PalettesView(ModelFormSetView): def get_context_data(self, **kwargs): context = super(_PalettesView, self).get_context_data(**kwargs) context['colors_header'] = redis.get('colors_header') context['color_packs_header'] = redis.get('color_packs_header') return context class ColorPackList(_PalettesView): model = ColorPack form_class = ColorPackForm template_name = 'palettes/colorpack_formset.html' extra = 1 class ColorList(_PalettesView): model = Color form_class = ColorForm template_name = 'palettes/color_formset.html' extra = 1
/******************************************************************************* * This file is part of the Symfony eclipse plugin. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ******************************************************************************/ package com.dubture.symfony.index.dao.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.eclipse.core.runtime.IPath; import org.eclipse.osgi.util.NLS; import com.dubture.symfony.index.Schema; import com.dubture.symfony.index.SymfonyDbFactory; import com.dubture.symfony.index.dao.IResourceDao; import com.dubture.symfony.index.handler.IResourceHandler; import com.dubture.symfony.index.log.Logger; import com.dubture.symfony.index.model.RoutingResource; public class ResourceDao extends BaseDao implements IResourceDao { public ResourceDao() { super(); } private static final String TABLENAME = "RESOURCE"; private static final String Q_INSERT_DECL = Schema.readSqlFile("Resources/index/resources/insert_decl.sql"); //$NON-NLS-1$ private static final String QUERY_FIND_BY_PATH = "SELECT RESOURCEPATH, TYPE, PREFIX FROM RESOURCE WHERE PATH = ?"; //$NON-NLS-1$ @Override public void insert(Connection connection, String path, String type, String prefix, IPath fullPath) throws Exception { if (type == null) type = ""; if (prefix == null) prefix = ""; String tableName = TABLENAME; String query; query = D_INSERT_QUERY_CACHE.get(tableName); if (query == null) { query = NLS.bind(Q_INSERT_DECL, tableName); D_INSERT_QUERY_CACHE.put(tableName, query); } synchronized (batchStatements) { PreparedStatement statement = batchStatements.get(query); if (statement == null) { statement = connection.prepareStatement(query); batchStatements.put(query, statement); } insertBatch(statement, path, type, prefix, fullPath); } } private void insertBatch(PreparedStatement statement, String resourcePath, String type, String prefix, IPath path) throws SQLException { int param = 0; statement.setString(++param, resourcePath); statement.setString(++param, type); statement.setString(++param, prefix); statement.setString(++param, path.toString()); statement.addBatch(); } @Override public void findResource(IPath path, IResourceHandler iResourceHandler) { Connection connection = null; try { connection = SymfonyDbFactory.getInstance().createConnection(); PreparedStatement statement = connection.prepareStatement(QUERY_FIND_BY_PATH); statement.setString(1, path.toString()); ResultSet result = statement.executeQuery(); while (result.next()) { int columnIndex = 0; String resourcePath = result.getString(++columnIndex); String type = result.getString(++columnIndex); String prefix = result.getString(++columnIndex); RoutingResource resource = new RoutingResource(type, resourcePath, prefix); iResourceHandler.handle(resource); } } catch (Exception e) { Logger.logException(e); } finally { closeIfExists(connection); } } }
#!/bin/bash # This script calculates the sum of two numbers echo "Please enter two numbers:" read num1 num2 sum=$(($num1 + $num2)) echo "The sum is: $sum"
#!/bin/bash # shellcheck disable=SC1091 source test/utils.sh function cleanup() { echo "Executing cleanup..." echo "Delete lighthouse-config configmap" kubectl delete configmap -n "$KEPTN_NAMESPACE" lighthouse-config echo "Deleting project ${SELF_MONITORING_PROJECT}" keptn delete project "$SELF_MONITORING_PROJECT" echo "Uninstalling dynatrace-sli-service" kubectl -n "$KEPTN_NAMESPACE" delete deployment dynatrace-sli-service echo "Removing secret dynatrace-credentials-${SELF_MONITORING_PROJECT}" kubectl -n "$KEPTN_NAMESPACE" delete secret "dynatrace-credentials-${SELF_MONITORING_PROJECT}" for project_nr in $(seq 1 "${NR_PROJECTS}") do keptn delete project "project-${project_nr}" done } function evaluate_service() { evaluated_project=$1 evaluated_service=$2 nr_projects=$3 nr_services=$4 nr_evaluations=$5 nr_invalidations=$6 cat << EOF > ./tmp-trigger-evaluation.json { "type": "sh.keptn.event.hardening.evaluation.triggered", "specversion": "1.0", "source": "travis-ci", "contenttype": "application/json", "data": { "project": "$evaluated_project", "stage": "hardening", "service": "$evaluated_service", "deployment": { "deploymentURIsLocal": ["$evaluated_service:8080"] }, "labels": { "nr_projects": "$nr_projects", "nr_services": "$nr_services", "nr_evaluations": "$nr_evaluations", "nr_invalidations": "$nr_invalidations" } } } EOF cat tmp-trigger-evaluation.json keptn_context_id=$(send_event_json ./tmp-trigger-evaluation.json) rm tmp-trigger-evaluation.json # try to fetch a evaluation.finished event echo "Getting evaluation.finished event with context-id: ${keptn_context_id}" response=$(get_event_with_retry sh.keptn.event.evaluation.finished "${keptn_context_id}" "${SELF_MONITORING_PROJECT}") echo "$response" } # test configuration DYNATRACE_SLI_SERVICE_VERSION=${DYNATRACE_SLI_SERVICE_VERSION:-master} SELF_MONITORING_PROJECT=${SELF_MONITORING_PROJECT:-keptn-selfmonitoring} KEPTN_NAMESPACE=${KEPTN_NAMESPACE:-keptn} NR_PROJECTS=${NR_PROJECTS:-5} NR_SERVICES_PER_PROJECT=${NR_SERVICES_PER_PROJECT:-15} NR_EVALUATIONS_PER_SERVICE=${NR_EVALUATIONS_PER_SERVICE:-100} NR_INVALIDATIONS_PER_SERVICE=${NR_INVALIDATIONS_PER_SERVICE:-10} if [[ $QG_INTEGRATION_TEST_DT_TENANT == "" ]]; then echo "No DT Tenant env var provided. Exiting." exit 1 fi if [[ $QG_INTEGRATION_TEST_DT_API_TOKEN == "" ]]; then echo "No DZ API Token env var provided. Exiting." exit 1 fi cleanup # get keptn API details if [[ "$PLATFORM" == "openshift" ]]; then KEPTN_ENDPOINT=http://api.${KEPTN_NAMESPACE}.127.0.0.1.nip.io/api else if [[ "$KEPTN_SERVICE_TYPE" == "NodePort" ]]; then API_PORT=$(kubectl get svc api-gateway-nginx -n "${KEPTN_NAMESPACE}" -o jsonpath='{.spec.ports[?(@.name=="http")].nodePort}') INTERNAL_NODE_IP=$(kubectl get nodes -o jsonpath='{ $.items[0].status.addresses[?(@.type=="InternalIP")].address }') KEPTN_ENDPOINT="http://${INTERNAL_NODE_IP}:${API_PORT}"/api else # shellcheck disable=SC2034 KEPTN_ENDPOINT=http://$(kubectl -n "${KEPTN_NAMESPACE}" get service api-gateway-nginx -o jsonpath='{.status.loadBalancer.ingress[0].ip}')/api fi fi # shellcheck disable=SC2034 KEPTN_API_TOKEN=$(kubectl get secret keptn-api-token -n "${KEPTN_NAMESPACE}" -o jsonpath='{.data.keptn-api-token}' | base64 --decode) # deploy dynatrace-sli service kubectl -n "${KEPTN_NAMESPACE}" create secret generic "dynatrace-credentials-${SELF_MONITORING_PROJECT}" --from-literal="DT_TENANT=$QG_INTEGRATION_TEST_DT_TENANT" --from-literal="DT_API_TOKEN=$QG_INTEGRATION_TEST_DT_API_TOKEN" echo "Install dynatrace-sli-service from: ${DYNATRACE_SLI_SERVICE_VERSION}" kubectl apply -f "https://raw.githubusercontent.com/keptn-contrib/dynatrace-sli-service/${DYNATRACE_SLI_SERVICE_VERSION}/deploy/service.yaml" -n "${KEPTN_NAMESPACE}" sleep 5 kubectl -n "${KEPTN_NAMESPACE}" set image deployment/dynatrace-sli-service dynatrace-sli-service=keptncontrib/dynatrace-sli-service:0.6.0-master sleep 10 wait_for_deployment_in_namespace "dynatrace-sli-service" "${KEPTN_NAMESPACE}" kubectl create configmap -n "${KEPTN_NAMESPACE}" "lighthouse-config-${SELF_MONITORING_PROJECT}" --from-literal=sli-provider=dynatrace # create the project keptn create project "$SELF_MONITORING_PROJECT" --shipyard=./test/assets/shipyard-quality-gates-self-monitoring.yaml keptn add-resource --project="$SELF_MONITORING_PROJECT" --resource=./test/assets/self_monitoring_sli.yaml --resourceUri=dynatrace/sli.yaml # create services SERVICES=("bridge" "eventbroker-go" "configuration-service" "mongodb-datastore" "approval-service" "remediation-service" "lighthouse-service" "statistics-service" "approval-service" "dynatrace-sli-service" "jmeter-service" "dynatrace-service" "api-service" "api-gateway-nginx") for SERVICE in "${SERVICES[@]}" do keptn create service "$SERVICE" --project="$SELF_MONITORING_PROJECT" done for SERVICE in "${SERVICES[@]}" do keptn add-resource --project="$SELF_MONITORING_PROJECT" --service="$SERVICE" --stage=hardening --resource=./test/assets/self_monitoring_slo.yaml --resourceUri=slo.yaml done # initial evaluation SELF_MONITORING_SERVICE=mongodb-datastore keptn add-resource --project="$SELF_MONITORING_PROJECT" --service="$SELF_MONITORING_SERVICE" --stage=hardening --resource=./test/assets/mongodb-performance.jmx --resourceUri=jmeter/load.jmx response=$(evaluate_service "$SELF_MONITORING_PROJECT" "$SELF_MONITORING_SERVICE" "0" "0" "0" "0") echo "$response" | jq . nr_services=0 nr_evaluations=0 nr_invalidations=0 # Create projects, services and evaluations to generate data for project_nr in $(seq 1 "${NR_PROJECTS}") do keptn create project "project-${project_nr}" --shipyard=./test/assets/shipyard-quality-gates.yaml for service_nr in $(seq 1 "${NR_SERVICES_PER_PROJECT}") do nr_services=$((nr_services+1)) keptn create service "service-${service_nr}" --project="project-${project_nr}" # shellcheck disable=SC2034 for evaluation_nr in $(seq 1 "${NR_EVALUATIONS_PER_SERVICE}") do nr_evaluations=$((nr_evaluations+1)) trigger_evaluation_request "project-${project_nr}" hardening "service-${service_nr}" done for invalidation_nr in $(seq 1 "${NR_INVALIDATIONS_PER_SERVICE}") do nr_invalidations=$((nr_invalidations+1)) send_evaluation_invalidated_event "project-${project_nr}" "hardening" "service-${service_nr}" "test-triggered-id-${invalidation_nr}" "test-context-id-${invalidation_nr}" done # do the evaluation again response=$(evaluate_service "$SELF_MONITORING_PROJECT" "$SELF_MONITORING_SERVICE" "$project_nr" "$nr_services" "$nr_evaluations" "$nr_invalidations") echo "$response" | jq . done done
#!/usr/bin/env bats load "./test_helper" @test "dctlenv version-file: returns current version file" { DCTLENV_ROOT=/tmp/dctlenv run dctlenv version-file assert_success assert_output '/tmp/dctlenv/version' }
<reponame>CARocha/cafod-joa # -*- coding: utf-8 -*- from django import forms from .models import * from lookups import * import selectable.forms as selectable from lugar.models import * class ProductorAdminForm(forms.ModelForm): class Meta(object): model = Encuesta fields = '__all__' widgets = { 'entrevistado': selectable.AutoCompleteSelectWidget(lookup_class=ProductorLookup), } def fecha_choice(): years = [] for en in Encuesta.objects.order_by('year').values_list('year', flat=True): years.append((en,en)) return list(sorted(set(years))) CHOICE_SEXO_FORM = (('','--------'),(1,'Mujer'),(2,'Hombre')) class ConsultarForm(forms.Form): fecha = forms.ChoiceField(choices=fecha_choice(), label="Años", required=True) pais = forms.ModelChoiceField(queryset=Pais.objects.all(), required=True) sexo = forms.ChoiceField(choices=CHOICE_SEXO_FORM, required=False) departamento = forms.ModelMultipleChoiceField(queryset=Departamento.objects.all(), required=False) organizacion = forms.ModelMultipleChoiceField(queryset=OrganizacionResp.objects.all(), required=False) municipio = forms.ModelMultipleChoiceField(queryset=Municipio.objects.all(), required=False) comunidad = forms.ModelMultipleChoiceField(queryset=Comunidad.objects.all(), required=False, label="Provincias") comunidad2 = forms.ModelMultipleChoiceField(queryset=Microcuenca.objects.all(), required=False, label="Comunidad")
package main; import java.awt.Image; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javazoom.jlgui.basicplayer.BasicPlayer; import javazoom.jlgui.basicplayer.BasicPlayerException; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import static javax.swing.JOptionPane.showMessageDialog; import lista.Cancion; import lista.ListaDE; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author <NAME> */ public class Interfaz extends javax.swing.JFrame { private boolean reproduciendo; //private Image play; /** * Creates new form Interfaz */ public Interfaz() { initComponents(); reproduciendo=false; btnPlay.setIcon(new ImageIcon(Class.class.getResource("/Iconos/Play.png"))); player = new BasicPlayer(); lista=new ListaDE(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jButton5 = new javax.swing.JButton(); btnPlay = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); pImg = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); lblEstado = new javax.swing.JLabel(); lblCancionActual = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(0, 0, 0)); jPanel2.setBackground(new java.awt.Color(0, 0, 0)); jButton5.setBackground(new java.awt.Color(0, 0, 0)); jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Izquierda.png"))); // NOI18N btnPlay.setBackground(new java.awt.Color(0, 0, 0)); btnPlay.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Pause.png"))); // NOI18N btnPlay.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPlayActionPerformed(evt); } }); jButton7.setBackground(new java.awt.Color(0, 0, 0)); jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Derecha.png"))); // NOI18N jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton5) .addGap(18, 18, 18) .addComponent(btnPlay) .addGap(18, 18, 18) .addComponent(jButton7) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jButton7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnPlay, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pImg.setBackground(new java.awt.Color(0, 0, 0)); pImg.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 0, 204))); javax.swing.GroupLayout pImgLayout = new javax.swing.GroupLayout(pImg); pImg.setLayout(pImgLayout); pImgLayout.setHorizontalGroup( pImgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 189, Short.MAX_VALUE) ); pImgLayout.setVerticalGroup( pImgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 189, Short.MAX_VALUE) ); jPanel4.setBackground(new java.awt.Color(0, 0, 0)); jButton2.setBackground(new java.awt.Color(0, 0, 0)); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Repeat.png"))); // NOI18N jButton3.setBackground(new java.awt.Color(0, 0, 0)); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Aleatorio.png"))); // NOI18N jButton4.setBackground(new java.awt.Color(0, 0, 0)); jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Hamburguesa.png"))); // NOI18N javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton2) .addGap(18, 18, 18) .addComponent(jButton3) .addGap(18, 18, 18) .addComponent(jButton4) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5.setBackground(new java.awt.Color(0, 0, 0)); lblEstado.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N lblEstado.setForeground(new java.awt.Color(255, 255, 255)); lblEstado.setText("Reproduciendo:"); lblCancionActual.setFont(new java.awt.Font("Times New Roman", 3, 14)); // NOI18N lblCancionActual.setForeground(new java.awt.Color(255, 255, 255)); lblCancionActual.setText("cancion.wav"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblEstado) .addComponent(lblCancionActual)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(lblEstado) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblCancionActual) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6.setBackground(new java.awt.Color(0, 0, 0)); jButton1.setBackground(new java.awt.Color(0, 0, 0)); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/Left.png"))); // NOI18N jButton6.setText("Agregar"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton6) .addContainerGap(284, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null}, {null}, {null}, {null} }, new String [] { "Lista" } ) { boolean[] canEdit = new boolean [] { false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(pImg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(pImg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayActionPerformed // TODO add your handling code here: if(reproduciendo) detener(); else reproducir(); }//GEN-LAST:event_btnPlayActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed // Agregar musica try { cont=0; JFileChooser filePick = new JFileChooser(); int returnVal = filePick.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { f = filePick.getSelectedFile(); actual=new Cancion(f); lista.insertar(actual); lblCancionActual.setText(f.getName()); } } catch (Exception e) { showMessageDialog(null, "Error al leer el archivo."); } }//GEN-LAST:event_jButton6ActionPerformed private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed // Siguiente lista.siguiente(actual); cont=0; reproducir(); }//GEN-LAST:event_jButton7ActionPerformed private void actualizarTbl(){ } private void detener(){ reproduciendo=false; btnPlay.setIcon(new ImageIcon(Class.class.getResource("/Iconos/Play.png"))); try { player.pause(); } catch (BasicPlayerException ex) { Logger.getLogger(Interfaz.class.getName()).log(Level.SEVERE, null, ex); } } private void reproducir(){ if(!lista.estaVacia()){ reproduciendo = true; btnPlay.setIcon(new ImageIcon(Class.class.getResource("/Iconos/Pause.png"))); if (cont <= 0) { try { player.open(actual.getArchivo()); player.play(); } catch (BasicPlayerException e) { //e.printStackTrace(); } } else { try { player.resume(); } catch (BasicPlayerException ex) { //Logger.getLogger(Interfaz.class.getName()).log(Level.SEVERE, null, ex); } } cont++; } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Interfaz().setVisible(true); } }); } private Cancion actual; private ListaDE lista; private String nombreCancion; private int cont; private BasicPlayer player; private File f; private File[] files; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnPlay; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JLabel lblCancionActual; private javax.swing.JLabel lblEstado; private javax.swing.JPanel pImg; // End of variables declaration//GEN-END:variables }
if (typeof(define) !== 'function') var define = require('amdefine')(module); define(function(require){ "use strict"; var objId = 1, protectedSpace = {}; function Base(){ protectedSpace[objId] = {}; this.objId = objId; // this._protected = function(){ return protectedSpace[objId]; }; this.destroy = function(){ delete protectedSpace[this.objId]; }; objId++; }; if(!Object.create){ Object.create = function createObject(proto) { function ctor() { } ctor.prototype = proto; return new ctor(); }; } function create(classFunction){ return extend(Base, classFunction); } function _polymorph(childFunction, parentFunction) { return function () { var output; this.__super = parentFunction; output = childFunction.apply(this, arguments); delete this.__super; return output; }; } function rename(classFunction, newClassName){ var f = (new Function("return function(classX) { return function " + newClassName + "() { return classX(this, arguments) }; };")()); return f(Function.apply.bind(classFunction)); } function _protected(obj){ return protectedSpace[obj.objId]; } function extend(classBase, classFunction){ function classX(option){ this._super = {}; classBase.call(this._super, option); this._protected = _protected(this._super); if(option.hasOwnProperty("debug") && option.debug) debug = true; for(var key in this._protected){ if(!this.hasOwnProperty(key)){ this[key] = this._protected[key]; } } for(var key in this._super){ if(!this.hasOwnProperty(key)){ this[key] = this._super[key]; } if(key[0] === "$" || key[0] === "_") protectedSpace[this.objId][key] = this._super[key]; } classFunction.call(this, option); for(var key in this){ if(this.hasOwnProperty(key) && (key[0] === "$" || key[0] === "_")) protectedSpace[this.objId][key] = this[key]; } //prevent accessing protected variables from outside delete this._protected; var _super = this._super; for(var key in this){ if(this.hasOwnProperty(key) && (key[0] === "$" || key[0] === "_")) delete this[key]; } this._super = _super; return this; } if(classFunction.name) classX = rename(classX, classFunction.name); classX.prototype = Object.create(classBase.prototype); classX.prototype.constructor = classX; classX.extend = function(classFunction){ return extend(classX, classFunction); }; return classX; } var NewClass = { create: create, extend: extend, rename: rename, debug: false, }; if(NewClass.debug){ NewClass._protectedSpace = protectedSpace; } return NewClass; });
package com.thinkaurelius.titan.diskstorage.keycolumnvalue; import com.thinkaurelius.titan.diskstorage.StorageException; /** * KeyColumnValueStoreManager provides the persistence context to the graph database middleware. * <p/> * A KeyColumnValueStoreManager provides transaction handles across multiple data stores that * are managed by this KeyColumnValueStoreManager. * * @author <NAME> (<EMAIL>); */ public interface KeyColumnValueStoreManager extends BufferMutationKeyColumnValueStore, StoreManager { /** * Opens an ordered database by the given name. If the database does not exist, it is * created. If it has already been opened, the existing handle is returned. * * @param name Name of database * @return Database Handle * @throws com.thinkaurelius.titan.diskstorage.StorageException * */ public KeyColumnValueStore openDatabase(String name) throws StorageException; }
package controllers; import play.data.DynamicForm; import play.data.FormFactory; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Result; import javax.inject.Inject; import javax.tools.Diagnostic; import java.util.ArrayList; import java.util.Random; public class GameController extends Controller { private FormFactory formFactory; final private String PLAYER_NAME_SESSION_KEY = "PLAYER_KEY"; final private String KITTEN_IMG_SESSION_KEY = "KITTEN_IMG"; final private String CREW_MEMBERS_SESSION_KEY = "CREW_MEMBERS"; final private String[] CREW_NAMES = new String[]{"Larry", "Doug", "Mark", "Dirk", "Tree", "Shane", "Nathan", "Harvy", "Lance", "Neil"}; @Inject public GameController(FormFactory formFactory) { this.formFactory = formFactory; } public Result getWelcome() { return ok(views.html.welcome.render()); } public Result getKittens() { return ok(views.html.kittens.render()); } public Result postStart(Http.Request request) { DynamicForm form = formFactory.form().bindFromRequest(request); final String PLAYER_NAME = form.get("playerName"); final String KITTEN_IMG = form.get("kitten"); final String CREW_COUNT = "10"; final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); return ok(views.html.start.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)) .addingToSession(request, PLAYER_NAME_SESSION_KEY, PLAYER_NAME) .addingToSession(request, KITTEN_IMG_SESSION_KEY, KITTEN_IMG) .addingToSession(request, CREW_MEMBERS_SESSION_KEY, CREW_COUNT); } public Result postHomePort(Http.Request request) { final String PLAYER_NAME = request.session().getOptional(PLAYER_NAME_SESSION_KEY).orElse("Unknown"); final String KITTEN_IMG = request.session().getOptional(KITTEN_IMG_SESSION_KEY).orElse("Unknown"); final String CREW_COUNT = request.session().getOptional(CREW_MEMBERS_SESSION_KEY).orElse("Unknown"); final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); return ok(views.html.homeport.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } public Result postEastFromEngland(Http.Request request) { final String PLAYER_NAME = request.session().getOptional(PLAYER_NAME_SESSION_KEY).orElse("Unknown"); final String KITTEN_IMG = request.session().getOptional(KITTEN_IMG_SESSION_KEY).orElse("Unknown"); final String CREW_COUNT = decrementCrewCount(request); final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); final String DEAD_MEMBER = CREW_NAMES[Integer.parseInt(CREW_COUNT)]; if (Integer.parseInt(CREW_COUNT) < 5) { return ok(views.html.oakisland.render(PLAYER_NAME, CREW_COUNT , KITTEN_IMG, CREW_NAMES)) .addingToSession(request, CREW_MEMBERS_SESSION_KEY, CREW_COUNT); } else { return ok(views.html.eastfromengland.render(CREW_COUNT, DEAD_MEMBER, KITTEN_IMG, CREW_NAMES)) .addingToSession(request, CREW_MEMBERS_SESSION_KEY, CREW_COUNT); } } public Result postEastEnd(Http.Request request) { final String PLAYER_NAME = request.session().getOptional(PLAYER_NAME_SESSION_KEY).orElse("Unknown"); final String KITTEN_IMG = request.session().getOptional(KITTEN_IMG_SESSION_KEY).orElse("Unknown"); final String CREW_COUNT = request.session().getOptional(CREW_MEMBERS_SESSION_KEY).orElse("Unknown"); final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); return ok(views.html.eastend.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } public Result postWestFromEngland(Http.Request request) { final String PLAYER_NAME = request.session().getOptional(PLAYER_NAME_SESSION_KEY).orElse("Unknown"); final String KITTEN_IMG = request.session().getOptional(KITTEN_IMG_SESSION_KEY).orElse("Unknown"); final String CREW_COUNT = decrementCrewCount(request); final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); if (Integer.parseInt(CREW_COUNT) < 5) { return ok(views.html.oakisland.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)) .addingToSession(request, CREW_MEMBERS_SESSION_KEY, CREW_COUNT); } else { return ok(views.html.westfromengland.render(CREW_COUNT, KITTEN_IMG, CREW_NAMES)) .addingToSession(request, CREW_MEMBERS_SESSION_KEY, CREW_COUNT); } } public Result postWestEnd(Http.Request request) { Random r = new Random(); int RANDOM_NUMBER = (r.nextInt(5) + 1); final String PLAYER_NAME = request.session().getOptional(PLAYER_NAME_SESSION_KEY).orElse("Unknown"); final String KITTEN_IMG = request.session().getOptional(KITTEN_IMG_SESSION_KEY).orElse("Unknown"); final String CREW_COUNT = request.session().getOptional(CREW_MEMBERS_SESSION_KEY).orElse("Unknown"); final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); if(RANDOM_NUMBER == 1) { return ok(views.html.dungeon.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } else { return ok(views.html.westend.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } } public Result postNorthFromEngland(Http.Request request) { final String PLAYER_NAME = request.session().getOptional(PLAYER_NAME_SESSION_KEY).orElse("Unknown"); final String KITTEN_IMG = request.session().getOptional(KITTEN_IMG_SESSION_KEY).orElse("Unknown"); final String CREW_COUNT = request.session().getOptional(CREW_MEMBERS_SESSION_KEY).orElse("Unknown"); final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); if (KITTEN_IMG.equals("/assets/images/agro.jpg") && CREW_COUNT.equals("6")) //EasterEgg { return ok(views.html.vikings.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } else { return ok(views.html.northfromengland.render(CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } } public Result postNorthEnd(Http.Request request) { Random r = new Random(); final int RANDOM_NUMBER = (r.nextInt(4) + 1); final String PLAYER_NAME = request.session().getOptional(PLAYER_NAME_SESSION_KEY).orElse("Unknown"); final String KITTEN_IMG = request.session().getOptional(KITTEN_IMG_SESSION_KEY).orElse("Unknown"); final String CREW_COUNT = request.session().getOptional(CREW_MEMBERS_SESSION_KEY).orElse("Unknown"); final String[] CREW_NAMES = getRemainingCrewMembers(Integer.parseInt(CREW_COUNT)); if (RANDOM_NUMBER == 1) { return ok(views.html.northpole.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } else { return ok(views.html.northend.render(PLAYER_NAME, CREW_COUNT, KITTEN_IMG, CREW_NAMES)); } } public String decrementCrewCount(Http.Request request) { final String CREW_COUNT = request.session().getOptional(CREW_MEMBERS_SESSION_KEY).orElse("Unknown"); int crewCountToInt = Integer.parseInt(CREW_COUNT); crewCountToInt--; return String.valueOf(crewCountToInt); } public String[] getRemainingCrewMembers(int crewCount) { String[] crewNames = new String[crewCount]; for (int i = 0; i < crewCount; i++) { crewNames[i] = CREW_NAMES[i]; } return crewNames; } }
<filename>src/Etterna/Screen/Gameplay/ScreenGameplayPractice.cpp #include "Etterna/Globals/global.h" #include "ScreenGameplayPractice.h" #include "Etterna/Models/Misc/Difficulty.h" #include "Etterna/Singletons/GameState.h" #include "Etterna/Singletons/PrefsManager.h" #include "Etterna/Singletons/ScreenManager.h" #include "Etterna/Singletons/StatsManager.h" #include "Etterna/Models/Songs/Song.h" #include "Etterna/Actor/Gameplay/ArrowEffects.h" #include "Etterna/Models/StepsAndStyles/Style.h" #include "Etterna/Models/Misc/GameConstantsAndTypes.h" #include "Etterna/Models/Misc/GamePreferences.h" #include "Etterna/Models/Misc/HighScore.h" #include "Etterna/Models/Misc/PlayerAI.h" #include "Etterna/Models/Misc/PlayerInfo.h" #include "Etterna/Models/Misc/PlayerStageStats.h" #include "Etterna/Models/NoteData/NoteDataWithScoring.h" #include "Etterna/Models/NoteData/NoteDataUtil.h" #include "Etterna/Models/NoteData/NoteData.h" #include "Etterna/Actor/Gameplay/Player.h" #include "Etterna/Actor/Gameplay/PlayerPractice.h" #include "Etterna/Models/Misc/RadarValues.h" #include "Etterna/Singletons/DownloadManager.h" #include "Etterna/Singletons/GameSoundManager.h" #include "RageUtil/Misc/RageInput.h" #include "Etterna/Singletons/SongManager.h" #include "Etterna/Models/Lua/LuaBinding.h" #include "Etterna/Singletons/LuaManager.h" REGISTER_SCREEN_CLASS(ScreenGameplayPractice); void ScreenGameplayPractice::FillPlayerInfo(PlayerInfo* playerInfoOut) { playerInfoOut->Load(PLAYER_1, MultiPlayer_Invalid, true, Difficulty_Invalid, GameplayMode_Practice); } ScreenGameplayPractice::ScreenGameplayPractice() { // covered by base class constructor } void ScreenGameplayPractice::Init() { ScreenGameplay::Init(); } ScreenGameplayPractice::~ScreenGameplayPractice() { if (PREFSMAN->m_verbose_log > 1) LOG->Trace("ScreenGameplayReplay::~ScreenGameplayReplay()"); } bool ScreenGameplayPractice::Input(const InputEventPlus& input) { // override default input here so we can reload the song // ... i wonder if this is doable. // haha dont try to break it please if (!IsTransitioning()) { bool bHoldingCtrl = INPUTFILTER->IsBeingPressed( DeviceInput(DEVICE_KEYBOARD, KEY_LCTRL)) || INPUTFILTER->IsBeingPressed(DeviceInput(DEVICE_KEYBOARD, KEY_RCTRL)); bool bHoldingShift = INPUTFILTER->IsBeingPressed( DeviceInput(DEVICE_KEYBOARD, KEY_LSHIFT)) || INPUTFILTER->IsBeingPressed(DeviceInput(DEVICE_KEYBOARD, KEY_RSHIFT)); wchar_t c = INPUTMAN->DeviceInputToChar(input.DeviceI, false); MakeUpper(&c, 1); // if you press ctrl+shift+R, you reload the song like in Music Select // the catch is that this can break a lot of things probably // so be careful with it // initial implementation below, might just end up restarting the song // and reloading there instead if (bHoldingCtrl && bHoldingShift && c == 'R') { Song* cursong = GAMESTATE->m_pCurSong; vector<Steps*> chartsForThisSong = cursong->GetAllSteps(); vector<std::string> oldKeys; for (auto k : chartsForThisSong) oldKeys.emplace_back(k->GetChartKey()); bool success = cursong->ReloadFromSongDir(); SONGMAN->ReconcileChartKeysForReloadedSong(cursong, oldKeys); if (!success || GAMESTATE->m_pCurSteps->GetNoteData().IsEmpty()) { LOG->Trace("The Player attempted something resulting in an " "unrecoverable error while in Gameplay Practice and " "has been ejected."); BeginBackingOutFromGameplay(); return true; } SetupNoteDataFromRow(GAMESTATE->m_pCurSteps); float fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut; GetMusicEndTiming(fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut); RageSoundParams p = m_pSoundMusic->GetParams(); float basicSongStart = GAMESTATE->m_pCurSong->GetFirstSecond() * p.m_fSpeed; // not using a loop region so just set the new sound params if (loopEnd == loopStart) { p.m_StartSecond = basicSongStart; p.m_LengthSeconds = fSecondsToStartTransitioningOut - p.m_StartSecond; } else { // using a loop region, check to see if either end is outside // the new song length if (loopStart < basicSongStart) { loopStart = basicSongStart; p.m_StartSecond = basicSongStart; } if (loopEnd > fSecondsToStartTransitioningOut) { loopEnd = fSecondsToStartTransitioningOut; p.m_LengthSeconds = fSecondsToStartTransitioningOut - p.m_StartSecond; } } RageTimer tm; const float fSeconds = m_pSoundMusic->GetPositionSeconds(NULL, &tm); if (fSeconds > fSecondsToStartTransitioningOut || fSeconds < p.m_StartSecond) { // i want to make sure things are done in a very particular // order m_pSoundMusic->SetParams(p); SOUND->SetSoundPosition(m_pSoundMusic, p.m_StartSecond); } else { m_pSoundMusic->SetParams(p); } // let the theme know we just changed so many things internally MESSAGEMAN->Broadcast("PracticeModeReload"); return true; } } return ScreenGameplay::Input(input); } void ScreenGameplayPractice::Update(float fDeltaTime) { if (GAMESTATE->m_pCurSong == NULL) { Screen::Update(fDeltaTime); return; } UpdateSongPosition(fDeltaTime); if (m_bZeroDeltaOnNextUpdate) { Screen::Update(0); m_bZeroDeltaOnNextUpdate = false; } else { Screen::Update(fDeltaTime); } if (SCREENMAN->GetTopScreen() != this) return; m_AutoKeysounds.Update(fDeltaTime); m_vPlayerInfo.m_SoundEffectControl.Update(fDeltaTime); { float fSpeed = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; RageSoundParams p = m_pSoundMusic->GetParams(); if (std::fabs(p.m_fSpeed - fSpeed) > 0.01f && fSpeed >= 0.0f) { p.m_fSpeed = fSpeed; m_pSoundMusic->SetParams(p); } } // If we are using a loop region, check if the music looped // If it did, reset the notedata. if (!m_Out.IsTransitioning() && loopStart != loopEnd && GAMESTATE->m_Position.m_fMusicSeconds + 0.1f < lastReportedSeconds) { if (!m_GiveUpTimer.IsZero()) return; auto td = GAMESTATE->m_pCurSteps->GetTimingData(); const float startBeat = td->GetBeatFromElapsedTime(loopStart); const float endBeat = td->GetBeatFromElapsedTime(loopEnd); const int rowStart = BeatToNoteRow(startBeat); const int rowEnd = BeatToNoteRow(endBeat); if (rowStart < rowEnd) SetupNoteDataFromRow(GAMESTATE->m_pCurSteps, rowStart, rowEnd); if (PREFSMAN->m_bEasterEggs) m_Toasty.Reset(); // Reset the wife/judge counter related visible stuff PlayerPractice* pl = static_cast<PlayerPractice*>(m_vPlayerInfo.m_pPlayer); pl->PositionReset(); } lastReportedSeconds = GAMESTATE->m_Position.m_fMusicSeconds; switch (m_DancingState) { case STATE_DANCING: { // Update living players' alive time // HACK: Don't scale alive time when using tab/tilde. Instead of // accumulating time from a timer, this time should instead be tied // to the music position. float fUnscaledDeltaTime = m_timerGameplaySeconds.GetDeltaTime(); m_vPlayerInfo.GetPlayerStageStats()->m_fAliveSeconds += fUnscaledDeltaTime * GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; // update fGameplaySeconds STATSMAN->m_CurStageStats.m_fGameplaySeconds += fUnscaledDeltaTime; float curBeat = GAMESTATE->m_Position.m_fSongBeat; Song& s = *GAMESTATE->m_pCurSong; if (curBeat >= s.GetFirstBeat() && curBeat < s.GetLastBeat()) { STATSMAN->m_CurStageStats.m_fStepsSeconds += fUnscaledDeltaTime; } // Handle the "give up" timer // except hard code it to fire after 1 second // instead of checking metrics // because we want to exit fast on demand bool bGiveUpTimerFired = false; bGiveUpTimerFired = !m_GiveUpTimer.IsZero() && m_GiveUpTimer.Ago() > 1.f; m_gave_up = bGiveUpTimerFired; if (bGiveUpTimerFired) { m_vPlayerInfo.GetPlayerStageStats()->gaveuplikeadumbass = true; m_vPlayerInfo.GetPlayerStageStats()->m_bDisqualified = true; LOG->Trace("Exited Practice Mode to Evaluation"); this->PostScreenMessage(SM_LeaveGameplay, 0); return; } } default: break; } PlayTicks(); SendCrossedMessages(); // ArrowEffects::Update call moved because having it happen once per // NoteField (which means twice in two player) seemed wasteful. -Kyz ArrowEffects::Update(); } void ScreenGameplayPractice::SetupNoteDataFromRow(Steps* pSteps, int minRow, int maxRow) { NoteData originalNoteData; pSteps->GetNoteData(originalNoteData); const Style* pStyle = GAMESTATE->GetCurrentStyle(m_vPlayerInfo.m_pn); NoteData ndTransformed; pStyle->GetTransformedNoteDataForStyle( m_vPlayerInfo.GetStepsAndTrailIndex(), originalNoteData, ndTransformed); m_vPlayerInfo.GetPlayerState()->Update(0); NoteDataUtil::RemoveAllButRange(ndTransformed, minRow, maxRow); // load player { m_vPlayerInfo.m_NoteData = ndTransformed; NoteDataUtil::RemoveAllTapsOfType(m_vPlayerInfo.m_NoteData, TapNoteType_AutoKeysound); m_vPlayerInfo.m_pPlayer->Reload(); } // load auto keysounds { NoteData nd = ndTransformed; NoteDataUtil::RemoveAllTapsExceptForType(nd, TapNoteType_AutoKeysound); m_AutoKeysounds.Load(m_vPlayerInfo.GetStepsAndTrailIndex(), nd); } { RString sType; switch (GAMESTATE->m_SongOptions.GetCurrent().m_SoundEffectType) { case SoundEffectType_Off: sType = "SoundEffectControl_Off"; break; case SoundEffectType_Speed: sType = "SoundEffectControl_Speed"; break; case SoundEffectType_Pitch: sType = "SoundEffectControl_Pitch"; break; default: break; } m_vPlayerInfo.m_SoundEffectControl.Load( sType, m_vPlayerInfo.GetPlayerState(), &m_vPlayerInfo.m_NoteData); } } void ScreenGameplayPractice::TogglePause() { // True if we were paused before now bool oldPause = GAMESTATE->GetPaused(); // True if we are becoming paused bool newPause = !GAMESTATE->GetPaused(); if (oldPause) { float rate = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; m_pSoundMusic->Stop(); RageTimer tm; const float fSeconds = m_pSoundMusic->GetPositionSeconds(NULL, &tm); float fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut; GetMusicEndTiming(fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut); // Restart the music with the proper params RageSoundParams p = m_pSoundMusic->GetParams(); p.m_StartSecond = fSeconds - 0.01f; p.m_fSpeed = rate; // If using a loop region, use the loop params instead if (loopStart != loopEnd) { p.m_fFadeOutSeconds = 1.f; p.m_LengthSeconds = loopEnd + 5.f - loopStart; p.StopMode = RageSoundParams::M_LOOP; } else { p.m_fFadeOutSeconds = MUSIC_FADE_OUT_SECONDS; p.m_LengthSeconds = fSecondsToStartFadingOutMusic + MUSIC_FADE_OUT_SECONDS - p.m_StartSecond; p.StopMode = RageSoundParams::M_CONTINUE; } p.m_bAccurateSync = true; // Go m_pSoundMusic->Play(false, &p); // To force the music to actually loop like it should, need to do this // after starting if (loopStart != loopEnd) { p.m_StartSecond = loopStart - 2.f; m_pSoundMusic->SetParams(p); } } m_pSoundMusic->Pause(newPause); GAMESTATE->SetPaused(newPause); } void ScreenGameplayPractice::SetSongPosition(float newSongPositionSeconds, float noteDelay, bool hardSeek, bool unpause) { bool isPaused = GAMESTATE->GetPaused(); RageSoundParams p = m_pSoundMusic->GetParams(); // Letting this execute will freeze the music most of the time and thats bad if (loopStart != loopEnd && newSongPositionSeconds > loopEnd) return; // If paused, we need to move fast so dont use slow seeking // but if we want to hard seek, we dont care about speed p.m_bAccurateSync = !isPaused || hardSeek; m_pSoundMusic->SetParams(p); // realign mp3 files by seeking backwards to force a full reseek, then // seeking forward to finish the job if (hardSeek && newSongPositionSeconds > GAMESTATE->m_Position.m_fMusicSeconds) SOUND->SetSoundPosition(m_pSoundMusic, GAMESTATE->m_Position.m_fMusicSeconds - 0.01f); // Set the final position SOUND->SetSoundPosition(m_pSoundMusic, newSongPositionSeconds - noteDelay); UpdateSongPosition(0); // Unpause the music if we want it unpaused if (unpause && isPaused) { m_pSoundMusic->Pause(false); GAMESTATE->SetPaused(false); } // Restart the notedata for the row we just moved to until the end of the // file Steps* pSteps = GAMESTATE->m_pCurSteps; TimingData* pTiming = pSteps->GetTimingData(); const float fSongBeat = GAMESTATE->m_Position.m_fSongBeat; const float fNotesBeat = pTiming->GetBeatFromElapsedTime(newSongPositionSeconds); const int rowNow = BeatToNoteRow(fNotesBeat); lastReportedSeconds = newSongPositionSeconds; // When using a loop region, just keep the loaded Notedata in the region if (loopStart != loopEnd) { const float endBeat = pTiming->GetBeatFromElapsedTime(loopEnd); const int rowEnd = BeatToNoteRow(endBeat); const float startBeat = pTiming->GetBeatFromElapsedTime(loopStart); const int rowStart = BeatToNoteRow(startBeat); const int rowUsed = max(rowStart, rowNow); // Assert crash if this check isn't done if (rowUsed < rowEnd) SetupNoteDataFromRow(pSteps, rowUsed, rowEnd); } else { SetupNoteDataFromRow(pSteps, rowNow); } // Reset the wife/judge counter related visible stuff PlayerPractice* pl = static_cast<PlayerPractice*>(m_vPlayerInfo.m_pPlayer); pl->RenderAllNotesIgnoreScores(); pl->PositionReset(); if (PREFSMAN->m_bEasterEggs) m_Toasty.Reset(); // just having a message we can respond to directly is probably the best way // to reset lua elements MESSAGEMAN->Broadcast("PracticeModeReset"); } float ScreenGameplayPractice::AddToRate(float amountAdded) { float rate = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; double newRate = std::floor((rate + amountAdded) * 100 + 0.5) / 100; // Rates outside of this range may crash // Use 0.25 because of floating point errors... if (newRate <= 0.25f || newRate > 3.f) return rate; RageTimer tm; const float fSeconds = m_pSoundMusic->GetPositionSeconds(NULL, &tm); float fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut; GetMusicEndTiming(fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut); // Set Music params using new rate float rate_plus = static_cast<float>(newRate); RageSoundParams p; p.m_fSpeed = rate_plus; GAMESTATE->m_SongOptions.GetSong().m_fMusicRate = rate_plus; GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate = rate_plus; GAMESTATE->m_SongOptions.GetPreferred().m_fMusicRate = rate_plus; // If using loop region, also consider the loop params if (loopStart != loopEnd) { p.m_StartSecond = loopStart - 2.f; p.m_fFadeOutSeconds = 1.f; p.m_LengthSeconds = loopEnd + 5.f - loopStart; p.StopMode = RageSoundParams::M_LOOP; } else { p.m_fFadeOutSeconds = MUSIC_FADE_OUT_SECONDS; p.m_LengthSeconds = fSecondsToStartFadingOutMusic + MUSIC_FADE_OUT_SECONDS - p.m_StartSecond; p.StopMode = RageSoundParams::M_CONTINUE; } p.m_bAccurateSync = true; // Apply param (rate) changes to the running Music m_pSoundMusic->SetParams(p); GAMESTATE->m_Position.m_fMusicSeconds = fSeconds; // Tell the theme we changed the rate MESSAGEMAN->Broadcast("CurrentRateChanged"); return static_cast<float>(rate_plus); } void ScreenGameplayPractice::SetLoopRegion(float start, float end) { // Don't allow a loop region that is too negative. // Some songs actually do start in negative time, so be lenient. if (start < -2 || end < -2) return; loopStart = start; loopEnd = end; // Tell the Music that it should loop on a given region instead // 2 seconds are removed from the start for "intro" // 5 seconds are added to the end for "outro" // No notedata will occupy that space. RageSoundParams p = m_pSoundMusic->GetParams(); p.m_StartSecond = start - 2.f; p.m_fFadeOutSeconds = 1.f; p.m_LengthSeconds = end + 5.f - start; p.StopMode = RageSoundParams::M_LOOP; // We dont reset notedata here because that could get repetitive and also be // annoying to users or cause other slowdowns m_pSoundMusic->SetParams(p); } void ScreenGameplayPractice::ResetLoopRegion() { // magic number defaults for loop region bounds loopStart = -2000.f; loopEnd = -2000.f; // Reload notedata for the entire file starting at current row RageTimer tm; const float fSeconds = m_pSoundMusic->GetPositionSeconds(NULL, &tm); auto td = GAMESTATE->m_pCurSteps->GetTimingData(); const float startBeat = td->GetBeatFromElapsedTime(fSeconds); const int rowNow = BeatToNoteRow(startBeat); SetupNoteDataFromRow(GAMESTATE->m_pCurSteps, rowNow); float fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut; GetMusicEndTiming(fSecondsToStartFadingOutMusic, fSecondsToStartTransitioningOut); // Reapply the standard Music parameters RageSoundParams p = m_pSoundMusic->GetParams(); p.m_StartSecond = GAMESTATE->m_pCurSong->GetFirstSecond() * GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; p.m_fFadeOutSeconds = MUSIC_FADE_OUT_SECONDS; p.m_LengthSeconds = fSecondsToStartFadingOutMusic + MUSIC_FADE_OUT_SECONDS - p.m_StartSecond; p.StopMode = RageSoundParams::M_CONTINUE; m_pSoundMusic->SetParams(p); } class LunaScreenGameplayPractice : public Luna<ScreenGameplayPractice> { public: static int SetSongPosition(T* p, lua_State* L) { float position = FArg(1); float delay = FArg(2); bool hardseek = BArg(3); p->SetSongPosition(position, delay, hardseek); return 0; } static int SetSongPositionAndUnpause(T* p, lua_State* L) { float position = FArg(1); float delay = FArg(2); bool hardseek = BArg(3); p->SetSongPosition(position, delay, hardseek, true); return 0; } static int AddToRate(T* p, lua_State* L) { float rate = FArg(1); lua_pushnumber(L, p->AddToRate(rate)); return 1; } static int TogglePause(T* p, lua_State* L) { p->TogglePause(); return 0; } static int SetLoopRegion(T* p, lua_State* L) { float begin = FArg(1); float end = FArg(2); p->SetLoopRegion(begin, end); return 0; } static int ResetLoopRegion(T* p, lua_State* L) { p->ResetLoopRegion(); return 0; } LunaScreenGameplayPractice() { ADD_METHOD(SetSongPosition); ADD_METHOD(SetSongPositionAndUnpause); ADD_METHOD(AddToRate); ADD_METHOD(TogglePause); ADD_METHOD(SetLoopRegion); ADD_METHOD(ResetLoopRegion); } }; LUA_REGISTER_DERIVED_CLASS(ScreenGameplayPractice, ScreenGameplay)
<reponame>lananh265/social-network "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.messages = void 0; var messages = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M21 7h-3c0-1.65-1.35-3-3-3h-12c-1.65 0-3 1.35-3 3v7c0 1.65 1.35 3 3 3v3l3-3c0 1.65 1.35 3 3 3h8l3 3v-3h1c1.65 0 3-1.35 3-3v-7c0-1.65-1.35-3-3-3zm-18 8c-.542 0-1-.458-1-1v-7c0-.542.458-1 1-1h12c.542 0 1 .458 1 1v1h-6.5c-1.379 0-2.5 1.121-2.5 2.5v4.5h-4zm19 2c0 .542-.458 1-1 1h-12c-.542 0-1-.458-1-1v-6.5c0-.827.673-1.5 1.5-1.5h11.5c.542 0 1 .458 1 1v7z" }, "children": [] }] }; exports.messages = messages;
def series(N): # Initialize the result list result = [] # Generate the series n = N while n <= N*2: result.append(n) n+=2 # Return the result return result
<filename>index.js var mapStream = require('map-stream'); var PluginError = require('gulp-util').PluginError; var fs = require('fs'); module.exports = gulpJsonStructureValidator; function jsondif(a,b,pre){ var dev = ''; for (var prop in a) { if(b[prop]==undefined){ dev += pre+prop+'\n'; } else { if (typeof b[prop] === 'object') { dev += jsondif(a[prop],b[prop],pre+prop+'.'); } } } return dev; }; function gulpJsonStructureValidator(option) { var template = ""; if (option) { template = option.template; } return mapStream(function(file, cb) { fs.readFile(template, 'utf8', function (err, data) { if (err) { error = new PluginError('gulp-json-structure-validator',{ name: 'JSON Structure Validate Error', filename: file.path, message: 'Read Template Error: ' + template }); cb(error, file); } else { var templateObject = JSON.parse(data); var content = file.contents; var error; if (content) { var e = jsondif(templateObject, JSON.parse(content), ''); if (e != '') { error = new PluginError('gulp-json-structure-validator',{ name: 'JSON Structure Validate Error', filename: file.path, message: '\nForgotten in "' + file.path + '"' + ':\n' +e }); } } cb(error, file); } }); }); }
import numpy as np def compare_investment_strategies(monthly_ret_fraction): frac_slow = np.sum(monthly_ret_fraction[0:11, 1]) frac_fast = np.sum(monthly_ret_fraction[0:11, 0]) avg_slow = frac_slow / 11 avg_fast = frac_fast / 11 if avg_slow > avg_fast: return "Strategy 1 has higher average monthly return." elif avg_fast > avg_slow: return "Strategy 2 has higher average monthly return." else: return "Both strategies have the same average monthly return." # Example usage monthly_ret_fraction = np.array([[0.02, 0.03], [0.01, 0.015], [0.025, 0.02], [0.015, 0.02], [0.03, 0.035], [0.02, 0.025], [0.025, 0.03], [0.03, 0.035], [0.035, 0.04], [0.04, 0.045], [0.045, 0.05]]) result = compare_investment_strategies(monthly_ret_fraction) print(result) # Output: "Strategy 2 has higher average monthly return."
num_list = [1, 2, 3, 4, 5] num_string = ''.join([str(num) for num in num_list]) print(num_string) # prints 12345
#!/bin/bash set -e set -x target=$1 shift fss="proc run dev" for fs in $fss do $dry_run mount -o bind /$fs $target/$fs done mkdir -p $target/ccache mount -o bind $CCACHEDIR $target/ccache #check run/resolvconf/resolv.conf if [ ! -e $target/run/resolvconf/resolv.conf ]; then mkdir /run/resolvconf cp /etc/resolv.conf /run/resolvconf/resolv.conf fi function unmount_special() { # Unmount special files for fs in $fss do $dry_run umount -l $target/$fs done umount -l $target/ccache rmdir $target/ccache || true } trap unmount_special EXIT export CFLAGS="${IMAGE_CFLAGS}" export CPPFLAGS="$CFLAGS" export PATH="/usr/lib/ccache:$PATH" export CCACHE_DIR=/ccache export CCACHE_MAXSIZE=15G export CCACHE_SLOPPINESS=file_macro,time_macros export CC=/usr/lib/ccache/gcc export CXX=/usr/lib/ccache/g++ for p in $@ do f=$WORKDIR/packages/$p if [ -e $f/pre.sh ]; then $dry_run $f/pre.sh $target fi if [ -e $f/qemu.sh ]; then $dry_run cp $f/qemu.sh $target $dry_run chroot $target bash qemu.sh $dry_run rm $target/qemu.sh fi if [ -e $f/post.sh ]; then $dry_run $f/post.sh $target fi done
#!/bin/bash set -e # define global server name to prevent apache2 warnings cat <<EOF >/etc/apache2/sites-available/000-default.conf ServerName ${SWARM_HOST} EOF # enable default virtual host a2ensite 000-default 1>/dev/null
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import IView from 'iview' import VueLazyload from 'vue-lazyload' import Distpicker from 'v-distpicker' import App from './App' import router from './router' import store from './store' import {picurl, ishot, isnull} from './filters' import vImg from '@/components/Lazyimg' import 'iview/dist/styles/iview.css' Vue.config.productionTip = false Vue.use(IView) Vue.use(VueLazyload, { preLoad: 1.3, error: require('./assets/images/404.png'), loading: require('./assets/images/loading.gif'), attempt: 1 }) Vue.component('v-img', vImg) Vue.component('v-distpicker', Distpicker) Vue.filter('pic', picurl) Vue.filter('ishot', ishot) Vue.filter('isnull', isnull) router.afterEach((to, from) => { if (to.path === '/') { router.push({path: '/hotel'}) } }) /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
#!/bin/bash docker build --rm -t trok/flexitserver --file Dockerfile .
<reponame>infinitemule/github-identicons<filename>src/test/scala/com/infinitemule/github/identicons/IdenticonSuite.scala /* * GitHub Identicons */ package com.infinitemule.github.identicons import org.scalatest.FunSuite /** * This is difficult to test since you don't know * what you are going to get because it's based on * a hash value. */ class IdenticonSuite extends FunSuite { test("Creating an Identicon should result in a 5 x 5 matrix of booleans") { val identicon = Identicon.create("test") assert(identicon.glyph.size === 5) assert(identicon.glyph(1).size === 5) } /** * Note this will fail if a different hash algo is used */ test("Using test as a username should create the spicified identicon") { val identicon = Identicon.create("test") assert(identicon.glyph(0)(1)) assert(identicon.glyph(0)(3)) assert(identicon.glyph(1)(0)) assert(identicon.glyph(1)(2)) assert(identicon.glyph(1)(4)) assert(identicon.glyph(2)(0)) assert(identicon.glyph(2)(1)) assert(identicon.glyph(2)(3)) assert(identicon.glyph(2)(4)) assert(identicon.glyph(3)(0)) assert(identicon.glyph(3)(2)) assert(identicon.glyph(3)(4)) assert(identicon.glyph(4)(0)) assert(identicon.glyph(4)(4)) assert(identicon.color.getRed() === 112) assert(identicon.color.getGreen() === 204) assert(identicon.color.getBlue() === 194) } }
#!/bin/sh edje_cc $@ -id . -fd /usr/share/fonts/truetype/dejavu/ headunit.edc -o headunit.edj
import { Medium } from './Medium'; export { Medium }; export default Medium;
<reponame>grind086/js-noise 'use strict'; var utils = require('./utils'); class Poisson extends Array { constructor(mean, threshold) { super(); if (!threshold) threshold = 0.0001; this.mean = mean; var ptot = 1, i = 0, p; while (ptot > threshold) { p = this.probability(i); this[i++] = p; ptot -= p; } this[i] = ptot; } probability(k) { return Math.pow(this.mean, k) * Math.pow(Math.E, -this.mean) / utils.factorial(k); } choose(n) { n = n ? n : Math.random(); for (var i = 0; i < this.length; i++) { n -= this[i]; if (n <= 0) return i; } return i; } } module.exports = Poisson;
import { MOVIES_LOADING, MOVIES_LOAD_SUCCESS, MOVIES_LOAD_ERROR, MOVIES_RATING_UPDATE } from "./constants"; import { fetchMovies } from "../services/api"; const moviesLoading = payload => ({ type: MOVIES_LOADING, payload }); const moviesLoadSuccess = payload => ({ type: MOVIES_LOAD_SUCCESS, payload }); const moviesLoadError = payload => ({ type: MOVIES_LOAD_ERROR, payload }); const genreToggle = payload => ({ type: MOVIES_RATING_UPDATE, payload }); const getMovies = (dispatch) => { dispatch(moviesLoading(true)); const left = ({ message }) => dispatch(moviesLoadError(message)) const right = ({ data: { results } }) => dispatch(moviesLoadSuccess(results)) fetchGenres() .fork(left, right) dispatch(moviesLoading(false)); }; export { moviesLoading, moviesLoadSuccess, moviesLoadError, moviesRatingUpdate, getMovies };
#!/bin/bash # This script parses in the command line parameters from runCust, # maps them to the correct command line parameters for DispNet training script and launches that task # The last line of runCust should be: bash $CONFIG_FILE --data-dir $DATA_DIR --log-dir $LOG_DIR # Parse the command line parameters # that runCust will give out DATA_DIR=NONE LOG_DIR=NONE CONFIG_DIR=NONE MODEL_DIR=NONE # Parsing command line arguments: while [[ $# > 0 ]] do key="$1" case $key in -h|--help) echo "Usage: run_dispnet_training_philly.sh [run_options]" echo "Options:" echo " -d|--data-dir <path> - directory path to input data (default NONE)" echo " -l|--log-dir <path> - directory path to save the log files (default NONE)" echo " -p|--config-file-dir <path> - directory path to config file directory (default NONE)" echo " -m|--model-dir <path> - directory path to output model file (default NONE)" exit 1 ;; -d|--data-dir) DATA_DIR="$2" shift # pass argument ;; -p|--config-file-dir) CONFIG_DIR="$2" shift # pass argument ;; -m|--model-dir) MODEL_DIR="$2" shift # pass argument ;; -l|--log-dir) LOG_DIR="$2" shift ;; *) echo Unkown option $key ;; esac shift # past argument or value done # Prints out the arguments that were passed into the script echo "DATA_DIR=$DATA_DIR" echo "LOG_DIR=$LOG_DIR" echo "CONFIG_DIR=$CONFIG_DIR" echo "MODEL_DIR=$MODEL_DIR" # Run training on philly # Add the root folder of the code to the PYTHONPATH export PYTHONPATH=$PYTHONPATH:$CONFIG_DIR # Run the actual job python $CONFIG_DIR/examples/AnytimeNetwork/resnet-ann.py \ --data_dir=$DATA_DIR \ --log_dir=$LOG_DIR \ --model_dir=$MODEL_DIR \ --load=${MODEL_DIR}/checkpoint \ --ds_name=cifar100 \ -f=11 \ --opt_at=-1 \ -n=1 \ -c=32 \ -s=1 \ --samloss=6 \ --batch_size=128 \
<gh_stars>100-1000 var app =getApp() Page({ data:{ "text":"修改安全密码" }, change:function(){ wx.showToast({ title: '修改成功', icon: 'success', duration: 2000 }) } })
#!/bin/bash -e psql -c 'CREATE DATABASE words;' psql -c 'CREATE EXTENSION pg_trgm;' words psql -c 'CREATE EXTENSION pgcrypto;' words psql -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";' words sqitch deploy # test user username: testusername # test user password: testpassword # test user languages: testpassword INSERT INTO users (email, username, passpass, languages) VALUES ('donald.duck@brazaville.com', 'passpass', 'donald.duck', '{}'); INSERT INTO users (email, username, passpass, languages) VALUES ('daisy.duck@brazaville.com', 'passpass', 'daisy.duck', '{"FR"}'); INSERT INTO users (email, username, passpass, languages) VALUES ('huey.duck@brazaville.com', 'passpass', 'huey.duck', '{}'); INSERT INTO users (email, username, passpass, languages) VALUES ('dewey.duck@brazaville.com', 'passpass', 'dewey.duck', '{}'); INSERT INTO users (email, username, passpass, languages) VALUES ('louie.duck@brazaville.com', 'passpass', 'louie.duck', '{}'); INSERT INTO users (email, username, passpass, languages) VALUES ('scrooge.mcduck@brazaville.com', 'passpass', 'scrooge.mcduck', '{"PL", "EN"}'); insertUser dbconnection "donald.duck@brazaville.com" "passpass" insertUser dbconnection "daisy.duck@brazaville.com" "passpass" insertUser dbconnection "huey.duck@brazaville.com" "passpass" insertUser dbconnection "dewey.duck@brazaville.com" "passpass" insertUser dbconnection "louie.duck@brazaville.com" "passpass" insertUser dbconnection "scrooge.mcduck@brazaville.com" "passpass"
<filename>src/app/libs/fontkit/tables/gvar.ts import r from 'restructure'; const shortFrac = new r.Fixed(16, 'BE', 14); class Offset { static decode(stream, parent) { // In short format, offsets are multiplied by 2. // This doesn't seem to be documented by Apple, but it // is implemented this way in Freetype. return parent.flags ? stream.readUInt32BE() : stream.readUInt16BE() * 2; } } const gvar = new r.Struct({ version: r.uint16, reserved: new r.Reserved(r.uint16), axisCount: r.uint16, globalCoordCount: r.uint16, globalCoords: new r.Pointer( r.uint32, new r.Array(new r.Array(shortFrac, 'axisCount'), 'globalCoordCount') ), glyphCount: r.uint16, flags: r.uint16, offsetToData: r.uint32, offsets: new r.Array( new r.Pointer(Offset, 'void', { relativeTo: 'offsetToData', allowNull: false, }), (t) => t.glyphCount + 1 ), }); export default gvar;
<filename>src/main/java/github/User.java package github; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @AllArgsConstructor @NoArgsConstructor @ToString @Data public class User { private int id; private String name; }
var _resize_8cpp = [ [ "Resize", "_resize_8cpp.xhtml#a25dc224be48103343302b5a6fd588fe7", null ] ];
def orientation(p, q, r): return ((q - p) * (r - p).conjugate()).imag ## ... # still points left on both lists, compare slopes of next hull edges # being careful to avoid divide-by-zero in slope calculation elif ((U[i+1] - U[i]) * (L[j] - L[j-1]).conjugate()).imag > 0: i += 1 else: j -= 1 ## ... def diameter(Points): diam, pair = max([(abs(p-q), (p,q)) for p,q in rotatingCalipers(Points)]) return pair
package com.cangetinshape.chefbook.Adapter; import android.content.Context; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.cangetinshape.chefbook.BestRecipe; import com.cangetinshape.chefbook.R; import com.cangetinshape.chefbook.StringUtils; import com.cangetinshape.chefbook.Utils; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; /** * Created by Amir on 1/4/2018. */ public class OnlineRecipeAdapter extends RecyclerView.Adapter<OnlineRecipeAdapter.OnlineRecipeViewHolder> { private Context mContext; private List<BestRecipe> mOnlineRecipes; public int mCurrentPosition; private static final String TAG = OnlineRecipeAdapter.class.getSimpleName(); public OnlineRecipeAdapter(Context context, List<BestRecipe> onlineRecipes) { mContext = context; mOnlineRecipes = onlineRecipes; } @Override public OnlineRecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // Get the RecyclerView item layout Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View recipeView = inflater.inflate(R.layout.online_recipe_list_item, parent, false); //recipeView.setFocusable(true); return new OnlineRecipeViewHolder(recipeView); } @Override public void onBindViewHolder(OnlineRecipeViewHolder holder, int position) { mCurrentPosition = position; BestRecipe currentOnlinerecipe = mOnlineRecipes.get(position); String recipeTitle = currentOnlinerecipe.getRecipeTitle(); String recipeCategory = currentOnlinerecipe.getCategory(); int servigs = currentOnlinerecipe.getServings(); int prepTime = currentOnlinerecipe.getPrepTime(); int cookingTime = currentOnlinerecipe.getCookingTime(); int yeildTime = currentOnlinerecipe.getYeildTime(); int totalTime = currentOnlinerecipe.getTotalTime(); String userName = currentOnlinerecipe.getUserName(); String userNameToshow = mContext.getString(R.string.added_by_text) + userName; String userId = currentOnlinerecipe.getUserID(); String allIngredients = currentOnlinerecipe.getIngredients(); String[] ingredientArray = StringUtils.convertStringToArray(allIngredients); ArrayList<BestRecipe.Ingredients> mIngredientObject = new ArrayList<>(); String allAmounts = currentOnlinerecipe.getAmount(); String[] amountArray = StringUtils.convertStringToArray(allAmounts); String allScales = currentOnlinerecipe.getScale(); String[] scaleArray = StringUtils.convertStringToArray(allScales); IngredientAdapter mIngredientAdapter; if (ingredientArray.length == amountArray.length && ingredientArray.length == scaleArray.length) { for (int i = 0; i < ingredientArray.length; i++) { mIngredientObject.add(new BestRecipe.Ingredients(ingredientArray[i], amountArray[i], scaleArray[i])); } } else { Log.e(TAG, mContext.getString(R.string.log_missing_information)); } mIngredientAdapter = new IngredientAdapter(mContext, 0, mIngredientObject); holder.mIngredientLV.setAdapter(mIngredientAdapter); Utils.dynamicallySetListViewHeight(holder.mIngredientLV); String allSteps = currentOnlinerecipe.getSteps(); String[] stepsArray = StringUtils.convertStringToArray(allSteps); ArrayAdapter<String> stepAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, stepsArray); holder.mStepsListLV.setAdapter(stepAdapter); Utils.dynamicallySetListViewHeight(holder.mStepsListLV); String firstImageAddress = currentOnlinerecipe.getImages().size() >= 1 ? currentOnlinerecipe.getImages().get(0) : null; String secondImageAddress = currentOnlinerecipe.getImages().size() >= 2 ? currentOnlinerecipe.getImages().get(1) : null; String thirdImageAddress = currentOnlinerecipe.getImages().size() >= 3 ? currentOnlinerecipe.getImages().get(2) : null; String forthImageAddress = currentOnlinerecipe.getImages().size() >= 4 ? currentOnlinerecipe.getImages().get(3) : null; holder.mListTitleTextView.setText(recipeTitle); holder.mListUserNameTextView.setText(userNameToshow); holder.mListCategoryTextView.setText(recipeCategory); String servingsString = mContext.getString(R.string.servings_txt) + String.valueOf(servigs); holder.mListServingsTextView.setText(servingsString); holder.mListPrepTimeTextView.setText(String.valueOf(prepTime)); holder.mListCookTimeTextView.setText(String.valueOf(cookingTime)); holder.mListYeildTimeTextView.setText(String.valueOf(yeildTime)); holder.mListTotalTimeTextView.setText(String.valueOf(totalTime)); if (firstImageAddress != null) Picasso.with(this.mContext).load(Uri.parse(firstImageAddress)) .placeholder(R.drawable.pic_placeholder).fit().into(holder.mListIV1); if (secondImageAddress != null) Picasso.with(this.mContext).load(Uri.parse(secondImageAddress)) .placeholder(R.drawable.pic_placeholder).fit().into(holder.mListIV2); if (thirdImageAddress != null) Picasso.with(this.mContext).load(Uri.parse(thirdImageAddress)) .placeholder(R.drawable.pic_placeholder).fit().into(holder.mListIV3); if (forthImageAddress != null) Picasso.with(this.mContext).load(Uri.parse(forthImageAddress)) .placeholder(R.drawable.pic_placeholder).fit().into(holder.mListIV4); } @Override public int getItemCount() { if (mOnlineRecipes != null) { return mOnlineRecipes.size(); } else return 0; } public class OnlineRecipeViewHolder extends RecyclerView.ViewHolder { TextView mListTitleTextView, mListUserNameTextView, mListCategoryTextView, mListServingsTextView, mListPrepTimeTextView, mListCookTimeTextView, mListYeildTimeTextView, mListTotalTimeTextView; ImageView mListIV1, mListIV2, mListIV3, mListIV4; ListView mIngredientLV, mStepsListLV; public OnlineRecipeViewHolder(View itemView) { super(itemView); mListTitleTextView = itemView.findViewById(R.id.od_list_title_tv); mListUserNameTextView = itemView.findViewById(R.id.od_list_username); mListCategoryTextView = itemView.findViewById(R.id.od_list_category_tv); mListServingsTextView = itemView.findViewById(R.id.od_list_servings_tv); mListPrepTimeTextView = itemView.findViewById(R.id.od_prep_time_tv_int); mListCookTimeTextView = itemView.findViewById(R.id.od_cook_time_tv_int); mListYeildTimeTextView = itemView.findViewById(R.id.od_yeild_time_tv_int); mListTotalTimeTextView = itemView.findViewById(R.id.od_list_total_time_tv_int); mListIV1 = itemView.findViewById(R.id.list_iv_1); mListIV2 = itemView.findViewById(R.id.list_iv_2); mListIV3 = itemView.findViewById(R.id.list_iv_3); mListIV4 = itemView.findViewById(R.id.list_iv_4); mIngredientLV = itemView.findViewById(R.id.od_ingredient_lv); mStepsListLV = itemView.findViewById(R.id.od_steps_lv); } } }
from typing import List class BitcoinTransactionInput: def __init__(self): self._txinwitness = [] self._sequence = 0 self._idx = 0 self._txid = "" self._vout = 0 self.scriptSig = ScriptSig() def set_txinwitness(self, txinwitness: List[str]) -> None: self._txinwitness = txinwitness def set_sequence(self, sequence: int) -> None: self._sequence = sequence def from_sql(self, vin): self._idx = vin[0] self.set_txid(vin[1]) self.set_vout(vin[2]) self.scriptSig.set_asm(vin[3]) self.scriptSig.set_hex(vin[4]) class ScriptSig: def __init__(self): self._asm = "" self._hex = "" def set_asm(self, asm: str) -> None: self._asm = asm def set_hex(self, hex_code: str) -> None: self._hex = hex_code
# shellcheck shell=bash check_bin bash check_bin dash check_bin bats check_bin basher [ ! -d "$XDG_DATA_HOME/bash-it" ] && { util.log_info "Installing bash-it" git clone "https://github.com/bash-it/bash-it" "$XDG_DATA_HOME/bash-it" source "$XDG_DATA_HOME/bash-it/install.sh" --no-modify-config } [ ! -d "$XDG_DATA_HOME/oh-my-bash" ] && { util.log_info "Installing oh-my-bash" git clone "https://github.com/ohmybash/oh-my-bash" "$XDG_DATA_HOME/oh-my-bash" } [ ! -d "$XDG_DATA_HOME/bash-git-prompt" ] && { util.log_info "Installing bash-git-prompt" git clone "https://github.com/magicmonty/bash-git-prompt" "$XDG_DATA_HOME/bash-git-prompt" } [ ! -d "$XDG_DATA_HOME/bashmarks" ] && { util.log_info "Installing bookmarks.sh" git clone "https://github.com/huyng/bashmarks" "$XDG_DATA_HOME/bashmarks" } [ ! -d "$XDG_DATA_HOME/basher" ] && { util.log_info "Installing basher" git clone https://github.com/basherpm/basher "$XDG_DATA_HOME/basher" }
<reponame>elbruno/Seeed_Python_reTerminal_QT5_Facerec import paho.mqtt.client as mqtt import time import logging class AddonMQTT: def __init__(self, address, port) -> None: self.client = mqtt.Client() self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.connect(address, port, 5) self.client.loop_start() logging.info("MQTT Init") def __delattr__(self, name: str) -> None: self.client.loop_stop() self.client.disconnect() logging.info("MQTT deinit") def on_connect(self, client, userdata, flags, rc): logging.info("Connected to with result code "+str(rc)) client.subscribe("face_rec/verified") def on_message(self, client, userdata, msg): logging.info(msg.topic+" " + str(msg.payload)) def send_data(self, topic, msg): self.client.publish(topic, msg) if __name__ == "__main__": MQTT = AddonMQTT("localhost", 1883) i = 0 try: while True: time.sleep(0.5) MQTT.send_data("mqtt/pimylifeup", i) i += 1 except KeyboardInterrupt: del MQTT
<html> <head> <title>Monthly Budget Calculator</title> <script type="text/javascript"> function calculateBudget() { // Get input values let income = document.getElementById("income").value; let expenses = document.getElementById("expenses").value; let savings = document.getElementById("savings").value; let spending = document.getElementById("spending").value; // Calculate budget let savingsAmount = income - expenses; let budgetAmount = savingsAmount - (savings + spending); // Display budget document.getElementById("budget").innerHTML = "Your total budget is $" + budgetAmount.toFixed(2); } </script> </head> <body> <h2>Monthly Budget Calculator</h2> <form> <p>Monthly income: <input type="number" id="income" /></p> <p>Monthly expenses: <input type="number" id="expenses" /></p> <p>Savings goal: <input type="number" id="savings" /></p> <p>Discretionary spending: <input type="number" id="spending" /></p> <input type="button" value="Calculate Budget" onclick="calculateBudget();" /> <p id="budget"></p> </form> </body> </html>
# Define the mixin class class CollapseTriggerRenderMixin: render_template = "djangocms_frontend/bootstrap5/collapse-trigger.html" # Define a sample subclass demonstrating the override class CustomCollapseTrigger(CollapseTriggerRenderMixin): render_template = "custom_templates/collapse-trigger.html" # Usage demonstration # Accessing the render_template variable from the subclass print(CustomCollapseTrigger.render_template) # Output: "custom_templates/collapse-trigger.html"
const httpServer = require("http-server"); const openPort = require("openport"); import { VIZ_PATH } from "./utils"; import * as path from "path"; import * as opn from "opn"; /** * @export * @param {string} dataPath Filename of data generated for graph * @param {string} [contextPath=__dirname] Path to be passed in when function is not consumed by bundle-buddy cli process */ export function launchServer( dataPath: string, contextPath: string = __dirname ) { openPort.find((err: Error, port: number) => { if (err != null) { console.log(err); process.exit(1); } httpServer .createServer({ root: path.join(contextPath, VIZ_PATH) }) .listen(port, "0.0.0.0", () => { console.log(`Server running on port ${port}`); console.log(`Press Control+C to Quit`); opn(`http://localhost:${port}?file=${dataPath}`); }); }); }
#!/bin/bash set -e TRUE=1 FALSE=0 RED=$'\e[1;31m' GREEN=$'\e[1;32m' RESET_COLOR=$'\033[0m' SCRIPT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" PROJECT_PATH="$(dirname "$SCRIPT_PATH")" LOCAL_MAVEN_PATH="${HOME}/.m2" ORG_PATH="com/github/urbancompass" CONFIG_FILE="${PROJECT_PATH}/buildSrc/src/main/kotlin/Config.kt" GRADLEW="${PROJECT_PATH}/gradlew" DATE=$(date '+%Y.%m.%d.%H.%M.%S') targets=("kmp-compass-api-ios64" "kmp-compass-api-iossim" "kmpcompass-android" "kmpcompass-common") function readProjectName() { nameLineRaw=$(grep "const val libraryName" "${CONFIG_FILE}") nameLine="$(echo -e "${nameLineRaw}" | tr -d '[:space:]')" echo "${nameLine}" | cut -d'"' -f 2 } PROJECT_NAME=$(readProjectName) AWS_BUCKET="<AWS BUCKET HERE>" # Change this AWS_RELEASE_FOLDER="${AWS_BUCKET}/${PROJECT_NAME}" function logError() { printf "%s%s%s\n" "${RED}" "${1}" "${RESET_COLOR}" } function logInfo() { printf "%s%s%s\n" "${GREEN}" "${1}" "${RESET_COLOR}" } function getVersionCode() { versionLineRaw=$(grep "const val thisLibrary" "${CONFIG_FILE}") versionLine="$(echo -e "${versionLineRaw}" | tr -d '[:space:]')" echo "${versionLine}" | cut -d'"' -f 2 } version=$(getVersionCode) function isProjectGitDirty() { echo ${FALSE} return 1 if [[ $(git diff --shortstat 2> /dev/null | tail -n1) != "" ]]; then echo ${TRUE} else echo ${FALSE} fi } function istMasterBranch() { branch=$(git rev-parse --abbrev-ref HEAD) if [[ "${branch}" == "master" ]]; then echo ${TRUE} else echo ${FALSE} fi } function isAlreadyReleasedInGit() { git fetch --tags --force if [ "$(git tag -l "${version}")" ]; then echo ${TRUE} else echo ${FALSE} fi } function isAlreadyReleasedInAws() { folder_out="$( aws s3 ls "${AWS_RELEASE_FOLDER}/${version}/")" if [ -n "${folder_out}" ]; then echo "${TRUE}" else echo "${FALSE}" fi } function backupLocalRepo() { backupFolderName="repository.${DATE}" if [[ -d "${LOCAL_MAVEN_PATH}/repository" ]]; then mv "${LOCAL_MAVEN_PATH}/repository" "${LOCAL_MAVEN_PATH}/${backupFolderName}" fi } function restoreLocalRepo() { backupFolderName="repository.${DATE}" releaseDate=$(date '+%Y.%m.%d.%H.%M.%S') releaseBackupFolder="${PROJECT_NAME}.release.${releaseDate}" if [[ -d "${LOCAL_MAVEN_PATH}/repository" ]]; then mv "${LOCAL_MAVEN_PATH}/repository" "${LOCAL_MAVEN_PATH}/${releaseBackupFolder}" fi if [[ -d "${LOCAL_MAVEN_PATH}/${backupFolderName}" ]]; then mv "${LOCAL_MAVEN_PATH}/${backupFolderName}" "${LOCAL_MAVEN_PATH}/repository" fi } function build() { ${GRADLEW} clean ${GRADLEW} :publishToMavenLocal } function releaseToGithub() { logInfo "Creating git tag ${version}" set -x git tag "${version}" git push origin "${version}" set +x logInfo "Pushed the tag to origin" } function releaseToAwsS3() { logInfo "Releasing artifacts to aws" for target in "${targets[@]}"; do relative_path="${ORG_PATH}/${target}" set -x aws s3 cp "${LOCAL_MAVEN_PATH}/repository/${relative_path}/${version}" "${AWS_RELEASE_FOLDER}/${relative_path}/${version}/" --recursive set +x done } function release() { logInfo "Releasing version ${version}" if [[ $(isAlreadyReleasedInGit) -ne ${TRUE} && $(isAlreadyReleasedInAws) -ne ${TRUE} ]]; then if [[ $(isProjectGitDirty) -eq ${TRUE} ]]; then logError "Current project has uncommitted changes. Please commit, or stash them" exit 1 fi if [[ $(istMasterBranch) -eq ${FALSE} ]]; then logError "Can only cut the release from master branch." exit 1 fi backupLocalRepo build releaseToGithub releaseToAwsS3 restoreLocalRepo else logError "The version you are trying to release is already released either on git tag, or aws: ${version}" exit 1 fi logInfo "Finished!" } # release echo "${PROJECT_NAME}"
func calculateTotalScore(_ scores: [Int]) -> Int { let sortedScores = scores.sorted(by: >) // Sort the scores in descending order var totalScore = 0 for i in 0..<min(3, sortedScores.count) { // Iterate through the first three scores or all available scores if less than 3 totalScore += sortedScores[i] // Add the score to the total score } return totalScore }
<gh_stars>10-100 """ ## Questions ### 462. [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Example 2: Input: nums = [1,10,2,9] Output: 16 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 """ # Solutions from typing import List class Solution: def minMoves2(self, nums: List[int]) -> int: nums.sort() median = nums[len(nums) // 2] steps = 0 for num in nums: steps += abs(num - median) return steps # Runtime : 72 ms, faster than 70.13% of Python3 online submissions # Memory Usage : 15.5 MB, less than 13.52% of Python3 online submissions
package org.hisp.dhis.reportsheet.exporting; /* * Copyright (c) 2004-2011, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import static org.hisp.dhis.reportsheet.utils.DateUtils.getEndQuaterly; import static org.hisp.dhis.reportsheet.utils.DateUtils.getEndSixMonthly; import static org.hisp.dhis.reportsheet.utils.DateUtils.getFirstDayOfMonth; import static org.hisp.dhis.reportsheet.utils.DateUtils.getFirstDayOfYear; import static org.hisp.dhis.reportsheet.utils.DateUtils.getLastDayOfYear; import static org.hisp.dhis.reportsheet.utils.DateUtils.getStartQuaterly; import static org.hisp.dhis.reportsheet.utils.DateUtils.getStartSixMonthly; import static org.hisp.dhis.reportsheet.utils.DateUtils.getTimeRoll; import static org.hisp.dhis.reportsheet.utils.ExpressionUtils.generateExpression; import static org.hisp.dhis.reportsheet.utils.ExpressionUtils.generateIndicatorExpression; import static org.hisp.dhis.system.util.MathUtils.calculateExpression; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitGroup; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.reportsheet.ExportItem; import org.hisp.dhis.reportsheet.ExportReport; import org.hisp.dhis.reportsheet.utils.ExcelUtils; import com.opensymphony.xwork2.Action; /** * @author <NAME> * @version $Id$ */ public abstract class AbstractGenerateExcelReportSupport extends GenerateExcelReportGeneric implements Action { // ------------------------------------------------------------------------- // Action implementation // ------------------------------------------------------------------------- public String execute() throws Exception { statementManager.initialise(); Period period = PeriodType.createPeriodExternalId( selectionManager.getSelectedPeriodIndex() ); ExportReport exportReport = exportReportService.getExportReport( selectionManager.getSelectedReportId() ); this.installPeriod( period ); executeGenerateOutputFile( exportReport, period ); this.complete(); statementManager.destroy(); return SUCCESS; } // ------------------------------------------------------------------------- // Overriding abstract method(s) // ------------------------------------------------------------------------- /** * The process method which must be implemented by subclasses. * * @param period * @param exportReport * @param organisationUnit */ protected abstract void executeGenerateOutputFile( ExportReport exportReport, Period period ) throws Exception; // ------------------------------------------------------------------------- // Abstract methods // ------------------------------------------------------------------------- protected void installExcelFormat() { // override } protected void installPeriod( Period period ) { Calendar calendar = Calendar.getInstance(); // Monthly period startDate = period.getStartDate(); endDate = period.getEndDate(); // So-far-this-month firstDayOfMonth = getFirstDayOfMonth( startDate ); firstDayOfMonth = getTimeRoll( firstDayOfMonth, Calendar.DATE, -1 ); // Last 3 month period // Last 2 months + this month = last 3 month last3MonthStartDate = getTimeRoll( startDate, Calendar.MONTH, -2 ); last3MonthStartDate = getTimeRoll( last3MonthStartDate, Calendar.DATE, -1 ); last3MonthEndDate = period.getEndDate(); // So far this year period calendar.setTime( endDate ); firstDayOfYear = getFirstDayOfYear( calendar.get( Calendar.YEAR ) ); firstDayOfYear = getTimeRoll( firstDayOfYear, Calendar.DATE, -1 ); endDateOfYear = getLastDayOfYear( calendar.get( Calendar.YEAR ) ); // Last 6 month period // Last 5 months + this month = last 6 month last6MonthStartDate = getTimeRoll( startDate, Calendar.MONTH, -5 ); last6MonthStartDate = getTimeRoll( last6MonthStartDate, Calendar.DATE, -1 ); last6MonthEndDate = period.getEndDate(); // Quarterly startQuaterly = getStartQuaterly( startDate ); startQuaterly = getTimeRoll( startQuaterly, Calendar.DATE, -1 ); endQuaterly = getEndQuaterly( startDate ); // Six monthly startSixMonthly = getStartSixMonthly( startDate ); startSixMonthly = getTimeRoll( startSixMonthly, Calendar.DATE, -1 ); endSixMonthly = getEndSixMonthly( startDate ); } protected void installReadTemplateFile( ExportReport exportReport, Period period, Object object ) throws Exception { Calendar calendar = Calendar.getInstance(); File reportTempDir = reportLocationManager.getExportReportTemporaryDirectory(); this.outputReportFile = new File( reportTempDir, currentUserService.getCurrentUsername() + this.dateformatter.format( calendar.getTime() ) + exportReport.getExcelTemplateFile() ); this.outputStreamExcelTemplate = new FileOutputStream( outputReportFile ); this.createWorkbookInstance( exportReport ); this.initExcelFormat(); this.installDefaultExcelFormat(); if ( exportReport.getOrganisationRow() != null && exportReport.getOrganisationColumn() != null ) { String value = ""; if ( object instanceof OrganisationUnit ) { OrganisationUnit orgunit = (OrganisationUnit) object; value = orgunit.getName(); } else { OrganisationUnitGroup orgunitGroup = (OrganisationUnitGroup) object; value = orgunitGroup.getName(); } ExcelUtils.writeValueByPOI( exportReport.getOrganisationRow(), exportReport.getOrganisationColumn(), value, ExcelUtils.TEXT, templateWorkbook.getSheetAt( 0 ), csText ); } if ( exportReport.getPeriodRow() != null && exportReport.getPeriodColumn() != null ) { ExcelUtils.writeValueByPOI( exportReport.getPeriodRow(), exportReport.getPeriodColumn(), format .formatPeriod( period ), ExcelUtils.TEXT, templateWorkbook.getSheetAt( 0 ), csText ); } } // ------------------------------------------------------------------------- // DataElement Value // ------------------------------------------------------------------------- protected double getDataValue( ExportItem exportItem, OrganisationUnit organisationUnit ) { double value = 0.0; if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.DAILY ) ) { value = calculateExpression( generateExpression( exportItem, startDate, startDate, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SO_FAR_THIS_MONTH ) ) { value = calculateExpression( generateExpression( exportItem, firstDayOfMonth, endDate, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SO_FAR_THIS_QUARTER ) ) { value = calculateExpression( generateExpression( exportItem, startQuaterly, endDate, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SELECTED_MONTH ) ) { value = calculateExpression( generateExpression( exportItem, startDate, endDate, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.LAST_3_MONTH ) ) { value = calculateExpression( generateExpression( exportItem, last3MonthStartDate, last3MonthEndDate, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.LAST_6_MONTH ) ) { value = calculateExpression( generateExpression( exportItem, last6MonthStartDate, last6MonthEndDate, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.QUARTERLY ) ) { value = calculateExpression( generateExpression( exportItem, startQuaterly, endQuaterly, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SIX_MONTH ) ) { value = calculateExpression( generateExpression( exportItem, startSixMonthly, endSixMonthly, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SO_FAR_THIS_YEAR ) ) { value = calculateExpression( generateExpression( exportItem, firstDayOfYear, endDate, organisationUnit, dataElementService, categoryService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.YEARLY ) ) { value = calculateExpression( generateExpression( exportItem, firstDayOfYear, endDateOfYear, organisationUnit, dataElementService, categoryService, aggregationService ) ); } return value; } // ------------------------------------------------------------------------- // Indicator Value // ------------------------------------------------------------------------- protected double getIndicatorValue( ExportItem exportItem, OrganisationUnit organisationUnit ) { double value = 0.0; if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.DAILY ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, startDate, startDate, organisationUnit, indicatorService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SELECTED_MONTH ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, startDate, endDate, organisationUnit, indicatorService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.LAST_3_MONTH ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, last3MonthStartDate, last3MonthEndDate, organisationUnit, indicatorService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SO_FAR_THIS_YEAR ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, firstDayOfYear, endDate, organisationUnit, indicatorService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.LAST_6_MONTH ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, last6MonthStartDate, last6MonthEndDate, organisationUnit, indicatorService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.YEARLY ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, firstDayOfYear, endDateOfYear, organisationUnit, indicatorService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.QUARTERLY ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, startQuaterly, endQuaterly, organisationUnit, indicatorService, aggregationService ) ); } else if ( exportItem.getPeriodType().equalsIgnoreCase( ExportItem.PERIODTYPE.SIX_MONTH ) ) { value = calculateExpression( generateIndicatorExpression( exportItem, startSixMonthly, endSixMonthly, organisationUnit, indicatorService, aggregationService ) ); } return value; } // ------------------------------------------------------------------------- // Formulae methods // ------------------------------------------------------------------------- protected void recalculatingFormula( Sheet sheet ) { for ( Row row : sheet ) { for ( Cell cell : row ) { if ( (cell != null) && (cell.getCellType() == Cell.CELL_TYPE_FORMULA) ) { this.evaluatorFormula.evaluateFormulaCell( cell ); } } } } protected void complete() throws IOException { this.templateWorkbook.write( outputStreamExcelTemplate ); this.outputStreamExcelTemplate.close(); selectionManager.setDownloadFilePath( outputReportFile.getPath() ); } }
#!/usr/bin/env bash # https://github.com/codecov/example-go#caveat-multiple-files echo "" > coverage.txt for d in $(go list ./... | grep -v vendor | grep -v dummy); do go test -race -coverprofile=profile.out -covermode=atomic $d if [ -f profile.out ]; then cat profile.out >> coverage.txt rm profile.out fi done
#!/bin/bash #SBATCH -p debug #SBATCH -N 12 #SBATCH -t 00:30:00 #SBATCH -e mysparkjob_%j.err #SBATCH -o mysparkjob_%j.out #SBATCH -C haswell #module load collectl #start-collectl.sh module load spark/2.1.0 start-all.sh sleep 15 # 6177583 by 8096 => 400 GB dataset # need about 3x times memory to store, relyout the matrix to do the GEMM needed in the alchemist SVD vs just store the matrix k=200 fname=/global/cscratch1/sd/gittens/large-datasets/smallOcean.parquet useAlc=0 spark-submit --verbose\ --driver-memory 120G\ --executor-memory 120G\ --executor-cores 32 \ --driver-cores 32 \ --num-executors 11 \ --conf spark.driver.extraLibraryPath=$SCRATCH/alchemistSHELL/alchemist/lib\ --conf spark.executor.extraLibraryPath=$SCRATCH/alchemistSHELL/alchemist/lib\ --conf spark.eventLog.enabled=true\ --conf spark.eventLog.dir=$SCRATCH/spark/event_logs\ --class org.apache.spark.mllib.linalg.distributed.ClimateSVD\ test/target/scala-2.11/alchemist-tests-assembly-0.0.2.jar $k $fname $useAlc 2>&1 | tee test.log stop-all.sh exit #stop-collectl.sh
import { CommonDTO } from "@common/dto"; import { IConfig, ITask } from "@common/types"; import { ConfigForm } from "../Config/Config.data"; /* A class that represents a task. */ export class TaskForm extends CommonDTO implements ITask { id: string; updatedAt: number; title: string = ""; progress: number = 0; webpage_url: string = ""; thumbnail: string = "https://dummyimage.com/200x120/333333/FFF&text=No-Image"; duration: number = 0; filesize: number = 0; extractor: string = ""; speed: string = ""; eta: string = ""; pending = false; config: IConfig = new ConfigForm(); }
<filename>src/components/Pagination.js<gh_stars>0 import React, { useEffect } from "react" import styled from "styled-components" import { ChevronLeft, ChevronRight } from "react-feather" import { useSearch } from "../context/context" const PaginationWrapper = styled.div` height: 30px; line-height: 30px; vertical-align: baseline; font-size: 2rem; ` const Pagination = props => { const state = useSearch() const clickHandler = async page => { if (page === "minus" && state.pageNumber > 1) { await state.setPageNumber(state.pageNumber - 1) } else if (page === "plus" && state.pageNumber < state.totalPageNumber) { await state.setPageNumber(state.pageNumber + 1) } } useEffect(() => { const run = async () => { const raw = await fetch( `https://api.unsplash.com/search/photos?page=${state.pageNumber};` + "client_id=65f622264cdd351d875fb557cdefbee529978cbe2e748d6df31ef0d1636d1971&" + "query=" + encodeURIComponent(state.searchTerm) ) const response = await raw.json() state.setTotalPageNumber(response.total_pages) await props.getImages(response) } run() }, [state.pageNumber]) return ( <PaginationWrapper> <ChevronLeft onClick={() => clickHandler("minus")} />{" "} {state.pageNumber + "/" + state.totalPageNumber} <ChevronRight onClick={() => clickHandler("plus")} /> </PaginationWrapper> ) } export default Pagination
<reponame>sk1pp3rFTW/CoffeeBot const { APIWrapper } = require('../') const { google } = require('googleapis') module.exports = class YoutubeAPI extends APIWrapper { constructor () { super() this.name = 'youtube' this.envVars = ['YOUTUBE_API_KEY'] } load () { this.Youtube = google.youtube({ version: 'v3', auth: process.env.YOUTUBE_API_KEY }) return this } getVideos (ids, part = 'snippet,statistics') { return this.Youtube.videos.list({ id: ids.join(), part }).then(r => r && r.data.items) } getVideo (id, part = 'snippet,statistics') { return this.getVideos([ id ], part).then(r => r && r[0]) } getChannels (ids, part = 'snippet,statistics') { return this.Youtube.channels.list({ id: ids.join(), part }).then(r => r && r.data.items) } getChannel (id, part = 'snippet,statistics') { return this.getChannels([ id ], part).then(r => r && r[0]) } getPlaylist (id, part = 'snippet') { return this.Youtube.playlists.list({ id, part }).then(r => r && r.data.items[0]) } getBestThumbnail (thumbnails) { if (!thumbnails) return {} const { high, maxres, medium, standard } = thumbnails return maxres || high || medium || standard || thumbnails['default'] } searchVideos (query, part = 'snippet', maxResults = 5) { return this.search(query, ['video'], part, 'relevance', maxResults) } search (query, type = ['video', 'channel', 'playlist'], part = 'snippet', order = 'relevance', maxResults = 5) { return this.Youtube.search.list({ q: query, type: type.join(), part, order, maxResults }).then(r => r.data) } }
import { Component, OnInit } from '@angular/core'; import { Note } from '../interfaces/note'; import { ActivatedRoute } from '@angular/router'; import { NotesService } from '../services/notes.service'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-detail', templateUrl: './detail.page.html', styleUrls: ['./detail.page.scss'], }) export class DetailPage implements OnInit { private note: Note; constructor( private route: ActivatedRoute, private notesService: NotesService, private navCtrl: NavController ) { // Initialize a placeholder note until the actual note can be loaded in this.note = { id: '', title: '', content: '' }; } ngOnInit() { // Get the id of the note from the URL const noteId = this.route.snapshot.paramMap.get('id'); // Check that the data is loaded before getting the note // handles the case when the detail page is loaded directly via the URL if (this.notesService.loaded) { this.note = this.notesService.getNote(noteId); } else { this.notesService.load().then(() => { this.note = this.notesService.getNote(noteId); }); } } noteChanged() { this.notesService.save(); } deleteNote() { this.notesService.deleteNote(this.note); this.navCtrl.navigateBack('/notes'); } }
#!/bin/bash source "$(dirname "${BASH_SOURCE}")/../../hack/lib/init.sh" trap os::test::junit::reconcile_output EXIT os::test::junit::declare_suite_start "cmd/delete" # No clusters notice os::cmd::try_until_text "_output/oshinko get" "There are no clusters in any projects. You can create a cluster with the 'create' command." # Create clusters so we can look at them os::cmd::expect_success "_output/oshinko create abc --workers=2" # name required os::cmd::expect_failure "_output/oshinko delete" # delete happens os::cmd::expect_success "_output/oshinko create bob" os::cmd::expect_success "_output/oshinko delete bob" os::cmd::expect_failure "_output/oshinko get bob" # ephemeral flags invalid os::cmd::expect_failure_and_text "_output/oshinko delete bob --app=sam-1" "unknown flag" os::cmd::expect_failure_and_text "_output/oshinko delete bob --app-status=completed" "unknown flag" os::test::junit::declare_suite_end
import { ISquareupMoney } from './i-squareup-money'; import { ISquareupOrder } from './i-squareup-order'; export class ISquareupCreateOrderRequest { idempotency_key: string; // A value you specify that uniquely identifies this order among orders you've created. // If you're unsure whether a particular order was created successfully, you can reattempt it with the same idempotency key without worrying about creating duplicate orders. // See Idempotency keys for more information. order: ISquareupOrder; // The order to be created. } export class ISquareupCreateOrderRequestLineItem { name: string; // The name of the line item. This value cannot exceed 500 characters. quantity: string; // The quantity to purchase, as a string representation of a number. Currently, only integer values are supported. base_price_money: ISquareupMoney; // The base price for a single unit of the line item's associated variation. If a line item represents a Custom Amount instead of a particular product, this field indicates that amount. } export class ISquareupCreateOrderRequestOrder { reference_id: string; // An optional ID you can associate with the order for your own purposes (such as to associate the order with an entity ID in your own database). // This value cannot exceed 40 characters. line_items: ISquareupCreateOrderRequestLineItem[]; // The line items to associate with this order. // Each line item represents a different product (or a custom monetary amount) to include in a purchase. }
#!/bin/bash function check_mysql_db(){ DB_NAME=$1 DB_USER=$2 DB_PASSWORD=$3 MYSQL_CONTAINER_NAME=$(getNeedValue $4 "mysql") RES=$(docker exec -i ${MYSQL_CONTAINER_NAME} mysql -u${DB_USER} -p${DB_PASSWORD} ${DB_NAME} -e "SHOW DATABASES LIKE '${DB_NAME}';") if [ -n "${RES}" ]; then echo "Y" else echo "N" fi } function check_mysql_empty_db(){ DB_NAME=$1 DB_USER=$2 DB_PASSWORD=$3 MYSQL_CONTAINER_NAME=$(getNeedValue "$4" "mysql") RES=$(docker exec -i ${MYSQL_CONTAINER_NAME} mysql -u${DB_USER} -p${DB_PASSWORD} ${DB_NAME} -e "use '${DB_NAME}'; show tables like 'b_user';") if [ -n "${RES}" ]; then echo "Y" else echo "N" fi } function getNeedValue(){ CHECK_VALUE=$1 DEFAULT_VALUE=$2 if [[ -n "$CHECK_VALUE" ]]; then echo $CHECK_VALUE else echo $DEFAULT_VALUE fi }
<reponame>PinoEire/archi /** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.ui.factory.elements; import org.eclipse.draw2d.geometry.Dimension; import com.archimatetool.editor.preferences.IPreferenceConstants; import com.archimatetool.editor.preferences.Preferences; import com.archimatetool.editor.ui.factory.AbstractGraphicalObjectUIProvider; import com.archimatetool.editor.ui.factory.IArchimateElementUIProvider; /** * Abstract Archimate Element UI Provider * * @author <NAME> */ public abstract class AbstractArchimateElementUIProvider extends AbstractGraphicalObjectUIProvider implements IArchimateElementUIProvider { protected AbstractArchimateElementUIProvider() { } @Override public Dimension getDefaultSize() { return DefaultRectangularSize; } @Override public Dimension getUserDefaultSize() { int width = Preferences.STORE.getInt(IPreferenceConstants.DEFAULT_ARCHIMATE_FIGURE_WIDTH); int height = Preferences.STORE.getInt(IPreferenceConstants.DEFAULT_ARCHIMATE_FIGURE_HEIGHT); return new Dimension(width, height); } @Override public boolean hasAlternateFigure() { return false; } @Override public int getDefaultTextAlignment() { return Preferences.STORE.getInt(IPreferenceConstants.DEFAULT_ARCHIMATE_FIGURE_TEXT_ALIGNMENT); } @Override public int getDefaultTextPosition() { return Preferences.STORE.getInt(IPreferenceConstants.DEFAULT_ARCHIMATE_FIGURE_TEXT_POSITION); } }
package com.piglin.optimization; public class Knapsack { /** * Knapsack Problem * <p/> * Greedy algorithm * <p/> * Continuous knapsack problem * * @param values values of items * @param weights weights of items * @param capacity knapsack capacity */ public static void knapsackProblem(int[] values, int[] weights, int capacity) { int distinctItems = values.length; /* Initialize knapsack */ int[] selected = new int[distinctItems]; for (int i = 0; i < distinctItems; i++) { selected[i] = 0; } int weight=0; int index = 0; while (weight <= capacity && index < distinctItems) { if (weight + weights[index] <= capacity) { /* Maximize value */ selected[index] = 1; weight = weight + weights[index]; } index++; } System.out.println("\nSolution:\n"); for (int i = 0; i < selected.length; i++) { System.out.print(selected[i] + "\t"); } System.out.println(); /*for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) { System.out.print(m[i][j] + "\t"); } System.out.println(); }*/ } }
<reponame>jmay/treet # encoding: UTF-8 class Treet::Repo attr_reader :root def initialize(path, opts = {}) raise Errno::ENOENT, "Missing or invalid source path #{path}" unless File.directory?(path) @root = path end def to_hash expand(root) end def compare(target) Treet::Hash.diff(to_hash, target.to_hash) end # patch keys can look like # name.first # emails[] # (address[1] syntax has been eliminated, we recognize array elements by matching the entire content) def self.filefor(keyname) if keyname =~ /\[/ keyname = keyname.match(/^(.*)\[\]$/).captures.first [keyname, '', nil] elsif keyname =~ /\./ # subelement # negative lookbehind; don't split on a dot at beginning of string filename,field = keyname.split(/(?<!^)\./) ['.', filename, field] else ['.', keyname] end end # Patching a repo is not the same as patching a hash. Make the changes # directly to the data files. def patch(diffs) @hash = nil # invalidate any cached image Dir.chdir(root) do diffs.each do |diff| flag, key, v1, _ = diff # if key =~ /\[/ # keyname = key.match(/^(.*)\[\]$/).captures # elsif key =~ /\./ # keyname, subkey = key.match(/^(.*)\.(.*)$/).captures # else # keyname = key # end dirname, filename, fieldname = Treet::Repo.filefor(key) filepath = "#{dirname}/#{filename}" case flag when '~' # change a value in place # load the current data & overwrite with the new value # idempotent: this will overwrite the file with the same contents if fieldname # hash entry data = File.exists?(filepath) ? JSON.load(File.open(filepath)) : {} data[fieldname] = v1 File.open(filepath, "w") {|f| f << JSON.pretty_generate(data)} else # string entry File.open(filepath, "w") {|f| f << v1} end when '+' # add something if fieldname # writing a value into a hash # idempotent: this will overwrite the file with the same contents data = File.exists?(filepath) ? JSON.load(File.open(filepath)) : {} data[fieldname] = v1 Dir.mkdir(dirname) unless Dir.exists?(dirname) File.open(filepath, "w") {|f| f << JSON.pretty_generate(data)} else # writing an entire hash into an array entry # idempotent: this will overwrite the file with the same contents subfile = "#{dirname}/#{Treet::Hash.digestify(v1)}" Dir.mkdir(dirname) unless Dir.exists?(dirname) case v1 when Hash # hash entry File.open(subfile, "w") {|f| f << JSON.pretty_generate(v1)} else # string entry - create empty file with this name FileUtils.touch(subfile) end end when '-' # remove something if fieldname # this is a key in a subhash if File.exists?(filepath) # if the subhash is missing, there's nothing to remove, so do nothing (for idempotence) data = JSON.load(File.open(filepath)) data.delete(fieldname) if data.empty? # all keys have been removed, clean up the file File.delete(filename) else File.open(filepath, "w") {|f| f << JSON.pretty_generate(data)} end end elsif dirname == "." # this is a top-level string File.delete(filename) if File.exists?(filename) # need the existence check for idempotence else # this is an array, we look for a match on the entire contents via digest subfile = "#{dirname}/#{Treet::Hash.digestify(v1)}" File.delete(subfile) if File.exists?(subfile) # need the existence check for idempotence # TODO: if dirname is now empty, should it be removed? is that worthwhile? end end end end to_hash # ?? return the patched data? or no return value? true/false for success? end private def expand_json(path) if File.file?(path) if File.zero?(path) # empty files are just keys or string elements in an array File.basename(path) else # if file contents is JSON, then parse it # otherwise treat it as a raw string value s = File.read(path) JSON.load(s) rescue s end else # should be a subdirectory containing files named with numbers, each containing JSON files = Dir.entries(path).select {|f| f !~ /^\./} files.sort_by(&:to_i).each_with_object([]) do |f, ary| ary << expand_json("#{path}/#{f}") end end end def expand(path) raw = filenames(path).each_with_object({}) {|f,h| h[f] = expand_json("#{path}/#{f}")} Treet::Hash.new(raw) end def filenames(path) Dir.entries(path).select {|f| f !~ /^\./} end end
#!/bin/bash dm-tool add-nested-seat --screen 1920x1080
<gh_stars>1-10 'use strict'; const { COLOR } = require('@data/config'); const { Command, SimplicityEmbed, CommandError } = require('@structures'); const { Constants, PermissionUtil, Util } = require('@util'); const { SPOTIFY_LOGO_PNG_URL, PERMISSIONS, ADMINISTRATOR_PERMISSION, NORMAL_PERMISSIONS } = Constants; const { dest, isEmpty } = Util; const moment = require('moment'); class UserInfo extends Command { constructor(client) { super(client, 'userinfo', { aliases: ['ui', 'user', 'userinformation', 'infouser', 'informationuser'], args: [ { acceptBot: true, acceptSelf: true, fetchGlobal: true, missingError: 'errors:invalidUser', required: false, type: 'user', }, ], category: 'util', flags: [ { aliases: ['music', 'song', 's', 'm'], name: 'spotify', type: 'booleanFlag', }, { aliases: ['r', 'role'], name: 'roles', type: 'booleanFlag', }, ], requirements: { clientPermissions: ['EMBED_LINKS'] }, }); } run({ author, channel, flags, guild, language, t, emoji }, user = author) { moment.locale(language); if (flags.spotify) { if (user.isPartial) { throw new CommandError('commands:userinfo.partial'); } else if (!this.isListeningToSpotify(user.presence)) { throw new CommandError('commands:userinfo.notListeningToSpotify'); } return channel.send(this.spotifyEmbed(author, user, t)); } else if (flags.roles) { const member = guild.member(user); if (!member) { throw new CommandError('commands:userinfo.notInGuild'); } return channel.send(this.rolesEmbed(member.roles.cache.filter((r) => r.id !== guild.id), user, author, t)); } else { const content = user.isPartial ? t('commands:userinfo.cannotPartial') : ''; return channel.send(content, this.userInfoEmbed(user, author, t, emoji, guild)); } } isListeningToSpotify(presence) { const activities = dest(presence, 'activites'); return !isEmpty(activities) && activities.some( (a) => a.type === 'LISTENING' && dest(a.party, 'id') && dest(a.party, 'id').includes('spotify:'), ); } spotifyEmbed(author, user, t) { const presence = user.presence; const activities = dest(presence, 'activities'); const activity = !isEmpty(activities) && activities.filter( (a) => a.type === 'LISTENING' && dest(a.party, 'id') && dest(a.party, 'id').includes('spotify:'), ); if (!activity) throw new CommandError('commands:userinfo.notListeningToSpotify'); const trackName = activity.details; const artist = activity.state.split(';').join(','); const album = activity.assets && activity.assets.largeText; const largeImage = activity.assets && activity.assets.largeImage; const image = largeImage && `https://i.scdn.co/image/${largeImage.replace('spotify:', '')}`; const embed = new SimplicityEmbed({ author, t }) .setAuthor('$$commands:userinfo.spotify', SPOTIFY_LOGO_PNG_URL) .addField('» $$commands:userinfo.track', trackName, true) .addField('» $$commands:userinfo.artist', artist, true) .addField('» $$commands:userinfo.album', album) .setColor('GREEN'); if (image) embed.setThumbnail(image); return embed; } rolesEmbed(roles, user, author, t) { const role = roles && roles.find((r) => r.color); return new SimplicityEmbed({ author, t }) .setAuthor( '» $$commands:userinfo.authorRoles', user.displayAvatarURL({ dynamic: true }), '', { user: user.username }, ) .setDescription(roles.map((r) => r).sort((a, b) => b.position - a.position).join('\n')) .setColor(role ? role.hexColor : COLOR); } getTitles(user, client, guild) { const titles = [user.tag]; if (PermissionUtil.verifyDev(user.id, client)) titles.push('#developer'); if (guild && guild.ownerID === user.id) titles.push('#crown'); if (user.bot) titles.push('#bot'); return titles; } getClientStatus(presence) { const status = presence.clientStatus && Object.keys(presence.clientStatus); if (status && status.length) return status.map((x) => `#${x}`); else return []; } getJoinPosition(id, guild) { if (!guild.member(id)) return; const array = guild.members.cache.array(); array.sort((a, b) => a.joinedAt - b.joinedAt); const result = array.map((m, i) => ({ id: m.user.id, index: i })).find((m) => m.id === id); return (result && result.index) || null; } // eslint-disable-next-line complexity userInfoEmbed(user, author, t, emoji, guild) { const { id, tag } = user; const member = guild.member(user); const presence = !user.isPartial && user.presence; const custom = this.getTitles(user, user.client, guild); const status = (presence && this.getClientStatus(presence)) || []; const titles = [...custom, ...status].join(' '); const highestRole = member && member.roles.highest.id !== guild.id && member.roles.highest; const activities = dest(presence, 'activities'); const activity = !isEmpty(activities) && activities.map((a) => a.name); const activityType = activity && activity.type && activity.name; const joinPosition = this.getJoinPosition(user.id, guild); const created = moment(user.createdAt); const joined = member && moment(member.joinedAt); const rolesClean = member && member.roles.cache .filter((r) => r.id !== guild.id) .map((r) => r.name || `${r}`); const embed = new SimplicityEmbed({ author, emoji, t }, { autoAuthor: false }) .setAuthor(titles, user.displayAvatarURL({ dynamic: true })) .setThumbnail(user) .addField('» $$commands:userinfo.username', tag, true); if (member && member.nickname) embed.addField('» $$commands:userinfo.nickname', member.nickname, true); embed.addField('» $$commands:userinfo.id', id, true); if (presence) { const userStatus = `#${presence.status} $$common:status.${presence.status}`; embed.addField('» $$commands:userinfo.status', userStatus, true); } if (member && highestRole && member.roles.cache.length > 5) { const roleString = highestRole.name || `${highestRole}`; embed.addField('» $$commands:userinfo.highestRole', roleString, true); } if (activityType) embed.addField(`» $$common:activityType.${activity.type}`, activity.name, true); if (rolesClean && rolesClean.length && rolesClean.length <= 5) { embed.addField('» $$commands:userinfo.roles', rolesClean.join(', '), true); } if (joinPosition) embed.addField('» $$commands:userinfo.joinPosition', joinPosition, true); embed.addField('» $$commands:userinfo.createdAt', `${created.format('LL')} (${created.fromNow()})`); if (joined) embed.addField('» $$commands:userinfo.joinedAt', `${joined.format('LL')} (${joined.fromNow()})`); const memberPermissions = member && member.permissions && member.permissions.toArray().filter((p) => !NORMAL_PERMISSIONS.includes(p)); let resultAdministrator, resultAllPermissions, resultPermissions; if (memberPermissions) { resultAdministrator = memberPermissions.includes(ADMINISTRATOR_PERMISSION) && t(`permissions:${ADMINISTRATOR_PERMISSION}`); resultAllPermissions = memberPermissions.sort((a, b) => PERMISSIONS.indexOf(a) - PERMISSIONS.indexOf(b)); resultPermissions = resultAdministrator || (resultAllPermissions && resultAllPermissions.map((p) => t(`permissions:${p}`)).join(', ')); } if (resultPermissions) embed.addField('» $$commands:userinfo.permissions', resultPermissions); return embed; } } module.exports = UserInfo;
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin docker push aikaka/web-fifa docker push aikaka/web-fifa:0.1.0
#!/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. if [ -z $REPORT_DIR ]; then REPORT_DIR="./" fi test_case=pegasus_rproxy_test GTEST_OUTPUT="xml:$REPORT_DIR/$test_case.xml" ./$test_case