text
stringlengths
1
1.05M
package org.lognet.springboot.grpc.boot; import org.lognet.springboot.grpc.demo.CalculateService; import org.lognet.springboot.grpc.demo.GreeterService; import org.lognet.springboot.grpc.demo.InvoiceService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Boot { @Bean public GreeterService getGreetingService() { System.out.println("greeting service created"); return new GreeterService(); } @Bean public CalculateService getCalculateService() { System.out.println("Calculate Service created"); return new CalculateService(); } @Bean public InvoiceService getInvoiceService() { System.out.println("Invoice Service created"); return new InvoiceService(); } public static void main(String args []){ System.out.println("Server is starting"); SpringApplication.run(Boot.class,args); System.out.println("Server started ..."); } }
<gh_stars>0 /* * Copyright 2008-2013 NVIDIA Corporation * Modifications Copyright© 2019 Advanced Micro Devices, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrust/device_malloc_allocator.h> #include <thrust/device_vector.h> #include <thrust/host_vector.h> #include <thrust/iterator/retag.h> #include <thrust/system/hip/config.h> #include <thrust/uninitialized_fill.h> #include "test_header.hpp" TESTS_DEFINE(UninitializedFillTests, FullTestsParams); template <typename ForwardIterator, typename T> void uninitialized_fill(my_system& system, ForwardIterator, ForwardIterator, const T&) { system.validate_dispatch(); } TEST(UninitializedFillTests, TestUninitializedFillDispatchExplicit) { thrust::device_vector<int> vec(1); my_system sys(0); thrust::uninitialized_fill(sys, vec.begin(), vec.begin(), 0); ASSERT_EQ(true, sys.is_valid()); } template <typename ForwardIterator, typename T> void uninitialized_fill(my_tag, ForwardIterator first, ForwardIterator, const T&) { *first = 13; } TEST(UninitializedFillTests, TestUninitializedFillDispatchImplicit) { thrust::device_vector<int> vec(1); thrust::uninitialized_fill( thrust::retag<my_tag>(vec.begin()), thrust::retag<my_tag>(vec.begin()), 0); ASSERT_EQ(13, vec.front()); } template <typename ForwardIterator, typename Size, typename T> ForwardIterator uninitialized_fill_n(my_system& system, ForwardIterator first, Size, const T&) { system.validate_dispatch(); return first; } TEST(UninitializedFillTests, TestUninitializedFillNDispatchExplicit) { thrust::device_vector<int> vec(1); my_system sys(0); thrust::uninitialized_fill_n(sys, vec.begin(), vec.size(), 0); ASSERT_EQ(true, sys.is_valid()); } template <typename ForwardIterator, typename Size, typename T> ForwardIterator uninitialized_fill_n(my_tag, ForwardIterator first, Size, const T&) { *first = 13; return first; } TEST(UninitializedFillTests, TestUninitializedFillNDispatchImplicit) { thrust::device_vector<int> vec(1); my_system sys(0); thrust::uninitialized_fill_n(sys, vec.begin(), vec.size(), 0); ASSERT_EQ(true, sys.is_valid()); } TYPED_TEST(UninitializedFillTests, TestUninitializedFillPOD) { using Vector = typename TestFixture::input_type; using T = typename Vector::value_type; Vector v(5); v[0] = T(0); v[1] = T(1); v[2] = T(2); v[3] = T(3); v[4] = T(4); T exemplar(7); thrust::uninitialized_fill(v.begin() + 1, v.begin() + 4, exemplar); ASSERT_EQ(v[0], T(0)); ASSERT_EQ(v[1], exemplar); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], exemplar); ASSERT_EQ(v[4], T(4)); exemplar = T(8); thrust::uninitialized_fill(v.begin() + 0, v.begin() + 3, exemplar); ASSERT_EQ(v[0], exemplar); ASSERT_EQ(v[1], exemplar); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], T(7)); ASSERT_EQ(v[4], T(4)); exemplar = T(9); thrust::uninitialized_fill(v.begin() + 2, v.end(), exemplar); ASSERT_EQ(v[0], T(8)); ASSERT_EQ(v[1], T(8)); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], exemplar); ASSERT_EQ(v[4], T(9)); exemplar = T(1); thrust::uninitialized_fill(v.begin(), v.end(), exemplar); ASSERT_EQ(v[0], exemplar); ASSERT_EQ(v[1], exemplar); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], exemplar); ASSERT_EQ(v[4], exemplar); } struct CopyConstructTest { CopyConstructTest(void) : copy_constructed_on_host(false) , copy_constructed_on_device(false) { } __host__ __device__ CopyConstructTest(const CopyConstructTest&) { #if defined(THRUST_HIP_DEVICE_CODE) copy_constructed_on_device = true; copy_constructed_on_host = false; #else copy_constructed_on_device = false; copy_constructed_on_host = true; #endif } __host__ __device__ CopyConstructTest& operator=(const CopyConstructTest& x) { copy_constructed_on_host = x.copy_constructed_on_host; copy_constructed_on_device = x.copy_constructed_on_device; return *this; } bool copy_constructed_on_host; bool copy_constructed_on_device; }; TEST(UninitializedFillTests, TestUninitializedFillNonPOD) { using T = CopyConstructTest; thrust::device_ptr<T> v = thrust::device_malloc<T>(5); T exemplar; ASSERT_EQ(false, exemplar.copy_constructed_on_device); ASSERT_EQ(false, exemplar.copy_constructed_on_host); T host_copy_of_exemplar(exemplar); ASSERT_EQ(false, host_copy_of_exemplar.copy_constructed_on_device); ASSERT_EQ(true, host_copy_of_exemplar.copy_constructed_on_host); // copy construct v from the exemplar thrust::uninitialized_fill(v, v + 1, exemplar); T x; ASSERT_EQ(false, x.copy_constructed_on_device); ASSERT_EQ(false, x.copy_constructed_on_host); x = v[0]; ASSERT_EQ(true, x.copy_constructed_on_device); ASSERT_EQ(false, x.copy_constructed_on_host); thrust::device_free(v); } TYPED_TEST(UninitializedFillTests, TestUninitializedFillNPOD) { using Vector = typename TestFixture::input_type; using T = typename Vector::value_type; Vector v(5); v[0] = T(0); v[1] = T(1); v[2] = T(2); v[3] = T(3); v[4] = T(4); T exemplar(7); using Iterator = typename Vector::iterator; Iterator iter = thrust::uninitialized_fill_n(v.begin() + 1, size_t(3), exemplar); ASSERT_EQ(v[0], T(0)); ASSERT_EQ(v[1], exemplar); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], exemplar); ASSERT_EQ(v[4], T(4)); ASSERT_EQ(v.begin() + 4, iter); exemplar = T(8); iter = thrust::uninitialized_fill_n(v.begin() + 0, size_t(3), exemplar); ASSERT_EQ(v[0], exemplar); ASSERT_EQ(v[1], exemplar); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], T(7)); ASSERT_EQ(v[4], T(4)); ASSERT_EQ(v.begin() + 3, iter); exemplar = T(9); iter = thrust::uninitialized_fill_n(v.begin() + 2, size_t(3), exemplar); ASSERT_EQ(v[0], T(8)); ASSERT_EQ(v[1], T(8)); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], exemplar); ASSERT_EQ(v[4], T(9)); ASSERT_EQ(v.end(), iter); exemplar = T(1); iter = thrust::uninitialized_fill_n(v.begin(), v.size(), exemplar); ASSERT_EQ(v[0], exemplar); ASSERT_EQ(v[1], exemplar); ASSERT_EQ(v[2], exemplar); ASSERT_EQ(v[3], exemplar); ASSERT_EQ(v[4], exemplar); ASSERT_EQ(v.end(), iter); } TEST(UninitializedFillTests, TestUninitializedFillNNonPOD) { using T = CopyConstructTest; thrust::device_ptr<T> v = thrust::device_malloc<T>(5); T exemplar; ASSERT_EQ(false, exemplar.copy_constructed_on_device); ASSERT_EQ(false, exemplar.copy_constructed_on_host); T host_copy_of_exemplar(exemplar); ASSERT_EQ(false, host_copy_of_exemplar.copy_constructed_on_device); ASSERT_EQ(true, host_copy_of_exemplar.copy_constructed_on_host); // copy construct v from the exemplar thrust::uninitialized_fill_n(v, size_t(1), exemplar); T x; ASSERT_EQ(false, x.copy_constructed_on_device); ASSERT_EQ(false, x.copy_constructed_on_host); x = v[0]; ASSERT_EQ(true, x.copy_constructed_on_device); ASSERT_EQ(false, x.copy_constructed_on_host); thrust::device_free(v); }
export LSCOLORS="exfxcxdxbxegedabagacad" export CLICOLOR=true fpath=($ZSH/functions $fpath) autoload -U $ZSH/functions/*(:t) HISTFILE=~/.zsh_history HISTSIZE=10000 SAVEHIST=10000 setopt NO_BG_NICE # don't nice background tasks setopt NO_HUP setopt NO_LIST_BEEP setopt LOCAL_OPTIONS # allow functions to have local options setopt LOCAL_TRAPS # allow functions to have local traps setopt HIST_VERIFY setopt SHARE_HISTORY # share history between sessions ??? setopt EXTENDED_HISTORY # add timestamps to history setopt PROMPT_SUBST setopt CORRECT setopt COMPLETE_IN_WORD setopt IGNORE_EOF setopt APPEND_HISTORY # adds history setopt INC_APPEND_HISTORY SHARE_HISTORY # adds history incrementally and share it across sessions setopt HIST_IGNORE_ALL_DUPS # don't record dupes in history setopt HIST_REDUCE_BLANKS setopt auto_cd # don't expand aliases _before_ completion has finished # like: git comm-[tab] # setopt complete_aliases bindkey '^[^[[D' backward-word bindkey '^[^[[C' forward-word bindkey '^[[5D' beginning-of-line bindkey '^[[5C' end-of-line bindkey '^[[3~' delete-char bindkey '^?' backward-delete-char
#!/bin/bash # Get week number alias week='date +%V'
import { connect } from 'react-redux' import { displayToConsole } from '../actions/console.js' import { get } from '../util/content.js' import View from '../views/fish.js' const mapStateToProps = (state) => { return {} } const mapDispatchToProps = (dispatch) => { return { click: (fish) => { dispatch(displayToConsole(get('FISH_MESSAGE', fish))) } } } export default connect( mapStateToProps, mapDispatchToProps )(View)
<gh_stars>0 #!/usr/bin/python3 import functools # https://leetcode.com/articles/distribute-candies/ def kindsOfCandie(candies): rng = 5 xs = [0] * (rng * 2 + 1) for c in candies: xs[c+rng] += 1 # count number of non-zero elements unique = functools.reduce(lambda acc,e: acc + (0 if e == 0 else 1), xs, 0) print(xs) print(f'unique kinds {unique}') assert len(candies) == sum(xs) return min(len(candies)//2, unique) def distribute(initial, people): remaining = initial xs = [0] * people n = 1 while remaining > 0: x = min(n, remaining) xs[(n-1) % len(xs)] += x remaining -= x n = n + 1 assert sum(xs) == initial return xs # given a set of student ratings allocate candies such that # - each student has at least 1 # - a student has more than his immediate neighbours if his score is higher # xs[i] is candies for student i def soln(ratings): n = len(ratings) xs = [1] * n for i in range(1,n): print(f'r {i} {ratings[i]}') if ratings[i] > ratings[i-1] and xs[i] <= xs[i-1]: xs[i] = xs[i-1] + 1 elif ratings[i] == ratings[i-1] and xs[i] < xs[i-1]: xs[i] = xs[i-1] for i in range(n-2,-1,-1): print(f'l {i} {ratings[i]}') if ratings[i] > ratings[i+1] and xs[i] <= xs[i+1]: xs[i] = xs[i+1] + 1 elif ratings[i] == ratings[i+1] and xs[i] < xs[i+1]: xs[i] = xs[i+1] print(xs) return sum(xs) # ratings = [3,3,2,1,2,3,3] # print(soln([2,2,2,2])) # print(soln([2,2,4,6,8,8])) # print(soln([9,9,7,5,3,3])) # print(soln(ratings)) # print(distribute(1000,10)) n = kindsOfCandie([-5,5,5,-5]) assert n == 2 n = kindsOfCandie([1,1,2,2,3,3]) assert n == 3 n = kindsOfCandie([1,1,2,3]) assert n == 2 n = kindsOfCandie(range(-5,5)) assert n == 5 # a list comprehension is a generator -> filter -> map [x * x for x in range(10) if x % 2 == 0]
<reponame>tombartkowski/phonestreamer-server import defaultMapper from '../../core/mapper.default'; import { Mapper } from '../../core/mapper'; import { App } from './app'; import AppModel from './appModel'; const appMapper = (): Mapper<App> => defaultMapper(App.create, AppModel); export default appMapper;
#!/usr/bin/bash if [ ! -f "src/py/spaas.py" ]; then echo "Please run from the project directory!" exit 1 fi python3 src/py/spaas.py
#!/bin/bash stage=0 train_stage=-100 # This trains only unadapted (just cepstral mean normalized) features, # and uses various combinations of VTLN warping factor and time-warping # factor to artificially expand the amount of data. . cmd.sh . utils/parse_options.sh # to parse the --stage option, if given [ $# != 0 ] && echo "Usage: local/run_4b.sh [--stage <stage> --train-stage <train-stage>]" && exit 1; set -e if [ $stage -le 0 ]; then # Create the training data. featdir=`pwd`/mfcc/nnet4b; mkdir -p $featdir fbank_conf=conf/fbank_40.conf echo "--num-mel-bins=40" > $fbank_conf steps/nnet2/get_perturbed_feats.sh --cmd "$train_cmd" \ $fbank_conf $featdir exp/perturbed_fbanks data/train data/train_perturbed_fbank & steps/nnet2/get_perturbed_feats.sh --cmd "$train_cmd" --feature-type mfcc \ conf/mfcc.conf $featdir exp/perturbed_mfcc data/train data/train_perturbed_mfcc & wait fi if [ $stage -le 1 ]; then steps/align_fmllr.sh --nj 30 --cmd "$train_cmd" \ data/train_perturbed_mfcc data/lang exp/tri3b exp/tri3b_ali_perturbed_mfcc fi if [ $stage -le 2 ]; then steps/nnet2/train_block.sh --stage "$train_stage" \ --bias-stddev 0.5 --splice-width 7 --egs-opts "--feat-type raw" \ --softmax-learning-rate-factor 0.5 --cleanup false \ --initial-learning-rate 0.04 --final-learning-rate 0.004 \ --num-epochs-extra 10 --add-layers-period 1 \ --mix-up 4000 \ --cmd "$decode_cmd" \ --hidden-layer-dim 450 \ data/train_perturbed_fbank data/lang exp/tri3b_ali_perturbed_mfcc exp/nnet4b || exit 1 fi if [ $stage -le 3 ]; then # Create the testing data. featdir=`pwd`/mfcc mkdir -p $featdir fbank_conf=conf/fbank_40.conf echo "--num-mel-bins=40" > $fbank_conf for x in test_mar87 test_oct87 test_feb89 test_oct89 test_feb91 test_sep92 train; do cp -rT data/$x data/${x}_fbank rm -r ${x}_fbank/split* || true steps/make_fbank.sh --fbank-config "$fbank_conf" --nj 8 \ --cmd "run.pl" data/${x}_fbank exp/make_fbank/$x $featdir || exit 1; steps/compute_cmvn_stats.sh data/${x}_fbank exp/make_fbank/$x $featdir || exit 1; done utils/combine_data.sh data/test_fbank data/test_{mar87,oct87,feb89,oct89,feb91,sep92}_fbank steps/compute_cmvn_stats.sh data/test_fbank exp/make_fbank/test $featdir fi if [ $stage -le 4 ]; then steps/nnet2/decode.sh --config conf/decode.config --cmd "$decode_cmd" --nj 20 --feat-type raw \ exp/tri3b/graph data/test_fbank exp/nnet4b/decode steps/nnet2/decode.sh --config conf/decode.config --cmd "$decode_cmd" --nj 20 --feat-type raw \ exp/tri3b/graph_ug data/test_fbank exp/nnet4b/decode_ug fi
<filename>app/models/request.rb # Copyright (c) 2010-2011, Diaspora Inc. This file is # t # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. class Request include Diaspora::Federated::Base include ActiveModel::Validations attr_accessor :sender, :recipient, :aspect xml_accessor :sender_handle xml_accessor :recipient_handle validates :sender, :presence => true validates :recipient, :presence => true validate :not_already_connected validate :not_friending_yourself # Initalize variables # @note we should be using ActiveModel::Serialization for this # @return [Request] def self.diaspora_initialize(opts = {}) req = self.new req.sender = opts[:from] req.recipient = opts[:to] req.aspect = opts[:into] req end # Alias of sender_handle # @return [String] def diaspora_handle sender_handle end # @note Used for XML marshalling # @return [String] def sender_handle sender.diaspora_handle end def sender_handle= sender_handle self.sender = Person.where(:diaspora_handle => sender_handle).first end # @note Used for XML marshalling # @return [String] def recipient_handle recipient.diaspora_handle end def recipient_handle= recipient_handle self.recipient = Person.where(:diaspora_handle => recipient_handle).first end # Defines the abstract interface used in sending a corresponding [Notification] given the [Request] # @param user [User] # @param person [Person] # @return [Notifications::StartedSharing] def notification_type(user, person) Notifications::StartedSharing end # Defines the abstract interface used in sending the [Request] # @param user [User] # @return [Array<Person>] The recipient of the request def subscribers(user) [self.recipient] end # Finds or initializes a corresponding [Contact], and will set Contact#sharing to true # Follows back if user setting is set so # @note A [Contact] may already exist if the [Request]'s recipient is sharing with the sender # @return [Request] def receive(user, person) Rails.logger.info("event=receive payload_type=request sender=#{self.sender} to=#{self.recipient}") contact = user.contacts.find_or_initialize_by_person_id(self.sender.id) contact.sharing = true contact.save user.share_with(person, user.auto_follow_back_aspect) if user.auto_follow_back && !contact.receiving self end private # Checks if a [Contact] does not already exist between the requesting [User] and receiving [Person] def not_already_connected if sender && recipient && Contact.where(:user_id => self.recipient.owner_id, :person_id => self.sender.id).exists? errors[:base] << 'You have already connected to this person' end end # Checks to see that the requesting [User] is not sending a request to himself def not_friending_yourself if self.recipient == self.sender errors[:base] << 'You can not friend yourself' end end end
<reponame>gorisanson/spring-framework /* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.aspectj; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.assertj.core.api.Assertions.assertThat; /** * @author <NAME> * @author <NAME> */ class DeclareParentsDelegateRefTests { private ClassPathXmlApplicationContext ctx; private NoMethodsBean noMethodsBean; private Counter counter; @BeforeEach void setup() { this.ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass()); noMethodsBean = (NoMethodsBean) ctx.getBean("noMethodsBean"); counter = (Counter) ctx.getBean("counter"); } @AfterEach void tearDown() { this.ctx.close(); } @Test void introductionWasMade() { assertThat(noMethodsBean).as("Introduction must have been made").isInstanceOf(ICounter.class); } @Test void introductionDelegation() { ((ICounter)noMethodsBean).increment(); assertThat(counter.getCount()).as("Delegate's counter should be updated").isEqualTo(1); } } interface NoMethodsBean { } class NoMethodsBeanImpl implements NoMethodsBean { }
<gh_stars>0 import React from "react" import { PageProps } from "gatsby" import i18n from "i18next" import SEO from "../../../../components/layout/seo" import { useCustomTranslation } from "../../../../i18n-hook" import { Comments } from "../../../../components/core/comments" import translationFr from "../../../../locales/fr/oceania/australia/queensland/kuranda-village.json" import translationEn from "../../../../locales/en/oceania/australia/queensland/kuranda-village.json" import { AustraliaBlogLayout, AustraliaHeadline } from "../../../../components/core/oceania/australia/australia" import { How, HowLong, HowMuch, Introduction, SectionContent, Visit, WhatTimeOfYear, WhereToHave, } from "../../../../components/core/section" import { Conclusion } from "../../../../components/core/conclusion" import { Divider } from "../../../../components/core/divider" import { Quote } from "../../../../components/core/quote" import { Title } from "../../../../components/core/title" import HomeImgUrl from "../../../../images/oceania/australia/queensland/kuranda-village/kuranda-village-main.jpg" import KurandaMap from "../../../../images/oceania/australia/queensland/kuranda-village/map.jpg" import ButterflySanctuary from "../../../../images/oceania/australia/queensland/kuranda-village/butterfly-sanctuary.jpg" import Birdworld from "../../../../images/oceania/australia/queensland/kuranda-village/birdworld.jpg" import KoalaGardens from "../../../../images/oceania/australia/queensland/kuranda-village/koala-gardens.jpg" import Riverboat from "../../../../images/oceania/australia/queensland/kuranda-village/riverboat.jpg" import ScenicRailway from "../../../../images/oceania/australia/queensland/kuranda-village/scenic-railway.jpg" import Skyrail from "../../../../images/oceania/australia/queensland/kuranda-village/skyrail.jpg" import { GroupOfImages, ImageAsLandscape, ImageAsLandscapeOnTheLeft, ImageAsLandscapeOnTheRight, ImageAsPortrait, } from "../../../../components/images/layout" import { SharedCardAustraliaImages } from "../../../../components/images/oceania/australia/shared-card-australia-images" import { KurandaVillageImages } from "../../../../components/images/oceania/australia/queensland/kuranda-village" import { BookingGygCardContainer, MapContainer } from "../../../../components/layout/layout" import { BasicTourCard } from "../../../../components/core/get-your-guide" import { css } from "@emotion/react" const namespace = "oceania/australia/queensland/kuranda-village" const id = "kuranda-village" i18n.addResourceBundle("fr", namespace, translationFr) i18n.addResourceBundle("en", namespace, translationEn) const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => { const { t, i18n } = useCustomTranslation([namespace, "common"]) const title = t(`common:country.australia.card.${id}`) return ( <> <SEO title={title} fullTitle={t("full-title")} socialNetworkDescription={t("social-network-description")} googleDescription={t("google-description")} image={HomeImgUrl} location={location} /> <AustraliaBlogLayout page={id} location={location}> <Title title={title} linkId={id} /> <ImageAsLandscape> <SharedCardAustraliaImages image="kurandaVillage" /> </ImageAsLandscape> <Quote>{t("quote")}</Quote> <Divider /> <Introduction>{t("introduction")}</Introduction> <Divider /> <How title={t("how.title")}> <p>{t("how.part1")}</p> <p>{t("how.part2")}</p> <p>{t("how.part3")}</p> <p>{t("how.part4")}</p> <ul> <li>{t("how.part5")}</li> <li>{t("how.part6")}</li> </ul> <p>{t("how.part7")}</p> <p>{t("how.part8")}</p> </How> <HowLong title={t("how-long.title")}> <p>{t("how-long.part1")}</p> <p>{t("how-long.part2")}</p> </HowLong> <WhatTimeOfYear title={t("what-time-of-year.title")}> <p>{t("what-time-of-year.part1")}</p> <p>{t("what-time-of-year.part2")}</p> <p>{t("what-time-of-year.part3")}</p> <p>{t("what-time-of-year.part4")}</p> <p>{t("what-time-of-year.part5")}</p> <p>{t("what-time-of-year.part6")}</p> </WhatTimeOfYear> <WhereToHave title={t("where-to-have.title")}> <p>{t("where-to-have.part1")}</p> <p>{t("where-to-have.part2")}</p> <ImageAsLandscape> <KurandaVillageImages image="restaurant" /> </ImageAsLandscape> <p>{t("where-to-have.part3")}</p> </WhereToHave> <Visit title={t("visit.title")}> {/* just to have the correct space*/} <SectionContent /> <Divider /> <section> <AustraliaHeadline>{t("visit.part1.title")}</AustraliaHeadline> <Divider /> <SectionContent> <p>{t("visit.part1.part1")}</p> <p>{t("visit.part1.part2")}</p> <p>{t("visit.part1.part3")}</p> <p>{t("visit.part1.part4")}</p> </SectionContent> </section> <Divider /> <section> <AustraliaHeadline>{t("visit.part2.title")}</AustraliaHeadline> <Divider /> <SectionContent> <p>{t("visit.part2.part1")}</p> <p>{t("visit.part2.part2")}</p> <p>{t("visit.part2.part3")}</p> <ImageAsLandscape> <KurandaVillageImages image="railway" /> </ImageAsLandscape> </SectionContent> </section> <Divider /> <section> <AustraliaHeadline>{t("visit.part3.title")}</AustraliaHeadline> <Divider /> <SectionContent> <p>{t("visit.part3.part1")}</p> <p>{t("visit.part3.part2")}</p> <p>{t("visit.part3.part3")}</p> <ImageAsLandscape> <KurandaVillageImages image="skyrail" /> </ImageAsLandscape> </SectionContent> </section> <Divider /> <section> <AustraliaHeadline>{t("visit.part4.title")}</AustraliaHeadline> <Divider /> <SectionContent> <p>{t("visit.part4.part1")}</p> <p>{t("visit.part4.part2")}</p> <p>{t("visit.part4.part3")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="butterfly" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="butterfly2" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <KurandaVillageImages image="butterfly3" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <KurandaVillageImages image="butterfly4" /> </ImageAsLandscapeOnTheRight> <ImageAsLandscape> <KurandaVillageImages image="butterfly5" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.part4.part4")}</p> <p>{t("visit.part4.part5")}</p> <GroupOfImages> <ImageAsLandscapeOnTheLeft> <KurandaVillageImages image="butterfly6" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <KurandaVillageImages image="butterfly7" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit.part4.part6")}</p> <p>{t("visit.part4.part7")}</p> <ImageAsLandscapeOnTheLeft> <KurandaVillageImages image="butterfly8" /> </ImageAsLandscapeOnTheLeft> <p>{t("visit.part4.part8")}</p> <p>{t("visit.part4.part9")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="butterfly9" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="butterfly10" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="butterfly11" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.part4.part10")}</p> <ImageAsLandscape> <KurandaVillageImages image="butterfly12" /> </ImageAsLandscape> </SectionContent> </section> <Divider /> <section> <AustraliaHeadline>{t("visit.part5.title")}</AustraliaHeadline> <Divider /> <SectionContent> <p>{t("visit.part5.part1")}</p> <p>{t("visit.part5.part2")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="bird" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="bird2" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.part5.part3")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="bird4" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="bird5" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <KurandaVillageImages image="bird3" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <KurandaVillageImages image="bird6" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit.part5.part4")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="bird7" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="bird8" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <KurandaVillageImages image="bird9" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <KurandaVillageImages image="bird10" /> </ImageAsLandscapeOnTheRight> <ImageAsLandscapeOnTheLeft> <KurandaVillageImages image="bird11" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <KurandaVillageImages image="bird12" /> </ImageAsLandscapeOnTheRight> <ImageAsLandscape> <KurandaVillageImages image="bird13" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="bird14" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="bird15" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="bird16" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="bird17" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.part5.part5")}</p> <ImageAsLandscape> <KurandaVillageImages image="bird18" /> </ImageAsLandscape> <p>{t("visit.part5.part6")}</p> <p>{t("visit.part5.part7")}</p> <ImageAsPortrait> <KurandaVillageImages image="bird19" /> </ImageAsPortrait> </SectionContent> </section> <Divider /> <section> <AustraliaHeadline>{t("visit.part6.title")}</AustraliaHeadline> <Divider /> <SectionContent> <p>{t("visit.part6.part1")}</p> <p>{t("visit.part6.part2")}</p> <p>{t("visit.part6.part3")}</p> <p>{t("visit.part6.part4")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="animal" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="animal2" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.part6.part5")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="animal3" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="animal4" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="animal5" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.part6.part6")}</p> <p>{t("visit.part6.part7")}</p> <ImageAsLandscape> <KurandaVillageImages image="animal6" /> </ImageAsLandscape> <p>{t("visit.part6.part8")}</p> <p>{t("visit.part6.part9")}</p> <p>{t("visit.part6.part10")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="animal7" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <KurandaVillageImages image="animal8" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <KurandaVillageImages image="animal9" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit.part6.part11")}</p> <ImageAsLandscape> <KurandaVillageImages image="animal10" /> </ImageAsLandscape> <p>{t("visit.part6.part12")}</p> </SectionContent> </section> <Divider /> <section> <AustraliaHeadline>{t("visit.part7.title")}</AustraliaHeadline> <Divider /> <SectionContent> <p>{t("visit.part7.part1")}</p> <p>{t("visit.part7.part2")}</p> <p>{t("visit.part7.part3")}</p> <p>{t("visit.part7.part4")}</p> <MapContainer> <img src={KurandaMap} alt="Kuranda Village Map" /> </MapContainer> </SectionContent> </section> </Visit> <Divider /> <HowMuch title={t("how-much.title")}> <SectionContent> <BookingGygCardContainer> <BasicTourCard to="https://australianbutterflies.com/" title="Butterfly Sanctuary" image={ButterflySanctuary} duration={{ value: 1, unit: "hour" }} price={12} /> </BookingGygCardContainer> <p>{t("how-much.part2")}</p> </SectionContent> <Divider /> <SectionContent> <BookingGygCardContainer> <BasicTourCard css={css` img { object-position: center 40%; } `} to="https://www.birdworldkuranda.com/" title="Birdworld" image={Birdworld} duration={{ value: 1, unit: "hour" }} price={12} /> </BookingGygCardContainer> <p>{t("how-much.part3")}</p> </SectionContent> <Divider /> <SectionContent> <BookingGygCardContainer> <BasicTourCard to="https://www.koalagardens.com/" title="Koala Gardens" image={KoalaGardens} duration={{ value: 1, unit: "hour" }} price={12} /> </BookingGygCardContainer> <p>{t("how-much.part4")}</p> </SectionContent> <Divider /> <SectionContent> <BookingGygCardContainer> <BasicTourCard to="https://kurandariverboat.com.au/" title="Riverboat" image={Riverboat} duration={{ value: 45, unit: "minute" }} price={12} /> </BookingGygCardContainer> <p>{t("how-much.part5")}</p> <ul> <li>{t("how-much.part6")}</li> <li>{t("how-much.part7")}</li> <li>{t("how-much.part8")}</li> <li>{t("how-much.part9")}</li> <li>{t("how-much.part10")}</li> </ul> </SectionContent> <Divider /> <SectionContent> <BookingGygCardContainer> <BasicTourCard to="https://www.ksr.com.au/Pages/Default.aspx/" title="Scenic Railway" image={ScenicRailway} duration={{ value: 2, unit: "hour" }} price={50} /> </BookingGygCardContainer> <p>{t("how-much.part11")}</p> <ul> <li>{t("how-much.part12")}</li> <li>{t("how-much.part13")}</li> </ul> <p>{t("how-much.part14")}</p> <ul> <li>{t("how-much.part15")}</li> <li>{t("how-much.part16")}</li> </ul> <p>{t("how-much.part18")}</p> </SectionContent> <Divider /> <BookingGygCardContainer> <BasicTourCard to="https://www.skyrail.com.au/plan/skyrail-rainforest-cableway/" title="Skyrail Rainforest" image={Skyrail} duration={{ value: 90, unit: "minute" }} price={35} /> </BookingGygCardContainer> <p>{t("how-much.part19")}</p> <p>{t("how-much.part20")}</p> <p>{t("how-much.part21")}</p> <p>{t("how-much.part17")}</p> </HowMuch> <Divider /> <SectionContent> <p>{t("how-much.part22")}</p> <p>{t("how-much.part23")}</p> <GroupOfImages> <ImageAsLandscape> <KurandaVillageImages image="overview" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="overview2" /> </ImageAsLandscape> <ImageAsLandscape> <KurandaVillageImages image="overview3" /> </ImageAsLandscape> </GroupOfImages> <p>{t("how-much.part24")}</p> </SectionContent> <Conclusion> <p>{t("conclusion")}</p> <ul> <li>{t("question1")}</li> <li>{t("question2")}</li> </ul> </Conclusion> <Divider /> <Comments collectionName={namespace} location={location} facebookQuote={`${t("facebook.part1")}\n${t("facebook.part2")}`} pinterest={{ description: t("pinterest"), nodes: i18n.languageCode === "fr" ? [ <KurandaVillageImages image="cardFr1" key="cardFr1" />, <KurandaVillageImages image="cardFr2" key="cardFr1" />, ] : [ <KurandaVillageImages image="cardEn1" key="cardEn1" />, <KurandaVillageImages image="cardEn2" key="cardEn1" />, ], }} /> </AustraliaBlogLayout> </> ) } export default IndexPage
#!/bin/bash ENV_BASE=~/envs ENV=$ENV_BASE/cockroach-python if [[ ! -d $ENV ]]; then mkdir -p $ENV virtualenv $ENV fi $ENV/bin/pip install -r dev-requirements.txt $ENV/bin/pip install -r requirements.txt
#!/bin/bash DATE=`date +%Y-%m-%d` echo "$DATE new posts" cd ${POST_HOME} git pull git add . git commit -m "$DATE new posts" git push
<gh_stars>1-10 /** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 <NAME>, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017-2020 <NAME>., Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/>. **/ #include "../PrecompiledHeaders.h" #include "MemoryStorageArea.h" #include "../OrthancException.h" #include "../Logging.h" namespace Orthanc { MemoryStorageArea::~MemoryStorageArea() { for (Content::iterator it = content_.begin(); it != content_.end(); ++it) { if (it->second != NULL) { delete it->second; } } } void MemoryStorageArea::Create(const std::string& uuid, const void* content, size_t size, FileContentType type) { LOG(INFO) << "Creating attachment \"" << uuid << "\" of \"" << static_cast<int>(type) << "\" type (size: " << (size / (1024 * 1024) + 1) << "MB)"; boost::mutex::scoped_lock lock(mutex_); if (size != 0 && content == NULL) { throw OrthancException(ErrorCode_NullPointer); } else if (content_.find(uuid) != content_.end()) { throw OrthancException(ErrorCode_InternalError); } else { content_[uuid] = new std::string(reinterpret_cast<const char*>(content), size); } } void MemoryStorageArea::Read(std::string& content, const std::string& uuid, FileContentType type) { LOG(INFO) << "Reading attachment \"" << uuid << "\" of \"" << static_cast<int>(type) << "\" content type"; boost::mutex::scoped_lock lock(mutex_); Content::const_iterator found = content_.find(uuid); if (found == content_.end()) { throw OrthancException(ErrorCode_InexistentFile); } else if (found->second == NULL) { throw OrthancException(ErrorCode_InternalError); } else { content.assign(*found->second); } } void MemoryStorageArea::Remove(const std::string& uuid, FileContentType type) { LOG(INFO) << "Deleting attachment \"" << uuid << "\" of type " << static_cast<int>(type); boost::mutex::scoped_lock lock(mutex_); Content::iterator found = content_.find(uuid); if (found == content_.end()) { // Ignore second removal } else if (found->second == NULL) { throw OrthancException(ErrorCode_InternalError); } else { delete found->second; content_.erase(found); } } }
package com.rostdev.survivalpack.model; /** * Created by Rosty on 7/7/2016. */ public class SensorInfo { private int image; private String title; private String info; public SensorInfo(int image, String title, String info) { this.image = image; this.title = title; this.info = info; } public int getImage() { return image; } public String getTitle() { return title; } public String getInfo() { return info; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SensorInfo that = (SensorInfo) o; return title.equals(that.title); } @Override public int hashCode() { return title.hashCode(); } }
package practice; import java.util.Stack; import structure.MinStack; public class StackQueue { public Stack<Integer> sortStack(Stack<Integer> stack){ Stack<Integer> back = new Stack<Integer>(); while(!stack.isEmpty()){ Integer temp = stack.pop(); while(!back.isEmpty() && back.peek() < temp){ stack.push(back.pop()); } back.push(temp); } return back; } }
class BinaryTree: def diameterOfBinaryTree(self, root: BinaryTreeNode) -> int: def height_and_diameter(node): if not node: return 0, 0 left_height, left_diameter = height_and_diameter(node.left) right_height, right_diameter = height_and_diameter(node.right) current_height = 1 + max(left_height, right_height) current_diameter = max(left_height + right_height, left_diameter, right_diameter) return current_height, current_diameter _, diameter = height_and_diameter(root) return diameter
# https://unix.stackexchange.com/questions/22615/how-can-i-get-my-external-ip-address-in-a-shell-script dig @resolver1.opendns.com ANY myip.opendns.com +short dig @resolver1.opendns.com ANY myip.opendns.com +short > ip_address.txt scp $USER@$HOST:/home/$USER/ip_address.txt
<gh_stars>1-10 /******************************************************************************* * Copyright 2020 <NAME> | ABI INC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package net.abi.abisEngine.components; import net.abi.abisEngine.math.vector.Vector3f; import net.abi.abisEngine.rendering.shader.shaders.ForwardPointShader; import net.abi.abisEngine.util.Attenuation; /** * @author abinash * */ public class PointLight extends Light { private static final int COLOR_DEPTH = 256; private Attenuation attenuation; private float range; public PointLight(Vector3f color, float intensity, Attenuation attenuation) { super(color, intensity); this.attenuation = attenuation; float a = attenuation.getExponent(), b = attenuation.getLinear(), c = attenuation.getConstant() - COLOR_DEPTH * getIntensity() * getColor().max(); this.range = (float) (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); super.setShader(new ForwardPointShader()); } public float getRange() { return range; } public void setRange(float range) { this.range = range; } public Attenuation getAttenuation() { return attenuation; } public void setAttenuation(Attenuation attenuation) { this.attenuation = attenuation; } }
<reponame>Jony635/Sym3DEngine #pragma once #include <vector> #include "Globals.h" #include <random> class Module; class ModuleWindow; class ModuleRenderer; class ModuleInput; class ModuleImGUI; class ModuleScene; class ModuleTime; class Application { enum AppState { NO_STATE = -1, START, UPDATE, FINISH, FINISH_ERROR }; friend int main(int argc, char* argv[]); public: Application(); bool Start(); bool Update(); bool CleanUp(); public: inline void FinishApp() { state = AppState::FINISH; } uint GetRandomUUID(); public: ModuleWindow* window = nullptr; ModuleRenderer* renderer = nullptr; ModuleInput* input = nullptr; ModuleImGUI* imgui = nullptr; ModuleScene* scene = nullptr; ModuleTime* time = nullptr; private: AppState state; std::vector<Module*> modules; std::random_device rd; }; extern Application* App;
export { default } from './AxyzProvider';
#!/bin/bash YEAR=2015 for MONTH in `seq -w 1 12`; do echo $YEAR$MONTH PARAMS="UserTableName=On_Time_Performance&DBShortName=&RawDataTable=T_ONTIME&sqlstr=+SELECT+FL_DATE%2CUNIQUE_CARRIER%2CAIRLINE_ID%2CCARRIER%2CFL_NUM%2CORIGIN_AIRPORT_ID%2CORIGIN_AIRPORT_SEQ_ID%2CORIGIN_CITY_MARKET_ID%2CORIGIN%2CDEST_AIRPORT_ID%2CDEST_AIRPORT_SEQ_ID%2CDEST_CITY_MARKET_ID%2CDEST%2CCRS_DEP_TIME%2CDEP_TIME%2CDEP_DELAY%2CTAXI_OUT%2CWHEELS_OFF%2CWHEELS_ON%2CTAXI_IN%2CCRS_ARR_TIME%2CARR_TIME%2CARR_DELAY%2CCANCELLED%2CCANCELLATION_CODE%2CDIVERTED%2CDISTANCE+FROM++T_ONTIME+WHERE+Month+%3D${MONTH}+AND+YEAR%3D${YEAR}&varlist=FL_DATE%2CUNIQUE_CARRIER%2CAIRLINE_ID%2CCARRIER%2CFL_NUM%2CORIGIN_AIRPORT_ID%2CORIGIN_AIRPORT_SEQ_ID%2CORIGIN_CITY_MARKET_ID%2CORIGIN%2CDEST_AIRPORT_ID%2CDEST_AIRPORT_SEQ_ID%2CDEST_CITY_MARKET_ID%2CDEST%2CCRS_DEP_TIME%2CDEP_TIME%2CDEP_DELAY%2CTAXI_OUT%2CWHEELS_OFF%2CWHEELS_ON%2CTAXI_IN%2CCRS_ARR_TIME%2CARR_TIME%2CARR_DELAY%2CCANCELLED%2CCANCELLATION_CODE%2CDIVERTED%2CDISTANCE&grouplist=&suml=&sumRegion=&filter1=title%3D&filter2=title%3D&geo=All%A0&time=March&timename=Month&GEOGRAPHY=All&XYEAR=${YEAR}&FREQUENCY=3&VarDesc=Year&VarType=Num&VarDesc=Quarter&VarType=Num&VarDesc=Month&VarType=Num&VarDesc=DayofMonth&VarType=Num&VarDesc=DayOfWeek&VarType=Num&VarName=FL_DATE&VarDesc=FlightDate&VarType=Char&VarName=UNIQUE_CARRIER&VarDesc=UniqueCarrier&VarType=Char&VarName=AIRLINE_ID&VarDesc=AirlineID&VarType=Num&VarName=CARRIER&VarDesc=Carrier&VarType=Char&VarDesc=TailNum&VarType=Char&VarName=FL_NUM&VarDesc=FlightNum&VarType=Char&VarName=ORIGIN_AIRPORT_ID&VarDesc=OriginAirportID&VarType=Num&VarName=ORIGIN_AIRPORT_SEQ_ID&VarDesc=OriginAirportSeqID&VarType=Num&VarName=ORIGIN_CITY_MARKET_ID&VarDesc=OriginCityMarketID&VarType=Num&VarName=ORIGIN&VarDesc=Origin&VarType=Char&VarDesc=OriginCityName&VarType=Char&VarDesc=OriginState&VarType=Char&VarDesc=OriginStateFips&VarType=Char&VarDesc=OriginStateName&VarType=Char&VarDesc=OriginWac&VarType=Num&VarName=DEST_AIRPORT_ID&VarDesc=DestAirportID&VarType=Num&VarName=DEST_AIRPORT_SEQ_ID&VarDesc=DestAirportSeqID&VarType=Num&VarName=DEST_CITY_MARKET_ID&VarDesc=DestCityMarketID&VarType=Num&VarName=DEST&VarDesc=Dest&VarType=Char&VarDesc=DestCityName&VarType=Char&VarDesc=DestState&VarType=Char&VarDesc=DestStateFips&VarType=Char&VarDesc=DestStateName&VarType=Char&VarDesc=DestWac&VarType=Num&VarName=CRS_DEP_TIME&VarDesc=CRSDepTime&VarType=Char&VarName=DEP_TIME&VarDesc=DepTime&VarType=Char&VarName=DEP_DELAY&VarDesc=DepDelay&VarType=Num&VarDesc=DepDelayMinutes&VarType=Num&VarDesc=DepDel15&VarType=Num&VarDesc=DepartureDelayGroups&VarType=Num&VarDesc=DepTimeBlk&VarType=Char&VarName=TAXI_OUT&VarDesc=TaxiOut&VarType=Num&VarName=WHEELS_OFF&VarDesc=WheelsOff&VarType=Char&VarName=WHEELS_ON&VarDesc=WheelsOn&VarType=Char&VarName=TAXI_IN&VarDesc=TaxiIn&VarType=Num&VarName=CRS_ARR_TIME&VarDesc=CRSArrTime&VarType=Char&VarName=ARR_TIME&VarDesc=ArrTime&VarType=Char&VarName=ARR_DELAY&VarDesc=ArrDelay&VarType=Num&VarDesc=ArrDelayMinutes&VarType=Num&VarDesc=ArrDel15&VarType=Num&VarDesc=ArrivalDelayGroups&VarType=Num&VarDesc=ArrTimeBlk&VarType=Char&VarName=CANCELLED&VarDesc=Cancelled&VarType=Num&VarName=CANCELLATION_CODE&VarDesc=CancellationCode&VarType=Char&VarName=DIVERTED&VarDesc=Diverted&VarType=Num&VarDesc=CRSElapsedTime&VarType=Num&VarDesc=ActualElapsedTime&VarType=Num&VarDesc=AirTime&VarType=Num&VarDesc=Flights&VarType=Num&VarName=DISTANCE&VarDesc=Distance&VarType=Num&VarDesc=DistanceGroup&VarType=Num&VarDesc=CarrierDelay&VarType=Num&VarDesc=WeatherDelay&VarType=Num&VarDesc=NASDelay&VarType=Num&VarDesc=SecurityDelay&VarType=Num&VarDesc=LateAircraftDelay&VarType=Num&VarDesc=FirstDepTime&VarType=Char&VarDesc=TotalAddGTime&VarType=Num&VarDesc=LongestAddGTime&VarType=Num&VarDesc=DivAirportLandings&VarType=Num&VarDesc=DivReachedDest&VarType=Num&VarDesc=DivActualElapsedTime&VarType=Num&VarDesc=DivArrDelay&VarType=Num&VarDesc=DivDistance&VarType=Num&VarDesc=Div1Airport&VarType=Char&VarDesc=Div1AirportID&VarType=Num&VarDesc=Div1AirportSeqID&VarType=Num&VarDesc=Div1WheelsOn&VarType=Char&VarDesc=Div1TotalGTime&VarType=Num&VarDesc=Div1LongestGTime&VarType=Num&VarDesc=Div1WheelsOff&VarType=Char&VarDesc=Div1TailNum&VarType=Char&VarDesc=Div2Airport&VarType=Char&VarDesc=Div2AirportID&VarType=Num&VarDesc=Div2AirportSeqID&VarType=Num&VarDesc=Div2WheelsOn&VarType=Char&VarDesc=Div2TotalGTime&VarType=Num&VarDesc=Div2LongestGTime&VarType=Num&VarDesc=Div2WheelsOff&VarType=Char&VarDesc=Div2TailNum&VarType=Char&VarDesc=Div3Airport&VarType=Char&VarDesc=Div3AirportID&VarType=Num&VarDesc=Div3AirportSeqID&VarType=Num&VarDesc=Div3WheelsOn&VarType=Char&VarDesc=Div3TotalGTime&VarType=Num&VarDesc=Div3LongestGTime&VarType=Num&VarDesc=Div3WheelsOff&VarType=Char&VarDesc=Div3TailNum&VarType=Char&VarDesc=Div4Airport&VarType=Char&VarDesc=Div4AirportID&VarType=Num&VarDesc=Div4AirportSeqID&VarType=Num&VarDesc=Div4WheelsOn&VarType=Char&VarDesc=Div4TotalGTime&VarType=Num&VarDesc=Div4LongestGTime&VarType=Num&VarDesc=Div4WheelsOff&VarType=Char&VarDesc=Div4TailNum&VarType=Char&VarDesc=Div5Airport&VarType=Char&VarDesc=Div5AirportID&VarType=Num&VarDesc=Div5AirportSeqID&VarType=Num&VarDesc=Div5WheelsOn&VarType=Char&VarDesc=Div5TotalGTime&VarType=Num&VarDesc=Div5LongestGTime&VarType=Num&VarDesc=Div5WheelsOff&VarType=Char&VarDesc=Div5TailNum&VarType=Char" RESPONSE=$(curl -X POST --data "$PARAMS" http://www.transtats.bts.gov/DownLoad_Table.asp?Table_ID=236&Has_Group=3&Is_Zipped=0) echo "Received $RESPONSE" ZIPFILE=$(echo $RESPONSE | tr '\"' '\n' | grep zip) echo $ZIPFILE curl -o $YEAR$MONTH.zip $ZIPFILE done
<gh_stars>0 package org.museautomation.ui.valuesource.map; /** * @author <NAME> (see LICENSE.txt for license details) */ public interface SubsourceNameValidator { boolean isValid(String name); }
package vaultengine import ( vault "github.com/hashicorp/vault/api" ) // Client describes the arguments that is needed to to establish a connecting to a Vault instance type Client struct { token string addr string namespace string engine string insecure bool vc *vault.Client } // NewClient creates a instance of the VaultClient struct func NewClient(addr, token string, insecure bool) *Client { client := &Client{ token: token, addr: addr, insecure: insecure} client.newVaultClient() return client } // UseEngine defines which engine the Vault client will use func (client *Client) UseEngine(engine string) { client.engine = engine } func (client *Client) newVaultClient() error { config := vault.Config{Address: client.addr} // Enable insecure config.ConfigureTLS(&vault.TLSConfig{ Insecure: client.insecure, }) vc, err := vault.NewClient(&config) if err != nil { return err } client.vc = vc // if client.namespace != "" { // client.vc.SetNamespace(client.namespace) // } if client.token != "" { client.vc.SetToken(client.token) } return nil }
#!/bin/bash # Install Ansible echo "INFO: Started Installing Ansible..." pip install ansible --upgrade pip install pywinrm echo "INFO: Finished Installing Ansible."
SELECT * FROM users WHERE joined_date < (CURRENT_DATE - INTERVAL '1 year');
<filename>lib/codelocks/net_code.rb module Codelocks class NetCode < Model class << self # Predefined method for generating a new NetCode # # @option [String] :lock_id The lock identifier # @option [String] :lock_model (K3CONNECT) The type of lock # @option [Time] :start (Time.now) The start datetime object # @option [Integer] :duration (0) The number of hours the generated code should be valid for from the start_time # @option [Boolean] :urm (false) Generate an URM code # @option [String] :identifier (Codelocks.access_key) The access key or lock identifier # # @return [Codelocks::NetCode::Response] def create(opts = {}) netcode = new(opts) if !netcode.identifier raise CodelocksError.new("Either a lock identifier or an access key must be provided") end client.requests.create("netcode/#{netcode.lock_id}", "id": netcode.lock_id, "start": netcode.start_datetime, "duration": netcode.duration_id, "lockmodel": netcode.lock_model, "identifier": netcode.identifier ) end end attr_accessor :opts def initialize(opts = {}) self.opts = { lock_model: nil || "K3CONNECT", lock_id: nil, start: nil, duration: 0, urm: false, identifier: nil }.merge!(opts) end def method_missing(method, *args, &block) return opts[method] if opts.include?(method) super end # Return either a supplied identifier or the predefined access key # # @return [String] def identifier opts[:identifier] || client.access_key end # String representing the start date in YYYY-MM-DD format # # @return [String] def start_date start.strftime("%Y-%m-%d") unless start.nil? end # String representing the start time. Hour has a leading zero # # @return [String] def start_time if urm? && duration_id >= 31 # URM enabled and >= 24 hours duration "00:00" else start.strftime("%H:%M") unless start.nil? end end # Full date time formatted for API use # # @return [String] def start_datetime [start_date, start_time].join(" ") end # NetCode duration ID # # @return [Integer] def duration_id if urm? urm_duration else base_duration end end # Are URM codes enabled? # # @return [Boolean] def urm? !!urm end private # Convert a duration in hours to the NetCode duration ID # # @return [Integer] def base_duration case duration when 0 0 when 1..12 # less than 13 hours duration - 1 when 13..24 # 1 day 12 when 25..48 # 2 days 13 when 49..72 # 3 days 14 when 73..96 # 4 days 15 when 97..120 # 5 days 16 when 121..144 # 6 days 17 else # 7 days 18 end end # Return the duration used for URM requests # # @return [Integer] def urm_duration 37 end end end
<reponame>openstack/python-watcherclient # Copyright (c) 2016 b<>com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import copy from osc_lib import utils from oslo_utils import uuidutils from watcherclient._i18n import _ from watcherclient.common import api_versioning from watcherclient.common import command from watcherclient.common import utils as common_utils from watcherclient import exceptions from watcherclient.v1 import resource_fields as res_fields def drop_unsupported_field(app_args, fields, field_labels): fields = copy.copy(fields) field_labels = copy.copy(field_labels) api_ver = app_args.os_infra_optim_api_version if not api_versioning.allow_start_end_audit_time(api_ver): for field, label in zip(('start_time', 'end_time'), ('Start Time', 'End Time')): fields.remove(field) field_labels.remove(label) if not api_versioning.launch_audit_forced(api_ver): fields.remove('force') field_labels.remove('Force') return fields, field_labels class ShowAudit(command.ShowOne): """Show detailed information about a given audit.""" def get_parser(self, prog_name): parser = super(ShowAudit, self).get_parser(prog_name) parser.add_argument( 'audit', metavar='<audit>', help=_('UUID or name of the audit'), ) return parser def take_action(self, parsed_args): client = getattr(self.app.client_manager, "infra-optim") try: audit = client.audit.get(parsed_args.audit) if audit.strategy_name is None: audit.strategy_name = 'auto' except exceptions.HTTPNotFound as exc: raise exceptions.CommandError(str(exc)) columns = res_fields.AUDIT_FIELDS column_headers = res_fields.AUDIT_FIELD_LABELS columns, column_headers = drop_unsupported_field( self.app_args, columns, column_headers) return column_headers, utils.get_item_properties(audit, columns) class ListAudit(command.Lister): """List information on retrieved audits.""" def get_parser(self, prog_name): parser = super(ListAudit, self).get_parser(prog_name) parser.add_argument( '--detail', dest='detail', action='store_true', default=False, help=_("Show detailed information about audits.")) parser.add_argument( '--goal', dest='goal', metavar='<goal>', help=_('UUID or name of the goal used for filtering.')) parser.add_argument( '--strategy', dest='strategy', metavar='<strategy>', help=_('UUID or name of the strategy used for filtering.')) parser.add_argument( '--limit', metavar='<limit>', type=int, help=_('Maximum number of audits to return per request, ' '0 for no limit. Default is the maximum number used ' 'by the Watcher API Service.')) parser.add_argument( '--sort-key', metavar='<field>', help=_('Audit field that will be used for sorting.')) parser.add_argument( '--sort-dir', metavar='<direction>', choices=['asc', 'desc'], help=_('Sort direction: "asc" (the default) or "desc".')) parser.add_argument( '--marker', dest='marker', metavar='<marker>', default=None, help=_('UUID of the last audit in the previous page; ' 'displays list of audits after "marker".')) return parser def take_action(self, parsed_args): client = getattr(self.app.client_manager, "infra-optim") params = {} # Optional if parsed_args.goal: params['goal'] = parsed_args.goal # Optional if parsed_args.strategy: params['strategy'] = parsed_args.strategy if parsed_args.detail: fields = res_fields.AUDIT_FIELDS field_labels = res_fields.AUDIT_FIELD_LABELS else: fields = res_fields.AUDIT_SHORT_LIST_FIELDS field_labels = res_fields.AUDIT_SHORT_LIST_FIELD_LABELS if parsed_args.detail: fields, field_labels = drop_unsupported_field( self.app_args, fields, field_labels) params.update(common_utils.common_params_for_list( parsed_args, fields, field_labels)) try: data = client.audit.list(**params) for audit in data: if audit.strategy_name is None: audit.strategy_name = 'auto' except exceptions.HTTPNotFound as ex: raise exceptions.CommandError(str(ex)) return (field_labels, (utils.get_item_properties(item, fields) for item in data)) class CreateAudit(command.ShowOne): """Create new audit.""" def get_parser(self, prog_name): parser = super(CreateAudit, self).get_parser(prog_name) parser.add_argument( '-t', '--audit_type', dest='audit_type', metavar='<audit_type>', default='ONESHOT', choices=['ONESHOT', 'CONTINUOUS', 'EVENT'], help=_("Audit type. It must be ONESHOT, CONTINUOUS or EVENT. " "Default is ONESHOT.")) parser.add_argument( '-p', '--parameter', dest='parameters', metavar='<name=value>', action='append', help=_("Record strategy parameter/value metadata. " "Can be specified multiple times.")) parser.add_argument( '-i', '--interval', dest='interval', metavar='<interval>', help=_('Audit interval (in seconds or cron format). ' 'Cron interval can be used like: ``*/5 * * * *``. ' 'Only used if the audit is CONTINUOUS.')) parser.add_argument( '-g', '--goal', dest='goal', metavar='<goal>', help=_('Goal UUID or name associated to this audit.')) parser.add_argument( '-s', '--strategy', dest='strategy', metavar='<strategy>', help=_('Strategy UUID or name associated to this audit.')) parser.add_argument( '-a', '--audit-template', dest='audit_template_uuid', metavar='<audit_template>', help=_('Audit template used for this audit (name or uuid).')) parser.add_argument( '--auto-trigger', dest='auto_trigger', action='store_true', default=False, help=_('Trigger automatically action plan ' 'once audit is succeeded.')) parser.add_argument( '--name', dest='name', metavar='<name>', help=_('Name for this audit.')) parser.add_argument( '--start-time', dest='start_time', metavar='<start_time>', help=_('CONTINUOUS audit local start time. ' 'Format: YYYY-MM-DD hh:mm:ss')) parser.add_argument( '--end-time', dest='end_time', metavar='<end_time>', help=_('CONTINUOUS audit local end time. ' 'Format: YYYY-MM-DD hh:mm:ss')) parser.add_argument( '--force', dest='force', action='store_true', help=_('Launch audit even if action plan ' 'is ongoing. default is False')) return parser def take_action(self, parsed_args): client = getattr(self.app.client_manager, "infra-optim") field_list = ['audit_template_uuid', 'audit_type', 'parameters', 'interval', 'goal', 'strategy', 'auto_trigger', 'name'] api_ver = self.app_args.os_infra_optim_api_version if api_versioning.allow_start_end_audit_time(api_ver): if parsed_args.start_time is not None: field_list.append('start_time') if parsed_args.end_time is not None: field_list.append('end_time') if api_versioning.launch_audit_forced(api_ver): if parsed_args.force is not None: field_list.append('force') fields = dict((k, v) for (k, v) in vars(parsed_args).items() if k in field_list and v is not None) fields = common_utils.args_array_to_dict(fields, 'parameters') if fields.get('audit_template_uuid'): if not uuidutils.is_uuid_like(fields['audit_template_uuid']): fields['audit_template_uuid'] = client.audit_template.get( fields['audit_template_uuid']).uuid audit = client.audit.create(**fields) if audit.strategy_name is None: audit.strategy_name = 'auto' columns = res_fields.AUDIT_FIELDS column_headers = res_fields.AUDIT_FIELD_LABELS columns, column_headers = drop_unsupported_field( self.app_args, columns, column_headers) return column_headers, utils.get_item_properties(audit, columns) class UpdateAudit(command.ShowOne): """Update audit command.""" def get_parser(self, prog_name): parser = super(UpdateAudit, self).get_parser(prog_name) parser.add_argument( 'audit', metavar='<audit>', help=_("UUID or name of the audit.")) parser.add_argument( 'op', metavar='<op>', choices=['add', 'replace', 'remove'], help=_("Operation: 'add', 'replace', or 'remove'.")) parser.add_argument( 'attributes', metavar='<path=value>', nargs='+', action='append', default=[], help=_("Attribute to add, replace, or remove. Can be specified " "multiple times. For 'remove', only <path> is necessary.")) return parser def take_action(self, parsed_args): client = getattr(self.app.client_manager, "infra-optim") patch = common_utils.args_array_to_patch( parsed_args.op, parsed_args.attributes[0], exclude_fields=['/interval']) audit = client.audit.update(parsed_args.audit, patch) columns = res_fields.AUDIT_FIELDS column_headers = res_fields.AUDIT_FIELD_LABELS columns, column_headers = drop_unsupported_field( self.app_args, columns, column_headers) return column_headers, utils.get_item_properties(audit, columns) class DeleteAudit(command.Command): """Delete audit command.""" def get_parser(self, prog_name): parser = super(DeleteAudit, self).get_parser(prog_name) parser.add_argument( 'audits', metavar='<audit>', nargs='+', help=_('UUID or name of the audit'), ) return parser def take_action(self, parsed_args): client = getattr(self.app.client_manager, "infra-optim") for audit in parsed_args.audits: client.audit.delete(audit)
<filename>app/controllers/AdminController.java package controllers; import play.db.jpa.Transactional; import play.mvc.Controller; import play.mvc.Result; public class AdminController extends Controller { private int pin; public Result getLogIn() { return ok(views.html.adminlogin.render()); } @Transactional public Result postLogIn() { Integer pin = 1234; return redirect(routes.ChartController.getInventoryChart()); } }
sap.ui.define([ "ch/avectris/todo/TodoListClient/test/unit/controller/Master.controller" ], function () { "use strict"; });
const path = require("path"); const resolve = dir => path.resolve(__dirname, dir); const CompressionWebpackPlugin = require("compression-webpack-plugin"); //Gzip const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; const BundleAnalyzerPlugin = require("webpack-bundle-analyzer") .BundleAnalyzerPlugin; //Webpack包文件分析器 const CopyWebpackPlugin = require("copy-webpack-plugin"); const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV); //env const isAnalyz = process.env.IS_ANALYZ === "true"; module.exports = { publicPath: process.env.NODE_ENV === "production" ? process.env.API_ROOT : "./", //打包后的位置(如果不设置这个静态资源会报404) outputDir: "docs", //打包后的目录名称 assetsDir: "static", //静态资源目录名称 productionSourceMap: false, //去掉打包的时候生成的map文件 lintOnSave: true, // eslint-loader 是否在保存的时候检查 filenameHashing: false, runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本 parallel: require("os").cpus().length > 1, // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。 pwa: {}, // 向 PWA 插件传递选项。 // css相关配置 css: { // 是否使用css分离插件 ExtractTextPlugin extract: true, // 开启 CSS source maps? sourceMap: !IS_PROD, // css预设器配置项 loaderOptions: { less: { javascriptEnabled: true } } }, chainWebpack: config => { // 打包分析 // if `IS_ANALYZ` env is TRUE on report bundle info isAnalyz && config.plugin("webpack-report").use(BundleAnalyzerPlugin, [ { analyzerMode: "static" } ]); // 修复HMR config.resolve.symlinks(true); // 如果使用多页面打包,使用vue inspect --plugins查看html是否在结果数组中 // config.plugin("html").tap(args => { // // 修复 Lazy loading routes Error // args[0].chunksSortMode = "none"; // return args; // }); // config.resolve.extensions // .prepend(".js") // .prepend(".vue") // .prepend(".json"); // 添加别名 config.resolve.alias .set("vue$", "vue/dist/vue.esm.js") .set("@", resolve("src")) .set("@components", resolve("src/components")) .set("@views", resolve("src/views")) .set("@router", resolve("src/router")) .set("@store", resolve("src/store")); // .set("@ant-design/icons/lib/dist$", resolve("src/utils/antdIcon.js")); if (IS_PROD) { // 压缩图片 // 需要 npm i -D image-webpack-loader config.module .rule("images") .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/) .use("image-webpack-loader") .loader("image-webpack-loader") .options({ mozjpeg: { progressive: true, quality: 65 }, optipng: { enabled: false }, pngquant: { quality: [0.65, 0.9], speed: 4 }, gifsicle: { interlaced: false } }); } }, devServer: { // overlay: { // 让浏览器 overlay 同时显示警告和错误 // warnings: true, // errors: true // }, // open: false, // 是否打开浏览器 // host: "localhost", // port: "8080", // 代理断就 // https: false, // hotOnly: false, // 热更新 proxy: { "/api": { target: "http://hosts/api", // 目标代理接口地址 secure: false, changeOrigin: true, // 开启代理,在本地创建一个虚拟服务端 // ws: true, // 是否启用 websockets pathRewrite: { "^/api": "/" } } } }, configureWebpack: config => { const plugins = []; // 拷贝static目录 plugins.push( new CopyWebpackPlugin([ { from: path.resolve(__dirname, "static"), to: path.resolve(__dirname, "docs/static"), ignore: [".*"] } ]) ); if (IS_PROD) { // 开启 gzip 压缩 // 需要 npm i -D compression-webpack-plugin plugins.push( new CompressionWebpackPlugin({ filename: "[path].gz[query]", algorithm: "gzip", test: productionGzipExtensions, threshold: 10240, minRatio: 0.8 }) ); } config.plugins = [...config.plugins, ...plugins]; } };
"use strict"; var KTLayoutQuickActions = function() { // Private properties var _element; var _offcanvasObject; // Private functions var _init = function() { var header = KTUtil.find(_element, '.offcanvas-header'); var content = KTUtil.find(_element, '.offcanvas-content'); _offcanvasObject = new KTOffcanvas(_element, { overlay: true, baseClass: 'offcanvas', placement: 'right', closeBy: 'kt_quick_actions_close', toggleBy: 'kt_quick_actions_toggle' }); KTUtil.scrollInit(content, { disableForMobile: true, resetHeightOnDestroy: true, handleWindowResize: true, height: function() { var height = parseInt(KTUtil.getViewPort().height); if (header) { height = height - parseInt(KTUtil.actualHeight(header)); height = height - parseInt(KTUtil.css(header, 'marginTop')); height = height - parseInt(KTUtil.css(header, 'marginBottom')); } if (content) { height = height - parseInt(KTUtil.css(content, 'marginTop')); height = height - parseInt(KTUtil.css(content, 'marginBottom')); } height = height - parseInt(KTUtil.css(_element, 'paddingTop')); height = height - parseInt(KTUtil.css(_element, 'paddingBottom')); height = height - 2; return height; } }); } // Public methods return { init: function(id) { _element = KTUtil.getById(id); if (!_element) { return; } // Initialize _init(); }, getElement: function() { return _element; } }; }(); export default KTLayoutQuickActions;
import { getAuth } from 'firebase/auth'; import { doc, getFirestore, updateDoc } from 'firebase/firestore'; import React, { useState } from 'react'; import Button from '../../../ui/Button/Button'; import ErrorBanner from '../../../ui/ErrorBanner/ErrorBanner'; import Input from '../../../ui/Input/Input'; import Spinner from '../../../ui/Spinner/Spinner'; import { IEditUser, IUser } from '../../../../interfaces/user'; import { getFirebaseApp } from '../../../../utils/firebase'; import { checkUrlImage } from '../../../../utils/regex'; import classes from './accountDetailsContainer.module.css'; import sharedClasses from '../../../../common.module.css'; interface IProps { user: IUser; setUser: (user: IUser) => void; } export default function AccountDetailsContainer({ user, setUser }: IProps) { const [error, setError] = useState(''); const [usernameError, setUsernameError] = useState(''); const [photoUrlError, setPhotoUrlError] = useState(''); const [isEditing, setIsEditing] = useState(false); const [isLoading, setIsLoading] = useState(false); const [editedUser, setEditedUser] = useState<IEditUser>({ username: user.username, photoUrl: user.photoUrl, website: user.website, }); const firebaseApp = getFirebaseApp()!; const auth = getAuth(firebaseApp); const firestore = getFirestore(firebaseApp); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { const { name, value } = event.target; setEditedUser({ ...editedUser, [name]: value }); }; const validate = () => { let isValid = true; setPhotoUrlError(''); setUsernameError(''); if (editedUser.username.trim() === '') { setUsernameError('Invalid Username'); isValid = false; } if (editedUser.photoUrl && !checkUrlImage(editedUser.photoUrl.trim())) { setPhotoUrlError('Invalid Photo URL'); isValid = false; } return isValid; }; const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); setError(''); if (!validate()) { return; } setIsLoading(true); try { if (user.uid === auth.currentUser!.uid) { const data: { [key: string]: string } = {}; for (const key in editedUser) { if (editedUser[key]) { data[key] = editedUser[key]; } } await updateDoc(doc(firestore, 'users', auth.currentUser!.uid), data); setUser({ ...user, ...data }); setIsEditing(false); } } catch (error) { // @ts-ignore setError(error.code); } setIsLoading(false); }; return ( <div className={classes.accountDetailsContainer}> {isLoading ? ( <Spinner /> ) : ( <> {isEditing ? ( <form className={classes.inputContainer} onSubmit={handleSubmit}> <Input placeholder="Username" name="username" value={editedUser.username} onChange={handleChange} error={!!usernameError} helperText={usernameError} fullwidth /> <Input placeholder="Photo URL" name="photoUrl" value={editedUser.photoUrl} onChange={handleChange} error={!!photoUrlError} helperText={photoUrlError} fullwidth /> <Input placeholder="Website" name="website" value={editedUser.website} onChange={handleChange} fullwidth /> {error && <ErrorBanner>{error}</ErrorBanner>} <Button type="submit" className={classes.button}> Save </Button> <Button onClick={() => setIsEditing(false)}>Cancel</Button> </form> ) : ( <> <div className={classes.profilePicContainer}> {user?.photoUrl ? ( <img className={classes.profilePic} src={user?.photoUrl} alt="profile-picture" /> ) : ( <h1 className={`${sharedClasses.h1} ${classes.placeholder}`}> {user?.username[0].toUpperCase()} </h1> )} </div> <div className={classes.infoContainer}> <h2 className={sharedClasses.h2}>{user!.username}</h2> {user!.website && ( <> <a href={user.website} className={`${sharedClasses.g} ${sharedClasses.link}`} rel="noopener noreferrer" target="_blank" > <i className={`fas fa-globe-americas ${sharedClasses.h4}`} /> {user.website} </a> </> )} </div> </> )} {auth.currentUser && auth.currentUser.uid === user?.uid && !isEditing && ( <button className={`${classes.editButton} ${sharedClasses.h2}`} onClick={() => setIsEditing(true)} > <i className="fas fa-edit" /> </button> )} </> )} </div> ); }
#!/bin/bash # ------------------------------------------------------- # Copyright (c) 2020-2021 Arm Limited. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # ------------------------------------------------------- # Version: 1.0 # Date: 2020-05-19 # This script installs required packs # # Pre-requisites: # - bash shell (for Windows: install git for Windows) usage() { echo "Usage:" echo " $(basename $0) <Test Output directory>" echo "" } # check command line for 1 argument if [ $# -eq 1 ]; then echo "info: using directory: $1" testoutdir="$1" elif [ $# -eq 0 ]; then echo "error: no argument passed" usage exit 1 else # >1 arguments are passed echo "error: more than one command line argument passed" usage exit 1 fi if [ ! -d "${testoutdir}" ]; then echo "error: directory ${testoutdir} does not exist" exit 1 fi # Set environment variables source ${testoutdir}/cbuild/etc/setup # Install packs packlist=${testoutdir}/pack.cpinstall > ${packlist} echo https://www.keil.com/pack/ARM.CMSIS.5.8.0.pack >> ${packlist} echo https://www.keil.com/pack/Keil.ARM_Compiler.1.6.3.pack >> ${packlist} echo http://www.keil.com/pack/Keil.STM32F4xx_DFP.2.14.0.pack >> ${packlist} echo http://www.keil.com/pack/Keil.MDK-Middleware.7.11.1.pack >> ${packlist} cp_install.sh ${packlist} exit 0
<reponame>justinnk/mason-ssa /* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.justinnk.masonssa.extension.ssa; import org.justinnk.masonssa.extension.SSASimState; /** Base class for all SSAs that use dependencies to optimise their performance. */ public class DependencyBasedSSA extends StochasticSimulationAlgorithm { /** The action-attribute dependency relations. */ public AttributeDependencyGraph attributeDependencies; /** The action-edge dependency relations. */ public EdgeDependencyGraph edgeDependencies; /** Create a new instance of this dependency-based SSA, initialising the dependency graphs. */ public DependencyBasedSSA() { super(); this.attributeDependencies = new AttributeDependencyGraph(); this.edgeDependencies = new EdgeDependencyGraph(); } @Override public void init(SSASimState model) { super.init(model); /* Important: clear the dependencies when the simulation is rerun. */ attributeDependencies.clearAllDependencies(); edgeDependencies.clearAllDependencies(); } }
package com.finbourne.lusid.utilities; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; public class FileConfigurationLoaderTest { private FileConfigurationLoader fileConfigurationLoader; // mock dependencies private ClassLoader classLoader; private File file; private URL configURL; // param private String configFilePath = "/home/dir/secrets.json"; private String configFileUrl = "file:/home/dir/secrets.json"; @Before public void setUp() throws MalformedURLException { classLoader = mock(ClassLoader.class); file = mock(File.class); configURL = new URL(configFileUrl); fileConfigurationLoader = spy(new FileConfigurationLoader()); doReturn(classLoader).when(fileConfigurationLoader).getClassLoader(); doReturn(file).when(fileConfigurationLoader).getFile(configFilePath); } @Test public void loadConfiguration_NotInResources_ShouldLoadAbsolutePath() throws IOException { // mock class loader not finding URL in resources doReturn(null).when(classLoader).getResource(configFilePath); // mock file existing in absolute path doReturn(true).when(file).exists(); // verify returned the file from the absolute path File result = fileConfigurationLoader.loadConfiguration(configFilePath); assertThat(result, equalTo(file)); } @Test public void loadConfiguration_InResources_ShouldLoadFromResource() throws IOException { // mock class loader finding URL in resources doReturn(configURL).when(classLoader).getResource(configFilePath); // file exists if in resources doReturn(true).when(file).exists(); // verify returned the file from resources File result = fileConfigurationLoader.loadConfiguration(configFilePath); // verify getName() and not getAbsolutePath() to keep this test platform agnostic assertThat(result.getName(), equalTo("secrets.json")); // verify we did not try and load from absolute path if already found in resources verify(fileConfigurationLoader, times(0)).getFile(anyString()); } @Test(expected = IOException.class) public void loadConfiguration_NotInResourcesAndPathDoesNotExist_ShouldThrowException() throws IOException { // mock class loader not finding URL in resources doReturn(null).when(classLoader).getResource(configFilePath); // mock file does not exist in absolute path doReturn(false).when(file).exists(); // should throw an exception if nothing has been found fileConfigurationLoader.loadConfiguration(configFilePath); } }
import sys import time print(sys.argv) if len(sys.argv) != 2: print("wrong number of arguments") sys.exit(1) with open(sys.argv[1]) as inputstr: DATA = inputstr.read() START = time.time() exec(DATA) END = time.time() print(START-END)
<gh_stars>0 import {DEFAULT_FORM_SETTINGS} from "@containers/active-form/const"; import {FormConfigProps} from "./../types"; export function addFormConfigSettingsLayer(formConfig: FormConfigProps = {}):FormConfigProps { //Слои настройки формы (Из библиотеки + из global + из самой формы) let customFormConfigLayers: FormConfigProps = { ...DEFAULT_FORM_SETTINGS, ...formConfig, } return customFormConfigLayers }
<filename>config/config.go // Config is put into a different package to prevent cyclic imports in case // it is needed in several locations package config import "time" type Config struct { Period time.Duration `config:"period"` NatsHost string `config:"nats_host"` NatsMonitorPort int `config:"nats_monitor_port"` } var DefaultConfig = Config{ Period: 1 * time.Second, NatsHost: "127.0.0.1", NatsMonitorPort: 8200, }
/* * Copyright 2015-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.netconf.ctl.impl; import com.google.common.annotations.Beta; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.channel.ClientChannel; import org.apache.sshd.client.future.ConnectFuture; import org.apache.sshd.client.future.OpenFuture; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.FactoryManager; import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.onlab.util.SharedExecutors; import org.onosproject.netconf.DatastoreId; import org.onosproject.netconf.NetconfDeviceInfo; import org.onosproject.netconf.NetconfDeviceOutputEvent; import org.onosproject.netconf.NetconfDeviceOutputEvent.Type; import org.onosproject.netconf.NetconfDeviceOutputEventListener; import org.onosproject.netconf.NetconfException; import org.onosproject.netconf.NetconfSession; import org.onosproject.netconf.NetconfSessionFactory; import org.onosproject.netconf.NetconfTransportException; import org.slf4j.Logger; import static java.nio.charset.StandardCharsets.UTF_8; import static org.slf4j.LoggerFactory.getLogger; import java.io.CharArrayReader; import java.io.IOException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.List; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Implementation of a NETCONF session to talk to a device. */ public class NetconfSessionMinaImpl implements NetconfSession { private static final Logger log = getLogger(NetconfSessionMinaImpl.class); /** * NC 1.0, RFC4742 EOM sequence. */ private static final String ENDPATTERN = "]]>]]>"; private static final String MESSAGE_ID_STRING = "message-id"; private static final String HELLO = "<hello"; private static final String NEW_LINE = "\n"; private static final String END_OF_RPC_OPEN_TAG = "\">"; private static final String EQUAL = "="; private static final String NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\""; private static final String RPC_OPEN = "<rpc "; private static final String RPC_CLOSE = "</rpc>"; private static final String GET_OPEN = "<get>"; private static final String GET_CLOSE = "</get>"; private static final String WITH_DEFAULT_OPEN = "<with-defaults "; private static final String WITH_DEFAULT_CLOSE = "</with-defaults>"; private static final String DEFAULT_OPERATION_OPEN = "<default-operation>"; private static final String DEFAULT_OPERATION_CLOSE = "</default-operation>"; private static final String SUBTREE_FILTER_OPEN = "<filter type=\"subtree\">"; private static final String SUBTREE_FILTER_CLOSE = "</filter>"; private static final String EDIT_CONFIG_OPEN = "<edit-config>"; private static final String EDIT_CONFIG_CLOSE = "</edit-config>"; private static final String TARGET_OPEN = "<target>"; private static final String TARGET_CLOSE = "</target>"; // FIXME hard coded namespace nc private static final String CONFIG_OPEN = "<config xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"; private static final String CONFIG_CLOSE = "</config>"; private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; private static final String NETCONF_BASE_NAMESPACE = "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""; private static final String NETCONF_WITH_DEFAULTS_NAMESPACE = "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\""; // FIXME hard coded namespace base10 private static final String SUBSCRIPTION_SUBTREE_FILTER_OPEN = "<filter xmlns:base10=\"urn:ietf:params:xml:ns:netconf:base:1.0\" base10:type=\"subtree\">"; private static final String INTERLEAVE_CAPABILITY_STRING = "urn:ietf:params:netconf:capability:interleave:1.0"; private static final String CAPABILITY_REGEX = "<capability>\\s*(.*?)\\s*</capability>"; private static final Pattern CAPABILITY_REGEX_PATTERN = Pattern.compile(CAPABILITY_REGEX); private static final String SESSION_ID_REGEX = "<session-id>\\s*(.*?)\\s*</session-id>"; private static final Pattern SESSION_ID_REGEX_PATTERN = Pattern.compile(SESSION_ID_REGEX); private static final String HASH = "#"; private static final String LF = "\n"; private static final String MSGLEN_REGEX_PATTERN = "\n#\\d+\n"; private static final String NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0"; private static final String NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1"; private String sessionID; private final AtomicInteger messageIdInteger = new AtomicInteger(1); protected final NetconfDeviceInfo deviceInfo; private Iterable<String> onosCapabilities = ImmutableList.of(NETCONF_10_CAPABILITY, NETCONF_11_CAPABILITY); private final Set<String> deviceCapabilities = new LinkedHashSet<>(); private NetconfStreamHandler streamHandler; // FIXME ONOS-7019 key type should be revised to a String, see RFC6241 /** * Message-ID and corresponding Future waiting for response. */ private Map<Integer, CompletableFuture<String>> replies; private List<String> errorReplies; // Not sure why we need this? private boolean subscriptionConnected = false; private String notificationFilterSchema = null; private final Collection<NetconfDeviceOutputEventListener> primaryListeners = new CopyOnWriteArrayList<>(); private final Collection<NetconfSession> children = new CopyOnWriteArrayList<>(); private int connectTimeout; private int replyTimeout; private int idleTimeout; private ClientChannel channel = null; private ClientSession session = null; private SshClient client = null; public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException { this.deviceInfo = deviceInfo; replies = new ConcurrentHashMap<>(); errorReplies = new ArrayList<>(); // FIXME should not immediately start session on construction // setOnosCapabilities() is useless due to this behavior startConnection(); } public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo, List<String> capabilities) throws NetconfException { this.deviceInfo = deviceInfo; replies = new ConcurrentHashMap<>(); errorReplies = new ArrayList<>(); setOnosCapabilities(capabilities); // FIXME should not immediately start session on construction // setOnosCapabilities() is useless due to this behavior startConnection(); } private void startConnection() throws NetconfException { connectTimeout = deviceInfo.getConnectTimeoutSec().orElse( NetconfControllerImpl.netconfConnectTimeout); replyTimeout = deviceInfo.getReplyTimeoutSec().orElse( NetconfControllerImpl.netconfReplyTimeout); idleTimeout = deviceInfo.getIdleTimeoutSec().orElse( NetconfControllerImpl.netconfIdleTimeout); log.info("Connecting to {} with timeouts C:{}, R:{}, I:{}", deviceInfo, connectTimeout, replyTimeout, idleTimeout); try { startClient(); } catch (IOException e) { throw new NetconfException("Failed to establish SSH with device " + deviceInfo, e); } } private void startClient() throws IOException { client = SshClient.setUpDefaultClient(); client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout)); client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout + 15L)); client.start(); client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider()); startSession(); } // FIXME blocking @Deprecated private void startSession() throws IOException { final ConnectFuture connectFuture; connectFuture = client.connect(deviceInfo.name(), deviceInfo.ip().toString(), deviceInfo.port()) .verify(connectTimeout, TimeUnit.SECONDS); session = connectFuture.getSession(); //Using the device ssh key if possible if (deviceInfo.getKey() != null) { try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME); try { KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject()); session.addPublicKeyIdentity(kp); } catch (IOException e) { throw new NetconfException("Failed to authenticate session with device " + deviceInfo + "check key to be a valid key", e); } } } else { session.addPasswordIdentity(deviceInfo.password()); } session.auth().verify(connectTimeout, TimeUnit.SECONDS); Set<ClientSession.ClientSessionEvent> event = session.waitFor( ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH, ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED), 0); if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) { log.debug("Session closed {} {}", event, session.isClosed()); throw new NetconfException("Failed to authenticate session with device " + deviceInfo + "check the user/pwd or key"); } openChannel(); } private PublicKey getPublicKey(byte[] keyBytes, String type) throws NoSuchAlgorithmException, InvalidKeySpecException { X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance(type); return kf.generatePublic(spec); } // FIXME blocking @Deprecated private void openChannel() throws IOException { channel = session.createSubsystemChannel("netconf"); OpenFuture channelFuture = channel.open(); if (channelFuture.await(connectTimeout, TimeUnit.SECONDS)) { if (channelFuture.isOpened()) { streamHandler = new NetconfStreamThread(channel.getInvertedOut(), channel.getInvertedIn(), channel.getInvertedErr(), deviceInfo, new NetconfSessionDelegateImpl(), replies); } else { throw new NetconfException("Failed to open channel with device " + deviceInfo); } sendHello(); } } @Beta protected void startSubscriptionStream(String filterSchema) throws NetconfException { boolean openNewSession = false; if (!deviceCapabilities.contains(INTERLEAVE_CAPABILITY_STRING)) { log.info("Device {} doesn't support interleave, creating child session", deviceInfo); openNewSession = true; } else if (subscriptionConnected && notificationFilterSchema != null && !Objects.equal(filterSchema, notificationFilterSchema)) { // interleave supported and existing filter is NOT "no filtering" // and was requested with different filtering schema log.info("Cannot use existing session for subscription {} ({})", deviceInfo, filterSchema); openNewSession = true; } if (openNewSession) { log.info("Creating notification session to {} with filter {}", deviceInfo, filterSchema); NetconfSession child = new NotificationSession(deviceInfo); child.addDeviceOutputListener(new NotificationForwarder()); child.startSubscription(filterSchema); children.add(child); return; } // request to start interleaved notification session String reply = sendRequest(createSubscriptionString(filterSchema)); if (!checkReply(reply)) { throw new NetconfException("Subscription not successful with device " + deviceInfo + " with reply " + reply); } subscriptionConnected = true; } @Override public void startSubscription() throws NetconfException { if (!subscriptionConnected) { startSubscriptionStream(null); } streamHandler.setEnableNotifications(true); } @Beta @Override public void startSubscription(String filterSchema) throws NetconfException { if (!subscriptionConnected) { notificationFilterSchema = filterSchema; startSubscriptionStream(filterSchema); } streamHandler.setEnableNotifications(true); } @Beta protected String createSubscriptionString(String filterSchema) { StringBuilder subscriptionbuffer = new StringBuilder(); subscriptionbuffer.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); subscriptionbuffer.append(" <create-subscription\n"); subscriptionbuffer.append("xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\">\n"); // FIXME Only subtree filtering supported at the moment. if (filterSchema != null) { subscriptionbuffer.append(" "); subscriptionbuffer.append(SUBSCRIPTION_SUBTREE_FILTER_OPEN).append(NEW_LINE); subscriptionbuffer.append(filterSchema).append(NEW_LINE); subscriptionbuffer.append(" "); subscriptionbuffer.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE); } subscriptionbuffer.append(" </create-subscription>\n"); subscriptionbuffer.append("</rpc>\n"); subscriptionbuffer.append(ENDPATTERN); return subscriptionbuffer.toString(); } @Override public void endSubscription() throws NetconfException { if (subscriptionConnected) { streamHandler.setEnableNotifications(false); } else { throw new NetconfException("Subscription does not exist."); } } private void sendHello() throws NetconfException { String serverHelloResponse = sendRequest(createHelloString(), true); Matcher capabilityMatcher = CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse); while (capabilityMatcher.find()) { deviceCapabilities.add(capabilityMatcher.group(1)); } sessionID = String.valueOf(-1); Matcher sessionIDMatcher = SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse); if (sessionIDMatcher.find()) { sessionID = sessionIDMatcher.group(1); } else { throw new NetconfException("Missing SessionID in server hello " + "reponse."); } } private String createHelloString() { StringBuilder hellobuffer = new StringBuilder(); hellobuffer.append(XML_HEADER); hellobuffer.append("\n"); hellobuffer.append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); hellobuffer.append(" <capabilities>\n"); onosCapabilities.forEach( cap -> hellobuffer.append(" <capability>") .append(cap) .append("</capability>\n")); hellobuffer.append(" </capabilities>\n"); hellobuffer.append("</hello>\n"); hellobuffer.append(ENDPATTERN); return hellobuffer.toString(); } @Override public void checkAndReestablish() throws NetconfException { try { if (client.isClosed()) { log.debug("Trying to restart the whole SSH connection with {}", deviceInfo.getDeviceId()); cleanUp(); startConnection(); } else if (session.isClosed()) { log.debug("Trying to restart the session with {}", session, deviceInfo.getDeviceId()); cleanUp(); startSession(); } else if (channel.isClosed()) { log.debug("Trying to reopen the channel with {}", deviceInfo.getDeviceId()); cleanUp(); openChannel(); } else { return; } if (subscriptionConnected) { log.debug("Restarting subscription with {}", deviceInfo.getDeviceId()); subscriptionConnected = false; startSubscription(notificationFilterSchema); } } catch (IOException | IllegalStateException e) { log.error("Can't reopen connection for device {}", e.getMessage()); throw new NetconfException("Cannot re-open the connection with device" + deviceInfo, e); } } private void cleanUp() { //makes sure everything is at a clean state. replies.clear(); } @Override public String requestSync(String request) throws NetconfException { String reply = sendRequest(request); checkReply(reply); return reply; } // FIXME rename to align with what it actually do /** * Validate and format netconf message. * - NC1.0 if no EOM sequence present on {@code message}, append. * - NC1.1 chunk-encode given message unless it already is chunk encoded * * @param message to format * @return formated message */ private String formatNetconfMessage(String message) { if (deviceCapabilities.contains(NETCONF_11_CAPABILITY)) { message = formatChunkedMessage(message); } else { if (!message.endsWith(ENDPATTERN)) { message = message + NEW_LINE + ENDPATTERN; } } return message; } /** * Validate and format message according to chunked framing mechanism. * * @param message to format * @return formated message */ private String formatChunkedMessage(String message) { if (message.endsWith(ENDPATTERN)) { // message given had Netconf 1.0 EOM pattern -> remove message = message.substring(0, message.length() - ENDPATTERN.length()); } if (!message.startsWith(LF + HASH)) { // chunk encode message message = LF + HASH + message.getBytes(UTF_8).length + LF + message + LF + HASH + HASH + LF; } return message; } @Override @Deprecated public CompletableFuture<String> request(String request) { return streamHandler.sendMessage(request); } /** * {@inheritDoc} * <p> * FIXME Note: as of 1.12.0 * {@code request} must not include message-id, this method will assign * and insert message-id on it's own. * Will require ONOS-7019 to remove this limitation. */ @Override public CompletableFuture<String> rpc(String request) { String rpc = request; // - assign message-id int msgId = messageIdInteger.incrementAndGet(); // - re-write request to insert message-id // FIXME avoid using formatRequestMessageId rpc = formatRequestMessageId(rpc, msgId); // - ensure it contains XML header rpc = formatXmlHeader(rpc); // - use chunked framing if talking to NC 1.1 device // FIXME avoid using formatNetconfMessage rpc = formatNetconfMessage(rpc); // TODO session liveness check & recovery log.debug("Sending {} to {}", rpc, this.deviceInfo.getDeviceId()); return streamHandler.sendMessage(rpc, msgId) .handleAsync((reply, t) -> { if (t != null) { // secure transport-layer error // cannot use NetconfException, which is // checked Exception. throw new NetconfTransportException(t); } else { // FIXME avoid using checkReply, error handling is weird checkReply(reply); return reply; } }, SharedExecutors.getPoolThreadExecutor()); } @Override public int timeoutConnectSec() { return connectTimeout; } @Override public int timeoutReplySec() { return replyTimeout; } @Override public int timeoutIdleSec() { return idleTimeout; } private CompletableFuture<String> request(String request, int messageId) { return streamHandler.sendMessage(request, messageId); } private String sendRequest(String request) throws NetconfException { // FIXME probably chunk-encoding too early request = formatNetconfMessage(request); return sendRequest(request, false); } private String sendRequest(String request, boolean isHello) throws NetconfException { checkAndReestablish(); int messageId = -1; if (!isHello) { messageId = messageIdInteger.getAndIncrement(); } // FIXME potentially re-writing chunked encoded String? request = formatXmlHeader(request); request = formatRequestMessageId(request, messageId); log.debug("Sending request to NETCONF with timeout {} for {}", replyTimeout, deviceInfo.name()); CompletableFuture<String> futureReply = request(request, messageId); String rp; try { rp = futureReply.get(replyTimeout, TimeUnit.SECONDS); replies.remove(messageId); // Why here??? } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new NetconfException("Interrupted waiting for reply for request" + request, e); } catch (TimeoutException e) { throw new NetconfException("Timed out waiting for reply for request " + request + " after " + replyTimeout + " sec.", e); } catch (ExecutionException e) { log.warn("Closing session {} for {} due to unexpected Error", sessionID, deviceInfo, e); try { session.close(); channel.close(); //Closes the socket which should interrupt NetconfStreamThread client.close(); } catch (IOException ioe) { log.warn("Error closing session {} on {}", sessionID, deviceInfo, ioe); } NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent( NetconfDeviceOutputEvent.Type.SESSION_CLOSED, null, "Closed due to unexpected error " + e.getCause(), Optional.of(-1), deviceInfo); publishEvent(event); errorReplies.clear(); // move to cleanUp()? cleanUp(); throw new NetconfException("Closing session " + sessionID + " for " + deviceInfo + " for request " + request, e); } log.debug("Result {} from request {} to device {}", rp, request, deviceInfo); return rp.trim(); } private String formatRequestMessageId(String request, int messageId) { if (request.contains(MESSAGE_ID_STRING)) { //FIXME if application provides his own counting of messages this fails that count // FIXME assumes message-id is integer. RFC6241 allows anything as long as it is allowed in XML request = request.replaceFirst(MESSAGE_ID_STRING + EQUAL + NUMBER_BETWEEN_QUOTES_MATCHER, MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\""); } else if (!request.contains(MESSAGE_ID_STRING) && !request.contains(HELLO)) { //FIXME find out a better way to enforce the presence of message-id request = request.replaceFirst(END_OF_RPC_OPEN_TAG, "\" " + MESSAGE_ID_STRING + EQUAL + "\"" + messageId + "\"" + ">"); } request = updateRequestLength(request); return request; } private String updateRequestLength(String request) { if (request.contains(LF + HASH + HASH + LF)) { int oldLen = Integer.parseInt(request.split(HASH)[1].split(LF)[0]); String rpcWithEnding = request.substring(request.indexOf('<')); String firstBlock = request.split(MSGLEN_REGEX_PATTERN)[1].split(LF + HASH + HASH + LF)[0]; int newLen = 0; newLen = firstBlock.getBytes(UTF_8).length; if (oldLen != newLen) { return LF + HASH + newLen + LF + rpcWithEnding; } } return request; } /** * Ensures xml start directive/declaration appears in the {@code request}. * @param request RPC request message * @return XML RPC message */ private String formatXmlHeader(String request) { if (!request.contains(XML_HEADER)) { //FIXME if application provides his own XML header of different type there is a clash if (request.startsWith(LF + HASH)) { request = request.split("<")[0] + XML_HEADER + request.substring(request.split("<")[0].length()); } else { request = XML_HEADER + "\n" + request; } } return request; } @Override public String doWrappedRpc(String request) throws NetconfException { StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append(RPC_OPEN); rpc.append(MESSAGE_ID_STRING); rpc.append(EQUAL); rpc.append("\""); rpc.append(messageIdInteger.get()); rpc.append("\" "); rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); rpc.append(request); rpc.append(RPC_CLOSE).append(NEW_LINE); rpc.append(ENDPATTERN); String reply = sendRequest(rpc.toString()); checkReply(reply); return reply; } @Override public String get(String request) throws NetconfException { return requestSync(request); } @Override public String get(String filterSchema, String withDefaultsMode) throws NetconfException { StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append(RPC_OPEN); rpc.append(MESSAGE_ID_STRING); rpc.append(EQUAL); rpc.append("\""); rpc.append(messageIdInteger.get()); rpc.append("\" "); rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); rpc.append(GET_OPEN).append(NEW_LINE); if (filterSchema != null) { rpc.append(SUBTREE_FILTER_OPEN).append(NEW_LINE); rpc.append(filterSchema).append(NEW_LINE); rpc.append(SUBTREE_FILTER_CLOSE).append(NEW_LINE); } if (withDefaultsMode != null) { rpc.append(WITH_DEFAULT_OPEN).append(NETCONF_WITH_DEFAULTS_NAMESPACE).append(">"); rpc.append(withDefaultsMode).append(WITH_DEFAULT_CLOSE).append(NEW_LINE); } rpc.append(GET_CLOSE).append(NEW_LINE); rpc.append(RPC_CLOSE).append(NEW_LINE); rpc.append(ENDPATTERN); String reply = sendRequest(rpc.toString()); checkReply(reply); return reply; } @Override public String getConfig(DatastoreId netconfTargetConfig) throws NetconfException { return getConfig(netconfTargetConfig, null); } @Override public String getConfig(DatastoreId netconfTargetConfig, String configurationSchema) throws NetconfException { StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append("<rpc "); rpc.append(MESSAGE_ID_STRING); rpc.append(EQUAL); rpc.append("\""); rpc.append(messageIdInteger.get()); rpc.append("\" "); rpc.append("xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); rpc.append("<get-config>\n"); rpc.append("<source>\n"); rpc.append("<").append(netconfTargetConfig).append("/>"); rpc.append("</source>"); if (configurationSchema != null) { rpc.append("<filter type=\"subtree\">\n"); rpc.append(configurationSchema).append("\n"); rpc.append("</filter>\n"); } rpc.append("</get-config>\n"); rpc.append("</rpc>\n"); rpc.append(ENDPATTERN); String reply = sendRequest(rpc.toString()); return checkReply(reply) ? reply : "ERROR " + reply; } @Override public boolean editConfig(String newConfiguration) throws NetconfException { if (!newConfiguration.endsWith(ENDPATTERN)) { newConfiguration = newConfiguration + ENDPATTERN; } return checkReply(sendRequest(newConfiguration)); } @Override public boolean editConfig(DatastoreId netconfTargetConfig, String mode, String newConfiguration) throws NetconfException { newConfiguration = newConfiguration.trim(); StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append(RPC_OPEN); rpc.append(MESSAGE_ID_STRING); rpc.append(EQUAL); rpc.append("\""); rpc.append(messageIdInteger.get()); rpc.append("\" "); rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); rpc.append(EDIT_CONFIG_OPEN).append("\n"); rpc.append(TARGET_OPEN); rpc.append("<").append(netconfTargetConfig).append("/>"); rpc.append(TARGET_CLOSE).append("\n"); if (mode != null) { rpc.append(DEFAULT_OPERATION_OPEN); rpc.append(mode); rpc.append(DEFAULT_OPERATION_CLOSE).append("\n"); } rpc.append(CONFIG_OPEN).append("\n"); rpc.append(newConfiguration); rpc.append(CONFIG_CLOSE).append("\n"); rpc.append(EDIT_CONFIG_CLOSE).append("\n"); rpc.append(RPC_CLOSE); rpc.append(ENDPATTERN); log.debug("{}", rpc); String reply = sendRequest(rpc.toString()); return checkReply(reply); } @Override public boolean copyConfig(DatastoreId destination, DatastoreId source) throws NetconfException { return bareCopyConfig(destination.asXml(), source.asXml()); } @Override public boolean copyConfig(DatastoreId netconfTargetConfig, String newConfiguration) throws NetconfException { return bareCopyConfig(netconfTargetConfig.asXml(), normalizeCopyConfigParam(newConfiguration)); } @Override public boolean copyConfig(String netconfTargetConfig, String newConfiguration) throws NetconfException { return bareCopyConfig(normalizeCopyConfigParam(netconfTargetConfig), normalizeCopyConfigParam(newConfiguration)); } /** * Normalize String parameter passed to copy-config API. * <p> * Provided for backward compatibility purpose * * @param input passed to copyConfig API * @return XML likely to be suitable for copy-config source or target */ private static CharSequence normalizeCopyConfigParam(String input) { input = input.trim(); if (input.startsWith("<url")) { return input; } else if (!input.startsWith("<")) { // assume it is a datastore name return DatastoreId.datastore(input).asXml(); } else if (!input.startsWith("<config>")) { return "<config>" + input + "</config>"; } return input; } private boolean bareCopyConfig(CharSequence target, CharSequence source) throws NetconfException { StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append(RPC_OPEN); rpc.append(NETCONF_BASE_NAMESPACE).append(">\n"); rpc.append("<copy-config>"); rpc.append("<target>"); rpc.append(target); rpc.append("</target>"); rpc.append("<source>"); rpc.append(source); rpc.append("</source>"); rpc.append("</copy-config>"); rpc.append("</rpc>"); rpc.append(ENDPATTERN); return checkReply(sendRequest(rpc.toString())); } @Override public boolean deleteConfig(DatastoreId netconfTargetConfig) throws NetconfException { if (netconfTargetConfig.equals(DatastoreId.RUNNING)) { log.warn("Target configuration for delete operation can't be \"running\"", netconfTargetConfig); return false; } StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append("<rpc>"); rpc.append("<delete-config>"); rpc.append("<target>"); rpc.append("<").append(netconfTargetConfig).append("/>"); rpc.append("</target>"); rpc.append("</delete-config>"); rpc.append("</rpc>"); rpc.append(ENDPATTERN); return checkReply(sendRequest(rpc.toString())); } @Override public boolean lock(DatastoreId configType) throws NetconfException { StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); rpc.append("<lock>"); rpc.append("<target>"); rpc.append("<"); rpc.append(configType.id()); rpc.append("/>"); rpc.append("</target>"); rpc.append("</lock>"); rpc.append("</rpc>"); rpc.append(ENDPATTERN); String lockReply = sendRequest(rpc.toString()); return checkReply(lockReply); } @Override public boolean unlock(DatastoreId configType) throws NetconfException { StringBuilder rpc = new StringBuilder(XML_HEADER); rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"); rpc.append("<unlock>"); rpc.append("<target>"); rpc.append("<"); rpc.append(configType.id()); rpc.append("/>"); rpc.append("</target>"); rpc.append("</unlock>"); rpc.append("</rpc>"); rpc.append(ENDPATTERN); String unlockReply = sendRequest(rpc.toString()); return checkReply(unlockReply); } @Override public boolean close() throws NetconfException { return close(false); } private boolean close(boolean force) throws NetconfException { StringBuilder rpc = new StringBuilder(); rpc.append("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"); if (force) { rpc.append("<kill-session/>"); } else { rpc.append("<close-session/>"); } rpc.append("</rpc>"); rpc.append(ENDPATTERN); return checkReply(sendRequest(rpc.toString())) || close(true); } @Override public String getSessionId() { return sessionID; } @Override public Set<String> getDeviceCapabilitiesSet() { return Collections.unmodifiableSet(deviceCapabilities); } @Override public void setOnosCapabilities(Iterable<String> capabilities) { onosCapabilities = capabilities; } @Override public void addDeviceOutputListener(NetconfDeviceOutputEventListener listener) { streamHandler.addDeviceEventListener(listener); primaryListeners.add(listener); } @Override public void removeDeviceOutputListener(NetconfDeviceOutputEventListener listener) { primaryListeners.remove(listener); streamHandler.removeDeviceEventListener(listener); } private boolean checkReply(String reply) { if (reply != null) { if (!reply.contains("<rpc-error>")) { log.debug("Device {} sent reply {}", deviceInfo, reply); return true; } else if (reply.contains("<ok/>") || (reply.contains("<rpc-error>") && reply.contains("warning"))) { // FIXME rpc-error with a warning is considered same as Ok?? log.debug("Device {} sent reply {}", deviceInfo, reply); return true; } } log.warn("Device {} has error in reply {}", deviceInfo, reply); return false; } protected void publishEvent(NetconfDeviceOutputEvent event) { primaryListeners.forEach(lsnr -> { if (lsnr.isRelevant(event)) { lsnr.event(event); } }); } static class NotificationSession extends NetconfSessionMinaImpl { private String notificationFilter; NotificationSession(NetconfDeviceInfo deviceInfo) throws NetconfException { super(deviceInfo); } @Override protected void startSubscriptionStream(String filterSchema) throws NetconfException { notificationFilter = filterSchema; requestSync(createSubscriptionString(filterSchema)); } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("deviceInfo", deviceInfo) .add("sessionID", getSessionId()) .add("notificationFilter", notificationFilter) .toString(); } } /** * Listener attached to child session for notification streaming. * <p> * Forwards all notification event from child session to primary session * listeners. */ private final class NotificationForwarder implements NetconfDeviceOutputEventListener { @Override public boolean isRelevant(NetconfDeviceOutputEvent event) { return event.type() == Type.DEVICE_NOTIFICATION; } @Override public void event(NetconfDeviceOutputEvent event) { publishEvent(event); } } public class NetconfSessionDelegateImpl implements NetconfSessionDelegate { @Override public void notify(NetconfDeviceOutputEvent event) { Optional<Integer> messageId = event.getMessageID(); log.debug("messageID {}, waiting replies messageIDs {}", messageId, replies.keySet()); if (!messageId.isPresent()) { errorReplies.add(event.getMessagePayload()); log.error("Device {} sent error reply {}", event.getDeviceInfo(), event.getMessagePayload()); return; } CompletableFuture<String> completedReply = replies.get(messageId.get()); // remove(..)? if (completedReply != null) { completedReply.complete(event.getMessagePayload()); } } } public static class MinaSshNetconfSessionFactory implements NetconfSessionFactory { @Override public NetconfSession createNetconfSession(NetconfDeviceInfo netconfDeviceInfo) throws NetconfException { return new NetconfSessionMinaImpl(netconfDeviceInfo); } } }
const $ = element => document.querySelector(element); const $l = element => document.querySelectorAll(element); // Introduction function displayIntro() { if (!localStorage.getItem('intro-displayed')) { $('.overlay').style.display = 'block'; } else { $('body').style.overflow = 'visible'; $('.overlay').style.display = 'none'; $('.overlay-2').style.display = 'none'; } } function saveToStorage() { localStorage.setItem('intro-displayed', true); } function fadeOut() { TweenMax.to(".intro-btn", 1, { y: -100, opacity: 0 }); TweenMax.to(".screen", 2, { y: -400, opacity: 0, ease: Power2.easeInOut, delay: 2 }); TweenMax.from(".overlay", 2, { ease: Power2.easeInOut }); TweenMax.to(".overlay", 2, { delay: 2.6, top: "-110%", ease: Expo.easeInOut }); TweenMax.to(".overlay-2", 2, { delay: 3, top: "-110%", ease: Expo.easeInOut }); } // Header const bodyElement = $('body'); const warnElement = $('#unofficial-header'); const headerElement = $('.header-bg'); const leftMenuElement = $('.menu-left'); function setMenuPosition() { let prevScrollpos = window.pageYOffset; window.addEventListener('scroll', () => { let currentScrollpos = window.pageYOffset; if (prevScrollpos > currentScrollpos) { if (currentScrollpos === 0 && warnElement.style.display !== "none") { headerElement.style.top = "32px"; } else { headerElement.style.top = "0px"; } leftMenuElement.style.top = "105px"; } else { headerElement.style.top = "-73px"; leftMenuElement.style.top = "0px"; } prevScrollpos = currentScrollpos; }); } function setDesktopHeader() { headerElement.style.position = "sticky"; headerElement.style.top = "32px"; headerElement.style.width = "100%"; setMenuPosition(); } if (window.screen.availWidth > 983) { setDesktopHeader(); } // Enable scroll (after introduction) function enableScroll() { bodyElement.style.overflow = "visible"; } // Close unofficial header box function closeUnofficialHeader() { warnElement.style.display = "none"; headerElement.style.top = "0px"; adaptSynopsisTitle(); } function adaptSynopsisTitle() { if (window.screen.availWidth >= 1220) { $('#title-synopsis').style.top = "118px"; } else if (window.screen.availWidth < 1220 && window.screen.availWidth >= 983) { $('#title-synopsis').style.top = "98px"; } else if (window.screen.availWidth < 983 && window.screen.availWidth >= 770) { $('#title-synopsis').style.top = "90px"; } } // Fullscreen menu for mobile devices const mobileButton = $('#burger-menu'); const fullscreenMenu = $('.fullscreen-menu'); const fullscreenList = $('.fullscreen-menu ul'); function openFullscreenMenu() { if (mobileButton.checked === true && window.screen.availWidth <= 983) { fullscreenMenu.style.height = '100vh'; fullscreenList.style.opacity = '1'; fullscreenList.style.visibility = 'visible'; bodyElement.style.overflow = "hidden"; } else { fullscreenMenu.style.height = '0vh'; fullscreenList.style.opacity = '0'; fullscreenList.style.visibility = 'hidden'; bodyElement.style.overflow = "visible"; } } function closeFullscreenMenu() { fullscreenMenu.style.height = '0vh'; fullscreenList.style.opacity = '0'; fullscreenList.style.visibility = 'hidden'; bodyElement.style.overflow = "visible"; mobileButton.checked = false; } // Scroll to section function getScrollTopByHref(element) { const id = element.getAttribute('href'); return $(id).offsetTop; } function getTargetPosition(target) { const to = getScrollTopByHref(target) - 72; scrollToPosition(to); } function scrollToPosition(to = 0) { window.scroll({ top: to, behavior: 'smooth' }); } // Listeners window.addEventListener('load', displayIntro); $('#close-box').addEventListener('click', closeUnofficialHeader); $('#burger-menu').addEventListener('click', openFullscreenMenu); $l('.menu-item[href^="#"]').forEach(item => item.addEventListener('click', event => { event.preventDefault(); if (item.closest('nav').classList.contains('fullscreen-menu')) { closeFullscreenMenu(); } getTargetPosition(event.target); })); $('.go-to-top').addEventListener('click', scrollToPosition); $('.intro-btn').addEventListener('click', () => { if (!localStorage.getItem('intro-displayed')) { saveToStorage(); } fadeOut(); setTimeout(enableScroll, 2800); }); // Service Worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('./service-worker.js') .then(reg => console.info('registered sw', reg)) .catch(err => console.error('error registering sw', err)); } // Footer copyright year const year = $('.copyright .year'); year.textContent = new Date().getFullYear();
mkdir -p build aws lambda invoke --function-name micronaut-runtime --payload '{"resource": "/{proxy+}", "path": "/ping", "httpMethod": "GET"}' build/response.txt echo "RESPONSE:" echo "---------" cat build/response.txt
import { ListTaskDefinitionsCommandInput, ListTaskDefinitionsCommandOutput } from "../commands/ListTaskDefinitionsCommand"; import { ECSPaginationConfiguration } from "./Interfaces"; import { Paginator } from "@aws-sdk/types"; export declare function paginateListTaskDefinitions(config: ECSPaginationConfiguration, input: ListTaskDefinitionsCommandInput, ...additionalArguments: any): Paginator<ListTaskDefinitionsCommandOutput>;
#!/bin/bash # Module specific variables go here # Files: file=/path/to/file # Arrays: declare -a array_name # Strings: foo="bar" # Integers: x=9 ############################################### # Bootstrapping environment setup ############################################### # Get our working directory cwd="$(pwd)" # Define our bootstrapper location bootstrap="${cwd}/tools/bootstrap.sh" # Bail if it cannot be found if [ ! -f ${bootstrap} ]; then echo "Unable to locate bootstrap; ${bootstrap}" && exit 1 fi # Load our bootstrap source ${bootstrap} ############################################### # Metrics start ############################################### # Get EPOCH s_epoch="$(gen_epoch)" # Create a timestamp timestamp="$(gen_date)" # Whos is calling? 0 = singular, 1 is as group caller=$(ps $PPID | grep -c stigadm) ############################################### # Perform restoration ############################################### # If ${restore} = 1 go to restoration mode if [ ${restore} -eq 1 ]; then report "Not yet implemented" && exit 1 fi ############################################### # STIG validation/remediation ############################################### # Module specific validation code should go here # Errors should go in ${errors[@]} array (which on remediation get handled) # All inspected items should go in ${inspected[@]} array errors=("${stigid}") # If ${change} = 1 #if [ ${change} -eq 1 ]; then # Create the backup env #backup_setup_env "${backup_path}" # Create a backup (configuration output, file/folde permissions output etc #bu_configuration "${backup_path}" "${author}" "${stigid}" "$(echo "${array_values[@]}" | tr ' ' '\n')" #bu_file "${backup_path}" "${author}" "${stigid}" "${file}" #if [ $? -ne 0 ]; then # Stop, we require a backup #report "Unable to create backup" && exit 1 #fi # Iterate ${errors[@]} #for error in ${errors[@]}; do # Work to remediate ${error} should go here #done #fi # Remove dupes #inspected=( $(remove_duplicates "${inspected[@]}") ) ############################################### # Results for printable report ############################################### # If ${#errors[@]} > 0 if [ ${#errors[@]} -gt 0 ]; then # Set ${results} error message #results="Failed validation" UNCOMMENT ONCE WORK COMPLETE! results="Not yet implemented!" fi # Set ${results} passed message [ ${#errors[@]} -eq 0 ] && results="Passed validation" ############################################### # Report generation specifics ############################################### # Apply some values expected for report footer [ ${#errors[@]} -eq 0 ] && passed=1 || passed=0 [ ${#errors[@]} -gt 0 ] && failed=1 || failed=0 # Calculate a percentage from applied modules & errors incurred percentage=$(percent ${passed} ${failed}) # If the caller was only independant if [ ${caller} -eq 0 ]; then # Show failures [ ${#errors[@]} -gt 0 ] && print_array ${log} "errors" "${errors[@]}" # Provide detailed results to ${log} if [ ${verbose} -eq 1 ]; then # Print array of failed & validated items [ ${#inspected[@]} -gt 0 ] && print_array ${log} "validated" "${inspected[@]}" fi # Generate the report report "${results}" # Display the report cat ${log} else # Since we were called from stigadm module_header "${results}" # Show failures [ ${#errors[@]} -gt 0 ] && print_array ${log} "errors" "${errors[@]}" # Provide detailed results to ${log} if [ ${verbose} -eq 1 ]; then # Print array of failed & validated items [ ${#inspected[@]} -gt 0 ] && print_array ${log} "validated" "${inspected[@]}" fi # Finish up the module specific report module_footer fi ############################################### # Return code for larger report ############################################### # Return an error/success code (0/1) exit ${#errors[@]} # Date: 2018-09-18 # # Severity: CAT-II # Classification: UNCLASSIFIED # STIG_ID: V004430 # STIG_Version: SV-27372r1 # Rule_ID: GEN003260 # # OS: AIX # Version: 6.1 # Architecture: # # Title: The cron.deny file must be owned by root, bin, or sys. # Description: The cron.deny file must be owned by root, bin, or sys.
#!/bin/bash # Builds docs in docs/. # # Run this in the container. cd docs make html
<gh_stars>0 import { inject as service } from '@ember/service'; import ModalComponent from 'ember-modal-service/components/modal'; export default ModalComponent.extend({ modal: service(), actions: { closeModal() { this.get('modal').close(); return false; }, } });
package ru.job4j.collecion; import java.util.HashMap; public class UsageMap { public static void main(String[] args) { HashMap<String, String> map = new HashMap<>(); map.put("<EMAIL>", "<NAME>"); map.put("<EMAIL>", "<NAME>"); map.put("<EMAIL>", "<NAME>"); for (String key : map.keySet()) { String value = map.get(key); System.out.println(key + " = " + value); } } }
<filename>artifacts/javaagent-dumper/ui/src/main/java/net/community/chest/javaagent/dumper/ui/tree/NodeExpansionHandler.java /* * */ package net.community.chest.javaagent.dumper.ui.tree; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import net.community.chest.awt.attributes.Selectible; import net.community.chest.javaagent.dumper.data.AbstractInfo; import net.community.chest.javaagent.dumper.ui.data.SelectibleClassInfo; import net.community.chest.javaagent.dumper.ui.data.SelectibleMethodInfo; import net.community.chest.javaagent.dumper.ui.data.SelectiblePackageInfo; /** * <P>Copyright as per GPLv2</P> * @author <NAME>. * @since Aug 14, 2011 2:52:18 PM */ public class NodeExpansionHandler extends MouseAdapter implements TreeWillExpandListener, TreeExpansionListener, TreeSelectionListener { private final JTree _tree; public NodeExpansionHandler (final JTree tree) { _tree = tree; } /* * @see javax.swing.event.TreeWillExpandListener#treeWillExpand(javax.swing.event.TreeExpansionEvent) */ @Override public void treeWillExpand (TreeExpansionEvent event) throws ExpandVetoException { handleExpansionEvent(event); } /* * @see javax.swing.event.TreeExpansionListener#treeExpanded(javax.swing.event.TreeExpansionEvent) */ @Override public void treeExpanded (TreeExpansionEvent event) { handleExpansionEvent(event); } /* * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) */ @Override public void valueChanged (TreeSelectionEvent e) { handleExpansionEvent(e.getNewLeadSelectionPath()); } /* * @see javax.swing.event.TreeWillExpandListener#treeWillCollapse(javax.swing.event.TreeExpansionEvent) */ @Override public void treeWillCollapse (TreeExpansionEvent event) throws ExpandVetoException { // ignored } /* * @see javax.swing.event.TreeExpansionListener#treeCollapsed(javax.swing.event.TreeExpansionEvent) */ @Override public void treeCollapsed (TreeExpansionEvent event) { // ignored } /* Interpret double click as collapse/expand - the opposite of whatever is * ths current state of the selected node * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked (final MouseEvent e) { if ((e == null) || (!SwingUtilities.isLeftMouseButton(e)) || (e.getClickCount() < 2)) return; final TreePath selPath=_tree.getSelectionPath(); final TreeNode selNode=(TreeNode) ((selPath == null) ? null : selPath.getLastPathComponent()); if (selNode == null) return; if (!_tree.isExpanded(selPath)) handleExpansionEvent(selPath); } protected void handleExpansionEvent (TreeExpansionEvent event) { handleExpansionEvent(event.getPath()); } protected void handleExpansionEvent (final TreePath selPath) { final TreeNode selNode=(TreeNode) ((selPath == null) ? null : selPath.getLastPathComponent()); if (selNode == null) return; final int numChildren=selNode.getChildCount(); if ((numChildren > 0) || (selNode instanceof MethodNode)) return; // skip if already expanded or nothing to expand if (selNode instanceof PackageNode) nodeStructureChanged(selPath, expandPackageNode((PackageNode) selNode)); else if (selNode instanceof ClassNode) nodeStructureChanged(selPath, expandClassNode((ClassNode) selNode)); } protected PackageNode expandPackageNode (final PackageNode node) { final SelectiblePackageInfo info=node.getAssignedValue(); final List<SelectibleClassInfo> classes=new ArrayList<SelectibleClassInfo>(info); Collections.sort(classes, SelectibleClassInfo.BY_SIMPLE_NAME_COMP); for (final SelectibleClassInfo clsInfo : classes) { if (!clsInfo.isPublic()) // show only public classes continue; node.add(new ClassNode(clsInfo)); } return node; } protected ClassNode expandClassNode (final ClassNode node) { final SelectibleClassInfo info=node.getAssignedValue(); @SuppressWarnings({ "rawtypes", "unchecked" }) final List<SelectibleMethodInfo> methods= new ArrayList<SelectibleMethodInfo>((Collection) info.getMethods()); Collections.sort(methods, AbstractInfo.BY_NAME_COMP); for (final SelectibleMethodInfo mthdInfo : methods) { if ((!mthdInfo.isPublic()) || mthdInfo.isConstructor()) continue; //skip constructors and non-public methods node.add(new MethodNode(mthdInfo)); } return node; } protected <S extends Selectible, N extends AbstractInfoNode<S>> N nodeStructureChanged ( final TreePath nodePath, final N node) { final DefaultTreeModel model=(DefaultTreeModel) _tree.getModel(); model.nodeStructureChanged(node); if (nodePath != null) _tree.expandPath(nodePath); return node; } }
#!/bin/bash cd ../userPanels grep TO *.svg > turnoutAddressList.tmp #remove closing xml tags perl -p -i -e 's/ \/>//g' turnoutAddressList.tmp #remove individual route segment identifiers perl -p -i -e 's/\.R//g' turnoutAddressList.tmp perl -p -i -e 's/\.N//g' turnoutAddressList.tmp #remove id perl -p -i -e 's/id=//g' turnoutAddressList.tmp #remove quotes perl -p -i -e 's/"//g' turnoutAddressList.tmp #remove colon perl -p -i -e 's/://g' turnoutAddressList.tmp #remove file extenstion perl -p -i -e 's/\.svg//g' turnoutAddressList.tmp #remove whitespace perl -p -i -e 's/ +/ /g' turnoutAddressList.tmp #remove index, indexAlt, PanelDefs.svg entries perl -p -i -e 's/^index\s.*$//g' turnoutAddressList.tmp perl -p -i -e 's/^indexAlt\s.*$//g' turnoutAddressList.tmp perl -p -i -e 's/PanelDefs\sTO\d+[A-Z]?//g' turnoutAddressList.tmp grep -v "^$" turnoutAddressList.tmp > turnoutAddressList3.tmp mv turnoutAddressList3.tmp turnoutAddressList.tmp #sort results sort -d turnoutAddressList.tmp > turnoutAddressList2.tmp mv turnoutAddressList2.tmp turnoutAddressList.tmp #remove duplicates perl -ne 'print unless $seen{$_}++' turnoutAddressList.tmp > turnoutAddressBlockRoutes.txt rm turnoutAddressList.tmp #find unique addresses cp turnoutAddressBlockRoutes.txt turnoutAddressUnique.tmp perl -p -i -e 's/[A-Z]$//g' turnoutAddressUnique.tmp #remove duplicates perl -ne 'print unless $seen{$_}++' turnoutAddressUnique.tmp > turnoutAddressBlockUnique.txt rm turnoutAddressUnique.tmp #find layout unique cp turnoutAddressBlockUnique.txt turnoutAddressLayoutUnique.txt perl -p -i -e 's/^\w+\sTO//g' turnoutAddressLayoutUnique.txt sort -g turnoutAddressLayoutUnique.txt > turnoutAddressLayoutUnique.tmp perl -ne 'print unless $seen{$_}++' turnoutAddressLayoutUnique.tmp > turnoutAddressLayoutUnique.txt rm turnoutAddressLayoutUnique.tmp #make JMRI config file entries for each turnout found cp turnoutAddressLayoutUnique.txt turnouts.xml perl -p -i -e 's/^r\d+\n//g' turnouts.xml perl -p -i -e 's/(\d+)/<turnout systemName=\"NT$1\" feedback=\"DIRECT\" inverted=\"false\" automate=\"Default\">\n\t<systemName>NT$1<\/systemName>\n<\/turnout>/g' turnouts.xml #more turnoutAddressBlockRoutes.txt #more turnoutAddressBlockUnique.txt #more turnoutAddressLayoutUnique.txt wc -l turnoutAddress*.txt cd ../core
import styled from 'styled-components' const HeaderStyle = styled.div` @media (orientation: landscape) { font-size: 1.5vw; } @media (orientation: portrait) { font-size: 2vh; } a { text-decoration: none; } a:hover { padding-bottom: 0.1em; border-bottom: 0.1em solid ${props => props.theme.textColor}; } .activePage { padding-bottom: 0.1em; border-bottom: 0.1em solid ${props => props.theme.textColor}; } header { position: fixed; z-index: 3; top: 0; left: 0; display: flex; flex-direction: row; justify-content: space-between; padding: 0.5em; width: 100%; margin: 0 auto; transition: ${props => props.theme.transition}; background-color: ${props => props.theme.bgColor}; box-shadow: ${props => (props.isScrolled ? ('0px 0px 1vh black') : 'none')}; } ` export default HeaderStyle
import { Client } from '../src/client' describe('Client#fetchPipelines', () => { beforeEach(() => { UrlFetchApp.fetch = jest.fn(() => { return { getContentText: () => ` { "pipelines": [ { "id": "595d430add03f01d32460080", "name": "New Issues", "issues": [] }, { "id": "595d430add03f01d32460081", "name": "Backlog", "issues": [] }, { "id": "595d430add03f01d32460082", "name": "To Do", "issues": [] } ] } ` } as GoogleAppsScript.URL_Fetch.HTTPResponse }) }) test('case1', () => { // arrange const workspaceId = 'myworkspace' const repositoryId = 123456789 const token = 'mytoken' // action const client = new Client(workspaceId, repositoryId, token) const pipelines = client.fetchPipelines() // assert expect(pipelines.size).toEqual(3) expect(pipelines.get('New Issues')).toEqual('595d430add03f01d32460080') expect(pipelines.get('Backlog')).toEqual('595d430add03f01d32460081') expect(pipelines.get('To Do')).toEqual('595d430add03f01d32460082') expect(UrlFetchApp.fetch).toHaveBeenCalledTimes(1) expect(UrlFetchApp.fetch).toHaveBeenLastCalledWith(`https://api.zenhub.com/p2/workspaces/${workspaceId}/repositories/${repositoryId}/board`, { method: 'get', headers: { 'Content-Type': 'application/json', 'X-Authentication-Token': token } }) }) }) describe('Client#setEstimate', () => { beforeEach(() => { UrlFetchApp.fetch = jest.fn() }) test('case1', () => { // arrange const workspaceId = 'myworkspace' const repositoryId = 123456789 const token = 'mytoken' const issueNo = 123 const estimate = 0.5 // action const client = new Client(workspaceId, repositoryId, token) client.setEstimate(issueNo, estimate) // assert expect(UrlFetchApp.fetch).toHaveBeenCalledTimes(1) expect(UrlFetchApp.fetch).toHaveBeenLastCalledWith(`https://api.zenhub.com/p1/repositories/${repositoryId}/issues/${issueNo}/estimate`, { method: 'put', headers: { 'Content-Type': 'application/json', 'X-Authentication-Token': token }, payload: JSON.stringify({estimate}) }) }) }) describe('Client#setEpic', () => { beforeEach(() => { UrlFetchApp.fetch = jest.fn() }) test('case1', () => { // arrange const workspaceId = 'myworkspace' const repositoryId = 123456789 const token = 'mytoken' const epicIssueNo = 50 const issueNo = 123 // action const client = new Client(workspaceId, repositoryId, token) client.setEpic(epicIssueNo, issueNo) // assert expect(UrlFetchApp.fetch).toHaveBeenCalledTimes(1) expect(UrlFetchApp.fetch).toHaveBeenLastCalledWith(`https://api.zenhub.com/p1/repositories/${repositoryId}/epics/${epicIssueNo}/update_issues`, { method: 'post', headers: { 'Content-Type': 'application/json', 'X-Authentication-Token': token }, payload: JSON.stringify({remove_issues: [], add_issues: [{repo_id: repositoryId, issue_number: issueNo}]}) }) }) }) describe('Client#movePipelineTo', () => { beforeEach(() => { UrlFetchApp.fetch = jest.fn() }) test('case1', () => { // arrange const workspaceId = 'myworkspace' const repositoryId = 123456789 const token = 'mytoken' const issueNo = 123 const pipelineId = 'pipeline1' // action const client = new Client(workspaceId, repositoryId, token) client.movePipelineTo(issueNo, pipelineId) // assert expect(UrlFetchApp.fetch).toHaveBeenCalledTimes(1) expect(UrlFetchApp.fetch).toHaveBeenLastCalledWith(`https://api.zenhub.com/p2/workspaces/${workspaceId}/repositories/${repositoryId}/issues/${issueNo}/moves`, { method: 'post', headers: { 'Content-Type': 'application/json', 'X-Authentication-Token': token }, payload: JSON.stringify({pipeline_id: pipelineId, position: 'top'}) }) }) })
def keyword_identification(sentence): # Preprocessing sentence = sentence.lower() sentence = re.sub(r'[^\w\s]', '', sentence) # Tokenize the sentence words = word_tokenize(sentence) keywords = [] # Identifying the keywords for word in words: if word not in stopwords: keywords.append(word) return keywords sentence = "This is an example sentence for keyword identification." print(keyword_identification(sentence)) # Output: ['example', 'sentence', 'keyword', 'identification']
<reponame>schgressive/salaclub export default ngModule => { ngModule.service('CommonService', ($http, $q, CONFIG, API_ROUTES) =>{ return { getRegions: () => { const deferred = $q.defer(); $http({ method: 'GET', url: CONFIG.apiBaseUrl + API_ROUTES.regions, }).then( (response) => { if (response.data) { deferred.resolve(response.data); } else { deferred.reject(response.data); } }, (error) => { deferred.reject(error.data); }); return deferred.promise; }, getRegionDetail: (regionId) => { const deferred = $q.defer(); $http({ method: 'GET', url: CONFIG.apiBaseUrl + API_ROUTES.regions + regionId, }).then( (response) =>{ if (response.data) { deferred.resolve(response.data); } else { deferred.reject(response.data); } }, (error) => { deferred.reject(error.data); }); return deferred.promise; }, sendMessage: (message) => { const deferred = $q.defer(); $http({ method: 'POST', url: CONFIG.apiBaseUrl + API_ROUTES.sendMessage, data: message }).then( (response) =>{ if (response.data) { deferred.resolve(response.data); } else { deferred.reject(response.data); } }, (error) => { deferred.reject(error.data); }); return deferred.promise; } }; }); };
<filename>src/scimmy.js import Types from "./lib/types.js"; import Messages from "./lib/messages.js"; import Resources from "./lib/resources.js"; import Schemas from "./lib/schemas.js"; import Config from "./lib/config.js"; /** * SCIMMY Container Class * @namespace SCIMMY * @description * SCIMMY exports a singleton class which provides the following interfaces: * * `{@link SCIMMY.Config}` * * SCIM Service Provider Configuration container store. * * `{@link SCIMMY.Types}` * * SCIMMY classes for implementing schemas and resource types. * * `{@link SCIMMY.Messages}` * * Implementations of non-resource SCIM "message" schemas, such as ListResponse and PatchOp. * * `{@link SCIMMY.Schemas}` * * Container store for declaring and retrieving schemas implemented by a service provider. * * Also provides access to bundled schema implementations of [SCIM Core Resource Schemas](https://datatracker.ietf.org/doc/html/rfc7643#section-4). * * `{@link SCIMMY.Resources}` * * Container store for declaring and retrieving resource types implemented by a service provider. * * Also provides access to bundled resource type implementations of [SCIM Core Resource Types](https://datatracker.ietf.org/doc/html/rfc7643#section-4). */ export default class SCIMMY { static Config = Config; static Types = Types; static Messages = Messages; static Schemas = Schemas; static Resources = Resources; }
package com.ifast.worker.domain; import java.io.Serializable; import java.util.Date; import java.math.BigDecimal; import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.ifast.common.base.BaseDO; import lombok.Data; import lombok.EqualsAndHashCode; /** * * <pre> * 清洁人员注册表 * </pre> * <small> 2018-11-27 14:11:44 | canxue</small> */ @Data @SuppressWarnings("serial") @TableName("db_worker") @EqualsAndHashCode(callSuper=true) public class WorkerDO extends Model<WorkerDO> implements Serializable { @TableId private Long id; /** 工牌号 */ private String workNo; /** 员工姓名 */ private String workName; /** 平台编号 */ private String platFormNo; /** 员工类型 */ private Integer workType; /** 手机 */ private String phone; /** openId */ private String openId; /** 微信 */ private String wechat; /** 头像路径 */ private String imgPath; /** 保底工资 */ private BigDecimal mininumSalary; /** */ private Integer status; /** */ private Date gmtCreate; /** */ private Date gmtModify; @Override protected Serializable pkVal() { return this.id; } }
//Variable that holds all global variables to shared between components const globals = {}; /** * Performs a get request with the specified arguments * @param {string} url The url of the endpoint that will handle the request * @param {object} args Arguments for the request * @param {callback} callback Function to handle ther response * @warning This function is meant to be use for our API and so it assumes that the response is a json object */ function GET(url, args, callback) { let req = new XMLHttpRequest(); req.responseType = 'json'; req.onreadystatechange = function() { if(this.readyState == 4 && (this.status == 200 || this.status == 204)) callback(this.response); }; const fullurl = join(url, args); req.open('get', fullurl, true); req.send(); } /** * Join the given url and arguments in new get like url * @param {string} url The url of the endpoint that will handle the request * @param {object} args Object containing the extra arguments to be appended on the url * @returns {string} The newly created get like url with the arguments appended to it */ function join(url, args) { let first = true; let fullurl = url; for(const prop in args) { if(args[prop] === '') continue; fullurl += (first ? '?' : '&') + `${prop}=${args[prop]}`; if(first) first = false; } return fullurl; } /** * Checks whether the given to keycode corresponds to a valid character * @param {number} keycode The keycode to be checked * @returns {boolean} True if the keycode coresponds to a valid character, false otherwise */ function ischar(keycode) { return (keycode > 47 && keycode < 58) || keycode == 32 || (keycode > 64 && keycode < 91) || (keycode > 95 && keycode < 112) || (keycode > 185 && keycode < 193) || (keycode > 218 && keycode < 223); } /** * Extracts get parameters from a given url * @param {String} url The url from which the get parameters will be extracted * @returns {object} Returns an object containing the parameters */ function get_params(url) { if(!url.includes('?'))//No get params return { 'page': 1 }; const raw = url.split('?')[1];//Raw parameters string const tokens = raw.split('&'); let obj = {}; for(let i = 0; i < tokens.length; i++) { const token = tokens[i]; const name = token.split('=')[0]; const value = token.split('=')[1]; obj[name] = isNaN(value) ? value : parseInt(value); } return obj; } /** * Extracts world from a given url * @param {String} url Thre url from which the world will be extracted * @returns {String} World name */ function extract_world(url) { const start = url.indexOf('/', 9) + 1; const endindex = url.indexOf('/', start); const end = endindex === -1 ? url.length : endindex; return url.substring(start, end); } /** * Format a number to a human friendly form * @param {number} num Number to be formatted * @returns {string} String containing the number in a human friendly form */ function format(num) { return (num).toLocaleString('en-us'); } /** * Transforms a given string to it's formal equivalent. It basically Capitalizes * the first letter of the string. * @param {string} str String to be formalized * @returns {string} The formal equivalent string */ function formalize(str) { return str.charAt(0).toUpperCase() + str.substring(1); } /** * Creates a date label base on the given timestamp * @param {number} timestamp Unix like timestamp in miliseconds * @returns {string[]} Two string in an array containg the date and time respectively */ function createDateLabel(timestamp) { const date = new Date(timestamp); let datestr = ''; if(date.getDate() < 10) datestr += '0'; datestr += date.getDate() + '/'; if(date.getMonth() + 1 < 10) datestr += '0'; datestr += (date.getMonth() + 1) + '/' + date.getFullYear(); let timestr = ''; if(date.getHours()<10) timestr += '0'; timestr += date.getHours() + ':'; if(date.getMinutes()<10) timestr += '0'; timestr += date.getMinutes() + ':'; if(date.getSeconds()<10) timestr += '0'; timestr += date.getSeconds(); return [datestr, timestr]; } /** * Creates a human readable string represantation for the given timestamp * @param {number} timestamp Unix like timestamp in miliseconds * @return {string} The date that was represented by the timestamp in human readable form */ function asString(timestamp) { const strings = createDateLabel(timestamp); return strings[0] + ' ' + strings[1]; } /** * Sets the url parameters for the given user input */ function build_url_params(reqobj) { let params = ''; let first = true; for(const prop in reqobj) { const value = reqobj[prop]; if (//Ingore default values (prop === 'page' && value === 1 ) || (prop === 'filter' && value === '') || (prop === 'items' && value === 12) || (prop === 'view' && value === 'overview') || (prop === 'show' && value === 'all') ) continue; params += (first ? '?' : '&') + `${prop}=${value}`; if(first) first = false; } const fullurl = document.location.pathname + params; window.history.replaceState(null, null, fullurl); }
package io.hackages.learning.domain.manager.aircraft.api; import io.hackages.learning.domain.model.Aircraft; import java.util.List; public interface AircraftService { List<Aircraft> getAircrafts(); Aircraft addAircraft(String code, String description); void deleteAircraft(String code); Aircraft changeDescription(String description); Aircraft getAircraftByCode(String code); }
<gh_stars>0 /* * Copyright (c) 2015. Seagate Technology PLC. All rights reserved. */ package com.seagate.alto.provider.example; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.dropbox.core.android.Auth; import com.seagate.alto.provider.Provider; import com.seagate.alto.provider.Providers; /** * Base class for Activities that require auth tokens. * Will redirect to auth flow if needed. */ public abstract class AuthActivity extends AppCompatActivity { public static final String USER_AGENT = "Alto-Android/0.0.1"; private Provider mProvider; protected Provider getProvider() { return mProvider; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onResume() { super.onResume(); String accessToken = getAccessToken(); if (accessToken == null) { accessToken = Auth.getOAuth2Token(); if (accessToken == null) return; saveAccessToken(accessToken); } initAndLoadData(accessToken); } protected String getAccessToken() { SharedPreferences prefs = getSharedPreferences("alto-cloud", MODE_PRIVATE); return prefs.getString("access-token", null); } protected void saveAccessToken(String accessToken) { SharedPreferences prefs = getSharedPreferences("alto-cloud", MODE_PRIVATE); prefs.edit().putString("access-token", accessToken).apply(); } private void initAndLoadData(String accessToken) { if (mProvider == null) { mProvider = Providers.LOCAL.provider; // mProvider = Providers.DROPBOX.provider; Providers.DROPBOX.provider.setAccessToken(accessToken); loadData(); } } protected abstract void loadData(); }
<reponame>sandeepdas05/lsm-crack-width<gh_stars>10-100 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include "../../util/helpers.h" /* A big ugly function for performing trilinear interpolation on * a 3d scalar field. */ double interpolate_point(double i, double j, double k, double * img, double di, double dj, double dk, // delta terms int m, int n, int p) { int ilow, ihigh, jlow, jhigh, klow, khigh; // Return zero for out-of-bounds values. if (i < 0 || i > (m-1)*di || j < 0 || j > (n-1)*dj || k < 0 || k > (p-1)*dk) { return 0.0; } i /= di; j /= dj; k /= dk; ilow = (int) i; jlow = (int) j; klow = (int) k; ihigh = ilow + 1; jhigh = jlow + 1; khigh = klow + 1; if (i < m-1 && j < n-1 && k < p-1) { // Full 3D interpolation. return (ihigh-i)*(jhigh-j)*(khigh-k)*img[mi3d(ilow , jlow , klow , m, n, p)] + (i-ilow )*(jhigh-j)*(khigh-k)*img[mi3d(ihigh, jlow , klow , m, n, p)] + (ihigh-i)*(j-jlow )*(khigh-k)*img[mi3d(ilow , jhigh, klow , m, n, p)] + (ihigh-i)*(jhigh-j)*(k-klow )*img[mi3d(ilow , jlow , khigh, m, n, p)] + (i-ilow )*(j-jlow )*(khigh-k)*img[mi3d(ihigh, jhigh, klow , m, n, p)] + (i-ilow )*(jhigh-j)*(k-klow )*img[mi3d(ihigh, jlow , khigh, m, n, p)] + (ihigh-i)*(j-jlow )*(k-klow )*img[mi3d(ilow , jhigh, khigh, m, n, p)] + (i-ilow )*(j-jlow )*(k-klow )*img[mi3d(ihigh, jhigh, khigh, m, n, p)]; } else if (i == m-1 && j < n-1 && k < p-1) { // 2D interpolation on bottom face. return (jhigh-j)*(khigh-k)*img[mi3d(m-1, jlow , klow , m, n, p)] + (j-jlow )*(khigh-k)*img[mi3d(m-1, jhigh, klow , m, n, p)] + (jhigh-j)*(k-klow )*img[mi3d(m-1, jlow , khigh, m, n, p)] + (j-jlow )*(k-klow )*img[mi3d(m-1, jhigh, khigh, m, n, p)]; } else if (i < m-1 && j == n-1 && k < p-1) { // 2D interpolation on right face. return (ihigh-i)*(khigh-k)*img[mi3d(ilow , n-1, klow , m, n, p)] + (i-ilow )*(khigh-k)*img[mi3d(ihigh, n-1, klow , m, n, p)] + (ihigh-i)*(k-klow )*img[mi3d(ilow , n-1, khigh, m, n, p)] + (i-ilow )*(k-klow )*img[mi3d(ihigh, n-1, khigh, m, n, p)]; } else if (i < m-1 && j < n-1 && k == p-1) { // 2D interpolation on back face. return (ihigh-i)*(jhigh-j)*img[mi3d(ilow , jlow , p-1, m, n, p)] + (i-ilow )*(jhigh-j)*img[mi3d(ihigh, jlow , p-1, m, n, p)] + (ihigh-i)*(j-jlow )*img[mi3d(ilow , jhigh, p-1, m, n, p)] + (i-ilow )*(j-jlow )*img[mi3d(ihigh, jhigh, p-1, m, n, p)]; } else if (i == m-1 && j == n-1 && k < p-1) { // 1D interpolation along bottom right edge. return (khigh-k)*img[mi3d(m-1, n-1, klow , m, n, p)] + (k-klow )*img[mi3d(m-1, n-1, khigh, m, n, p)]; } else if (i == m-1 && j < n-1 && k == p-1) { // 1D interpolation along back bottom edge. return (jhigh-j)*img[mi3d(m-1, jlow , p-1, m, n, p)] + (j-jlow )*img[mi3d(m-1, jhigh, p-1, m, n, p)]; } else if (i < m-1 && j == n-1 && k == p-1) { // 1D interpolation along back, right edge. // _ // /_/|<- // |_|/ return (ihigh-i)*img[mi3d(ilow , n-1, p-1, m, n, p)] + (i-ilow )*img[mi3d(ihigh, n-1, p-1, m, n, p)]; } else { return img[mi3d(m-1, n-1, p-1, m, n, p)]; } } //void interpolate(double * igrid, double * jgrid, double * kgrid, // int q, int r, int s, double * img, int m, int n, int p, // double * irp) { // int l; // // for (int i=0; i < q; i++) { // for (int j=0; j < r; j++) { // for (int k=0; k < s; k++) { // l = mi3d(i,j,k,q,r,s); // irp[l] = interpolate_point(igrid[l], jgrid[l], kgrid[l], // img, m, n, p); // } // } // } //}
package com.github.bingoohuang.blackcat.agent.collectors; import org.gridkit.lab.sigar.SigarFactory; import org.hyperic.sigar.SigarProxy; public class SigarSingleton { public static final SigarProxy SIGAR = SigarFactory.newSigar(); }
#!/bin/bash # Install public key for root set -e HOST=$1 if [ -z "$HOST" ]; then echo "Missing host argument." echo "Usage: install-root-public-key.sh <host>" exit 1 fi install_public_key() { PUBKEY_FILE=~/.ssh/id_rsa.pub echo "Using public key from $PUBKEY_FILE" PUBKEY=$(cat ~/.ssh/id_rsa.pub) if [ -z "$PUBKEY" ]; then echo "Empty public key" exit 1 fi ssh root@$HOST 'bash -s' <<EOF set -e mkdir -p /root/.ssh chmod 700 /root/.ssh cat <<INNER_EOF> /root/.ssh/authorized_keys $PUBKEY INNER_EOF EOF } RESULT=FAIL report_result() { echo $RESULT } trap "report_result;" EXIT install_public_key $HOST RESULT=OK
<filename>app/controllers/membership_controller.rb class MembershipsController < ApplicationController inherit_resources defaults :resource_class => Membership, :collection_name => 'memberships', :instance_name => 'membership' belongs_to :project, :finder => :get, :parent_class => Yogo::Project belongs_to :user, :finder => :get belongs_to :role, :finder => :get respond_to :html, :json def create if params.has_key?(:project_id) @project = Yogo::Project.get(params[:project_id]) else @project = Yogo::Project.get(params[:id]) end if params.has_key?(:user_id) @users = [User.get(params[:user_id])] else @users = params[:memberships][:users].map { |idx| User.get(idx) } end @roles = params[:memberships][:roles].map { |idx| Role.get(idx) } @users.each do |u| @roles.each do |r| Membership.create(:user => u, :role => r, :project => @project) end end redirect_to(:back) end def destroy if params.has_key?(:project_id) @project = Yogo::Project.get(params[:project_id]) else @project = Yogo::Project.get(params[:id]) end if params.has_key?(:user_id) @user = User.get([params[:user_id]]) else @user = User.get(params[:id]) end memberships = Membership.all(:user => @user, :project => @project) memberships.destroy redirect_to(:back) end def edit if params.has_key?(:project_id) @project = Yogo::Project.get(params[:project_id]) else @project = Yogo::Project.get(params[:id]) end if params.has_key?(:user_id) @user = User.get([params[:user_id]]) else @user = User.get(params[:id]) end @role_names = Role.all(:id => Membership.all(:project => @project, :user => @user).map { |m| m.role_id }).map { |r| r.name } respond_to do |format| format.html end end def update @project = Yogo::Project.get(params[:project_id]) @user = User.get(params[:id]) @roles = params[:memberships][:roles].map { |rid| Role.get(rid) } memberships = Membership.all(:user => @user, :project => @project) memberships.destroy @roles.each do |role| Membership.create(:user => @user, :project => @project, :role => role) end redirect_to(edit_yogo_project_url(@project)) end end
#!/bin/sh erlc hw.erl erl -noshell -s hw start -s init stop ./hw2.erl
<filename>src/main/java/fr/clementgre/pdf4teachers/interfaces/windows/gallery/GalleryWindow.java package fr.clementgre.pdf4teachers.interfaces.windows.gallery; import fr.clementgre.pdf4teachers.Main; import fr.clementgre.pdf4teachers.components.HBoxSpacer; import fr.clementgre.pdf4teachers.components.SliderWithoutPopup; import fr.clementgre.pdf4teachers.interfaces.autotips.AutoTipsManager; import fr.clementgre.pdf4teachers.interfaces.windows.MainWindow; import fr.clementgre.pdf4teachers.interfaces.windows.language.TR; import fr.clementgre.pdf4teachers.panel.sidebar.paint.gridviewfactory.ImageGridElement; import fr.clementgre.pdf4teachers.panel.sidebar.paint.gridviewfactory.ImageGridView; import fr.clementgre.pdf4teachers.panel.sidebar.paint.gridviewfactory.ShapesGridView; import fr.clementgre.pdf4teachers.utils.panes.PaneUtils; import fr.clementgre.pdf4teachers.utils.PlatformUtils; import fr.clementgre.pdf4teachers.utils.image.ImageUtils; import fr.clementgre.pdf4teachers.utils.svg.SVGPathIcons; import fr.clementgre.pdf4teachers.utils.style.Style; import fr.clementgre.pdf4teachers.utils.style.StyleManager; import javafx.collections.ListChangeListener; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.text.TextAlignment; import javafx.stage.Stage; import jfxtras.styles.jmetro.JMetroStyleClass; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class GalleryWindow extends Stage{ private final VBox root = new VBox(); private final HBox settings = new HBox(); private final GridPane sortPanel = new GridPane(); public final ComboBox<String> filter = new ComboBox<>(); protected final SliderWithoutPopup zoomSlider = new SliderWithoutPopup(50, 500, 150); private final Button reload = new Button(); private final Label emptyGalleryLabel = new Label(TR.tr("galleryWindow.noImagesMessage")); private final HBox messageContainer = new HBox(emptyGalleryLabel); private final ImageGridView list = new ImageGridView(false,500, zoomSlider, true); public GalleryWindow(){ Scene scene = new Scene(root); getIcons().add(new Image(getClass().getResource("/logo.png") + "")); setWidth(1200*Main.settings.zoom.getValue()); setHeight(800*Main.settings.zoom.getValue()); setMinWidth(700*Main.settings.zoom.getValue()); setMinHeight(400*Main.settings.zoom.getValue()); Main.window.centerWindowIntoMe(this); setTitle(TR.tr("galleryWindow.title")); setScene(scene); StyleManager.putStyle(scene, Style.DEFAULT); root.getStyleClass().add(JMetroStyleClass.BACKGROUND); PaneUtils.setupScaling(root, true, false); scene.setFill(Color.web("#252525")); setOnCloseRequest((e) -> { AutoTipsManager.hideAll(); MainWindow.paintTab.galleryWindow = null; }); setup(); Main.window.centerWindowIntoMe(this); MainWindow.preventWindowOverflowScreen(this); show(); PlatformUtils.runLaterOnUIThread(1000, () -> { AutoTipsManager.showByAction("opengallery", this); }); } private void setupSettings(){ list.setupSortManager(sortPanel, ShapesGridView.SORT_FOLDER, ShapesGridView.SORT_FOLDER, ShapesGridView.SORT_NAME, ShapesGridView.SORT_FILE_EDIT_TIME, ShapesGridView.SORT_SIZE, ShapesGridView.SORT_USE, ShapesGridView.SORT_LAST_USE); VBox.setVgrow(list, Priority.ALWAYS); root.setFillWidth(true); filter.setCellFactory(param -> new DirFilterListCell(this)); filter.setVisibleRowCount(10); updateComboBoxItems(); filter.getSelectionModel().select(0); filter.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if(newValue == null) return; if(newValue.equals(TR.tr("galleryWindow.filterAndEditCombo.addDirectoryButton")) && !newValue.equals(oldValue)){ filter.getSelectionModel().select(oldValue); return; } if(newValue.equals(TR.tr("galleryWindow.filterAndEditCombo.everywhere"))){ list.setFilterType(null); }else{ list.setFilterType(newValue); } }); filter.setStyle("-fx-padding: 0 5;"); PaneUtils.setHBoxPosition(sortPanel, 0, 26, 0); PaneUtils.setHBoxPosition(zoomSlider, 0, 26, 0); PaneUtils.setHBoxPosition(filter, 0, 26, 0); PaneUtils.setHBoxPosition(reload, 26, 26, 0); reload.setGraphic(SVGPathIcons.generateImage(SVGPathIcons.REDO, "black", 0, 16, 16, ImageUtils.defaultDarkColorAdjust)); reload.setTooltip(PaneUtils.genWrappedToolTip(TR.tr("galleryWindow.reloadButton.tooltip"))); reload.setOnAction((e) -> { list.setItems(Collections.emptyList()); list.addItems(getImages(list)); reloadImageList(); updateComboBoxItems(); }); settings.setSpacing(10); settings.setPadding(new Insets(0, 20, 0, 20)); settings.getChildren().addAll(sortPanel, zoomSlider, new HBoxSpacer(), filter, reload); } private void setup(){ setupSettings(); emptyGalleryLabel.setStyle("-fx-font: 18 \"Noto Sans KR\";"); emptyGalleryLabel.setTextAlignment(TextAlignment.CENTER); messageContainer.setAlignment(Pos.CENTER); VBox.setVgrow(messageContainer, Priority.ALWAYS); list.getItems().addListener((ListChangeListener<ImageGridElement>) c -> { updateMessage(); }); root.setAlignment(Pos.CENTER); root.getChildren().addAll(settings, list); list.addItems(getImages(list)); updateMessage(); } private void updateMessage(){ if(list.getAllItems().isEmpty()){ root.getChildren().add(messageContainer); list.setMaxHeight(0); }else{ root.getChildren().remove(messageContainer); list.setMaxHeight(Double.MAX_VALUE); } } public void updateStyle(){ StyleManager.putStyle(getScene(), Style.DEFAULT); list.getSortManager().updateGraphics(); } void updateComboBoxItems(){ String selected = filter.getSelectionModel().getSelectedItem(); List<String> items = GalleryManager.getSavePaths(); items.sort(String::compareTo); items.add(0, TR.tr("galleryWindow.filterAndEditCombo.favourites")); items.add(0, TR.tr("galleryWindow.filterAndEditCombo.everywhere")); items.add(TR.tr("galleryWindow.filterAndEditCombo.addDirectoryButton")); filter.getItems().setAll(items); if(filter.getItems().contains(selected)) filter.getSelectionModel().select(selected); else filter.getSelectionModel().select(TR.tr("galleryWindow.filterAndEditCombo.everywhere")); } public void reloadImageList(){ list.editImages(getImages(list)); if(MainWindow.paintTab.gallery.isLoaded()){ MainWindow.paintTab.gallery.reloadGalleryImageList(); } } public List<ImageGridElement> getListItems(){ return list.getAllItems(); } public ShapesGridView<ImageGridElement> getList(){ return list; } public static List<ImageGridElement> getImages(ImageGridView gridView){ return GalleryManager.getImages().stream().map((img) -> new ImageGridElement(img.getImageId(), gridView)).collect(Collectors.toList()); } }
#!/bin/bash #By Kristjan Krusic aka. krusic22 #Don't forget to adjust the variables according to your own needs! #This script requires drive_linux and zstd installed. https://github.com/odeke-em/drive #This example will create a new backup directory for the day (that part should only be run on 1 machine), #after that it will create a full backup of the machine, it can be easily restored and should just run, #this is only recommended for smaller servers, larger servers should backup each part of the server separately. #Multiple parts can be backed up simultaneously using "(tar -I pzstd ... & tar -I pzstd ...)", which will also ensure that all backups are completed before the upload starts. #I also used nice and ionice in this example to lower the performance impact on the server, nice controls CPU priority, ionice controls disk IO, both should be set to the lowest priority already. #To restore the backup use: "drive_linux pull Backups/25-02-2020/ServerName-25-02-2020.tar.zst", #after the download completes, move to the "Backups/25-02-2020/" directory and use "tar -xf ServerName-25-02-2020.tar.zst" to extract the backup. _now=$(date +"%d-%m-%Y") #This will give an output date, example: 25-02-2020 drive_linux new -folder Backups/$_now/ #This should only happen once a day! So run it only on your fastest server. If you run it multiple times you're going to have multiple directories with the same name. nice -n 19 ionice -c2 -n7 tar --exclude="ServerName-$_now.tar.zst" --exclude="/sys" --exclude="/proc" -I pzstd -cvf ServerName-$_now.tar.zst / #Backups the entire server excluding the backup itself, sys and proc. nice -n 19 ionice -c2 -n7 drive_linux push -destination /Backups/$_now/ -files ServerName-$_now.tar.zst #Pushes the backup to /Backups/(date) under your Google Drive. rm ServerName-$_now.tar.zst #Removes local backup.
#!/bin/bash #SBATCH --job-name=Ldhot #SBATCH --mail-type=END #SBATCH --mail-user=elise.rolland@univ-rennes1.fr #SBATCH --chdir=/omaha-beach/erolland #SBATCH --output=/home/genouest/cnrs_umr6553/erolland/Ldhot_%j.out #SBATCH --error=/home/genouest/cnrs_umr6553/erolland/Ldhot_%j.err wd=/omaha-beach/erolland wd_group=/groups/landrec # Working directory prefix=Hordeum_vulgare_Dreissig2019 # The ID of the dataset indiv=18 # Size of the population sampled # Chromosome names MUST BE integers (e.g. 1) or integers+characters (e.g. 1A) in the vcf # Chromosome names given in argument to the script chrom=1 cluster=1 input_data=$wdgroup/data/polymorphism_data/$prefix # Input from data directory #input=$wd/ldhat/$prefix/input/indiv_$indiv/chrom$chrom # Input directory input=$wd/ldhat/$prefix/input/indiv_$indiv/cluster$cluster # Input directory #output=$wd/ldhat/$prefix/output/indiv_$indiv/chrom$chrom # Output directory output=$wd/ldhat/$prefix/output/indiv_$indiv/cluster$cluster # Output directory cd $output #----------------------------------- # LDHOT, hotspot detection #----------------------------------- PathToLDhot=$wd_group/ldhat/LDhot $PathToLDhot/ldhot --seq $prefix.chromosome$chrom.cluster$cluster.ldhat.sites \ --loc $prefix.chromosome$chrom.cluster$cluster.ldhat.locs \ --lk lk_ldpop.chromosome$chrom.cluster$cluster.txt \ --res res.txt \ --nsim 100 \ --out $prefix.chromosome$chrom.cluster$cluster.sim $PathToLDhot/ldhot_summary --res res.sim.txt \ --hot "$prefix.chromosome$chrom.cluster$cluster.sim.hotspots.txt" \ --out "$prefix.chromosome$chrom.cluster$cluster.sim"
import re import shlex import mock from detect_secrets.core.usage import ParserBuilder from detect_secrets.main import main from detect_secrets.plugins.base import RegexBasedDetector from detect_secrets.plugins.common.util import import_plugins # https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python _ansi_escape = re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]') def uncolor(text): return _ansi_escape.sub('', text) def get_regex_based_plugins(): return { name: plugin for name, plugin in import_plugins(custom_plugin_paths=()).items() if issubclass(plugin, RegexBasedDetector) } def parse_pre_commit_args_with_correct_prog(argument_string=''): parser = ParserBuilder() # Rename from pytest.py to what it is when ran parser.parser.prog = 'detect-secrets-hook' return parser.add_pre_commit_arguments()\ .parse_args(argument_string.split()) def wrap_detect_secrets_main(command): with mock.patch( 'detect_secrets.main.parse_args', return_value=_parse_console_use_args_with_correct_prog(command), ): return main(command.split()) def _parse_console_use_args_with_correct_prog(argument_string=''): parser = ParserBuilder() # Rename from pytest.py to what it is when ran parser.parser.prog = 'detect-secrets' return parser.add_console_use_arguments()\ .parse_args(shlex.split(argument_string))
import React from "react"; import PropTypes from "prop-types"; import { PickerIOS, Text, View } from "react-native"; import { createStackNavigator } from "react-navigation"; import { initFirebase } from "../actions"; import { Cell, Section, TableView } from "react-native-tableview-simple"; import firebase from "react-native-firebase"; const PickerItemIOS = PickerIOS.Item; import { connect } from "react-redux"; import mapStateToProps from "../reducers/stateToProps"; import createTheme from '../theme'; const theme = createTheme() export class SettingsScreen extends React.Component { static propTypes = {}; static defaultProps = {}; static navigationOptions = ({ navigation }) => { const params = navigation.state.params || {}; return { title: "Settings", ...theme.headers }; }; constructor(props) { super(props); this.state = {}; } render() { const username = this.props.user.user ? this.props.user.user.email : "Logged out"; return ( <View style={{backgroundColor: theme.containerColor, flex: 1}}> <TableView> <Section header={"Account"} sectionTintColor={"transparent"} {...theme.uiTable.section}> <Cell {...theme.uiTable.cell} cellStyle={"RightDetail"} title={username} detail={"Logout"} detailTextStyle={{color: theme.dangerColor}} onPress={() => { firebase.auth().signOut(); }} /> </Section> </TableView> </View> ); } } const mapDispatchToProps = dispatch => ({ //fetchData: () => dispatch(fetchData()), //saveAlertField: ()=> dispatch() }); const connectedSettingsScreen = connect(mapStateToProps)(SettingsScreen); //export default connectedSettingsScreen export default createStackNavigator({ Settings: connectedSettingsScreen }, { headerMode: "float" }); /* export default createStackNavigator( { //Devices: DevicesScreen, Settings: connectedSettingsScreen, }, { headerMode: "float" } ); */
const dbConfig = require('../secrets'); const mongoose = require("mongoose"); const mongoosePaginate = require('mongoose-paginate-v2'); mongoose.Promise = global.Promise; const db = {}; db.mongoose = mongoose; db.url = dbConfig.getSecret; db.tutorials = require("./customTitle/index")(mongoose, mongoosePaginate); module.exports = db;
#!/bin/bash git subtree push --prefix web heroku master # OR # git subtree push --prefix web heroku <branch> # more info on adding remote for heroku to your git repo (locally) # https://devcenter.heroku.com/articles/git#creating-a-heroku-remote # more info on deploying just folders # http://stackoverflow.com/questions/7539382/how-can-i-deploy-push-only-a-subdirectory-of-my-git-repo-to-heroku
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" elif [ -L "${binary}" ]; then echo "Destination binary is symlinked..." dirname="$(dirname "${binary}")" binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" warn_missing_arch=${2:-true} if [ -r "$source" ]; then # Copy the dSYM into the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .dSYM "$source")" binary_name="$(ls "$source/Contents/Resources/DWARF")" binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then strip_invalid_archs "$binary" "$warn_missing_arch" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" fi fi } # Copies the bcsymbolmap files of a vendored framework install_bcsymbolmap() { local bcsymbolmap_path="$1" local destination="${BUILT_PRODUCTS_DIR}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" warn_missing_arch=${2:-true} # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then if [[ "$warn_missing_arch" == "true" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." fi STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } install_artifact() { artifact="$1" base="$(basename "$artifact")" case $base in *.framework) install_framework "$artifact" ;; *.dSYM) # Suppress arch warnings since XCFrameworks will include many dSYM files install_dsym "$artifact" "false" ;; *.bcsymbolmap) install_bcsymbolmap "$artifact" ;; *) echo "error: Unrecognized artifact "$artifact"" ;; esac } copy_artifacts() { file_list="$1" while read artifact; do install_artifact "$artifact" done <$file_list } ARTIFACT_LIST_FILE="${BUILT_PRODUCTS_DIR}/cocoapods-artifacts-${CONFIGURATION}.txt" if [ -r "${ARTIFACT_LIST_FILE}" ]; then copy_artifacts "${ARTIFACT_LIST_FILE}" fi if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/Moya/Moya.framework" install_framework "${BUILT_PRODUCTS_DIR}/MoyaLaconicPlugin/MoyaLaconicPlugin.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/Moya/Moya.framework" install_framework "${BUILT_PRODUCTS_DIR}/MoyaLaconicPlugin/MoyaLaconicPlugin.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
<filename>meta-iotqa/lib/oeqa/runtime/connectivity/wifi/wifi_stability.py import time import os import string from oeqa.runtime.wifi import wifi try: import ConfigParser except: import configparser as ConfigParser from oeqa.oetest import oeRuntimeTest from oeqa.utils.helper import shell_cmd_timeout ssid_config = ConfigParser.ConfigParser() config_path = os.path.join(os.path.dirname(__file__), "files/config.ini") ssid_config.readfp(open(config_path)) class CommWiFiStable(oeRuntimeTest): """ @class CommWiFiStable """ def setUp(self): ''' initialize wifi class @fn setUp @param self @return ''' self.wifi = wifi.WiFiFunction(self.target) def tearDown(self): ''' disable after testing @fn tearDown @param self @return ''' # disable wifi self.wifi.disable_wifi() def test_wifi_onoff_multiple_time(self): '''connmanctl to enable/disable wifi for multiple times @fn test_wifi_onoff_multiple_time @param self @return ''' time=200 for i in range(1, time): self.wifi.enable_wifi() self.wifi.disable_wifi() if i % 10 == 0: print ("Finish %d times, successful." % i)
<reponame>huyhuynh2705/tmdt /* * * Users * */ import React from 'react'; import { connect } from 'react-redux'; import actions from '../../actions'; import UserList from '../../components/Manager/UserList'; import UserSearch from '../../components/Manager/UserSearch'; import SubPage from '../../components/Manager/SubPage'; import NotFound from '../../components/Common/NotFound'; class Users extends React.PureComponent { componentDidMount() { this.props.fetchUsers(); } render() { const { users, searchUsers } = this.props; return ( <div className="users-dashboard"> <SubPage title="Users" /> <UserSearch onSearchSubmit={searchUsers} /> {users.length > 0 ? ( <UserList users={users} /> ) : ( <NotFound message="No Users Found!" /> )} </div> ); } } const mapStateToProps = (state) => { return { users: state.users.users, }; }; export default connect(mapStateToProps, actions)(Users);
package io.opensphere.wps.envoy; import org.apache.commons.lang3.StringUtils; /** * Enumeration over the supported WPS Request Types. */ public enum WpsRequestType { /** OGC WPS GetCapabilities request. */ GET_CAPABLITIES("GetCapabilities"), /** OGC WPS DescribeProcessType request. */ DESCRIBE_PROCESS_TYPE("DescribeProcess"), /** The OGC WPS Execute request type. */ EXECUTE("Execute"); /** The string representation of the request type. */ private String myValue; /** * Instantiate a new request type. * * @param pType the string representation of the request type */ WpsRequestType(String pType) { myValue = pType; } /** * Gets the value. * * @return the value */ public String getValue() { return myValue; } /** * Gets the request type corresponding to the supplied value. If none is * found, a null value is returned.F * * @param pValue the textual value of the request type to return. * @return a {@link WpsRequestType} instance corresponding to the supplied * text. */ public static WpsRequestType fromValue(String pValue) { for (WpsRequestType requestType : values()) { if (StringUtils.equals(pValue, requestType.getValue())) { return requestType; } } return null; } }
#!/bin/bash set -e set -o pipefail python cli.py \ --max_eps 20 \ --max_steps 200 \ --batch_size 32 \ --logging_level critical \ --render \ --epsilon 0.6 \ --learning_rate 0.01 \ --train_per_episode 64 \ --rounds_per_episode 10 \ --game_id Skiing-v0 \ --update_freq 1 \ --model_location=skiing \ --checkpoint_location=skiing \ --eval_freq=5
<gh_stars>1000+ package cmd import ( "github.com/spf13/cobra" ) // deleteCmd represents the delete command var deleteCmd = &cobra.Command{ Use: "delete [project]", Short: "Deletes a project", Long: `Deletes a project`, } func init() { rootCmd.AddCommand(deleteCmd) }
<gh_stars>10-100 const moment = require('moment') const { stripIndent } = require('common-tags') const { setUserCallback } = require('../methods/userMethods') const { botReply } = require('../utilities/botReply') const { UserAction } = require('../models') const { UserConversation, Reps, Campaign } = require('../models') const ACTION_TYPE_PAYLOADS = UserAction.ACTION_TYPE_PAYLOADS const { logMessage } = require('../utilities/logHelper') async function startCallConversation(user, userConversation, representatives, campaignCall) { // for testing so that we can ensure that an error on one user, does not botch the whole run if (campaignCall.subject === 'TestErrorLogging' && user.firstName === 'Max' && user.lastName === 'Fowler') { throw new Error('Testing error logging within conversation initiation') } // then begin the conversation representatives = await Reps.find({ _id: { $in: representatives } }).exec() const isFirstTimeCaller = user.firstTimeCaller // only send one representative if it's the user's first time calling if (isFirstTimeCaller) { representatives = representatives.slice(0, 1) } const convoData = { firstName: user.firstName, issueMessage: campaignCall.message, issueLink: campaignCall.issueLink, shareLink: campaignCall.shareLink, issueSubject: campaignCall.subject, issueTask: campaignCall.task, campaignCall: campaignCall.toObject({ virtuals: false }), // without toObject mongoose goes into an infinite loop on insert userConversationId: userConversation._id, representatives: representatives.map(representative => ({ repType: representative.legislatorTitle, repShortTitle: representative.shortTitle, repName: representative.official_full, repTitle: representative.repTitle, repId: representative._id, repImage: representative.image_url, repPhoneNumbers: [ representative.phoneNumbers.filter(({ officeType }) => officeType === 'district')[0], representative.phoneNumbers.filter(({ officeType }) => officeType === 'capitol')[0] ].filter(Boolean), // filter out undefined values repWebsite: representative.url, })), currentRepresentativeIndex: 0, numUserCalls: 0, // the number of calls this user has made for this campaignCall isFirstTimeCaller: isFirstTimeCaller, } // save params as convoData userConversation.convoData = convoData await userConversation.save() await user.populate('currentConvo').execPopulate() if (isFirstTimeCaller) { return firstTimeIntroConvo(user, null) } else { return areYouReadyConvo(user, null) } } // part 1 function areYouReadyConvo(user) { // begin the conversation return botReply(user, `Hi ${user.currentConvo.convoData.firstName}. We've got an issue to call about.` ) .then(() => botReply(user, `${user.currentConvo.convoData.issueMessage} You can find out more about it here:`)) .then(() => botReply(user, `${user.currentConvo.convoData.issueLink}`)) .then(() => { const msg_attachment = { attachment: { type: 'template', payload: { template_type: 'button', text: `Are you ready to call? (You can come back later if you're busy)`, buttons: [ { type: 'postback', title: 'Yes send me the info', payload: ACTION_TYPE_PAYLOADS.isReady }, { type: 'postback', title: "I don't want to call", payload: ACTION_TYPE_PAYLOADS.noCall }, ] } } } return botReply(user, msg_attachment).then(() => setUserCallback(user, '/calltoaction/readyResponse') ) }) } function firstTimeIntroConvo(user) { user.firstTimeCaller = false user.save() return botReply(user, `Hi ${user.currentConvo.convoData.firstName}. We've got an issue to call about.` ) .then(() => botReply(user, `${user.currentConvo.convoData.issueMessage} You can find out more about it here: `)) .then(() => botReply(user, `${user.currentConvo.convoData.issueLink}`)) .then(() => { return botReply(user, `It’s your first call so we’ll walk through the steps: When you call your member's office, you'll either talk to a staffer or leave a voicemail. The staffer is there to listen to you and pass your concerns on to the Member of Congress. They're your buddy (and you'll probably talk to them again) so be friendly.`) }) .then(() => botReply(user, `Give me a thumbs up if that sounds good!`)) .then(() => setUserCallback(user, '/calltoaction/firstTimeAreYouReady')) } function firstTimeAreYouReadyConvo(user) { return botReply(user, { attachment: { type: 'image', payload: { url: 'https://storage.googleapis.com/callparty/thumbsup.gif' } } }) .then(() => botReply(user, stripIndent` Awesome. When you call, you're going to tell them your name, that you're a constituent (because you only want to be calling your own Members of Congress), and why you're calling. We'll give you a specific action to tell your representative to take, and feel free to share any personal feelings or stories so they understand why it matters to you. `)) .then(() => botReply(user, stripIndent` The staffer will probably ask for your address or phone number to confirm you're a constituent. Thank them, and that's it! `)) .then(() => { const msg_attachment = { attachment: { type: 'template', payload: { template_type: 'button', text: `Ready to make your first call? (You can come back later if you're busy)`, buttons: [ { type: 'postback', title: 'Yes send me the info', payload: ACTION_TYPE_PAYLOADS.isReady }, { type: 'postback', title: "I don't want to call", payload: ACTION_TYPE_PAYLOADS.noCall } ] } } } return botReply(user, msg_attachment).then(() => setUserCallback(user, '/calltoaction/firstTimeReadyResponse') ) }) } async function firstTimeReadyResponseConvo(user, message) { if (!Object.values(ACTION_TYPE_PAYLOADS).includes(message.text)) { logMessage(`++ User responded to firstTimeReadyResponseConvo with unexpected message: ${message.text}`) return botReply(user, `I'm sorry, I didn't understand that! Try choosing from one of the options above, or shoot us an email to talk to a person at ${user.bot.orgEmail}. You can also say 'stop' or 'unsubscribe' to stop receiving messages.`) } await UserAction.create({ actionType: message.text, campaignCall: user.currentConvo.convoData.campaignCall._id, representative: user.currentConvo.convoData.representatives[user.currentConvo.convoData.currentRepresentativeIndex].repId, user: user._id, }) if (message.text === ACTION_TYPE_PAYLOADS.isReady) { const representative = user.currentConvo.convoData.representatives[0] return botReply(user, `Here’s your first script and the information for your representative: "Hello, my name is ${user.currentConvo.convoData.firstName} and I’m a constituent of ${representative.repTitle}. I’m calling about ${user.currentConvo.convoData.issueSubject}. I’d like to ask that ${representative.repTitle} ${user.currentConvo.convoData.issueTask}. Thanks for listening, have a good day!"`) .then(() => sendRepCard(user, message)) } else if (message.text === ACTION_TYPE_PAYLOADS.noCall) { return noCallConvo(user, message) } else { throw new Error('Received unexpected message at path /calltoaction/firstTimeReadyResponse: ' + message.text) } } async function readyResponseConvo(user, message) { if (!Object.values(ACTION_TYPE_PAYLOADS).includes(message.text)) { logMessage(`++ User responded to readyResponseConvo with unexpected message: ${message.text}`) return botReply(user, `I'm sorry, I didn't understand that! Try choosing from one of the options above, or shoot us an email to talk to a person at ${user.bot.orgEmail}. You can also say 'stop' or 'unsubscribe' to stop receiving messages.`) } await UserAction.create({ actionType: message.text, campaignCall: user.currentConvo.convoData.campaignCall._id, representative: user.currentConvo.convoData.representatives[user.currentConvo.convoData.currentRepresentativeIndex].repId, user: user._id, }) if (message.text === ACTION_TYPE_PAYLOADS.isReady) { const hasOneRep = user.currentConvo.convoData.representatives.length === 1 const representative = user.currentConvo.convoData.representatives[0] let msgToSend if (hasOneRep) { msgToSend = stripIndent` Great! You'll be calling ${representative.repTitle}. You'll either talk to a staffer or leave a voicemail. When you call: \u2022 Be sure to say you're a constituent calling about ${user.currentConvo.convoData.issueSubject} \u2022 Let them know you'd like ${representative.repTitle} to ${user.currentConvo.convoData.issueTask} \u2022 Share any personal feelings or stories you have on the issue \u2022 Answer any questions the staffer has, and be friendly! ` } else { msgToSend = stripIndent` Great! You'll be calling ${user.currentConvo.convoData.representatives.length} Members of Congress. You'll either talk to a staffer or leave a voicemail. When you call: \u2022 Be sure to say you're a constituent calling about ${user.currentConvo.convoData.issueSubject} \u2022 Let them know you'd like them to ${user.currentConvo.convoData.issueTask} \u2022 Share any personal feelings or stories you have on the issue \u2022 Answer any questions the staffer has, and be friendly! Your first call is ${representative.repTitle}: ` } return botReply(user, msgToSend) .then(() => sendRepCard(user, message)) } else if (message.text === ACTION_TYPE_PAYLOADS.noCall) { return noCallConvo(user, message) } else { throw new Error('Received unexpected message at path /calltoaction/readyResponse: ' + message.text) } } function sendRepCard(user) { const representative = user.currentConvo.convoData.representatives[user.currentConvo.convoData.currentRepresentativeIndex] const officeTypeLabels = { district: 'Local', capitol: 'DC' } const phoneNumberButtons = representative.repPhoneNumbers.map(({ officeType, phoneNumber }) => ({ type: 'phone_number', title: `${officeTypeLabels[officeType]}: ${phoneNumber}`, payload: `+1${phoneNumber.split('-').join('')}` })) return botReply(user, { attachment: { type: 'template', payload: { template_type: 'generic', image_aspect_ratio: 'square', elements: [ { title: `${representative.repShortTitle} ${representative.repName}`, image_url: representative.repImage, // TODO: for some reason facebook is throwing error with this default_action included // default_action: { // type: 'phone_number', // title: user.currentConvo.convoData.repPhoneNumber, // payload: user.currentConvo.convoData.repPhoneNumber // }, buttons: [ ...phoneNumberButtons, { type: 'web_url', url: representative.repWebsite, title: 'View Website' } ] } ] } } }) .then(() => botReply(user, `Give me a thumbs up once you've tried to call!`)) .then(() => setUserCallback(user, `/calltoaction/howDidItGo`)) } function noCallConvo(user) { return botReply(user, `That's okay! Want to tell me why?`).then(() => { return setUserCallback(user, `/calltoaction/tellMeWhyResponse`) }) } function tellMeWhyResponseConvo(user, message) { // this log line logs the user feedback to the _feedback channel in slack logMessage(`++ [${user.botId}] ${user.firstName} ${user.lastName} (${user.fbId}) said in response to I don't want to call: "${message.text}"`, '#_feedback') return botReply(user, `Got it – I'll let you know when there's another issue to call about.`).then(() => { return setUserCallback(user, null) }) } function howDidItGoConvo(user) { const msg_attachment = { attachment: { type: 'template', payload: { template_type: 'button', text: "How'd it go?", buttons: [ { type: 'postback', title: 'Talked to a staffer', payload: ACTION_TYPE_PAYLOADS.staffer }, { type: 'postback', title: 'Left a voicemail', payload: ACTION_TYPE_PAYLOADS.voicemail }, { type: 'postback', title: 'Something went wrong', payload: ACTION_TYPE_PAYLOADS.error } ] } } } return botReply(user, msg_attachment).then(() => setUserCallback(user, '/calltoaction/howDidItGoResponse') ) } function noNextRepResponse(user, message, numCalls) { return botReply(user, { attachment: { type: 'image', payload: { url: 'https://storage.googleapis.com/callparty/success.gif' } } }) .then(() => { // if the user is the first caller if (numCalls <= 1) { return botReply(user, stripIndent` Congrats, you're the first caller on this issue! I'll reach out with updates and an outcome on this issue. Thanks for your work! `) } // if the user is only person who has made calls, then it's weird to tell them how many calls so far so remove that part else if (numCalls === user.currentConvo.convoData.numUserCalls) { return botReply(user, stripIndent` Woo thanks for your work! We'll reach out when we have updates and an outcome on the issue. `) } // otherwise tell them how many calls have been made so far else { return botReply(user, stripIndent` Woo thanks for your work! We've had ${numCalls} calls so far. We'll reach out when we have updates and an outcome on the issue. `) } }).then(() => { // if callparty then send share link if (user.bot.botType === 'callparty') { const share_msg = { attachment: { type: 'template', payload: { template_type: 'generic', elements: [{ title: 'Share this issue with your friends to make it a party', subtitle: user.currentConvo.convoData.issueSubject, image_url: 'https://storage.googleapis.com/callparty/cpshare.jpg', buttons: [ { type: 'element_share', share_contents: { attachment: { type: 'template', payload: { template_type: 'generic', elements: [{ title: 'Call your Members of Congress and join the CallParty!', subtitle: user.currentConvo.convoData.issueSubject, image_url: 'https://storage.googleapis.com/callparty/cpshare.jpg', default_action: { type: 'web_url', url: user.currentConvo.convoData.shareLink }, buttons: [ { type: 'web_url', url: user.currentConvo.convoData.shareLink, title: 'View More Info' } ] }] } } } }, { type: 'web_url', url: user.currentConvo.convoData.shareLink, title: 'View More Info' }, ] }] } } } return botReply(user, share_msg).then(() => setUserCallback(user, null)) } // no share fo gov track else { return setUserCallback(user, null) } }) } function hasNextRepResponse(user, message, numCalls) { const nextRep = user.currentConvo.convoData.representatives[user.currentConvo.convoData.currentRepresentativeIndex] let botReplyPromise if (numCalls <= 1) { botReplyPromise = botReply(user, stripIndent` Congrats, you're the first caller on this issue! Next is ${nextRep.repTitle}. `) } else { botReplyPromise = botReply(user, stripIndent` Excellent, we're at ${numCalls} calls! Next is ${nextRep.repTitle}. `) } return botReplyPromise.then(() => sendRepCard(user, message)) } async function userMadeCallResponse(user, message) { const campaign = await Campaign.findById(user.currentConvo.convoData.campaignCall.campaign).populate('campaignActions').exec() const numCalls = await UserAction.count({ campaignCall: { $in: campaign.campaignCalls.map(call => call._id) }, actionType: { $in: [ ACTION_TYPE_PAYLOADS.voicemail, ACTION_TYPE_PAYLOADS.staffer ] } }).exec() user.currentConvo.convoData.currentRepresentativeIndex++ user.currentConvo.convoData.numUserCalls++ user.currentConvo.markModified('convoData') await user.currentConvo.save() // log message in case we reached invalid state if (numCalls < 1) { logMessage('++ @here: this if clause is only executed if the user made a call. So if there are 0 calls something is weird') } // but continue regardless const hasNextRep = user.currentConvo.convoData.currentRepresentativeIndex < user.currentConvo.convoData.representatives.length if (!hasNextRep) { return noNextRepResponse(user, message, numCalls) } else { return hasNextRepResponse(user, message, numCalls) } } function somethingWentWrongResponse(user) { const messagePromise = botReply(user, { attachment: { type: 'image', payload: { url: 'https://storage.googleapis.com/callparty/bummer.gif' } } }) user.currentConvo.convoData.currentRepresentativeIndex++ user.currentConvo.markModified('convoData') const updateUserConvoPromise = user.currentConvo.save() return Promise.all([updateUserConvoPromise, messagePromise]) .then(() => { const hasNextRep = user.currentConvo.convoData.currentRepresentativeIndex < user.currentConvo.convoData.representatives.length if (hasNextRep) { return botReply(user, stripIndent` We're sorry to hear that, but good on you for trying! `) .then(() => botReply(user, { attachment: { type: 'template', payload: { template_type: 'button', text: ' Do you want to try your next member?', buttons: [ { type: 'postback', title: 'Yes', payload: ACTION_TYPE_PAYLOADS.tryNextRep }, { type: 'postback', title: 'No', payload: ACTION_TYPE_PAYLOADS.noCall } ] } } })) .then(() => setUserCallback(user, '/calltoaction/tryNextRepResponse')) } else { return botReply(user, 'We’re sorry to hear that, but good on you for trying! Want to tell us about it?' ) .then(() => setUserCallback(user, '/calltoaction/thanksForSharing')) } }) } async function howDidItGoResponseConvo(user, message) { if (!Object.values(ACTION_TYPE_PAYLOADS).includes(message.text)) { logMessage(`++ User responded to howDidItGoResponseConvo with unexpected message: ${message.text}`) return botReply(user, `I'm sorry, I didn't understand that! Try choosing from one of the options above, or shoot us an email to talk to a person at ${user.bot.orgEmail}. You can also say 'stop' or 'unsubscribe' to stop receiving messages.`) } await UserAction.create({ actionType: message.text, campaignCall: user.currentConvo.convoData.campaignCall._id, representative: user.currentConvo.convoData.representatives[user.currentConvo.convoData.currentRepresentativeIndex].repId, user: user._id, }) if ([ACTION_TYPE_PAYLOADS.voicemail, ACTION_TYPE_PAYLOADS.staffer].indexOf(message.text) >= 0) { return userMadeCallResponse(user, message) } else if (message.text === ACTION_TYPE_PAYLOADS.error) { return somethingWentWrongResponse(user, message) } else { throw new Error('Received unexpected message at path /calltoaction/howDidItGoResponse: ' + message.text) } } async function tryNextRepResponseConvo(user, message) { if (!Object.values(ACTION_TYPE_PAYLOADS).includes(message.text)) { logMessage(`++ User responded to tryNextRepResponseConvo with unexpected message: ${message.text}`) return botReply(user, `I'm sorry, I didn't understand that! Try choosing from one of the options above, or shoot us an email to talk to a person at ${user.bot.orgEmail}. You can also say 'stop' or 'unsubscribe' to stop receiving messages.`) } await UserAction.create({ actionType: message.text, campaignCall: user.currentConvo.convoData.campaignCall._id, representative: user.currentConvo.convoData.representatives[user.currentConvo.convoData.currentRepresentativeIndex].repId, user: user._id, }) if (message.text === ACTION_TYPE_PAYLOADS.tryNextRep) { return sendRepCard(user, message) } else if (message.text === ACTION_TYPE_PAYLOADS.noCall) { return noCallConvo(user, message) } else { throw new Error('Received unexpected message at path /calltoaction/tryNextRepResponse: ' + message.text) } } // thanks for sharing function thanksForSharingConvo(user, message) { logMessage(`++ [${user.botId}] ${user.firstName} ${user.lastName} (${user.fbId}) said in response to something went wrong: "${message.text}"`, '#_feedback') return UserConversation.update({ _id: user.currentConvo.convoData.userConversationId }, { dateCompleted: moment.utc().toDate() }).exec() .then(() => botReply(user, `Got it – we'll reach back out if we can be helpful.`)) .then(function () { // Should be logged to sentry and then slack. console.log(message.text) return setUserCallback(user, null) }) } module.exports = { startCallConversation, readyResponseConvo, tellMeWhyResponseConvo, howDidItGoConvo, howDidItGoResponseConvo, thanksForSharingConvo, tryNextRepResponseConvo, firstTimeAreYouReadyConvo, firstTimeReadyResponseConvo }
#!/bin/bash INCLUDE=1 . "$(dirname "$0")"/rmlib.sh || exit 1 if [ -z "$1" ]; then echo "Usage: $0 newversion" >&2 echo " $0 clear" >&2 exit 1; fi if [ "$1" = "clear" ]; then rm-hasversion || error "Not tagged with a version, nothing to clear" git tag -d "$(rm-version)" || error "git tag failed" else echo "$1" | rm-version-checkformat || error "Invalid version format" rm-hasversion && error "Already tagged with version $(rm-version)" git tag "$1" || error "git tag failed" fi
<gh_stars>0 package homedir import ( "errors" "os" ) func dir() (string, error) { // First prefer the HOME environmental variable if home := os.Getenv("HOME"); home != "" { return home, nil } // Prefer standard environment variable USERPROFILE if home := os.Getenv("USERPROFILE"); home != "" { return home, nil } drive := os.Getenv("HOMEDRIVE") path := os.Getenv("HOMEPATH") if drive == "" || path == "" { return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") } return drive + path, nil }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ed.biodare2.backend.repo.dao; import com.fasterxml.jackson.databind.ObjectMapper; import ed.biodare2.Fixtures; import ed.biodare2.SimpleRepoTestConfig; //import ed.biodare2.backend.SimpleTestConfiguration; import ed.biodare2.backend.repo.db.dao.DBSystemInfoRep; import ed.biodare2.backend.security.dao.UserAccountRep; import ed.biodare2.backend.security.dao.UserGroupRep; import ed.biodare2.backend.security.dao.db.UserAccount; import ed.biodare2.backend.repo.db.dao.db.DBSystemInfo; import ed.biodare2.backend.repo.isa_dom.DomRepoTestBuilder; import ed.biodare2.backend.repo.isa_dom.exp.ExperimentalAssay; import ed.biodare2.backend.repo.system_dom.SystemDomTestBuilder; import ed.biodare2.backend.repo.system_dom.SystemInfo; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.runner.RunWith; import static org.unitils.reflectionassert.ReflectionAssert.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringRunner; //import org.springframework.transaction.annotation.Transactional; /** * * @author tzielins */ @RunWith(SpringRunner.class) //@DataJpaTest(showSql = false) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @AutoConfigureTestEntityManager //need this to get entity manager @Import(SimpleRepoTestConfig.class) public class SystemCopierTest { //@Autowired SystemCopier copier; @Autowired DBSystemInfoRep dbSystemInfos; @Autowired UserAccountRep accounts; @Autowired UserGroupRep groups; @Autowired TestEntityManager entityManager; @Autowired EntityManagerFactory EMF; Fixtures fixture; DBSystemInfo dbSysInfo; public SystemCopierTest() { } @Before //@Transactional public void setup() { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); //mapper.enable(SerializationFeature.INDENT_OUTPUT); //DBSystemInfoRep dbSystemInfos = mock(DBSystemInfoRep.class); fixture = Fixtures.build();//Fixtures.build(accounts,groups); copier = new SystemCopier(dbSystemInfos,mapper); } @After public void clean() { } @Test public void testCopySystemInfo() { SystemInfo org = SystemDomTestBuilder.makeSystemInfo(); SystemInfo cpy = copier.copy(org); assertNotSame(org,cpy); assertEquals(org,cpy); assertReflectionEquals(org,cpy); } @Test public void testCopyExperimentalAssay() { ExperimentalAssay org = DomRepoTestBuilder.makeExperimentalAssay(); ExperimentalAssay cpy = copier.copy(org); assertNotSame(org,cpy); //assertEquals(org,cpy); assertEquals(org.getId(),cpy.getId()); assertReflectionEquals(org,cpy); } protected DBSystemInfo insertDBSysInfo() { EntityManager EM = EMF.createEntityManager(); EM.getTransaction().begin(); System.out.println("\n\nBefore user"); UserAccount user = new UserAccount(); user.setLogin("auser"); user.setFirstName("auser"); user.setLastName("auser"); user.setPassword("<PASSWORD>"); user.setEmail("<EMAIL>"); user.setInstitution("UoE"); EM.persist(user); EM.flush(); //user = EM.find(UserAccount.class, user.getId()); //assertNotNull(user); //user.getGroups().forEach(EM::persist); //EM.persist(user); DBSystemInfo org = SystemDomTestBuilder.makeDBSystemInfo(SystemDomTestBuilder.makeSystemInfo()); org.getAcl().setCreator(user); org.getAcl().setOwner(user); org.getAcl().setSuperOwner(user); System.out.println("\n\nBefore insert"); EM.persist(org); EM.flush(); EM.getTransaction().commit(); //org = dbSystemInfos.save(org); dbSysInfo = org; return dbSysInfo; } @Test public void testCopyDBSytemInfo() { DBSystemInfo org = insertDBSysInfo(); //DBSystemInfo org = dbSysInfo; long p =org.getParentId(); org.setParentId(p+1); System.out.println("\n\n\nCopy"); DBSystemInfo cpy = copier.copy(org); assertEquals(org.getInnerId(),cpy.getInnerId()); assertEquals(p,cpy.getParentId()); assertNotSame(org,cpy); //fail("ON purpose"); /* UserAccount user = fixture.demoUser; user.getGroups().forEach(entityManager::persist); user = entityManager.persistAndFlush(user); DBSystemInfo org = SystemDomTestBuilder.makeDBSystemInfo(SystemDomTestBuilder.makeSystemInfo()); org.getAcl().setCreator(user); org.getAcl().setOwner(user); org.getAcl().setSuperOwner(user); org = entityManager.persistAndFlush(org); DBSystemInfo cpy = copier.copy(org); assertNotSame(org,cpy); assertEquals(org.getInnerId(),cpy.getInnerId()); */ } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //prevent the page from refreshing when contact form is submitted var form = document.getElementById("contact-form") form.addEventListener("submit", (e) => e.preventDefault()); //Switches the project description and image to the project that was clicked on. function switchProject(elem) { //get the name of the project that was clicked var project = elem.innerText; //get the current project that we see var currentActiveProj = document.getElementsByClassName("active-proj")[0]; var currentActiveProjLink = document.getElementsByClassName("active")[0]; //remove the active/active-proj classes from the project that we currently see //the active/active-proj classes determine whether or not we can see the element currentActiveProj.classList.remove("active-proj"); currentActiveProjLink.classList.remove("active"); //get the project description/image that we clicked on var nextActiveProj = document.getElementById(project); //add the active/active-proj classes to the project we clicked so we can see the description/image elem.classList.add("active"); nextActiveProj.classList.add("active-proj"); } //Called when user submits contact form. function submitContactForm() { //If the user already submitted the contact form, remove the response message (email successfully sent or not) clearSubmissionMessage(); const params = new URLSearchParams(); params.append("name", contactForm.name.value); params.append("email", contactForm.email.value); params.append("message", contactForm.message.value); fetch("/send-email", {method: "POST", body: params}).then(response => { var contactFormContainer = document.getElementById("contact-form-container"); var resultMessage = document.createElement("p"); //if email was sent if(response.ok) { resultMessage.innerText = "Email sent!"; //there was an error } else { resultMessage.innerText = "Sorry, there was a problem sending the email."; } contactFormContainer.appendChild(resultMessage); //clear the contact form since not refreshing page contactForm.reset(); }); } //Clears the message under the contact form if the user previously submitted the form function clearSubmissionMessage() { var contactFormContainer = document.getElementById("contact-form-container"); var submissionMessage = contactFormContainer.querySelector("p"); if(submissionMessage !== null) { contactFormContainer.removeChild(submissionMessage); } }
/zap/zap-baseline.py -r index.html -t https://mem-mmt-dev.pathfinder.gov.bc.ca/
<filename>controller/Relation/index.js const Relation = require('express').Router(); const postUserPlaceConquest = require('./postUserPlaceConquest'); Relation.post('/conquest', async (request, response) => { try { response.json({ success: true, data: await postUserPlaceConquest(request.body), }); } catch (error) { console.error(error); response.status(error.status || 500).json({ success: false, data: error, }); } }); module.exports = Relation;
import { QueryConstraint, where, WhereFilterOp, FieldPath, orderBy, limit, query, collection, Query, } from 'firebase/firestore'; import { DiscountCode, Image, Member, Opinion, UserData } from '../../types'; import { db } from '../configuration/firebase'; type whereType = [ keyof Opinion | keyof Member | keyof Image | keyof UserData | keyof DiscountCode, WhereFilterOp, string | number | boolean | string[] ]; type OrderType = [string | FieldPath, 'asc' | 'desc']; export interface OptionsProps { whereArg?: whereType; secWhereArg?: whereType; orderByArg?: OrderType; secOrderByArg?: OrderType; limitArg?: number; } export const manageQueryOpinions = ( coll: string, queryOptions: OptionsProps, collOptions?: string[] ) => { const queryArgs: QueryConstraint[] = []; if (queryOptions.whereArg) { const whereParams = where( queryOptions.whereArg[0], queryOptions.whereArg[1], queryOptions.whereArg[2] ); queryArgs.push(whereParams); } if (queryOptions.orderByArg) { const orderByParams = orderBy(queryOptions.orderByArg[0], queryOptions.orderByArg[1]); queryArgs.push(orderByParams); } if (queryOptions.secOrderByArg) { const orderByParams = orderBy(queryOptions.secOrderByArg[0], queryOptions.secOrderByArg[1]); queryArgs.push(orderByParams); } if (queryOptions.limitArg) { const limitParams = limit(queryOptions.limitArg); queryArgs.push(limitParams); } let q: Query; if (collOptions) q = query(collection(db, coll, ...collOptions), ...queryArgs); else q = query(collection(db, coll), ...queryArgs); return q; };
package io.github.poulad.hnp.web.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.poulad.hnp.story.hn_api.ItemDto; import io.github.poulad.hnp.common.Constants; import javax.annotation.Nonnull; import lombok.extern.log4j.Log4j2; import lombok.val; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.concurrent.CompletableFuture; @Log4j2 @Service public class StoriesService { @Autowired @Nonnull private RabbitTemplate rabbitTemplate; @Autowired @Nonnull private HttpClient httpClient; @Nonnull public CompletableFuture<Void> publishTopHackerNewsStories() { log.info("Getting top HN stories"); val request = HttpRequest.newBuilder( URI.create("https://hacker-news.firebaseio.com/v0/topstories.json") ).build(); httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenApply(body -> { try { return new ObjectMapper().readValue(body.body(), ItemDto.class); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } }); // .thenCompose() return CompletableFuture.runAsync( () -> rabbitTemplate.send(Constants.Queues.STORIES.getName(), null) ); } }
<reponame>QDigital-Noir/FEU-App<filename>FarEasternU/Pods/RDImageViewerController/Pod/Classes/RDImageViewerController/RDImageViewerController.h // // RDImageViewerController.h // // Created by <NAME> on 2014/03/20. // Copyright (c) 2014年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "RDPagingView.h" #import "RDImageScrollView.h" @class RDImageViewerController; @protocol RDImageViewerControllerDelegate <NSObject> @optional - (void)imageViewerController:(RDImageViewerController *)viewController willChangeIndexTo:(NSInteger)index; @end @interface RDImageViewerController : UIViewController <RDPagingViewDelegate, UIScrollViewDelegate> extern NSString *const RDImageViewerControllerReuseIdentifierImage; extern NSString *const RDImageViewerControllerReuseIdentifierRemoteImage; @property (nonatomic, assign) id<RDImageViewerControllerDelegate>delegate; @property (nonatomic) NSUInteger preloadCount; @property (nonatomic, assign) NSInteger currentPageIndex; @property (nonatomic, readonly) NSInteger numberOfPages; @property (nonatomic, assign) NSTimeInterval autoBarsHiddenDuration; @property (nonatomic, assign) BOOL restoreBarsState; @property (nonatomic, assign) BOOL pagingEnabled; @property (nonatomic, assign) BOOL loadAsync; @property (nonatomic, assign) BOOL precedenceLatestImageLoadRequest; @property (nonatomic, assign) BOOL showSlider; @property (nonatomic, assign) BOOL showPageNumberHud; @property (nonatomic, assign) RDImageScrollViewResizeMode landscapeMode; @property (nonatomic, assign) CGFloat maximumZoomScale; @property (nonatomic, copy) UIColor *pageSliderMaximumTrackTintColor; @property (nonatomic, copy) UIColor *pageSliderMinimumTrackTintColor; @property (nonatomic, readonly) UILabel *currentPageHudLabel; @property (nonatomic, copy) UIImage *(^imageHandler)(NSInteger pageIndex); @property (nonatomic, copy) NSURLRequest *(^remoteImageHandler)(NSInteger pageIndex); @property (nonatomic, copy) void (^requestCompletionHandler)(NSURLResponse *response, NSData *data, NSError *connectionError); @property (nonatomic, copy) UIImage *(^imageDecodeHandler)(NSData *data, NSInteger pageIndex); @property (nonatomic, copy) void(^imageViewConfigurationHandler)(NSInteger pageIndex, RDImageScrollView *imageView); @property (nonatomic, copy) UIView *(^viewHandler)(NSString *identifier, NSInteger pageIndex, UIView *reusedView); @property (nonatomic, copy) NSString *(^reuseIdentifierHandler)(NSInteger pageIndex); @property (nonatomic, copy) void(^reloadViewHandler)(NSString *identifier, NSInteger pageIndex, UIView *view); @property (nonatomic, copy) void(^contentViewWillAppearHandler)(NSInteger pageIndex, UIView *view); - (instancetype)initWithNumberOfPages:(NSInteger)num direction:(RDPagingViewForwardDirection)direction; - (instancetype)initWithImageHandler:(UIImage *(^)(NSInteger pageIndex))imageHandler numberOfImages:(NSInteger)pageCount direction:(RDPagingViewForwardDirection)direction; - (instancetype)initWithViewHandler:(UIView *(^)(NSString *reuseIdentifier, NSInteger pageIndex, UIView *reusedView))viewHandler reuseIdentifier:(NSString *(^)(NSInteger pageIndex))reuseIdentifierHandler numberOfImages:(NSInteger)pageCount direction:(RDPagingViewForwardDirection)direction; - (instancetype)initWithRemoteImageHandler:(NSURLRequest *(^)(NSInteger pageIndex))remoteImageHandler numberOfImages:(NSInteger)pageCount direction:(RDPagingViewForwardDirection)direction; - (void)setRemoteImageHandler:(NSURLRequest *(^)(NSInteger pageIndex))remoteImageHandler completionHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError))completionHandler decodeHandler:(UIImage *(^)(NSData *data, NSInteger pageIndex))decodeHandler; - (void)setBarsHidden:(BOOL)hidden animated:(BOOL)animated; - (void)setHudHidden:(BOOL)hidden animated:(BOOL)animated; - (void)setPageHudNumberWithPageIndex:(NSInteger)pageIndex; - (void)setBarHiddenByTapGesture; - (void)cancelAutoBarHidden; - (void)reloadViewAtIndex:(NSInteger)index; @end
<filename>ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/Packet.java /* * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.p2p.discovery.internal; import static com.google.common.base.Preconditions.checkArgument; import static org.hyperledger.besu.crypto.Hash.keccak256; import static org.hyperledger.besu.util.Preconditions.checkGuard; import org.hyperledger.besu.crypto.SECP256K1; import org.hyperledger.besu.crypto.SECP256K1.PublicKey; import org.hyperledger.besu.crypto.SECP256K1.Signature; import org.hyperledger.besu.ethereum.p2p.discovery.PeerDiscoveryPacketDecodingException; import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput; import org.hyperledger.besu.ethereum.rlp.RLP; import org.hyperledger.besu.ethereum.rlp.RLPException; import java.math.BigInteger; import java.util.Arrays; import java.util.Optional; import io.vertx.core.buffer.Buffer; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.MutableBytes; import org.apache.tuweni.units.bigints.UInt256; public class Packet { private static final int PACKET_TYPE_INDEX = 97; private static final int PACKET_DATA_INDEX = 98; private static final int SIGNATURE_INDEX = 32; private final PacketType type; private final PacketData data; private final Bytes hash; private final Signature signature; private final PublicKey publicKey; private Packet(final PacketType type, final PacketData data, final SECP256K1.KeyPair keyPair) { this.type = type; this.data = data; final Bytes typeBytes = Bytes.of(this.type.getValue()); final Bytes dataBytes = RLP.encode(this.data::writeTo); this.signature = SECP256K1.sign(keccak256(Bytes.wrap(typeBytes, dataBytes)), keyPair); this.hash = keccak256(Bytes.concatenate(encodeSignature(signature), typeBytes, dataBytes)); this.publicKey = keyPair.getPublicKey(); } private Packet(final PacketType packetType, final PacketData packetData, final Bytes message) { final Bytes hash = message.slice(0, SIGNATURE_INDEX); final Bytes encodedSignature = message.slice(SIGNATURE_INDEX, PACKET_TYPE_INDEX - SIGNATURE_INDEX); final Bytes signedPayload = message.slice(PACKET_TYPE_INDEX, message.size() - PACKET_TYPE_INDEX); // Perform hash integrity check. final Bytes rest = message.slice(SIGNATURE_INDEX, message.size() - SIGNATURE_INDEX); if (!Arrays.equals(keccak256(rest).toArray(), hash.toArray())) { throw new PeerDiscoveryPacketDecodingException( "Integrity check failed: non-matching hashes."); } this.type = packetType; this.data = packetData; this.hash = hash; this.signature = decodeSignature(encodedSignature); this.publicKey = PublicKey.recoverFromSignature(keccak256(signedPayload), this.signature) .orElseThrow( () -> new PeerDiscoveryPacketDecodingException( "Invalid packet signature, " + "cannot recover public key")); } public static Packet create( final PacketType packetType, final PacketData packetData, final SECP256K1.KeyPair keyPair) { return new Packet(packetType, packetData, keyPair); } public static Packet decode(final Buffer message) { checkGuard( message.length() >= PACKET_DATA_INDEX, PeerDiscoveryPacketDecodingException::new, "Packet too short: expected at least %s bytes, got %s", PACKET_DATA_INDEX, message.length()); final byte type = message.getByte(PACKET_TYPE_INDEX); final PacketType packetType = PacketType.forByte(type) .orElseThrow( () -> new PeerDiscoveryPacketDecodingException("Unrecognized packet type: " + type)); final PacketType.Deserializer<?> deserializer = packetType.getDeserializer(); final PacketData packetData; try { packetData = deserializer.deserialize(RLP.input(message, PACKET_DATA_INDEX)); } catch (final RLPException e) { throw new PeerDiscoveryPacketDecodingException("Malformed packet of type: " + packetType, e); } return new Packet(packetType, packetData, Bytes.wrapBuffer(message)); } public Buffer encode() { final Bytes encodedSignature = encodeSignature(signature); final BytesValueRLPOutput encodedData = new BytesValueRLPOutput(); data.writeTo(encodedData); final Buffer buffer = Buffer.buffer(hash.size() + encodedSignature.size() + 1 + encodedData.encodedSize()); hash.appendTo(buffer); encodedSignature.appendTo(buffer); buffer.appendByte(type.getValue()); appendEncoded(encodedData, buffer); return buffer; } protected void appendEncoded(final BytesValueRLPOutput encoded, final Buffer buffer) { final int size = encoded.encodedSize(); if (size == 0) { return; } // We want to append to the buffer, and Buffer always grows to accommodate anything writing, // so we write the last byte we know we'll need to make it resize accordingly. final int start = buffer.length(); buffer.setByte(start + size - 1, (byte) 0); encoded.writeEncoded(MutableBytes.wrapBuffer(buffer, start, size)); } @SuppressWarnings("unchecked") public <T extends PacketData> Optional<T> getPacketData(final Class<T> expectedPacketType) { if (data == null || !data.getClass().equals(expectedPacketType)) { return Optional.empty(); } return Optional.of((T) data); } public Bytes getNodeId() { return publicKey.getEncodedBytes(); } public PacketType getType() { return type; } public Bytes getHash() { return hash; } @Override public String toString() { return "Packet{" + "type=" + type + ", data=" + data + ", hash=" + hash + ", signature=" + signature + ", publicKey=" + publicKey + '}'; } private static Bytes encodeSignature(final SECP256K1.Signature signature) { final MutableBytes encoded = MutableBytes.create(65); UInt256.valueOf(signature.getR()).toBytes().copyTo(encoded, 0); UInt256.valueOf(signature.getS()).toBytes().copyTo(encoded, 32); final int v = signature.getRecId(); encoded.set(64, (byte) v); return encoded; } private static SECP256K1.Signature decodeSignature(final Bytes encodedSignature) { checkArgument( encodedSignature != null && encodedSignature.size() == 65, "encodedSignature is 65 bytes"); final BigInteger r = encodedSignature.slice(0, 32).toUnsignedBigInteger(); final BigInteger s = encodedSignature.slice(32, 32).toUnsignedBigInteger(); final int recId = encodedSignature.get(64); return SECP256K1.Signature.create(r, s, (byte) recId); } }
<filename>src/main/java/com/crowdin/client/projectsgroups/model/Project.java package com.crowdin.client.projectsgroups.model; import lombok.Data; import java.util.Date; import java.util.List; @Data public class Project { private Long id; private Long groupId; private Long userId; private String sourceLanguageId; private List<String> targetLanguageIds; private String name; private String identifier; private String description; private String logo; private String background; private boolean isExternal; private String externalType; private Long workflowId; private boolean hasCrowdsourcing; private Date createdAt; private Date updatedAt; }
<filename>robocode.tests/src/test/java/net/sf/robocode/test/naval/WeaponComponentTest.java package net.sf.robocode.test.naval; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; import robocode.naval.ComponentManager; import robocode.naval.Components.CannonComponents.SingleBarrelCannon; import robocode.naval.CannonType; import robocode.naval.Components.CannonComponents.CannonComponent; import robocode.util.Utils; @Ignore public class WeaponComponentTest { private CannonComponent weaponComponent; private double start = 90; private double extent = 180; private double end = start + extent; public WeaponComponentTest(){ weaponComponent = new SingleBarrelCannon(); } public double testTurnRadians(double turnRemaining, boolean log){ double output = weaponComponent.turnRadians(turnRemaining); if(log) System.out.println("Turn Radians Test - TurnRemaining before: " + Math.toDegrees(turnRemaining) + " turnRemaining after: " + Math.toDegrees(output)); return output; } @Test public void testTurnRadians1(){testTurnRadiansStopAtBlindSpot("testTurnRadians1", -5, false);} @Test public void testTurnRadians2(){testTurnRadiansStopAtBlindSpot("testTurnRadians2", 8, false);} @Test public void testTurnRadians3(){testTurnRadiansStopAtBlindSpot("testTurnRadians3", -90, false);} @Test public void testTurnRadians4(){testTurnRadiansStopAtBlindSpot("testTurnRadians4", 90, false);} @Test public void testTurnRadians5(){testTurnRadiansStopAtBlindSpot("testTurnRadians5", 150, false);} @Test public void testTurnRadians6(){testTurnRadiansStopAtBlindSpot("testTurnRadians6", -93, false);} @Test public void testStopAtBlindSpot1(){testStopAtBlindSpot("testStopAtBlindSpot1" , 450, false);} @Test public void testStopAtBlindSpot2(){testStopAtBlindSpot("testStopAtBlindSpot2" , 108, false);} @Test public void testStopAtBlindSpot3(){testStopAtBlindSpot("testStopAtBlindSpot3" , -110, false);} @Test public void testStopAtBlindSpot4(){testStopAtBlindSpot("testStopAtBlindSpot4" , -108, false);} @Test public void testBooleanAtBlindSpot1(){ String name = "testBooleanAtBlindSpot1"; boolean log = false; testStopAtBlindSpot(name , 120, log); assertEquals(name, weaponComponent.getAtBlindSpot(), true); testStopAtBlindSpot(name, -20, log); assertEquals(name, weaponComponent.getAtBlindSpot(), false); } @Test public void testBooleanAtBlindSpot2(){ String name = "testBooleanAtBlindSpot2"; boolean log = false; testStopAtBlindSpot(name , -340, log); assertEquals(name, weaponComponent.getAtBlindSpot(), true); testStopAtBlindSpot(name, 50, log); assertEquals(name, weaponComponent.getAtBlindSpot(), false); } /** * Turns by the given turnRemaining. Breaks automatically once the BlindSpot is reached. * Basically tests whether the steps are taken correctly. Gives error when the weapon isn't turned by the NavalRules.GUN_TURN_RATE for example. * @param testName Name of the test * @param turnRemaining Amount you want to turn in degrees * @param log true for logging. False for no logging. */ public void testTurnRadiansStopAtBlindSpot(String testName, double turnRemaining, boolean log){ double degreesToTurn = turnRemaining; boolean turnRight = turnRemaining > 0; double result; //Turn until the blindspot or the destination is reached while(!weaponComponent.getAtBlindSpot() && !Utils.isNear(degreesToTurn, 0.0)){ //Turn as much as you can result = testTurnRadians(Math.toRadians(degreesToTurn), log); //Make sure the testing value isn't 0 and that it won't go over the blindSpot if(turnRight){ degreesToTurn -= CannonType.SINGLE_BARREL.getTurnRate(); if(degreesToTurn < 0) degreesToTurn = 0; if(weaponComponent.getAngle() + weaponComponent.getTurnRateRadians() > weaponComponent.getCopyOfBlindSpot().getFarRight()) break; } else{ degreesToTurn += CannonType.SINGLE_BARREL.getTurnRate(); if(degreesToTurn > 0) degreesToTurn = 0; if(weaponComponent.getAngle() - weaponComponent.getTurnRateRadians() < Utils.normalRelativeAngle(weaponComponent.getCopyOfBlindSpot().getFarLeft())) break; } assertEquals(testName, Utils.isNear(result, Math.toRadians(degreesToTurn)), true); } if(log){ System.out.println("*** End of " + testName + " ***"); } } public void testStopAtBlindSpot(String testName, double turnRemaining, boolean log){ double degreesToTurn = Math.toRadians(turnRemaining); degreesToTurn = weaponComponent.turnRadians(degreesToTurn); if(Utils.isNear(turnRemaining,50)){ System.out.println("turnRemaining 50 gives degreesToTurn: " + Math.toDegrees(degreesToTurn)); } while(!weaponComponent.getAtBlindSpot() && !Utils.isNear(degreesToTurn, 0.0)){ degreesToTurn = weaponComponent.turnRadians(degreesToTurn); } // System.out.println("getAtBlindSpot() " + weaponComponent.getAtBlindSpot() + " degrees to turn : " + Math.toDegrees(degreesToTurn)); if(turnRemaining == Double.POSITIVE_INFINITY || turnRemaining == Double.NEGATIVE_INFINITY){ System.out.println("Test@"); } else if(turnRemaining > 0 && !Utils.isNear(degreesToTurn, 0.0)){ assertEquals(testName, Utils.isNear(degreesToTurn, Math.toRadians(turnRemaining-start)), true); } else if(turnRemaining < 0 && !Utils.isNear(degreesToTurn, 0.0)){ assertEquals(testName, Utils.isNear(degreesToTurn, Math.toRadians(360-end + turnRemaining)), true); } else if (log && Utils.isNear(degreesToTurn, 0.0)){ System.out.println("The WeaponComponent reached its destination without encountering its blindspot. Please consider using a different value for testing."); } if(log){ System.out.println("Degrees to turn: " + Math.toDegrees(degreesToTurn) + " Radians to turn: " + degreesToTurn + " \n*** End of " + testName + " ***"); } } }
def find_pair_indices(nums, target): num_indices = {} for i, num in enumerate(nums): complement = target - num if complement in num_indices: return [num_indices[complement], i] num_indices[num] = i return "No such pair found"
#!/bin/sh gst hello.st
package accounts import ( "encoding/json" "errors" "net/http" "yatter-backend-go/app/handler/httperror" "yatter-backend-go/app/handler/request" ) // Handle request for `GET /v1/accounts/:username` func (h *handler) Get(w http.ResponseWriter, r *http.Request) { ctx := r.Context() username, err := request.UsernameOf(r) if err != nil { httperror.InternalServerError(w, err) return } daoAccount := h.app.Dao.Account() // domain/repository の取得 account, err := daoAccount.FindByUsername(ctx, username) if err != nil { httperror.InternalServerError(w, err) return } if account == nil { err := errors.New("user not found") println(err.Error()) return } w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(account); err != nil { httperror.InternalServerError(w, err) return } }
<gh_stars>1-10 import puppeteer from 'puppeteer'; import {loadAccNameLibraries, runComparison} from './compare'; import {getNodeRefFromSelector} from './node_ref'; import {writeWPTResults} from './output'; /** * Runs each of the implementations on every Web Platform Test * at http://wpt.live/accname/. * Returns an ID number for the results to the tests. */ export async function runWPT(): Promise<number> { const browser = await puppeteer.launch({ args: ['--enable-blink-features=AccessibilityObjectModel'], }); const page = await browser.newPage(); await page.goto('http://wpt.live/accname/'); // Get a list of URLs for the accname tests const nameTestUrls = (await page.evaluate( `Array.from(document.querySelectorAll('a')) .map(node => node.href) .filter(href => href.includes('accname/name'));` )) as string[]; // Metrics const implToNumTestsFailed: {[impl: string]: number} = {}; let numTestsRun = 0; let totalIncorrect = 0; const testComparisons = new Array<WPTComparison>(); for (const url of nameTestUrls) { try { await page.goto(url); const client = await page.target().createCDPSession(); await loadAccNameLibraries(page); // Target node identified by #test for each WPT const targetNode = await getNodeRefFromSelector('#test', client, page); const comparison = await runComparison(targetNode, page, client); // Correct name for a given test is stored in a 'theTest' object // in a <script> tag in the <head> of each WPT page. const correctName = (await page.evaluate( 'theTest.Tests[0].test.ATK[0][3];' )) as string; const incorrectImpls = new Array<string>(); // Identify implementations that got the incorrect accessible name for (const [impl, name] of Object.entries(comparison.accnames)) { if (name !== correctName) { incorrectImpls.push(impl); implToNumTestsFailed[impl] ? (implToNumTestsFailed[impl] += 1) : (implToNumTestsFailed[impl] = 1); } } if (incorrectImpls.length > 0) { totalIncorrect += 1; } testComparisons.push({ correctName: correctName, accnames: comparison.accnames, incorrectImpls: incorrectImpls, testURL: url, }); numTestsRun += 1; console.log(`${numTestsRun}/${nameTestUrls.length}`); } catch (error) { console.log( `Skipped test at ${url} due to the following error:\n\n${error}` ); } } // Results & performance for all WPTs at wpt.live/accname const results = { testsRun: numTestsRun, totalIncorrect: totalIncorrect, implPerformance: implToNumTestsFailed, testResults: testComparisons, }; const resultId = writeWPTResults(results); return resultId; }
#!/usr/bin/env bash # Download and unpack Istio ISTIO_VERSION=1.2.4 DOWNLOAD_URL=https://github.com/istio/istio/releases/download/${ISTIO_VERSION}/istio-${ISTIO_VERSION}-linux.tar.gz wget --no-check-certificate $DOWNLOAD_URL if [ $? != 0 ]; then echo "Failed to download istio package" exit 1 fi tar xzf istio-${ISTIO_VERSION}-linux.tar.gz ( # subshell in downloaded directory cd istio-${ISTIO_VERSION} || exit # Create CRDs template helm template --namespace=istio-system \ install/kubernetes/helm/istio-init \ `# Removing trailing whitespaces to make automation happy` \ | sed 's/[ \t]*$//' \ > ../istio-crds.yaml # Create a custom cluster local gateway, based on the Istio custom-gateway template. helm template --namespace=istio-system install/kubernetes/helm/istio --values ../values-extras.yaml \ `# Removing trailing whitespaces to make automation happy` \ | sed 's/[ \t]*$//' \ > ../istio-knative-extras.yaml # A template with sidecar injection enabled. helm template --namespace=istio-system install/kubernetes/helm/istio --values ../values.yaml \ `# Removing trailing whitespaces to make automation happy` \ | sed 's/[ \t]*$//' \ > ../istio.yaml # A lighter template, with just pilot/gateway. # Based on install/kubernetes/helm/istio/values-istio-minimal.yaml helm template --namespace=istio-system install/kubernetes/helm/istio --values ../values-lean.yaml \ `# Removing trailing whitespaces to make automation happy` \ | sed 's/[ \t]*$//' \ > ../istio-lean.yaml ) # Clean up. rm -rf istio-${ISTIO_VERSION} rm istio-${ISTIO_VERSION}-linux.tar.gz # Add in the `istio-system` namespace to reduce number of commands. patch istio-crds.yaml namespace.yaml.patch patch istio.yaml namespace.yaml.patch patch istio-lean.yaml namespace.yaml.patch patch -l istio.yaml prestop-sleep.yaml.patch
package malte0811.controlengineering.client.render.utils; import com.google.common.base.Preconditions; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormatElement; import com.mojang.math.Vector3f; import com.mojang.math.Vector4f; import malte0811.controlengineering.util.BitUtils; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.world.phys.Vec2; import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import static com.mojang.blaze3d.vertex.DefaultVertexFormat.*; //TODO copied from IE public class TransformingVertexBuilder extends DelegatingVertexBuilder<TransformingVertexBuilder> { protected final PoseStack transform; protected final List<ObjectWithGlobal<?>> allObjects = new ArrayList<>(); protected final ObjectWithGlobal<Vec2> uv = new ObjectWithGlobal<>(); protected final ObjectWithGlobal<Vec3> pos = new ObjectWithGlobal<>(); protected final ObjectWithGlobal<Vec2i> overlay = new ObjectWithGlobal<>(); protected final ObjectWithGlobal<Vec2i> lightmap = new ObjectWithGlobal<>(); protected final ObjectWithGlobal<Vector3f> normal = new ObjectWithGlobal<>(); protected final ObjectWithGlobal<Vector4f> color = new ObjectWithGlobal<>(); protected final VertexFormat format; public TransformingVertexBuilder(VertexConsumer base, PoseStack transform, VertexFormat format) { super(base); this.transform = transform; this.format = format; } public TransformingVertexBuilder(VertexConsumer base, VertexFormat format) { this(base, new PoseStack(), format); } public TransformingVertexBuilder(MultiBufferSource buffer, RenderType type, PoseStack transform) { this(buffer.getBuffer(type), transform, type.format()); } @Nonnull @Override public TransformingVertexBuilder vertex(double x, double y, double z) { pos.putData(new Vec3(x, y, z)); return this; } @Nonnull @Override public TransformingVertexBuilder color(int red, int green, int blue, int alpha) { color.putData(new Vector4f(red / 255f, green / 255f, blue / 255f, alpha / 255f)); return this; } @Nonnull @Override public TransformingVertexBuilder uv(float u, float v) { uv.putData(new Vec2(u, v)); return this; } @Nonnull @Override public TransformingVertexBuilder overlayCoords(int u, int v) { overlay.putData(new Vec2i(u, v)); return this; } @Nonnull @Override public TransformingVertexBuilder uv2(int u, int v) { lightmap.putData(new Vec2i(u, v)); return this; } @Nonnull @Override public TransformingVertexBuilder normal(float x, float y, float z) { normal.putData(new Vector3f(x, y, z)); return this; } @Override public void endVertex() { for (VertexFormatElement element : format.getElements()) { if (element == ELEMENT_POSITION) pos.ifPresent(pos -> delegate.vertex( transform.last().pose(), (float) pos.x, (float) pos.y, (float) pos.z )); else if (element == ELEMENT_COLOR) color.ifPresent(c -> delegate.color(c.x(), c.y(), c.z(), c.w())); else if (element == ELEMENT_UV0) uv.ifPresent(uv -> delegate.uv(uv.x, uv.y)); else if (element == ELEMENT_UV1) overlay.ifPresent(overlay -> delegate.overlayCoords(overlay.x, overlay.y)); else if (element == ELEMENT_UV2) lightmap.ifPresent(lightmap -> delegate.uv2(lightmap.x, lightmap.y)); else if (element == ELEMENT_NORMAL) normal.ifPresent( normal -> delegate.normal(transform.last().normal(), normal.x(), normal.y(), normal.z()) ); } delegate.endVertex(); allObjects.forEach(ObjectWithGlobal::clear); } public void defaultColor(float r, float g, float b, float a) { color.setGlobal(new Vector4f(r, g, b, a)); } @Override public void defaultColor(int r, int g, int b, int a) { defaultColor(r / 255f, g / 255f, b / 255f, a / 255f); } @Override public void unsetDefaultColor() { color.setGlobal(null); } public TransformingVertexBuilder setLight(int light) { lightmap.setGlobal(new Vec2i(light & 255, light >> 16)); return getThis(); } public TransformingVertexBuilder setNormal(float x, float y, float z) { Vector3f vec = new Vector3f(x, y, z); vec.normalize(); normal.setGlobal(vec); return getThis(); } public TransformingVertexBuilder setNormal(Vec3 normal) { return setNormal((float) normal.x, (float) normal.y, (float) normal.z); } public TransformingVertexBuilder setOverlay(int packedOverlayIn) { overlay.setGlobal(new Vec2i(packedOverlayIn & 0xffff, packedOverlayIn >> 16)); return getThis(); } @Override protected TransformingVertexBuilder getThis() { return this; } public TransformingVertexBuilder setColor(int color) { defaultColor( BitUtils.getBits(color, 16, 8) / 255f, BitUtils.getBits(color, 8, 8) / 255f, BitUtils.getBits(color, 0, 8) / 255f, BitUtils.getBits(color, 24, 8) / 255f ); return this; } private record Vec2i(int x, int y) { } protected class ObjectWithGlobal<T> { @Nullable private T obj; private boolean isGlobal; public ObjectWithGlobal() { allObjects.add(this); } public void putData(T newVal) { if (obj == null) obj = newVal; } public void setGlobal(@Nullable T obj) { this.obj = obj; isGlobal = obj != null; } public T read() { T ret = Preconditions.checkNotNull(obj); clear(); return ret; } public boolean hasValue() { return obj != null; } public void clear() { if (!isGlobal) obj = null; } public void ifPresent(Consumer<T> out) { if (hasValue()) out.accept(read()); } } }
// 3752. 가능한 시험 점수 // 2019.07.08 #include<iostream> using namespace std; int visit[10001]; int score[101]; int main() { int t; cin >> t; for (int test_case = 1; test_case <= t; test_case++) { int n; cin >> n; fill(visit, visit + 10001, 0); int count = 0; visit[0] = 1; // 0점은 가능 count++; int sum = 0; for (int i = 0; i < n; i++) { cin >> score[i]; } for (int i = 0; i < n; i++) { int curScore = score[i]; for (int j = sum; j >= 0; j--) { // 가능한 시험점수라면 true로 if (visit[j] && !visit[j + curScore]) { count++; // 개수 증가 visit[j + curScore] = true; } } sum += curScore; } printf("#%d %d\n", test_case, count); } return 0; }
# The Book of Ruby - http://www.sapphiresteel.com ob1 = Object.new ob2 = Object.new puts( ob1==ob2 ) puts( ob1.equal?(ob2) ) puts s1 = "hello" s2 = "hello" puts( s1==s2 ) puts( s1.equal?(s2) )
<gh_stars>0 # coding:utf-8 # https://codereview.stackexchange.com/questions/148305/remove-comments-from-c-like-source-code import re import os import sys _thisDir = os.path.dirname(__file__) src_dir = os.path.join(_thisDir, 'src') new_dir = os.path.join(_thisDir, 'new') if not os.path.exists(new_dir): os.makedirs(new_dir) #ms_lib = os.path.join(src_dir, 'CR43D66Lib.ms') ms_lib = os.path.join(src_dir, 'comment_test.txt') #new_msLib = os.path.join(new_dir, 'CR43D66Lib.ms') new_msLib = os.path.join(new_dir, 'comment_test.txt') COMMENTS = re.compile(r''' (//[^\n]*(?:\n|$)) # Everything between // and the end of the line/file | # or (/\*.*?\*/) # Everything between /* and */ ''', re.VERBOSE) def remove_comments(content): return COMMENTS.sub('\n', content) content = '' with open(ms_lib, 'r') as fp: content = fp.read() print(remove_comments(content)) #txt = 'if (matchPattern theLine pattern:"*:*") or (matchPattern theLine pattern:"*\\*") or (matchPattern theLine pattern:"*/*") then' # print(remove_comments(txt))
package org.insightcentre.nlp.saffron.config; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.insightcentre.nlp.saffron.data.SaffronPath; import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonIgnore; import java.time.Duration; /** * Term extraction configuration * @author <NAME> &lt;<EMAIL>&gt; */ public class TermExtractionConfiguration { /** Minimum threshold score to extract */ public double threshold = 0.0; /** Maximum number of terms to extract */ @JsonAlias("maxTopics") //Enable compatibility with 3.3 public int maxTerms = 100; /** The shortest length of term to consider */ public int ngramMin = 1; /** The longest term to consider */ public int ngramMax = 4; /** The minimum term frequency to consider */ public int minTermFreq = 2; /** The minimum document frequency percentage to consider */ public double minDocFreq = 0.0; /** The maximum number of documents to consider */ public int maxDocs = Integer.MAX_VALUE; /** The Weighting Method to use */ public WeightingMethod method = WeightingMethod.one; /** The features to use */ public List<Feature> features = java.util.Arrays.asList(Feature.comboBasic, Feature.weirdness, Feature.totalTfIdf, Feature.cValue, Feature.residualIdf); /** The corpus to use (path to this file) */ public SaffronPath corpus; /** The info measure to use */ //public String infoMeasure; /** The path to the word2vec model */ //public String w2vmodelPath; /** The base feature to use */ public Feature baseFeature = Feature.comboBasic; /** The number of threads to use */ public int numThreads; /** The path to the part-of-speech tagger's model */ public SaffronPath posModel; /** The path to the tokenizer's model */ public SaffronPath tokenizerModel; /** The path to the lemmatizer's model */ public SaffronPath lemmatizerModel; /** The path to the list of stop words (one per line) */ public SaffronPath stopWords; /** The set of tags allowed in non-final position in a noun phrase */ public Set<String> preceedingTokens = new HashSet<>(Arrays.asList("NN", "NNS", "JJ", "NNP")); /** The set of tags allowed in non-final position, but not completing */ public Set<String> middleTokens = new HashSet<>(Arrays.asList("IN")); /** The set of final tags allows in a noun phrase */ public Set<String> headTokens = new HashSet<>(Arrays.asList("NN", "NNS", "CD")); /** The position of the head of a noun phrase (true=final) */ public boolean headTokenFinal = true; /** * A list of terms that should never be generated */ public Set<String> blacklist = Collections.EMPTY_SET; /** * A file containing a list of black terms */ public SaffronPath blacklistFile; /** * The length of time (in days) to use as intervals in temporal prediction * or negative to disable temporal prediction */ public int intervalDays = 365; /** * If set always output at least one term for each input document (overrides maxTerms * if necessary) */ @JsonAlias("oneTopicPerDoc") //Enable compatibility with 3.3 public boolean oneTermPerDoc; /** The Weighting method to use */ public enum WeightingMethod { one, voting, puatr }; /** The features for term extraction */ public enum Feature { weirdness, avgTermFreq, termFreq, residualIdf, totalTfIdf, cValue, basic, comboBasic, postRankDC, relevance, /*domainCoherence,*/ /*domainPertinence,*/ novelTopicModel, /*linkProbability, keyConceptRelatedness*/ futureBasic, futureComboBasic }; /** The default English list of stopwords */ public static final String[] ENGLISH_STOPWORDS = new String[]{ "i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now", "d", "ll", "m", "o", "re", "ve", "y", "ain", "aren", "couldn", "didn", "doesn", "hadn", "hasn", "haven", "isn", "ma", "mightn", "mustn", "needn", "shan", "shouldn", "wasn", "weren", "won", "wouldn", "com", // for URLs and other common junk "http", "www", "nbsp" }; public void setCorpus(SaffronPath corpus) { this.corpus = corpus; } public SaffronPath getCorpus() { return this.corpus; } public void setPosModel(SaffronPath posModel) { this.posModel = posModel; } public SaffronPath getPosModel() { return this.posModel; } public void setTokenizerModel(SaffronPath tokenizerModel) { this.tokenizerModel = tokenizerModel; } public SaffronPath getTokenizerModel() { return this.tokenizerModel; } public void setLemmatizerModel(SaffronPath lemmatizerModel) { this.lemmatizerModel = lemmatizerModel; } public SaffronPath getLemmatizerModel() { return this.lemmatizerModel; } public void setStopWords(SaffronPath stopWords) { this.stopWords = stopWords; } public SaffronPath getStopWords() { return this.stopWords; } }