text
stringlengths
1
1.05M
# Import necessary libraries import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer # Initialize the sentiment analyzer sentiment_analyzer = SentimentIntensityAnalyzer() # Define a function for sentiment analysis def sentiment_analyze(text): score = sentiment_analyzer.polarity_scores(text) if score['compound'] >= 0.05: return 'Positive' elif score['compound'] <= -0.05: return 'Negative' else: return 'Neutral'
<reponame>lixinrongNokia/GeneralManagement<gh_stars>0 package com.gzwl.demo.controller.sys; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.gzwl.demo.pojo.DictionaryType; import com.gzwl.demo.search.sys.DictionaryTypeSearch; import com.gzwl.demo.service.sys.DictionaryTypeService; import com.gzwl.demo.util.ResultUtil; /** * * @version:1.0 * @Description:字典类型 * @author:李云飞 * @date: 2019年3月29日上午11:49:53 */ @Controller @RequestMapping("/dictionaryType") public class DictionaryTypeController { @Resource private DictionaryTypeService lwDictionaryTypeService; /** * 打开页面 * * @param model * @return */ @RequestMapping("/list") public String list(Model model) { return "/sys/dictionary/dictionaryTcList"; } /** * 查询 or 条件查询 * * @param lwDictionaryTypeSearch * @return */ @RequestMapping("getData") @ResponseBody public ResultUtil getData(DictionaryTypeSearch lwDictionaryTypeSearch) { return lwDictionaryTypeService.ListByPage(lwDictionaryTypeSearch); } /** * 进入新增或修改页面 * * @param id * @param model * @param method * @return */ @RequestMapping(value = "/toInsertOrupdate") public String toInsertOrupdate(Model model, String method, Integer dictionaryTypeId) { List<DictionaryType> dictionaryTypeList = lwDictionaryTypeService.ListByTable(); model.addAttribute("dictionaryTypeList", dictionaryTypeList); if (method.equals("ADD")) { model.addAttribute("titleName", "添加"); } else if (method.equals("EDIT")) { DictionaryType dictionary = lwDictionaryTypeService.getById(dictionaryTypeId); model.addAttribute("titleName", "编辑"); model.addAttribute("data", dictionary); } return "/sys/dictionary/dictionaryTcEdit"; } /** * 执行新增或修改保存 * * @param lwDictionaryType * @param request * @return */ @RequestMapping(value = "/insertOrupdate") @ResponseBody public Map<String, Object> insertOrupdate(DictionaryType lwDictionaryType, HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); if (null != lwDictionaryType.getDictionaryTypeId() && lwDictionaryType.getDictionaryTypeId() != 0) {// 修改 if (lwDictionaryTypeService.updateSelective(lwDictionaryType) > 0) { result.put("STATE", "SUCCESS"); } else { result.put("STATE", "FAIL"); } } else { if (lwDictionaryTypeService.insert(lwDictionaryType) > 0) { result.put("STATE", "SUCCESS"); } else { result.put("STATE", "FAIL"); } } return result; } }
import { Component, Output, OnInit, ChangeDetectorRef, EventEmitter } from '@angular/core'; import { FirebaseService } from '../../../shared/services/firebase/firebase.service'; @Component({ selector: 'ra-participants-selector', host: { 'class': 'ng-animate' }, styles: [` :host { display: flex; justify-content: center; align-items: center; position: fixed; top: 0; bottom: 0; right: 0; left: 0; background: rgba(0,0,0,.5); z-index: 1000; } :host(.ng-enter) { transition: opacity 0.3s ease-out; opacity: 0; } :host(.ng-enter) .dialog { transition: transform 0.2s ease-out; transform: perspective(200px) translate3d(0px,-1000px,-1000px); } :host(.ng-enter-active) { opacity: 1; } :host(.ng-enter-active) .dialog { transform: perspective(0); } .dialog { position: relative; padding: 32px; background-color: #ffffff; border-radius: 3px; color: #182531; z-index: 100; } .close { text-align: center; line-height: 20px; width: 24px; height: 24px; font-weight: 700; position: absolute; right: 4px; top: 4px; cursor: pointer; border-radius: 50%; } .close:hover { background-color: #f6f7f8; } .label { text-align: center; font-size: 18px; font-weight: 700; margin-bottom: 24px; } .participant { display: flex; flex-direction: row; align-items: center; margin-top: 8px; padding: 8px; border-radius: 5px; cursor: pointer; } .participant:hover { background-color: #f6f7f8; } img { width: 40px; height: 40px; border-radius: 50%; margin-right: 16px; } .name { font-size: 14px; font-weight: 700; } `], template: ` <div class="dialog"> <div class="close" (click)="onClose()">x</div> <div class="label">Choose a teammate:</div> <div class="participant" *ngFor="let participant of participants" (click)="onSelect(participant)"> <img [src]="participant.photoURL"/> <div class="name">{{participant.name}}</div> </div> </div> ` }) export class ParticipantsSelectorComponent { @Output() close = new EventEmitter(); @Output() select = new EventEmitter(); participants = []; constructor(private fb: FirebaseService, private ref: ChangeDetectorRef) {} ngOnInit() { this.fb.ref('participants').on('child_added', (snapshot) => { this.participants.push({ uid: snapshot.key, name: snapshot.val().name, photoURL: snapshot.val().photoURL }); this.ref.detectChanges(); }); } onClose() { this.close.emit(null); } onSelect(participant) { this.select.emit(participant); } }
package io.opensphere.core.appl; import java.util.Collection; import java.util.Map; import java.util.ServiceLoader; import java.util.concurrent.ConcurrentHashMap; import io.opensphere.core.UnitsRegistry; import io.opensphere.core.preferences.Preferences; import io.opensphere.core.preferences.PreferencesRegistry; import io.opensphere.core.units.InvalidUnitsException; import io.opensphere.core.units.UnitsParseException; import io.opensphere.core.units.UnitsProvider; /** * An implementation for {@link UnitsRegistry}. */ final class UnitsRegistryImpl implements UnitsRegistry { /** The preferences registry. */ private final PreferencesRegistry myPreferencesRegistry; /** The map of units types to providers. */ private final Map<Class<?>, UnitsProvider<?>> myProviderMap = new ConcurrentHashMap<>(); /** * Constructor. * * @param preferencesRegistry The preferences registry. */ public UnitsRegistryImpl(PreferencesRegistry preferencesRegistry) { myPreferencesRegistry = preferencesRegistry; Preferences preferences = myPreferencesRegistry.getPreferences(UnitsRegistry.class); for (UnitsProvider<?> provider : ServiceLoader.load(UnitsProvider.class)) { provider.setPreferences(preferences); addUnitsProvider(provider); } } @Override public void addUnitsProvider(UnitsProvider<?> provider) { myProviderMap.put(provider.getSuperType(), provider); } @Override public <S, T extends S> T convert(Class<S> unitsSupertype, Class<T> desiredUnits, S from) throws InvalidUnitsException, UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).convert(desiredUnits, from); } @Override public <T> T convertUsingLongLabel(Class<T> unitsSupertype, T magnitude, String longLabel) throws UnitsParseException, UnitsProviderNotFoundException, InvalidUnitsException { Class<? extends T> type = getUnitsProvider(unitsSupertype).getUnitsWithLongLabel(longLabel); if (type == null) { throw new UnitsParseException("Failed to find appropriate units for string: " + longLabel); } return getUnitsProvider(unitsSupertype).convert(type, magnitude); } @Override public <T> T convertUsingShortLabel(Class<T> unitsSupertype, T magnitude, String shortLabel) throws UnitsParseException, UnitsProviderNotFoundException, InvalidUnitsException { UnitsProvider<T> unitsProvider = getUnitsProvider(unitsSupertype); return unitsProvider.convert(unitsProvider.getUnitsWithShortLabel(shortLabel), magnitude); } @Override public <T> T fromLongLabelString(Class<T> unitsSupertype, String label) throws UnitsParseException, UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).fromLongLabelString(label); } @Override public <T> T fromMagnitudeAndLongLabel(Class<T> unitsSupertype, Number magnitude, String longLabel) throws UnitsParseException, InvalidUnitsException, UnitsProviderNotFoundException { UnitsProvider<T> unitsProvider = getUnitsProvider(unitsSupertype); return unitsProvider.fromMagnitudeAndLongLabel(magnitude, longLabel); } @Override public <T> T fromMagnitudeAndShortLabel(Class<T> unitsSupertype, Number magnitude, String shortLabel) throws UnitsParseException, UnitsProviderNotFoundException, InvalidUnitsException { UnitsProvider<T> unitsProvider = getUnitsProvider(unitsSupertype); return unitsProvider.fromMagnitudeAndShortLabel(magnitude, shortLabel); } @Override public <T> T fromShortLabelString(Class<T> unitsSupertype, String label) throws UnitsParseException, UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).fromShortLabelString(label); } @Override public <T> T fromUnitsAndMagnitude(Class<? super T> unitsSupertype, Class<T> type, Number magnitude) throws InvalidUnitsException, UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).fromUnitsAndMagnitude(type, magnitude); } @Override public <T> Collection<Class<? extends T>> getAvailableUnits(Class<T> unitsSupertype, boolean allowAutoscale) throws UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).getAvailableUnits(allowAutoscale); } @Override public <T> String[] getAvailableUnitsSelectionLabels(Class<T> unitsSupertype, boolean allowAutoscale) throws UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).getAvailableUnitsSelectionLabels(allowAutoscale); } @Override public <T> Class<? extends T> getPreferredFixedScaleUnits(Class<T> unitsSupertype, T value) throws UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).getPreferredFixedScaleUnits(value); } @Override public <T> Class<? extends T> getPreferredUnits(Class<T> unitsSupertype) throws UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).getPreferredUnits(); } @Override public <T> Class<? extends T> getPrevPreferredUnits(Class<T> unitsSupertype) throws UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).getPrevPreferredUnits(); } @Override public <T> UnitsProvider<T> getUnitsProvider(Class<T> unitsSupertype) throws UnitsProviderNotFoundException { @SuppressWarnings("unchecked") UnitsProvider<T> unitsProvider = (UnitsProvider<T>)myProviderMap.get(unitsSupertype); if (unitsProvider == null) { throw new UnitsProviderNotFoundException(unitsSupertype); } return unitsProvider; } @Override public Collection<? extends UnitsProvider<?>> getUnitsProviders() { return myProviderMap.values(); } @Override public <T> Class<? extends T> getUnitsWithSelectionLabel(Class<T> unitsSupertype, String label) throws UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).getUnitsWithSelectionLabel(label); } @Override public void removeUnitsProvider(UnitsProvider<?> provider) { myProviderMap.remove(provider.getSuperType()); } @Override public void resetAllPreferredUnits(Object source) { myPreferencesRegistry.resetPreferences(UnitsRegistry.class, source); } @Override public <T> String toShortLabelString(Class<? super T> unitsSupertype, T obj) throws UnitsProviderNotFoundException { return getUnitsProvider(unitsSupertype).toShortLabelString(obj); } }
""" ORY Keto Ory Keto is a cloud native access control server providing best-practice patterns (RBAC, ABAC, ACL, AWS IAM Policies, Kubernetes Roles, ...) via REST APIs. # noqa: E501 The version of the OpenAPI document: v0.7.0-alpha.1 Contact: <EMAIL> Generated by: https://openapi-generator.tech """ import sys import unittest import ory_keto_client from ory_keto_client.model.internal_relation_tuple import InternalRelationTuple globals()['InternalRelationTuple'] = InternalRelationTuple from ory_keto_client.model.get_relation_tuples_response import GetRelationTuplesResponse class TestGetRelationTuplesResponse(unittest.TestCase): """GetRelationTuplesResponse unit test stubs""" def setUp(self): pass def tearDown(self): pass def testGetRelationTuplesResponse(self): """Test GetRelationTuplesResponse""" # FIXME: construct object with mandatory attributes with example values # model = GetRelationTuplesResponse() # noqa: E501 pass if __name__ == '__main__': unittest.main()
import flask from flask import Flask, request, render_template app = Flask(name) @app.route('/user', methods=['GET', 'POST']) def user(): if request.method == 'GET': name = request.args.get('name') return render_template('user.html', name=name) else: post_data = request.form # Update or create user profile return 'Updated profile'
<filename>client/src/app/project/list/project-list.component.ts import { Component, EventEmitter, OnInit } from '@angular/core'; import { Apollo } from 'apollo-angular'; import { NgxSpinnerService } from 'ngx-spinner'; import { getProjectListQueryGql, GetProjectListQueryInterface, GetProjectListQueryProjectsFieldItemInterface, } from './get-project-list.query'; import { ActionButtonInterface, ActionButtonType, } from '../../title/title.component'; @Component({ selector: 'app-project-list', templateUrl: './project-list.component.html', styles: [], }) export class ProjectListComponent implements OnInit { projects: GetProjectListQueryProjectsFieldItemInterface[]; actions: ActionButtonInterface[]; constructor( protected apollo: Apollo, protected spinner: NgxSpinnerService, ) {} ngOnInit() { this.setUpActions(); this.getProjects(); } protected setUpActions(): void { this.actions = [ { type: ActionButtonType.success, label: 'Add', routerLink: '/project/add', }, ]; } protected getProjects() { this.spinner.show(); this.apollo .watchQuery<GetProjectListQueryInterface>({ query: getProjectListQueryGql, }) .valueChanges.subscribe(result => { const resultData: GetProjectListQueryInterface = result.data; this.projects = resultData.projects; this.spinner.hide(); }); } }
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ { path: '', loadChildren: () => import('./pages/home/home.module').then(mod => mod.HomeModule), pathMatch: 'full', data: { meta: [ { name: 'description', content: 'Dev tools made by developers for developers to make your day to day dev life easier. Free and Open Source.' } ] } }, { path: 'hash-generator', loadChildren: () => import('./pages/hash-generator/hash-generator.module').then( mod => mod.HashGeneratorModule ), data: { title: 'Hash Generator', meta: [ { name: 'description', content: 'Generate cryptographic hash codes from a message or file. It supports most used common hash algorithms, such as SHA-1, SHA-256, SHA-384, SHA-512.' } ] } }, { path: 'epoch-converter', loadChildren: () => import('./pages/epoch-converter/epoch-converter.module').then( mod => mod.EpochConverterModule ), data: { title: 'Epoch Time Converter', meta: [ { name: 'description', content: 'Convert Epoch and Unix timestamp to human readable time, local time, ISO time format, and vice versa. Timestamp Converter for developers.' } ] } }, { path: 'unicode-converter', loadChildren: () => import('./pages/unicode-converter/unicode-converter.module').then( mod => mod.UnicodeConverterModule ), data: { title: 'Unicode Converter', meta: [ { name: 'description', content: 'Text processing tool to encode your text and convert it to UTF-8, UTF-16 and UTF-32 and get their various representation formats.' } ] } }, { path: '**', redirectTo: '' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
#!/bin/bash # This shell script converts BigQuery .sql files into PostgreSQL .sql files. # String replacements are necessary for some queries. export REGEX_SCHEMA='s/`physionet-data.(mimic_core|mimic_icu|mimic_derived|mimic_hosp).(.+?)`/\1.\2/g' # Note that these queries are very senstive to changes, e.g. adding whitespaces after comma can already change the behavior. export REGEX_DATETIME_DIFF="s/DATETIME_DIFF\((.+?),\s?(.+?),\s?(DAY|MINUTE|SECOND|HOUR|YEAR)\)/DATETIME_DIFF(\1,\2,'\3')/g" export REGEX_DATETIME_TRUNC="s/DATETIME_TRUNC\((.+?),\s?(DAY|MINUTE|SECOND|HOUR|YEAR)\)/DATE_TRUNC('\2', \1)/g" # Add necessary quotes to INTERVAL, e.g. "INTERVAL 5 hour" to "INTERVAL '5' hour" export REGEX_INTERVAL="s/interval\s([[:digit:]]+)\s(hour|day|month|year)/INTERVAL '\1' \2/gI" # Add numeric cast to ROUND(), e.g. "ROUND(1.234, 2)" to "ROUND( CAST(1.234 as numeric), 2)". export PERL_REGEX_ROUND='s/ROUND\(((.|\n)*?)\, /ROUND\( CAST\( \1 as numeric\)\,/g' # Specific queries for some problems that arose with some files. export REGEX_INT="s/CAST\(hr AS INT64\)/CAST\(hr AS bigint\)/g" export REGEX_ARRAY="s/GENERATE_ARRAY\(-24, CEIL\(DATETIME\_DIFF\(it\.outtime_hr, it\.intime_hr, HOUR\)\)\)/ARRAY\(SELECT \* FROM generate\_series\(-24, CEIL\(DATETIME\_DIFF\(it\.outtime_hr, it\.intime_hr, HOUR\)\)\)\)/g" export REGEX_HOUR_INTERVAL="s/INTERVAL CAST\(hr AS INT64\) HOUR/interval \'1\' hour * CAST\(hr AS bigint\)/g" export REGEX_SECONDS="s/SECOND\)/\'SECOND\'\)/g" export CONNSTR='-U postgres -h localhost -p 5500 -d mimic-iv' # -d mimic # First, we re-create the postgres-make-concepts.sql file. echo "\echo ''" > postgres/postgres-make-concepts.sql # Now we add some preamble for the user running the script. echo "\echo '==='" >> postgres/postgres-make-concepts.sql echo "\echo 'Beginning to create materialized views for MIMIC database.'" >> postgres/postgres-make-concepts.sql echo "\echo '"'Any notices of the form "NOTICE: materialized view "XXXXXX" does not exist" can be ignored.'"'" >> postgres/postgres-make-concepts.sql echo "\echo 'The scripts drop views before creating them, and these notices indicate nothing existed prior to creating the view.'" >> postgres/postgres-make-concepts.sql echo "\echo '==='" >> postgres/postgres-make-concepts.sql echo "\echo ''" >> postgres/postgres-make-concepts.sql # reporting to stdout the folder being run echo -n "Dependencies:" # output table creation calls to the make-concepts script echo "" >> postgres/postgres-make-concepts.sql echo "-- dependencies" >> postgres/postgres-make-concepts.sql for dir_and_table in demographics.icustay_times demographics.weight_durations measurement.urine_output organfailure.kdigo_uo; do d=`echo ${dir_and_table} | cut -d. -f1` tbl=`echo ${dir_and_table} | cut -d. -f2` # make the sub-folder for postgres if it does not exist mkdir -p "postgres/${d}" # convert the bigquery script to psql and output it to the appropriate subfolder echo -n " ${d}.${tbl} .." echo "-- THIS SCRIPT IS AUTOMATICALLY GENERATED. DO NOT EDIT IT DIRECTLY." > "postgres/${d}/${tbl}.sql" echo "DROP TABLE IF EXISTS ${tbl}; CREATE TABLE ${tbl} AS " >> "postgres/${d}/${tbl}.sql" # for two scripts, add a perl replace to cast rounded values as numeric if [[ "${tbl}" == "icustay_times" ]] || [[ "${tbl}" == "urine_output" ]]; then cat "${d}/${tbl}.sql" | sed -r -e "${REGEX_ARRAY}" | sed -r -e "${REGEX_HOUR_INTERVAL}" | sed -r -e "${REGEX_INT}" | sed -r -e "${REGEX_DATETIME_DIFF}" | sed -r -e "${REGEX_DATETIME_TRUNC}" | sed -r -e "${REGEX_SCHEMA}" | sed -r -e "${REGEX_INTERVAL}" | sed -r -e "${REGEX_SECONDS}" | perl -0777 -pe "${PERL_REGEX_ROUND}" >> "postgres/${d}/${tbl}.sql" else cat "${d}/${tbl}.sql" | sed -r -e "${REGEX_ARRAY}" | sed -r -e "${REGEX_HOUR_INTERVAL}" | sed -r -e "${REGEX_INT}" | sed -r -e "${REGEX_DATETIME_DIFF}" | sed -r -e "${REGEX_DATETIME_TRUNC}" | sed -r -e "${REGEX_SCHEMA}" | sed -r -e "${REGEX_INTERVAL}" | sed -r -e "${REGEX_SECONDS}" >> "postgres/${d}/${tbl}.sql" fi # write out a call to this script in the make concepts file echo "\i ${d}/${tbl}.sql" >> postgres/postgres-make-concepts.sql done echo " done!" # Iterate through each concept subfolder, and: # (1) apply the above regular expressions to update the script # (2) output to the postgres subfolder # (3) add a line to the postgres-make-concepts.sql script to generate this table # order of the folders is important for a few tables here: # * scores (sofa et al) depend on labs, icustay_hourly # * sepsis depends on score (sofa.sql in particular) # * organfailure depends on measurement and firstday # the order *only* matters during the conversion step because our loop is # inserting table build commands into the postgres-make-concepts.sql file for d in demographics measurement comorbidity medication treatment firstday organfailure score sepsis; do mkdir -p "postgres/${d}" echo -n "${d}:" echo "" >> postgres/postgres-make-concepts.sql echo "-- ${d}" >> postgres/postgres-make-concepts.sql for fn in `ls $d`; do # only run SQL queries if [[ "${fn: -4}" == ".sql" ]]; then # table name is file name minus extension tbl="${fn::-4}" # skip first_day_sofa as it depends on other firstday queries, we'll generate it later # we also skipped tables generated in the "Dependencies" loop above. if [[ "${tbl}" == "first_day_sofa" ]] || [[ "${tbl}" == "icustay_times" ]] || [[ "${tbl}" == "weight_durations" ]] || [[ "${tbl}" == "urine_output" ]] || [[ "${tbl}" == "kdigo_uo" ]] || [[ "${tbl}" == "sepsis3" ]]; then continue fi echo -n " ${tbl} .." echo "-- THIS SCRIPT IS AUTOMATICALLY GENERATED. DO NOT EDIT IT DIRECTLY." > "postgres/${d}/${tbl}.sql" echo "DROP TABLE IF EXISTS ${tbl}; CREATE TABLE ${tbl} AS " >> "postgres/${d}/${tbl}.sql" cat "${d}/${tbl}.sql" | sed -r -e "${REGEX_ARRAY}" | sed -r -e "${REGEX_HOUR_INTERVAL}" | sed -r -e "${REGEX_INT}" | sed -r -e "${REGEX_DATETIME_DIFF}" | sed -r -e "${REGEX_DATETIME_TRUNC}" | sed -r -e "${REGEX_SCHEMA}" | sed -r -e "${REGEX_INTERVAL}" | perl -0777 -pe "${PERL_REGEX_ROUND}" >> "postgres/${d}/${fn}" echo "\i ${d}/${fn}" >> postgres/postgres-make-concepts.sql fi done echo " done!" done # finally generate first_day_sofa which depends on concepts in firstday folder echo "" >> postgres/postgres-make-concepts.sql echo "-- final tables dependent on previous concepts" >> postgres/postgres-make-concepts.sql for dir_and_table in firstday.first_day_sofa sepsis.sepsis3 do d=`echo ${dir_and_table} | cut -d. -f1` tbl=`echo ${dir_and_table} | cut -d. -f2` # make the sub-folder for postgres if it does not exist mkdir -p "postgres/${d}" # convert the bigquery script to psql and output it to the appropriate subfolder echo -n " ${d}.${tbl} .." echo "-- THIS SCRIPT IS AUTOMATICALLY GENERATED. DO NOT EDIT IT DIRECTLY." > "postgres/${d}/${tbl}.sql" echo "DROP TABLE IF EXISTS ${tbl}; CREATE TABLE ${tbl} AS " >> "postgres/${d}/${tbl}.sql" cat "${d}/${tbl}.sql" | sed -r -e "${REGEX_ARRAY}" | sed -r -e "${REGEX_HOUR_INTERVAL}" | sed -r -e "${REGEX_INT}" | sed -r -e "${REGEX_DATETIME_DIFF}" | sed -r -e "${REGEX_DATETIME_TRUNC}" | sed -r -e "${REGEX_SCHEMA}" | sed -r -e "${REGEX_INTERVAL}" | sed -r -e "${REGEX_SECONDS}" >> "postgres/${d}/${tbl}.sql" # write out a call to this script in the make concepts file echo "\i ${d}/${tbl}.sql" >> postgres/postgres-make-concepts.sql done echo " done!"
<reponame>npmccallum/krb5-pake<filename>src/client.c<gh_stars>1-10 /* * Copyright (c) 2015 Red Hat, Inc. * Copyright (c) 2015 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <krb5/clpreauth_plugin.h> #include "global.h" #include "common.h" #include "kconv.h" #include "pake/pake.h" #include <errno.h> #include <string.h> struct krb5_clpreauth_moddata_st { krb5_octet buffer[EVP_MAX_MD_SIZE]; ASN1_OCTET_STRING *prv; global global; }; static krb5_error_code pake_client_prep_questions(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt, krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock, krb5_kdc_req *request, krb5_data *encoded_request_body, krb5_data *encoded_previous_request, krb5_pa_data *pa_data) { cb->need_as_key(context, rock); return 0; } static krb5_error_code pake_client_process(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt, krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock, krb5_kdc_req *request, krb5_data *encoded_request_body, krb5_data *encoded_previous_request, krb5_pa_data *pa_data, krb5_prompter_fct prompter, void *prompter_data, krb5_pa_data ***pa_data_out) { const ASN1_OCTET_STRING *inmsg = NULL; const global *g = &moddata->global; const krb5_octet *hbuf = NULL; const EC_GROUP *grp = NULL; const EVP_MD *md = NULL; ASN1_OCTET_STRING *outmsg = NULL; ASN1_OCTET_STRING *outprv = NULL; krb5_error_code retval = 0; krb5_keyblock *ask = NULL; /* Alias; don't free. */ krb5_keyblock *dsk = NULL; PAKE_MESSAGE *in = NULL; EC_POINT *kek = NULL; krb5_int32 ptype; /* Create the PA data array. */ *pa_data_out = calloc(2, sizeof(**pa_data_out)); if (*pa_data_out == NULL) { goto error; } /* Get the key. */ retval = cb->get_as_key(context, rock, &ask); if (retval) goto error; /* Decode the PA data. */ in = padata2item(pa_data, PAKE_MESSAGE); if (in == NULL) { retval = EINVAL; /* Bad input. */ goto error; } if (in->type == PAKE_MESSAGE_TYPE_EXCHANGE) inmsg = in->value.data->data; /* Setup crypto. */ retval = global_profile(g, ask, in, &ptype, NULL, &grp, &md); if (retval != 0) goto error; /* Hash the incoming packet. */ if (in->type != PAKE_MESSAGE_TYPE_INFO) hbuf = moddata->buffer; retval = common_hash_padata(md, hbuf, pa_data, moddata->buffer); if (retval != 0) goto error; /* Perform PAKE iteration. */ retval = common_pake(ptype, request, ask, FALSE, grp, md, inmsg, moddata->prv, &outmsg, &outprv, &kek, g->ctx); ASN1_OCTET_STRING_free(moddata->prv); moddata->prv = outprv; if (retval != 0) goto error; if (outmsg != NULL) { /* Make the output PA data. */ retval = common_padata(ptype, ask->enctype, grp, md, PAKE_MESSAGE_TYPE_EXCHANGE, outmsg, &(*pa_data_out)[0]); if (retval != 0) goto error; /* Hash the outgoing packet. */ retval = common_hash_padata(md, moddata->buffer, (*pa_data_out)[0], moddata->buffer); if (retval != 0) goto error; } else { if (kek == NULL) { retval = EINVAL; goto error; } /* Derive the key. */ retval = common_derive(context, request, ask, grp, md, moddata->buffer, kek, &dsk, g->ctx); if (retval != 0) goto error; /* Make the verifier. */ outmsg = common_verifier(md, dsk); if (outmsg == NULL) { retval = ENOMEM; goto error; } /* Make the output PA data. */ retval = common_padata(ptype, ask->enctype, grp, md, PAKE_MESSAGE_TYPE_VERIFIER, outmsg, &(*pa_data_out)[0]); if (retval != 0) goto error; retval = cb->set_as_key(context, rock, dsk); if (retval != 0) goto error; } error: if (retval != 0) common_free_padata(pa_data_out); krb5_free_keyblock(context, dsk); ASN1_OCTET_STRING_free(outmsg); PAKE_MESSAGE_free(in); EC_POINT_free(kek); return retval; } static krb5_error_code pake_init(krb5_context context, krb5_clpreauth_moddata *moddata_out) { krb5_clpreauth_moddata md; krb5_error_code retval; *moddata_out = calloc(1, sizeof(*md)); if (*moddata_out == NULL) return ENOMEM; retval = global_init(&(*moddata_out)->global); if (retval != 0) { free(*moddata_out); return retval; } OpenSSL_add_all_digests(); return 0; } static void pake_fini(krb5_context context, krb5_clpreauth_moddata moddata) { ASN1_OCTET_STRING_free(moddata->prv); global_free(&moddata->global); free(moddata); EVP_cleanup(); } krb5_error_code clpreauth_pake_initvt(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable) { static krb5_preauthtype types[] = { PA_PAKE, 0 }; krb5_clpreauth_vtable vt; if (maj_ver != 1) return KRB5_PLUGIN_VER_NOTSUPP; vt = (krb5_clpreauth_vtable)vtable; vt->name = "pake"; vt->pa_type_list = types; vt->init = pake_init; vt->fini = pake_fini; vt->prep_questions = pake_client_prep_questions; vt->process = pake_client_process; return 0; }
#!/usr/bin/env bash # Copyright 2020 The Knative Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -o errexit set -o nounset set -o pipefail source $(dirname $0)/../vendor/knative.dev/hack/codegen-library.sh # If we run with -mod=vendor here, then generate-groups.sh looks for vendor files in the wrong place. export GOFLAGS=-mod= echo "=== Update Codegen for $MODULE_NAME" echo "GOPATH=$GOPATH" group "Kubernetes Codegen" # generate the code with: # --output-base because this script should also be able to run inside the vendor dir of # k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir # instead of the $GOPATH directly. For normal projects this can be dropped. ${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ knative.dev/discovery/pkg/client knative.dev/discovery/pkg/apis \ "discovery:v1alpha1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt group "Knative Codegen" # Knative Injection ${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \ knative.dev/discovery/pkg/client knative.dev/discovery/pkg/apis \ "discovery:v1alpha1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt group "Update deps post-codegen" # Make sure our dependencies are up-to-date ${REPO_ROOT_DIR}/hack/update-deps.sh
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * <EMAIL> */ /***************************************************************************** Source esm_main.c Version 0.1 Date 2012/12/04 Product NAS stack Subsystem EPS Session Management Author <NAME> Description Defines the EPS Session Management procedure call manager, the main entry point for elementary ESM processing. *****************************************************************************/ #include "3gpp_24.007.h" #include "esm_main.h" #include "commonDef.h" #include "log.h" #include "emmData.h" #include "esmData.h" #include "esm_pt.h" #include "esm_ebr.h" /****************************************************************************/ /**************** E X T E R N A L D E F I N I T I O N S ****************/ /****************************************************************************/ /****************************************************************************/ /******************* L O C A L D E F I N I T I O N S *******************/ /****************************************************************************/ /****************************************************************************/ /****************** E X P O R T E D F U N C T I O N S ******************/ /****************************************************************************/ /**************************************************************************** ** ** ** Name: esm_main_initialize() ** ** ** ** Description: Initializes ESM internal data ** ** ** ** Inputs: None ** ** Others: None ** ** ** ** Outputs: None ** ** Return: None ** ** Others: None ** ** ** ***************************************************************************/ void esm_main_initialize ( void) { OAILOG_FUNC_IN (LOG_NAS_ESM); /* * Retreive MME supported configuration data */ if (mme_api_get_esm_config (&_esm_data.conf) != RETURNok) { OAILOG_ERROR (LOG_NAS_ESM, "ESM-MAIN - Failed to get MME configuration data\n"); } /* * Initialize the EPS bearer context manager */ esm_ebr_initialize (); OAILOG_FUNC_OUT (LOG_NAS_ESM); } /**************************************************************************** ** ** ** Name: esm_main_cleanup() ** ** ** ** Description: Performs the EPS Session Management clean up procedure ** ** ** ** Inputs: None ** ** Others: None ** ** ** ** Outputs: None ** ** Return: None ** ** Others: None ** ** ** ***************************************************************************/ void esm_main_cleanup ( void) { OAILOG_FUNC_IN (LOG_NAS_ESM); OAILOG_FUNC_OUT (LOG_NAS_ESM); } /****************************************************************************/ /********************* L O C A L F U N C T I O N S *********************/ /****************************************************************************/
#!/usr/bin/env bash RootPath=$(cd $(dirname $0)/..; pwd) Version=`git describe --abbrev=0 --tags 2>/dev/null` BranchName=`git rev-parse --abbrev-ref HEAD 2>/dev/null` CommitID=`git rev-parse HEAD 2>/dev/null` BuildTime=`date +%Y-%m-%d\ %H:%M` SrcPath=${RootPath}/libsdk case `uname` in Linux) TargetFile=${1:-${SrcPath}/libcfs.so} ;; *) echo "Unsupported platform" exit 0 ;; esac [[ "-$GOPATH" == "-" ]] && { echo "GOPATH not set"; exit 1; } LDFlags="-X github.com/cubefs/cubefs/proto.Version=${Version} \ -X github.com/cubefs/cubefs/proto.CommitID=${CommitID} \ -X github.com/cubefs/cubefs/proto.BranchName=${BranchName} \ -X 'github.com/cubefs/cubefs/proto.BuildTime=${BuildTime}' " go build \ -ldflags "${LDFlags}" \ -buildmode c-shared \ -o $TargetFile \ ${SrcPath}/*.go
#!/bin/bash # This script is meant to be called by the "install" step defined in # build.yml. The behavior of the script is controlled by environment # variables defined in the build.yml in .github/workflows/. set -e if [[ "$RUNNER_OS" == "Linux" ]]; then sudo apt-get update -qq sudo apt-get install -qq gfortran libgfortran3 fi if [[ "$PYTHON_VERSION" == "3.5" ]]; then conda install mkl pip pytest scipy=1.1 numpy=1.15 lapack ecos scs osqp flake8 cvxopt elif [[ "$PYTHON_VERSION" == "3.6" ]]; then conda install mkl pip pytest scipy=1.1 numpy=1.15 lapack ecos scs osqp flake8 cvxopt elif [[ "$PYTHON_VERSION" == "3.7" ]]; then conda install mkl pip pytest scipy=1.1 numpy=1.15 lapack ecos scs osqp flake8 cvxopt elif [[ "$PYTHON_VERSION" == "3.8" ]]; then # There is a config that works with numpy 1.14, but not 1.15! # So we fix things at 1.16. # Assuming we use numpy 1.16, the earliest version of scipy we can use is 1.3. conda install mkl pip pytest scipy=1.3 numpy=1.16 lapack ecos scs osqp flake8 cvxopt elif [[ "$PYTHON_VERSION" == "3.9" ]]; then # The earliest version of numpy that works is 1.19. # Given numpy 1.19, the earliest version of scipy we can use is 1.5. conda install mkl pip pytest scipy=1.5 numpy=1.19 lapack ecos scs flake8 cvxopt python -m pip install osqp fi if [[ "$USE_OPENMP" == "True" ]]; then conda install -c conda-forge openmp fi python -m pip install diffcp if [[ "$COVERAGE" == "True" ]]; then python -m pip install coverage coveralls fi
<filename>src/main/scala/com/craftinginterpreters/lox/Resolver.scala<gh_stars>1-10 package com.craftinginterpreters.lox import scala.collection.mutable object Resolver { private sealed trait FunctionType private case object NONE extends FunctionType private case object FUNCTION extends FunctionType private case object INITIALIZER extends FunctionType private case object METHOD extends FunctionType private sealed trait ClassType private case object NOCLASS extends ClassType private case object CLASS extends ClassType private case object SUBCLASS extends ClassType private val scopes = mutable.Stack[mutable.Map[String, Boolean]]() private var currentFunction: FunctionType = NONE private var currentClass: ClassType = NOCLASS def resolve(statements: Seq[Stmt]): Unit = for (statement <- statements) resolve(statement) private def resolve(statement: Stmt): Unit = statement match { case Var(name, initializer) => declare(name) initializer match { case None => () case Some(init) => resolve(init) } define(name) case f @ Function(name, _, _) => declare(name) define(name) resolveFunction(f, FUNCTION) // simple cases case Block(statements) => beginScope() resolve(statements) endScope() case Class(name, superclass, methods) => val enclosingClass = currentClass currentClass = CLASS declare(name) define(name) superclass match { case None => () case Some(s @ Variable(n)) => if (name.lexeme.equals(n.lexeme)) Lox.error(n, "A class cannot inherit from itself.") currentClass = SUBCLASS resolve(s) beginScope() scopes.top += ("super" -> true) } beginScope() scopes.top += ("this" -> true) for (method <- methods) { val declaration = if (method.name.lexeme.equals("init")) INITIALIZER else METHOD resolveFunction(method, declaration) } endScope() superclass match { case None => () case Some(_) => endScope() } currentClass = enclosingClass case Expression(expr) => resolve(expr) case If(condition, thenBranch, elseBranch) => resolve(condition) resolve(thenBranch) elseBranch match { case None => () case Some(branch) => resolve(branch) } case Print(expr) => resolve(expr) case Return(keyword, expr) => currentFunction match { case NONE => Lox.error(keyword, "Cannot return from top-level code.") case INITIALIZER if expr != Literal(NilVal) => Lox.error(keyword, "Cannot return a value from an initializer.") case _ => () } resolve(expr) case While(condition, body) => resolve(condition) resolve(body) case End => () } private def resolve(expr: Expr): Unit = expr match { case Variable(name) => if (scopes.nonEmpty) scopes.top.get(name.lexeme) match { case Some(false) => Lox.error(name, "Cannot read local variable in its own initializer.") case _ => () } resolveLocal(expr, name) case Assign(name, right) => resolve(right) resolveLocal(expr, name) // simple cases case Binary(left, _, right) => resolve(left) resolve(right) case Call(callee, _, args) => resolve(callee) for (arg <- args) resolve(arg) case Get(obj, _) => resolve(obj) case Grouping(expr) => resolve(expr) case Literal(_) => () case Set(obj, _, value) => resolve(value) resolve(obj) case Super(keyword, _) => currentClass match { case NOCLASS => Lox.error(keyword, "Cannot use 'super' outside of a class.") case SUBCLASS => () case _ => Lox.error(keyword, "Cannot use 'super' in a class with no superclass.") } resolveLocal(expr, keyword) case This(keyword) => currentClass match { case NOCLASS => Lox.error(keyword, "Cannot use 'this' outside of a class.") case _ => resolveLocal(expr, keyword) } case Unary(_, right) => resolve(right) } private def resolveLocal(expr: Expr, name: Token): Unit = for ((scope, i) <- scopes.zipWithIndex) if (scope.contains(name.lexeme)) { Interpreter.resolve(expr, i) return } private def resolveFunction(function: Function, functionType: FunctionType): Unit = { val enclosingFunction = currentFunction currentFunction = functionType beginScope() for (param <- function.params) { declare(param) define(param) } resolve(function.body) endScope() currentFunction = enclosingFunction } private def declare(name: Token): Unit = if (scopes.isEmpty) () else if (scopes.top.contains(name.lexeme)) Lox.error(name, "Variable with this name already declared in this scope.") else scopes.top += (name.lexeme -> false) private def define(name: Token): Unit = if (scopes.isEmpty) () else scopes.top += (name.lexeme -> true) private def beginScope(): Unit = { scopes.push(mutable.Map()) () } private def endScope(): Unit = { scopes.pop() () } }
<reponame>thiagopnts/audio-to-text-telegram-bot const TelegramBot = require('node-telegram-bot-api'); const Speech = require('@google-cloud/speech'); const get = require('lodash.get'); const path = require('path'); const ffmpeg = require('fluent-ffmpeg'); const fs = require('fs'); const TOKEN = process.env.TELEGRAM_BOT_TOKEN || new Error('You should set TELEGRAM_BOT_TOKEN env variable'); const AUDIO_PATH = path.join(process.cwd(), './voice'); const allowEverything = process.env.DISALLOW_ALL ? false : true; const nameRegExp = new RegExp(process.env.BOTNAME || 'speechtotextbot', 'i'); const textLang = process.env.TEXT_LANG || 'pt-BR'; const allowed = process.env.ALLOWED_IDS ? process.env.ALLOWED_IDS.split(',') : []; const bot = new TelegramBot(TOKEN, {polling: true}); const speech = new Speech({}); let recognize = (file, config={encoding:'FLAC', sampleRate: 48000, languageCode: 'pt-BR'}) => { console.log('transcripting'); return speech.startRecognition(file, config) .then(result => { const op = result[0]; return op.promise(); }); } let transcode = file => { console.log('transcoding'); const filename = path.basename(file); const nameWithoutExt = filename.replace(path.extname(filename), ''); const output = path.join(AUDIO_PATH, `${nameWithoutExt}.flac`); return new Promise(resolve => { ffmpeg().input(file) .outputFormat('flac') .saveToFile(output) .on('end', () => resolve(output)); }) }; let cleanup = file => { const fullFilenameWithoutExt = filename.replace(path.extname(filename), ''); return new Promise((resolve, reject) => { s.unlink(`${fullFilenameWithoutExt}.oga`, err => err ? reject(err) : resolve()); }) .then(() => { s.unlink(`${fullFilenameWithoutExt}.flac`, err => err ? reject(err) : resolve()); }); } // TODO: clean up files after sending bot.on('message', msg => { let isAllowed = allowEverything || (allowed.indexOf(get(msg, 'from.id', -1)) >= 0 || allowed.indexOf(get(msg, 'chat.id', -1)) >= 0); if (isAllowed && (msg.text || '').match(nameRegExp)) { const file = get(msg, 'reply_to_message.voice', null); file && bot.downloadFile(file.file_id, AUDIO_PATH) .then(transcode) .catch(err => { console.log('problem transcoding', err); }) .then(recognize) .then(transcription => { let reply = transcription[0] ? '"' + transcription[0] + '"' : 'sorry I couldnt understand'; console.log('reply', reply); bot.sendMessage(msg.chat.id, reply, {reply_to_message_id: msg.message_id}); }) .catch(err => { bot.sendMessage(msg.chat.id, 'sorry can you say it again', {reply_to_message_id: msg.message_id}); console.log('problem with transcription', err); }); } else { !isAllowed && bot.sendMessage(msg.chat.id, 'sorry I dont speak with strangers', {reply_to_message_id: msg.message_id}); } });
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' if [ -z "$1" ]; then echo "missing path to iso" exit 1 fi if [ "$(whoami)" != "root" ]; then echo "missing sudo" exit 1 fi storagegb=16 memgb=2 cpus=1 MB=$[1024*1024] GB=$[1024*$MB] dd if=/dev/zero of=storage.img bs=$[1*$GB] count=$storagegb xhyve \ -A \ -c "$cpus" \ -m "${memgb}G" \ -s 0,hostbridge \ -s 2,virtio-net \ -s "3,ahci-cd,$1" \ -s 4,virtio-blk,storage.img \ -s 31,lpc \ -l com1,stdio \ -f "kexec,boot/vmlinuz,boot/initrd.gz,earlyprintk=serial console=ttyS0"
#!/bin/bash # usage: ./countdown.sh 10 # check that exactly one argument was given if [[ $# -ne 1 ]]; then echo "Error: Must provide one argument." exit 1 fi # print the countdown number=$1 while [[ $number -gt 0 ]]; do echo $number number=$(($number-1)) done echo "0"
package baselib.base2; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.ColorFilter; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.view.MotionEvent; import android.view.TouchDelegate; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.Group; import androidx.core.content.ContextCompat; import androidx.databinding.BindingAdapter; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.target.CustomViewTarget; import com.bumptech.glide.request.target.ImageViewTarget; import com.bumptech.glide.request.transition.Transition; import java.io.File; import baselib.App; import baselib.util.FastBlur; public abstract class DataBindingConfig { @BindingAdapter("url") public static void setImageUrl(ImageView imageView, String url) { Glide.with(imageView.getContext()) .load(url) .into(imageView); } @BindingAdapter("onFocusChanged") public static void onFocusChanged(EditText view, View.OnFocusChangeListener onFocusChangeListener) { if (onFocusChangeListener != null) { view.setOnFocusChangeListener(onFocusChangeListener); } } @BindingAdapter("selected") public static void selected(View view, boolean selected) { view.setSelected(selected); } @BindingAdapter("enabled") public static void enable(View view, boolean enabled) { view.setEnabled(enabled); } @BindingAdapter("visible") public static void setVisible(View v, boolean visible) { v.setVisibility(visible ? View.VISIBLE : View.GONE); } @BindingAdapter("android:paddingBottom") public static void setPaddingBottom(View view, float padding) { view.setPadding(view.getPaddingStart(), view.getPaddingTop(), view.getPaddingEnd(), (int) padding); } @BindingAdapter("android:layout_marginStart") public static void setMarginStart(View v, float margin) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); params.leftMargin = (int) margin; v.setLayoutParams(params); } @BindingAdapter("android:layout_marginStart") public static void setMarginStart(View v, int margin) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); params.leftMargin = margin; v.setLayoutParams(params); } @BindingAdapter("android:layout_marginTop") public static void setMarginTop(View v, float margin) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); params.topMargin = (int) margin; v.setLayoutParams(params); } @BindingAdapter("android:layout_marginTop") public static void setMarginTop(View v, int margin) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); params.topMargin = margin; v.setLayoutParams(params); } @BindingAdapter("android:layout_marginBottom") public static void setMarginBottom(View v, float margin) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); params.bottomMargin = (int) margin; v.setLayoutParams(params); } @BindingAdapter("android:layout_marginEnd") public static void setMarginEnd(View v, float margin) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams(); params.rightMargin = (int) margin; v.setLayoutParams(params); } @BindingAdapter("android:layout_height") public static void setLayoutHeight(View view, float height) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.height = (int) height; view.setLayoutParams(layoutParams); } @BindingAdapter("android:layout_width") public static void setLayoutWidth(View view, float width) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.width = (int) width; view.setLayoutParams(layoutParams); } @BindingAdapter("android:layout_weight") public static void setWeight(View view, float weight) { LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams(); layoutParams.weight = weight; view.requestLayout(); } @BindingAdapter({"android:drawableStart"}) public static void setDrawableStart(TextView view, @DrawableRes int resourceId) { Drawable[] drawables = view.getCompoundDrawables(); if (resourceId == 0) { view.setCompoundDrawables(null, drawables[1], drawables[2], drawables[3]); } else { Drawable drawable = ContextCompat.getDrawable(view.getContext(), resourceId); if (drawable != null) { drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); } view.setCompoundDrawables(drawable, drawables[1], drawables[2], drawables[3]); } } @BindingAdapter({"android:drawableEnd"}) public static void setDrawableEnd(TextView view, @DrawableRes int resourceId) { Drawable[] drawables = view.getCompoundDrawables(); if (resourceId == 0) { view.setCompoundDrawables(drawables[0], drawables[1], null, drawables[3]); } else { Drawable drawable = ContextCompat.getDrawable(view.getContext(), resourceId); if (drawable != null) { drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); } view.setCompoundDrawables(drawables[0], drawables[1], drawable, drawables[3]); } } @BindingAdapter({"bold"}) public static void setBold(TextView textView, boolean bold) { if (bold) { textView.setTypeface(textView.getTypeface(), Typeface.BOLD); } else { textView.setTypeface(textView.getTypeface(), Typeface.NORMAL); } } @BindingAdapter({"android:textColor"}) public static void setTextColor(TextView textView, @ColorInt int color) { textView.setTextColor(color); } @BindingAdapter({"android:drawablePadding"}) public static void setDrawablePaddingStart(TextView view, float padding) { view.setCompoundDrawablePadding((int) padding); } @BindingAdapter({"android:onClick"}) public static void setGroupOnClickListener(Group group, View.OnClickListener listener) { int refIds[] = group.getReferencedIds(); for (int id : refIds) { ViewGroup parent = (ViewGroup) group.getParent(); parent.findViewById(id).setOnClickListener(listener); } } @BindingAdapter({"content", "subcontent1", "subcontent2", "subcontent3", "color", "backColor", "onClick1", "onClick2", "onClick3"}) public static void setTextSpecialColorAndClickListener(View view, String content, String subcontent1, String subcontent2, String subcontent3, int color, int backColor, View.OnClickListener listener1, View.OnClickListener listener2, View.OnClickListener listener3) { if (!(view instanceof TextView)) { return; } SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content); int start1 = 0; int end1 = 0; if (!TextUtils.isEmpty(subcontent1) && content.contains(subcontent1)) { ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(color); start1 = content.indexOf(subcontent1); end1 = start1 + subcontent1.length(); if (start1 < end1) { stringBuilder.setSpan(foregroundColorSpan1, start1, end1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } int start2 = 0; int end2 = 0; if (!TextUtils.isEmpty(subcontent2) && content.contains(subcontent2)) { ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(color); start2 = content.indexOf(subcontent2); end2 = start2 + subcontent2.length(); if (start2 < end2) { stringBuilder.setSpan(foregroundColorSpan2, start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } int start3 = 0; int end3 = 0; if (!TextUtils.isEmpty(subcontent3) && content.contains(subcontent3)) { ForegroundColorSpan foregroundColorSpan3 = new ForegroundColorSpan(color); start3 = content.indexOf(subcontent3); end3 = start3 + subcontent3.length(); if (start3 < end3) { stringBuilder.setSpan(foregroundColorSpan3, start3, end3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } ClickableSpan clickableSpan1 = new ClickableSpan() { @Override public void onClick(@NonNull View widget) { listener1.onClick(widget); } @Override public void updateDrawState(TextPaint ds) { ds.setUnderlineText(false); } }; ClickableSpan clickableSpan2 = new ClickableSpan() { @Override public void onClick(@NonNull View widget) { listener2.onClick(widget); } @Override public void updateDrawState(TextPaint ds) { ds.setUnderlineText(false); } }; ClickableSpan clickableSpan3 = new ClickableSpan() { @Override public void onClick(@NonNull View widget) { listener3.onClick(widget); } @Override public void updateDrawState(TextPaint ds) { ds.setUnderlineText(false); } }; stringBuilder.setSpan(clickableSpan1, start1, end1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(clickableSpan2, start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(clickableSpan3, start3, end3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ((TextView) view).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) view).setHighlightColor(backColor); ((TextView) view).setText(stringBuilder); } @BindingAdapter({"fade"}) public static void setVisibilityAnim(View view, int visibility) { if (view.getVisibility() == visibility) { return; } if (visibility == View.VISIBLE) { view.clearAnimation(); view.setVisibility(View.VISIBLE); view.animate().alpha(1).setDuration(200).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.clearAnimation(); view.animate().setListener(null); } }).start(); } else { view.clearAnimation(); view.animate().alpha(0).setDuration(200).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.clearAnimation(); view.setVisibility(visibility); } }); } } @BindingAdapter({"fade"}) public static void setGroupFade(Group group, int visibility) { int refIds[] = group.getReferencedIds(); for (int id : refIds) { ViewGroup parent = (ViewGroup) group.getParent(); View view = parent.findViewById(id); if (visibility == View.VISIBLE) { view.clearAnimation(); group.setVisibility(View.VISIBLE); view.animate().alpha(1).setDuration(200).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.clearAnimation(); } }).start(); } else { view.clearAnimation(); view.animate().alpha(0).setDuration(200).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.clearAnimation(); group.setVisibility(visibility); } }); } if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { setVisibilityAnim(viewGroup.getChildAt(i), visibility); } } } } @SuppressLint("ClickableViewAccessibility") @BindingAdapter("pressAlpha") public static void setPressAlpha(View view, float alpha) { view.setOnTouchListener((v, event) -> { if (view.isEnabled()) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: view.setAlpha(alpha); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: view.setAlpha(1.0f); break; } } return false; }); } @BindingAdapter("gray") public static void setGray(ImageView v, boolean gray) { ColorFilter filter = null; if (gray) { ColorMatrix matrix = new ColorMatrix(); matrix.setSaturation(0); filter = new ColorMatrixColorFilter(matrix); } v.setColorFilter(filter); } /** * 用于url图片加载,并且实现高斯模糊效果 */ @BindingAdapter({"url", "blur"}) public static void loadImage(ImageView view, String url, int blur) { if (!TextUtils.isEmpty(url) && blur > 0) { Glide.with(App.getAppalication()).asBitmap().load(url).into(new ImageViewTarget<Bitmap>(view) { @Override protected void setResource(@Nullable Bitmap resource) { if (resource != null) { Bitmap blurBg = FastBlur.doBlur(resource, blur, false); view.setImageBitmap(blurBg); } else { view.setImageBitmap(null); } } }); } } @BindingAdapter({"android:src"}) public static void loadImage(ImageView view, int res) { if (res > 0) { view.setImageResource(res); } } @BindingAdapter({"path"}) public static void loadImageFromPath(ImageView view, String path) { if (!TextUtils.isEmpty(path)) { Glide.with(view).load(new File(path)).into(view); } } @BindingAdapter({"url_withNoCache"}) public static void loadImageNoCache(ImageView view, String url) { Glide.with(view).load(url).diskCacheStrategy(DiskCacheStrategy.NONE).into(view); } @BindingAdapter({"layout_height"}) public static void setHeight(View view, int height) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams != null) { layoutParams.height = height; view.requestLayout(); } else { view.setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height)); } } /** * 加载view的背景图 * * @param view 任意view * @param background 背景图url * @param placeHolder 占位图 */ @BindingAdapter(value = {"android:background", "bgPlaceHolder"}, requireAll = false) public static void loadBackgroundImage(View view, String background, Drawable placeHolder) { view.setBackground(placeHolder); if (!TextUtils.isEmpty(background)) { Glide.with(view) .asBitmap() .load(background) .placeholder(placeHolder) .error(placeHolder) .into(new CustomViewTarget<View, Bitmap>(view) { @Override protected void onResourceCleared(@Nullable Drawable placeholder) { view.setBackground(null); } @Override public void onLoadFailed(@Nullable Drawable errorDrawable) { view.setBackground(errorDrawable); } @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { Drawable drawable = new BitmapDrawable(view.getResources(), resource); view.setBackground(drawable); } }); } } @BindingAdapter("spanCount") public static void setSpanCount(RecyclerView recyclerView, int spanCount) { if (recyclerView.getLayoutManager() instanceof GridLayoutManager) { ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanCount(spanCount); } } @BindingAdapter("touchArea") public static void expandTouchArea(View view, int touchArea) { try { view.post(() -> { View viewParent = (View) view.getParent(); Rect rect = new Rect(); view.getHitRect(rect); rect.top = rect.top - touchArea >= 0 ? rect.top - touchArea : rect.top; rect.bottom += touchArea; rect.left = rect.left - touchArea >= 0 ? rect.left - touchArea : rect.left; rect.right += touchArea; if (viewParent != null) { viewParent.setTouchDelegate(new TouchDelegate(rect, view)); } }); } catch (Exception e) { e.printStackTrace(); } } @BindingAdapter("touchArea") public static void expandTouchArea(View view, float touchArea) { expandTouchArea(view, (int) touchArea); } @BindingAdapter("nested_scrolling_enabled") public static void setNestedScrollingEnable(RecyclerView recyclerView, Boolean enable) { recyclerView.setNestedScrollingEnabled(enable); } }
<filename>src/containers/ap/ApGuestRegister.tsx import * as React from "react"; import { setAPImage } from "../../util/set-bg-image"; import FactaArticleRegion from '@facta/FactaArticleRegion'; import FactaNotitleRegion from "@facta/FactaNotitleRegion"; import { History } from 'history' import DateTriPicker, { DateTriPickerProps } from "@components/DateTriPicker"; import PhoneTriBox, { PhoneTriBoxProps } from "@components/PhoneTriBox"; import { SingleCheckbox } from "@components/InputGroup"; import formUpdateState from '../../util/form-update-state'; import TextInput from '../../components/TextInput'; import Validation from '../../util/Validation'; import FactaButton from '../../theme/facta/FactaButton'; import { Option, none, some } from 'fp-ts/lib/Option'; import { postWrapper as createGuest } from "@async/ap/create-ap-guest" import { makePostJSON, PostURLEncoded } from "@core/APIWrapperUtil"; import {FactaErrorDiv} from "@facta/FactaErrorDiv"; import FactaMainPage from "../../theme/facta/FactaMainPage"; import * as moment from 'moment'; import range from "@util/range"; import {postWrapper as refreshProto} from "@async/check-proto-person-cookie" type Props = { history: History<any> } type NewGuestInformation = { ticketHTML: string } type State = { formData: Form, validationErrors: string[], pageState: PageState, waiverAccepted: boolean, createResults: Option<NewGuestInformation> } enum PageState{ GUEST_INFORMATION, EC_INFORMATION, WAIVER, FINISH } const defaultForm = { firstName: none as Option<string>, lastName: none as Option<string>, email: none as Option<string>, dobMonth: none as Option<string>, dobDay: none as Option<string>, dobYear: none as Option<string>, guestPhoneFirst: none as Option<string>, guestPhoneSecond: none as Option<string>, guestPhoneThird: none as Option<string>, guestPhoneExt: none as Option<string>, guestPhoneType: none as Option<string>, ecFirstName: none as Option<string>, ecLastName: none as Option<string>, ecPhoneFirst: none as Option<string>, ecPhoneSecond: none as Option<string>, ecPhoneThird: none as Option<string>, ecPhoneExt: none as Option<string>, ecPhoneType: none as Option<string>, ecRelationship: none as Option<string> } type Form = typeof defaultForm class FormInput extends TextInput<Form> {} /* * DOB is a valid date (e.g. 2/31/1990 should throw an error) * Email is a valid email (I use the regex /^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/i ) * Phone number is valid (matches /^[0-9]{10}.*$/ ie exactly 10 digits, with the .* for any extension ) */ const phoneRegExp = new RegExp(/^[0-9]{10}([0-9])*$/); const isPhoneValid = (p1 : Option<string>, p2 : Option<string>, p3 : Option<string>, pe : Option<string>) => phoneRegExp.test(makePhone(pe, p1, p2, p3)); const isNotNull = (os: Option<string>) => os.isSome() && os.getOrElse("").length > 0; const validateECInfo: (state: State) => string[] = state => { const validations = [ new Validation(isNotNull(state.formData.ecFirstName), "Please enter an emergency contact first name."), new Validation(isNotNull(state.formData.ecLastName), "Please enter an emergency contact last name."), new Validation(isNotNull(state.formData.ecRelationship), "Please enter your relationship to your emergency contact."), new Validation(isPhoneValid(state.formData.ecPhoneFirst, state.formData.ecPhoneSecond, state.formData.ecPhoneThird, state.formData.ecPhoneExt), "Please enter a valid emergency contact phone number."), new Validation(isNotNull(state.formData.ecPhoneType), "Please specify phone number type."), ]; return validations.filter(v => !v.pass).map(v => v.errorString); } const validateGuestInfo: (state: State) => string[] = state => { const emailRegexp = new RegExp(/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/i); const isEmailValid = (os : Option<string>) => os.isSome() && emailRegexp.test(os.getOrElse("")) const isDOBValid = (state : State) => getDOBMoment(state).isValid(); const validations = [ new Validation(isNotNull(state.formData.firstName), "Please enter your first name."), new Validation(isNotNull(state.formData.lastName), "Please enter your last name."), new Validation(isDOBValid(state), "Please enter a valid birthday."), new Validation(isPhoneValid(state.formData.guestPhoneFirst, state.formData.guestPhoneSecond, state.formData.guestPhoneThird, state.formData.guestPhoneExt), "Please enter a valid guest phone number."), new Validation(isNotNull(state.formData.guestPhoneType), "Please specify phone number type."), new Validation(isEmailValid(state.formData.email), "Please enter a valid email.") ]; return validations.filter(v => !v.pass).map(v => v.errorString); } function makePhone (ext : Option<string>, first : Option<string>, second : Option<string>, third : Option<string>) : string { return first.getOrElse("").concat(second.getOrElse("")).concat(third.getOrElse("")).concat(ext.getOrElse("")); } function getDOBMoment (state : State) : any { return moment({year: Number.parseInt(state.formData.dobYear.getOrElse("-1")), month: (Number.parseInt(state.formData.dobMonth.getOrElse("-1"))-1), date: Number.parseInt(state.formData.dobDay.getOrElse("-1"))}); } export default class ApPreRegister extends React.PureComponent<Props, State> { constructor(props: Props) { super(props); this.state = { formData: defaultForm, validationErrors: [], pageState: PageState.GUEST_INFORMATION, waiverAccepted: false, createResults: none }; refreshProto.send(PostURLEncoded({})); } handlePrint = () => { //TODO maybe redo this in react style, if jon wants. var a = window.open('', '', 'height=500px, width=600px'); a.document.write('<html>'); a.document.write('<head>'); a.document.write('<title>'); a.document.write(this.state.formData.firstName.getOrElse("FIRST").concat(' ').concat(this.state.formData.lastName.getOrElse("LAST"))); a.document.write(' Guest Ticket</title>'); a.document.write('<body>'); a.document.write(this.state.createResults.map(r => r.ticketHTML.replace("$API_URL$", "")).getOrElse("")); a.document.write('</body></html>'); //a.document.body.append(this.printableDivRef.current); a.document.close(); a.onload = () => { a.print(); }; } progressFunction = () => { var validationResults; switch(this.state.pageState){ case PageState.GUEST_INFORMATION: validationResults = validateGuestInfo(this.state); if (validationResults.length > 0) { this.setState({ ...this.state, validationErrors: validationResults }) return Promise.resolve(); } else { this.setState({ ...this.state, validationErrors: [], pageState: PageState.EC_INFORMATION }); refreshProto.send(PostURLEncoded({})); return Promise.resolve(); } break; case PageState.EC_INFORMATION: validationResults = validateECInfo(this.state); if (validationResults.length > 0) { this.setState({ ...this.state, validationErrors: validationResults }) return Promise.resolve(); } else { this.setState({ ...this.state, validationErrors: [], pageState: PageState.WAIVER }); refreshProto.send(PostURLEncoded({})); return Promise.resolve(); } break; case PageState.WAIVER: let formattedDate = (getDOBMoment(this.state)).format('MM/DD/YYYY'); let guestPhone = makePhone(this.state.formData.guestPhoneExt, this.state.formData.guestPhoneFirst, this.state.formData.guestPhoneSecond, this.state.formData.guestPhoneThird); let emergPhone = makePhone(this.state.formData.ecPhoneExt, this.state.formData.ecPhoneFirst, this.state.formData.ecPhoneSecond, this.state.formData.ecPhoneThird); if(this.state.waiverAccepted){ const self = this; this.setState({ ...this.state, validationErrors: [] }) return createGuest.send(makePostJSON({ firstName: this.state.formData.firstName.getOrElse(""), lastName: this.state.formData.lastName.getOrElse(""), emailAddress: this.state.formData.email.getOrElse(""), dob: formattedDate, phonePrimary: guestPhone, emerg1Name: this.state.formData.ecFirstName.getOrElse("") + " " + this.state.formData.ecLastName.getOrElse(""), emerg1Relation: this.state.formData.ecRelationship.getOrElse(""), emerg1PhonePrimary: emergPhone, previousMember: false, phonePrimaryType: this.state.formData.guestPhoneType.getOrElse(""), emerg1PhonePrimaryType: this.state.formData.ecPhoneType.getOrElse(""), })).then(res => { if(res.type === "Success"){ self.setState({ ...self.state, pageState: PageState.FINISH, createResults: some({ ticketHTML: res.success.ticketHTML }), validationErrors: [] }); refreshProto.send(PostURLEncoded({})); return Promise.resolve("Success"); }else{ self.setState({ ...self.state, validationErrors: ["An internal error has occured, please try again later"] }) return Promise.resolve("Failure"); } }); }else{ this.setState({ ...this.state, validationErrors: ["Please agree to the terms to continue"] }); } break; } return Promise.resolve("Success"); } render() { const thisYear = Number(moment().format("YYYY")) const years = range(thisYear-120, thisYear) const updateState = formUpdateState(this.state, this.setState.bind(this), "formData"); const progressButton = (<FactaButton key={"key..."} text="next >" onClick={this.progressFunction} spinnerOnClick />); const self=this; const errorPopup = ( (this.state.validationErrors.length > 0) ? <FactaErrorDiv errors={this.state.validationErrors}/> : "" ); const guestContent = ( <div id="guestinfo"> Guests must self register. Members please direct your guests to this page to register themselves. Under 18 guests must be registered by their parent or guardian. <br /> At the end of registration you will be able to print or save your ticket, you'll also receive an email ticket. <br /> <table id="info" style={{ width: "100%"}}><tbody> <tr><th style={{ width: "250px" }}>Guest Information</th><th style={{ width: "350px" }} /></tr> <FormInput id="firstName" label="<NAME>" isPassword={false} isRequired value={self.state.formData.firstName} updateAction={updateState} /> <FormInput id="lastName" label="<NAME>" isRequired value={self.state.formData.lastName} updateAction={updateState} /> <DateTriPicker<Form, DateTriPickerProps<Form>> years={years} monthID="dobMonth" dayID="dobDay" yearID="dobYear" isRequired monthValue={self.state.formData.dobMonth} dayValue={self.state.formData.dobDay} yearValue={self.state.formData.dobYear} updateAction={updateState} /> <PhoneTriBox<Form, PhoneTriBoxProps<Form>> label="Phone" firstID="guestPhoneFirst" secondID="guestPhoneSecond" thirdID="guestPhoneThird" extID="guestPhoneExt" typeID="guestPhoneType" firstValue={self.state.formData.guestPhoneFirst} secondValue={self.state.formData.guestPhoneSecond} thirdValue={self.state.formData.guestPhoneThird} extValue={self.state.formData.guestPhoneExt} typeValue={self.state.formData.guestPhoneType} updateAction={updateState} isRequired /> <FormInput id="email" label="Email" isPassword={false} isRequired value={self.state.formData.email} updateAction={updateState} /> <tr><td /><td /><td> {progressButton} </td></tr> </tbody></table> </div> ); const ecContent = ( <div id="ecinfo"> <table id="ecInfo" style={{ width: "100%"}}><tbody> <tr><th style={{ width: "250px" }}>Emergency Contact Information</th><th style={{ width: "350px" }} /></tr> <tr><td /><td>This should be someone close to you who is not going on the water with you.</td></tr> <tr><td /><td>For under 18 guests this should be a parent or guardian.</td></tr> <FormInput id="ecFirstName" label="<NAME>" isPassword={false} isRequired value={self.state.formData.ecFirstName} updateAction={updateState} /> <FormInput id="ecLastName" label="<NAME>" isPassword={false} isRequired value={self.state.formData.ecLastName} updateAction={updateState} /> <FormInput id="ecRelationship" label="Relationship" isPassword={false} isRequired value={self.state.formData.ecRelationship} updateAction={updateState} /> <PhoneTriBox<Form, PhoneTriBoxProps<Form>> label="Emergency Contact Phone" firstID="ecPhoneFirst" secondID="ecPhoneSecond" thirdID="ecPhoneThird" extID="ecPhoneExt" typeID="ecPhoneType" firstValue={self.state.formData.ecPhoneFirst} secondValue={self.state.formData.ecPhoneSecond} thirdValue={self.state.formData.ecPhoneThird} extValue={self.state.formData.ecPhoneExt} typeValue={self.state.formData.ecPhoneType} updateAction={updateState} isRequired /> <tr><td /><td /><td> { progressButton } </td></tr> </tbody></table> </div>); const finishScreenContent = ( <div> <h1>Success!</h1> <h3>You are now registered as a guest!</h3> <p>You may print or save your card below, you will also receive a confirmation email with your card attatched. </p> <p>Please bring your card along in print or on a mobile device when you visit the boathouse.</p> <p>You will have the option to print your card at the boathouse if you don't have a printer or mobile device available.</p> <a href="#" onClick={self.handlePrint}>Guest Card</a> </div>); const agreeCheckbox = (<FactaNotitleRegion> <SingleCheckbox id="accept" label="I Agree To These Terms" updateAction={(id: string, waiverValue: any) => { self.setState({ ...this.state, waiverAccepted: (waiverValue === true) }) }} value={self.state ? some(self.state.waiverAccepted) : none} justElement={true} /> </FactaNotitleRegion>); const adultWaiverContent = (<div id="adultwaiver"> <table width="100%"><tbody> <tr> <td> <iframe title="Waiver of Liability" src="/waivers/live/ApGuestWaiver.html" width="100%" height="400px"></iframe> </td> </tr> <tr> <td> {agreeCheckbox} {progressButton} </td> </tr> </tbody></table> </div>); const under18WaiverContent = ( <div id="under18waiver"> <table width="100%"><tbody> <tr> <td> <iframe title="Waiver of Liability" src="/waivers/live/Under18GuestWaiver.html" width="100%" height="400px"></iframe> </td> </tr> <tr> <td>{ agreeCheckbox } { progressButton }</td> </tr> </tbody></table> </div>); var articleContent = guestContent; switch(this.state.pageState){ case PageState.GUEST_INFORMATION: articleContent = guestContent; break; case PageState.EC_INFORMATION: articleContent = ecContent; break; case PageState.WAIVER: articleContent = adultWaiverContent; let now = moment(); let dob = getDOBMoment(this.state); if(dob.isAfter(now.subtract(18, "years"))) articleContent = under18WaiverContent; break; case PageState.FINISH: articleContent = finishScreenContent; break; } return <FactaMainPage setBGImage={setAPImage}> {errorPopup} <FactaArticleRegion title="Guest Registration"> { articleContent } </FactaArticleRegion> </FactaMainPage> } }
package org.jooby.internal; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.jooby.MediaType; import org.jooby.Renderer; import org.jooby.test.MockUnit; import org.jooby.test.MockUnit.Block; import org.junit.Test; public class BytesRendererTest { private Block defaultType = unit -> { Renderer.Context ctx = unit.get(Renderer.Context.class); expect(ctx.type(MediaType.octetstream)).andReturn(ctx); }; @Test public void render() throws Exception { byte[] bytes = "bytes".getBytes(); new MockUnit(Renderer.Context.class) .expect(defaultType) .expect(unit -> { Renderer.Context ctx = unit.get(Renderer.Context.class); ctx.send(bytes); }) .run(unit -> { BuiltinRenderer.bytes .render(bytes, unit.get(Renderer.Context.class)); }); } @Test public void renderIgnoredAnyOtherArray() throws Exception { int[] bytes = new int[0]; new MockUnit(Renderer.Context.class) .run(unit -> { BuiltinRenderer.bytes .render(bytes, unit.get(Renderer.Context.class)); }); } @Test public void renderIgnore() throws Exception { new MockUnit(Renderer.Context.class) .run(unit -> { BuiltinRenderer.bytes .render(new Object(), unit.get(Renderer.Context.class)); }); } @Test(expected = IOException.class) public void renderWithFailure() throws Exception { byte[] bytes = "bytes".getBytes(); new MockUnit(Renderer.Context.class, InputStream.class, OutputStream.class) .expect(defaultType) .expect(unit -> { Renderer.Context ctx = unit.get(Renderer.Context.class); ctx.send(bytes); expectLastCall().andThrow(new IOException("intentational err")); }) .run(unit -> { BuiltinRenderer.bytes .render(bytes, unit.get(Renderer.Context.class)); }); } }
(function(){ console.log('activated'); var prettify = angular.module('prettify', []); prettify.controller('TableController', function TableController($scope, $http){ $http.get('tables.json').success(function(data){ $scope.tables = data; $scope.tblOrderField = "record_count"; }); }); prettify.controller('ColumnController', function ColumnController($scope, $http){ $http.get('columns.json').success(function(data){ $scope.columns = data; }); }); })();
class <%= class_name %>Observer < ActiveRecord::Observer def after_create(<%= file_name %>) <%= class_name %>Mailer.deliver_signup_notification(<%= file_name %>) end def after_save(<%= file_name %>) <% if options[:include_activation] %> <%= class_name %>Mailer.deliver_activation(<%= file_name %>) if <% if options[:aasm] || options[:stateful] %> <%= file_name %>.recently_activated <% else %><%= file_name %>.activated_at<% end %> <% end %> end end
<gh_stars>0 # -*- coding: utf-8 -*- import sys __author__ = 'pawel' from xml.dom.minidom import parse # Create the minidom document class XMLreader: def __init__(self,file): xml_file = open(file) self.doc = parse(xml_file) #Metoda sprawdzająca czy dany plik XML jest plikiem opisu płytki def isDescriptionFile(self): if self.doc.getElementsByTagName("device"): return True else: return False #Metoda parusjąca plik opisu płytki def parseFile(self, file="des", floorplan=None): if (file=="des"): size = self.doc.getElementsByTagName("size")[0] self.cols = int(size.getAttribute("cols")) self.rows = int(size.getAttribute("rows")) self.obstacles = self.doc.getElementsByTagName("obstacle") self.units = self.doc.getElementsByTagName("unit") self.floorplan = [] '''Zdefiniowanie pustego floorplanu''' '''Wyczysczenie listy''' for i in range(self.rows): for j in range(self.cols): self.floorplan.append(0) '''Wczytanie obstacli''' for obs in self.obstacles: x = int(obs.getAttribute("x")) y = int(obs.getAttribute("y")) self.floorplan[y * (self.cols) + x] = 1 '''Wczytywanie unitów ''' for uni in self.units: x = int(uni.getAttribute("x")) y = int(uni.getAttribute("y")) self.floorplan[y * (self.cols) + x] = 2 else: board = self.doc.getElementsByTagName("board")[0] #Wczytywanie grzałek do floorplanu heaters = board.getElementsByTagName("heater") for i,h in enumerate(heaters): name = h.getAttribute("name") color = h.getAttribute("FMColor") params = {"name": name, "type": "RO1", "color": color} floorplan.addNewHeater(params) clb = h.getElementsByTagName("clb") for c in clb: floorplan.addHeaterUnit(name,int(c.getAttribute("col")),int(c.getAttribute("row"))) #Wczytywanie termometrów do floorplanu terms = board.getElementsByTagName("thermometer") try: terms.sort(key=lambda x: int(x.attributes['name'].value)) except ValueError: terms.sort(key=lambda x: x.attributes['name'].value) for i, t in enumerate(terms): params = { 'index':i, 'name': t.getAttribute("name"), 'type': t.getAttribute("type"), 'col': int(t.getAttribute("col")), 'row': int(t.getAttribute("row")) } floorplan.addNewTerm(params) floorplan.addTermUnit(params['name'], params['col'], params['row'], True) '''Metoda wypisująca tekstowo wyglad płytki''' def printTextFloorplan(self): k = 0 for i in range(self.rows): if i!=0: sys.stdout.write(str(i) + "\t") for j in range(self.cols): if i==0: sys.stdout.write("\t" + str(j+1)) else: sys.stdout.write(str(self.floorplan[self.cols*(i-1) + j]) + " ") k += 1 sys.stdout.write("\n") print "Razem bloków funkcyjnych: " + str(k) '''Metoda podająca zawartość danego bloku''' def getElement(self, x, y): return self.floorplan(self.cols*y + x)
/** * User.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/#!documentation/models */ module.exports = { schema: true, attributes: { name: { type: 'string', required: true }, title: { type: 'string' }, email: { type: 'string', email: true, required: true, unique: true }, encryptedPassword: { type: 'string' }, online: { type: 'boolean', defaultsTo: false }, admin: { type: 'boolean', defaultsTo: false }, toJSON: function() { var obj = this.toObject(); delete obj.password; delete obj.confirmation; delete obj.encryptedPassword; delete obj._csrf; return obj; } }, /*beforeValidation: function (values, next) { console.log(values); if (typeof values.admin !== 'undefined') { if (values.admin === 'unchecked') { values.admin = false; } else if (values.admin[1] === 'on') { values.admin = true; } } next(); },*/ beforeCreate: function (values, next) { // This checks to make sure the password and password confirmation match // before creating record if (!values.password || values.password != values.confirmation) { return next({err: ["Password doesn't match password confirmation"]}); } require('bcrypt').hash(values.password, 10, function passwordEncrypted (err, encryptedPassword) { if (err) return next(err); values.encryptedPassword = <PASSWORD>Password; // values.online = true; next(); }); } };
import pandas as pd import matplotlib.pyplot as plt import math files = ["./csv_files/interval_point_1.csv", "./csv_files/interval_point_2.csv" , "./csv_files/interval_point_4.csv", "./csv_files/interval_point_5.csv"] acc = [0.1,0.2,0.4,0.5] for index,file_name in enumerate(files): df = pd.read_csv (file_name) x = df['x'] y = df['y'] val = df['val'] MSE = 0 for i,x_val in enumerate(x): MSE += ( val[i] - ( x[i]*(math.e**(-1*(x[i]**2 + y[i]**2))) ) )**2 MSE = MSE/len(x) print("MSE for interval " + str(acc[index]) + " is " + str(MSE))
package io.quarkus.qson.runtime; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks a method to be called back for Qson setup and initialization when running within * Quarkus. This method must be public and static and return void and take * QuarkusQsonGenerator as a parameter. Note that this method runs at build time!!! * * <pre> * public class MyQsonInitializers { * &#64;QuarkusQsonInitilizer * public static void initQsonForMe(QuarkusQsonGenerator generator) { * ... do some stuff ... * } * } * </pre> * */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface QuarkusQsonInitializer { }
CREATE FUNCTION get_words(input_string VARCHAR(255)) RETURNS TABLE AS RETURN SELECT * FROM (SELECT SPLIT_STR(TRIM(input_string), ' ', 0)) AS words(word);
<reponame>Tolgahan20/Furthersoft var fps = 60, interval = 1000 / fps, lastTime = (new Date()).getTime(), currentTime = 0, delta = 0; var mouseX = 0, mouseY = 0, mouseRadius = 100, mousePower = 10, particleDensity = 4, particleStiffness = 0.15, particleOffset = 0, particleFriction = 0.9, particles = [], text = 'FurtherSoft', isPopulated = false; (function test() { "use strict"; const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); function init() { bindMouse(); window.onresize(); window.requestAnimationFrame(render); } window.onresize = function() { if (window.innerWidth < 900) { text = "F" } else { text = "Furthersoft" } canvas.width = window.innerWidth; canvas.height = window.innerHeight; }; class Particle { constructor(canvas, context, x, y) { this.canvas = canvas; this.context = context; this.x = x; this.y = y; this.radius = particleDensity / 2.3; this.spring = { x: x, y: y }; this.dX = 0; this.dY = 0; } getDistanceTo(x, y) { let dX = x - this.x, dY = y - this.y; return { x: dX, y: dY, dist: Math.sqrt(dX * dX + dY * dY) }; } repulseTo(x, y) { let distance = this.getDistanceTo(x, y), repulseAngle = Math.atan2(distance.y, distance.x), repulseForce = (-1 * Math.pow(mousePower, 2)) / distance.dist; this.dX += Math.cos(repulseAngle) * repulseForce; this.dY += Math.sin(repulseAngle) * repulseForce; } springTo() { this.dX += (this.spring.x - this.x) * particleStiffness; this.dY += (this.spring.y - this.y) * particleStiffness; } update() { this.springTo(); this.dX *= particleFriction; this.dY *= particleFriction; this.x += this.dX; this.y += this.dY; } draw() { this.context.fillStyle = '#FFFFFF'; this.context.beginPath(); this.context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false); this.context.fill(); } } function bindMouse() { canvas.addEventListener('mousemove', (event) => { mouseX = event.clientX - canvas.offsetLeft; mouseY = event.clientY - canvas.offsetTop; }); } function createParticle(x, y) { particles.push(new Particle(canvas, context, x, y)); } function convertTextToParticle() { context.save(); context.fillStyle = "#F10708"; context.font = "Bold 200px Helvetica"; let textSize = context.measureText(text), textHeight = 50; context.translate((canvas.width / 2) - (textSize.width / 2), canvas.height / 2); context.fillText(text, 0, textHeight); context.restore(); let image = context.getImageData(0, 0, canvas.width, canvas.height); particles = []; for (var y = 0; y < canvas.height; y += particleDensity) { for (var x = 0; x < canvas.width; x += particleDensity) { let opacity = image.data[((x + (y * canvas.width)) * 4 + 3)]; if (opacity > 0) { createParticle(x, y); } } } isPopulated = true; } function update() { for (var i = 0; i < particles.length; i++) { let p = particles[i]; if (p.getDistanceTo(mouseX, mouseY).dist <= mouseRadius + p.radius) { p.repulseTo(mouseX, mouseY); } p.update(); } } function draw() { for (var i = 0; i < particles.length; i++) { let p = particles[i]; p.draw(); } } function clear() { context.clearRect(0, 0, canvas.width, canvas.height); } function render() { currentTime = (new Date()).getTime(); delta = currentTime - lastTime; if (delta > interval) { update(); clear(); if (!isPopulated) { convertTextToParticle(); } else { draw(); } lastTime = currentTime - (delta % interval); } window.requestAnimationFrame(() => { render(); }); } init(); })(); (function gui() { let gui = new dat.GUI(); textGUI = gui.add(this, 'text').name('Text'); textGUI.onChange(() => { this.isPopulated = false; }); let f1 = gui.addFolder('Mouse'); f1.add(this, 'mouseRadius', 10, 100).name('Radius'); f1.add(this, 'mousePower', 5, 15).name('Power'); // f1.open(); let f2 = gui.addFolder('Particle'); f2.add(this, 'particleStiffness', 0.1, 1).name('Stiffness'); f2.add(this, 'particleFriction', 0.1, 0.95).name('Friction'); f2.open(); })();
<reponame>hengxin/jepsen-in-java<filename>src/test/java/core/checker/util/PerfTest.java package core.checker.util; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class PerfTest { @Test void broadenRange() { List<Double> range = List.of(3.14, 3.14); List<Double> res = Perf.broadenRange(3.14, 3.14); List<Double> resExpected = List.of(2.14, 4.140000000000001); Assertions.assertEquals(resExpected, res); } @Test void broadenRange2() { List<Double> range = List.of(3.14, 5.14); List<Double> res = Perf.broadenRange(3.14, 5.14); List<Double> resExpected = List.of(3.1, 5.2); Assertions.assertEquals(resExpected, res); } @Test void broadenRange3() { List<List<Double>> identicalPoints = List.of(List.of( 0d, 0d, -1d, 1d ), List.of( -1d, -1d, -2d, 0d ), List.of( 4d, 4d, 3d, 5d ) ); List<List<Double>> normalIntegers = List.of(List.of( 0d, 1d, 0.0, 1d ), List.of( 1d, 2d, 1.0, 2d ), List.of( 9d, 10d, 9.0, 10d ), List.of( 0d, 10d, 0.0, 10d )); List<List<Double>> biggerInteger = List.of(List.of( 1000d, 10000d, 1000.0, 10000d ), List.of( 1234d, 5678d, 1000.0, 6000.0 ), List.of( 4d, 4d, 3d, 5d ) ); List<List<Double>> tinyNumbers = List.of( List.of( 0.03415, 0.03437, 0.034140000000000004, 0.034370000000000005 ) ); for (List<Double> i : identicalPoints) { Assertions.assertEquals(Perf.broadenRange(i.get(0), i.get(1)), i.subList(2, 4)); } for (List<Double> i : normalIntegers) { Assertions.assertEquals(Perf.broadenRange(i.get(0), i.get(1)), i.subList(2, 4)); } for (List<Double> i : biggerInteger) { Assertions.assertEquals(Perf.broadenRange(i.get(0), i.get(1)), i.subList(2, 4)); } for (List<Double> i : tinyNumbers) { Assertions.assertEquals(Perf.broadenRange(i.get(0), i.get(1)), i.subList(2, 4)); } } @Test void bucketScale() { long dt = 10, b = 2; double res = Perf.bucketScale(dt, b); Assertions.assertEquals(res, 25); } @Test void bucketTime() { long dt = 10, b = 2; double res = Perf.bucketTime(dt, b); Assertions.assertEquals(res, 5); } @Test void buckets() { long dt = 10, b = 30; List<Double> res = Perf.buckets(dt, b); List<Double> resExpected = List.of(5d, 15d, 25d); Assertions.assertEquals(resExpected, res); } @Test void bucketPoints() { long dt = 10; List<List<?>> points = List.of(List.of(33L, 1), List.of(36L, 1), List.of(68L, 2)); Map<Double, List<List<?>>> res = new HashMap<>(Perf.bucketPoints(dt, points)); Map<Double, List<List<?>>> resExpected = new HashMap<>(Map.of( 65d, new ArrayList<>(List.of(new ArrayList<>(List.of(68, 2)))), 35d, new ArrayList<>(List.of(new ArrayList<>(List.of(33, 1)), new ArrayList<>(List.of(36, 1)))) )); Assertions.assertEquals(res.keySet(), resExpected.keySet()); for (Map.Entry<Double, List<List<?>>> entry : res.entrySet()) { Assertions.assertEquals(resExpected.get(entry.getKey()).size(), entry.getValue().size()); } } @Test void quantiles() { List<Double> quantiles = List.of(0.33, 0.14, 0.55); List<Double> points = List.of(33d, 1d, 36d, 1d, 68d, 2d); Map<Double, Double> res = Perf.quantiles(quantiles, points); Map<Double, Double> resExpected = new HashMap<>(Map.of( 0.33, 1.0, 0.14, 1.0, 0.55, 33.0 )); Assertions.assertEquals(res, resExpected); } @Test void testBucketPoints() { List<List<?>> points = List.of( List.of(1, "a"), List.of(7, "g"), List.of(5, "e"), List.of(2, "b"), List.of(3, "c"), List.of(4, "d"), List.of(6, "f") ); Map<Double,List<List<?>>> res=Perf.bucketPoints(2, points); Assertions.assertEquals(res,Map.of( 1L,List.of(List.of(1,"a")), 3L,List.of(List.of(2,"b"),List.of(3,"c")), 5L,List.of(List.of(5,"e"),List.of(4,"d")), 7L,List.of(List.of(7,"g"),List.of(6,"f")) )); } @Test void latencies2quantiles() { Map<Double,List<List<?>>> res=Perf.latencies2quantiles(5,List.of(0d,1d),List.of( List.of(0,0), List.of(1,10), List.of(2,1), List.of(3,1), List.of(4,1), List.of(5,20), List.of(6,21), List.of(7,22), List.of(8,25), List.of(9,25), List.of(10,25) )); Map<?,List<List<?>>> expected=Map.of( 0,List.of(List.of(5.0/2,0d),List.of(15.0/2,20d),List.of(25.0/2,25d)), 1,List.of(List.of(5.0/2,10d),List.of(15.0/2,25d),List.of(25.0/2,25d)) ); Assertions.assertEquals(res.get(0d),expected.get(0)); Assertions.assertEquals(res.get(1d),expected.get(1)); } }
#!/bin/bash # # Copyright 2021 Google 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. start() { /opt/kafka/bin/zookeeper-server-start.sh -daemon /opt/kafka/config/zookeeper.properties sleep 10 /opt/kafka/bin/kafka-server-start.sh -daemon /opt/kafka/config/server.properties } stop(){ /opt/kafka/bin/kafka-server-stop.sh /opt/kafka/config/server.properties /opt/kafka/bin/zookeeper-server-stop.sh /opt/kafka/config/zookeeper.properties } case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo "Usage: $0 {start|stop|restart}" esac
module.exports = { preset: 'ts-jest', testEnvironment: 'node', roots: ['<rootDir>/server'], globals: { 'ts-jest': { tsConfig: '<rootDir>/server/tsconfig.json' } } };
<filename>src/app/auth/updateuser/updateuser.component.ts import { Component, OnInit, ViewChild, ElementRef, OnDestroy } from '@angular/core'; import { FormGroup, FormControl, Validators } from "@angular/forms"; import { TextField } from 'tns-core-modules/ui/text-field'; import { RouterExtensions } from "nativescript-angular/router"; import { AuthService } from "../auth.service"; import { Subscription } from "rxjs"; import { GetUserResult, UpdateUserResult } from "../auth.model"; import { TNSFancyAlert } from "nativescript-fancyalert"; //Import for config file import * as appSettings from "tns-core-modules/application-settings"; @Component({ selector: 'ns-updateuser', templateUrl: './updateuser.component.html', styleUrls: ['./updateuser.component.scss'], moduleId: module.id }) export class UpdateuserComponent implements OnInit { //set user variable userid = ""; getuserResultSub: Subscription; public getuser: GetUserResult; public userFound: boolean; updateResultSub: Subscription; update: UpdateUserResult; //form form: FormGroup; idControlIsValid = true; usernameControlIsValid = true; nameControlIsValid = true; surnameControlIsValid = true; emailControlIsValid = true; isLoading = false; @ViewChild('idEl', {static:false}) idEl: ElementRef<TextField>; @ViewChild('usernameEl', {static:false}) usernameEl: ElementRef<TextField>; @ViewChild('nameEl', {static:false}) nameEl: ElementRef<TextField>; @ViewChild('surnameEl', {static:false}) surnameEl: ElementRef<TextField>; @ViewChild('emailEl', {static:false}) emailEl: ElementRef<TextField>; constructor(private authServ: AuthService) { } ngOnInit() { //form controls this.form = new FormGroup({ id: new FormControl( null, { updateOn: 'blur', validators: [ Validators.required ] } ), username: new FormControl( null, { updateOn: 'blur', validators: [ Validators.required ] } ), name: new FormControl( null, { updateOn: 'blur', validators: [ Validators.required ] } ), surname: new FormControl( null, { updateOn: 'blur', validators: [ Validators.required ] } ), email: new FormControl( null, { updateOn: 'blur', validators: [ Validators.required ] } ) }); this.form.get('id').statusChanges.subscribe(status => { this.idControlIsValid = status === 'VALID'; }); this.form.get('username').statusChanges.subscribe(status => { this.usernameControlIsValid = status === 'VALID'; }); this.form.get('name').statusChanges.subscribe(status => { this.nameControlIsValid = status === 'VALID'; }); this.form.get('surname').statusChanges.subscribe(status => { this.surnameControlIsValid = status === 'VALID'; }); this.form.get('email').statusChanges.subscribe(status => { this.emailControlIsValid = status === 'VALID'; }); this.updateResultSub = this.authServ.currentUpdateUser.subscribe( updateresult => { if(updateresult){ this.isLoading = false; this.update = updateresult; // TODO : Need to validate if this is a valid register if(this.update.responseStatusCode === 200 && this.update.UserUpdated === true){ //Save user details and rememberme info TNSFancyAlert.showError("Update Success", this.update.Message, "Dismiss") this.authServ.clearAllObjects(); } else { TNSFancyAlert.showError("Register Error", this.update.Message, "Dismiss"); } } } ); //find User from app settings this.userFound = false; const id = appSettings.getString("userid"); console.log(appSettings.getString("userid")); //subscribe to Get User result this.getuserResultSub = this.authServ.currentGetUser.subscribe( userResult => { if(userResult) { this.getuser = userResult if(this.getuser.responseStatusCode === 200){ console.log(this.getuser); this.userFound = true; } else { TNSFancyAlert.showError("Data Retrieval", "Unable to retrieve data."); } } } ); //Send User ID from app settings this.authServ.GetUser(id); } ngOnDestroy() { if(this.getuserResultSub && this.updateResultSub){ this.getuserResultSub.unsubscribe(); this.updateResultSub.unsubscribe(); } } onUpdateUser() { this.idEl.nativeElement.focus(); this.usernameEl.nativeElement.focus(); this.nameEl.nativeElement.focus(); this.surnameEl.nativeElement.focus(); this.emailEl.nativeElement.focus(); this.emailEl.nativeElement.dismissSoftInput(); if(!this.form.valid){ return; } const id = this.form.get('id').value; const username = this.form.get('username').value; const name = this.form.get('name').value; const surname = this.form.get('surname').value; const email = this.form.get('email').value; this.isLoading = true; //Timeout to give loading bar time to appear setTimeout(() =>{ //Verify register Credentials this.authServ.UpdateUser(id, username, name, surname, email); },100); } }
<filename>src/actionTypes.js const LOGOUT = 'LOGOUT' const LOGIN_START = 'LOGIN_START' const LOGIN_END = 'LOGIN_END' const READ_POSTS_START = 'READ_POSTS_START' const READ_POSTS_END = 'READ_POSTS_END' export { LOGOUT, LOGIN_START, LOGIN_END, READ_POSTS_START, READ_POSTS_END }
package controllers import play.api._ import play.api.mvc._ import play.api.Play.current object Application extends Controller { def index = Action { Ok(views.html.index()) } def echoSocket = WebSocket.acceptWithActor[String, String] { request => out => actors.EchoSocketActor.props(out) } }
// Before testing this case, it is necessary to run testtool/prepare.sh // for replacing MockStub module in fabric project package token import ( "errors" "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" pb "github.com/hyperledger/fabric/protos/peer" "github.com/kenmazsyma/soila/chaincode/peer" "github.com/kenmazsyma/soila/chaincode/project" "github.com/kenmazsyma/soila/chaincode/root" . "github.com/kenmazsyma/soila/chaincode/test" "os" "testing" ) // =============================== // Test environment // =============================== var invoke_list = map[string]root.InvokeRoutineType{ "token.register": Register, "token.update": Update, "token.remove": Remove, "project.register": project.Register, "project.get": project.Get, "project.updatestatus": project.UpdateStatus, "peer.register": peer.Register, "peer.update": peer.Update, "peer.get": peer.Get, "peer.deregister": peer.Deregister, } func initialize() { fmt.Println("init") } func terminate() { fmt.Println("term") } func TestMain(m *testing.M) { initialize() retCode := m.Run() terminate() os.Exit(retCode) } // =================================== // sub routine // =================================== func getKeyFromPayload(res pb.Response) (key string, err error) { fmt.Printf("\nPAYLOAD:%s\n", res.Payload) o, err := UnmarshalPayload(res.Payload) if err != nil { return } if len(o) < 1 { err = errors.New("number of response is not correct.") return } key = o[0].(string) return } func prepare(stub *shim.MockStub) (key string, prjkey string, err error) { res := stub.MockInvoke("1", MakeParam("peer.register", "1")) if res.Status != 200 { err = errors.New("failed to register PEER") return } if key, err = getKeyFromPayload(res); err != nil { return } fmt.Printf("PEERKEY:%s\n", key) res = stub.MockInvoke("1", MakeParam("project.register", "12345")) if prjkey, err = getKeyFromPayload(res); err != nil { return } fmt.Printf("PROJECTKEY:%s\n", prjkey) return } // =================================== // Test Case // =================================== func Test_Register(t *testing.T) { peer1 := []byte("abcdef0123456789") stub := CreateStub(invoke_list) // prepare a premise data stub.SetCreator(peer1) _, prjkey, err := prepare(stub) if err != nil { t.Errorf(err.Error()) return } res := stub.MockInvoke("1", MakeParam("token.register", prjkey, "12345", "test", "aaaaa")) CheckStatus("a-1", t, res, 200) tokenkey, err := getKeyFromPayload(res) if err != nil { t.Errorf(err.Error()) return } fmt.Printf("\nTOKENKEY:%s\n", tokenkey) }
#!/bin/bash #编译完毕之后,拷贝gonc文件到桌面 source "exportenv.sh" OBJ_DIR="${OBJECT_FILE_DIR_normal}/${ARCHS}" ME=$(whoami) DESKTOP="/Users/${ME}/Desktop" DEFAULT_OBJ_DIR="/Users/${ME}/Desktop/mmobjs" rm -rf ${DEFAULT_OBJ_DIR} mkdir ${DEFAULT_OBJ_DIR} #cp -r ${OBJ_DIR} ${DEFAULT_OBJ_DIR} find ${OBJ_DIR} -name "*.gcno" -exec cp {} ${DEFAULT_OBJ_DIR}; scripts="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo "gcno files has been copied to your desktop"
#!/bin/bash python setup.py install mkdir ROSCO/build cd ROSCO/build cmake -DCMAKE_INSTALL_PREFIX=${PREFIX} .. make install
<filename>sql/updates/Rel18/12552_01_mangos_item_enchantment_template.sql<gh_stars>0 ALTER TABLE db_version CHANGE COLUMN required_c12484_01_mangos_string required_c12552_01_mangos_item_enchantment_template bit; ALTER TABLE item_enchantment_template MODIFY COLUMN entry mediumint(8) NOT NULL DEFAULT '0';
package com.example.laura.quiz; public class Opciones { private static int numPreg; private static String difficulty; public static int getNumPreg() { return numPreg; } public static void setNumPreg(int numPreg) { Opciones.numPreg = numPreg; } public static String getDifficulty() { return difficulty; } public static void setDifficulty(String difficulty) { Opciones.difficulty = difficulty; } }
<filename>test/bulk_insert_test.rb<gh_stars>1-10 require 'test_helper' class BulkInsertTest < ActiveSupport::TestCase test "bulk_insert without block should return worker" do result = Testing.bulk_insert assert_kind_of BulkInsert::Worker, result end test "bulk_insert with block should yield worker" do result = nil Testing.bulk_insert { |worker| result = worker } assert_kind_of BulkInsert::Worker, result end test "bulk_insert with block should save automatically" do assert_difference "Testing.count", 1 do Testing.bulk_insert do |worker| worker.add greeting: "Hello" end end end test "bulk_insert with array should save the array immediately" do assert_difference "Testing.count", 2 do Testing.bulk_insert values: [ [ "Hello", 15, true, "green" ], { greeting: "Hey", age: 20, happy: false } ] end end test "default_bulk_columns should return all columns without id" do default_columns = %w(greeting age happy created_at updated_at color) assert_equal Testing.default_bulk_columns, default_columns end end
export DB2_DB=lubm export DB2_HOST=localhost export DB2_PORT=50002 export DB2_USER=db2inst1 export DB2_PASSWORD=db2admin export DB2_SCHEMA=db2inst1 export DB_ENGINE=db2
#! /bin/bash # # Run tests that aren't ran on CI (yet) # # to run all no-ci tests # $ (plotly.js) ./tasks/noci_test.sh # # to run jasmine no-ci tests # $ (plotly.js) ./tasks/noci_test.sh jasmine # to run image no-ci tests # $ (plotly.js) ./tasks/noci_test.sh image # # ----------------------------------------------- EXIT_STATE=0 root=$(dirname $0)/.. # jasmine specs with @noCI tag test_jasmine () { npm run test-jasmine -- --tags=noCI,noCIdep --nowatch || EXIT_STATE=$? } # mapbox image tests take too much resources on CI # # since the update to mapbox-gl@0.44.0, we must use orca # as mapbox-gl versions >0.22.1 aren't supported on nw.js@0.12 used in the # 'old' image server test_image () { $root/../orca/bin/orca.js graph \ $root/test/image/mocks/mapbox_* \ --plotly $root/build/plotly.js \ --mapbox-access-token "pk.eyJ1IjoiZXRwaW5hcmQiLCJhIjoiY2luMHIzdHE0MGFxNXVubTRxczZ2YmUxaCJ9.hwWZful0U2CQxit4ItNsiQ" \ --output-dir $root/test/image/baselines/ \ --verbose || EXIT_STATE=$? } case $1 in jasmine) test_jasmine ;; image) test_image ;; *) test_jasmine test_image ;; esac exit $EXIT_STATE
<reponame>wnbx/snail package com.acgist.snail.net.torrent.peer; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.acgist.snail.config.PeerConfig.ExtensionType; import com.acgist.snail.context.exception.NetException; import com.acgist.snail.pojo.session.PeerSession; /** * <p>扩展协议类型</p> * * @author acgist */ public abstract class ExtensionTypeMessageHandler implements IExtensionMessageHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ExtensionTypeMessageHandler.class); /** * <p>扩展协议类型</p> */ protected final ExtensionType extensionType; /** * <p>Peer信息</p> */ protected final PeerSession peerSession; /** * <p>扩展协议代理</p> */ protected final ExtensionMessageHandler extensionMessageHandler; /** * @param extensionType 扩展协议类型 * @param peerSession Peer信息 * @param extensionMessageHandler 扩展协议代理 */ protected ExtensionTypeMessageHandler(ExtensionType extensionType, PeerSession peerSession, ExtensionMessageHandler extensionMessageHandler) { this.extensionType = extensionType; this.peerSession = peerSession; this.extensionMessageHandler = extensionMessageHandler; } @Override public void onMessage(ByteBuffer buffer) throws NetException { if(!this.supportExtensionType()) { LOGGER.debug("处理扩展协议消息错误(未知类型):{}", this.extensionType); return; } this.doMessage(buffer); } /** * <p>处理扩展消息</p> * * @param buffer 消息 * * @throws NetException 网络异常 */ protected abstract void doMessage(ByteBuffer buffer) throws NetException; /** * <p>是否支持扩展协议</p> * * @return true-支持;false-不支持; */ public boolean supportExtensionType() { return this.peerSession.supportExtensionType(this.extensionType); } /** * <p>获取扩展协议ID</p> * * @return 扩展协议ID */ protected Byte extensionTypeId() { return this.peerSession.extensionTypeId(this.extensionType); } /** * <p>发送扩展消息</p> * * @param buffer 扩展消息 */ protected void pushMessage(ByteBuffer buffer) { this.pushMessage(buffer.array()); } /** * <p>发送扩展消息</p> * * @param bytes 扩展消息 */ protected void pushMessage(byte[] bytes) { this.extensionMessageHandler.pushMessage(this.extensionTypeId(), bytes); } }
/*jslint node:true*/ module.exports = function (sequelize, Datatypes) { "use strict"; var Episode = sequelize.define("Episode", { ShowId: { type: Datatypes.INTEGER, allowNull: false, primaryKey: true, model: "Shows", key: "id", onDelete: "cascade" }, season: { type: Datatypes.INTEGER, allowNull: false, primaryKey: true }, episode: { type: Datatypes.INTEGER, allowNull: false, primaryKey: true }, title: { type: Datatypes.STRING, allowNull: false }, date: { type: Datatypes.DATE } }, { timestamps: false, paranoid: false } ); return Episode; };
#! /bin/bash function run () { bash ./run.sh $@ let "all_errors += $?" cat failed.txt >> failed_all.txt } set_store_features echo "features: " echo "STORE_STATEMENT_ANNOTATION = ${STORE_STATEMENT_ANNOTATION}" echo "STORE_INDEXED_TIMES = ${STORE_INDEXED_TIMES}" echo "STORE_INDEXED_EVENTS = ${STORE_INDEXED_EVENTS}" if [[ "$1" != "" ]] then for ((i = 0; i < $1; i ++)) do echo -n "${i}: " bash run_all.sh done; else all_errors=0 echo -n > failed_all.txt # start with empty output file date initialize_all_repositories # problems with the repository content # run extensions/git run extensions/graph-store-protocol run extensions/sparql-protocol/collation run extensions/sparql-protocol/meta-data run extensions/sparql-protocol/describe run extensions/sparql-protocol/parameters run extensions/sparql-protocol/provenance run extensions/sparql-protocol/revisions run extensions/sparql-protocol/sparql-operators # some translations depend on gensym state # run extensions/sparql-protocol/sql run extensions/sparql-protocol/temporal-data run extensions/sparql-protocol/values run extensions/sparql-protocol/views run extensions/sparql-protocol/xpath-operators # no tests yet run linked-data-platform run sparql-graph-store-http-protocol run sparql-protocol run tickets run triple-pattern-fragments run web-ui run accounts-api/accounts/openrdf-sesame/authorization/ echo echo "${all_errors} errors for run_all.sh" fi
The code snippet is a function that takes an array of strings as an argument. It loops through each string in the array and retrieves the first letter of the string. It then checks the result object for a key that is equal to the first letter. If there is a key that matches the retrieved letter, the associated value will be updated by appending an asterisk ('*') to the existing value. However, if there is no key that matches the retrieved letter, the letter itself will be used as its value. The final result is an object with the keys equal to the first letters of each item in the array and the values determined as described above. The function then returns the resulting object. The code snippet is useful for creating an object that has keys composed of the first letters of an array of strings, and the values containing the letter itself or the letter plus one or more asterisks. This could be useful for representing categorical data, such as a list of cities beginning with a particular letter. It could also be used to group objects by first letter in a list, or for searching through an array for strings beginning with a particular letter.
#!/bin/bash python -c 'import tensorflow as tf; print(tf.__version__)' # for Python 2
<reponame>bludnic/lisk-sdk /* * Copyright © 2020 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography'; import { CHAIN_STATE_BURNT_FEE, GENESIS_BLOCK_MAX_BALANCE } from './constants'; import { TransferAsset } from './transfer_asset'; import { TokenAccount } from './types'; import { getTotalFees } from './utils'; import { BaseModule } from '../base_module'; import { AfterBlockApplyContext, AfterGenesisBlockApplyContext, StateStore, TransactionApplyContext, GenesisConfig, } from '../../types'; const DEFAULT_MIN_REMAINING_BALANCE = '5000000'; export class TokenModule extends BaseModule { public name = 'token'; public id = 2; public accountSchema = { type: 'object', properties: { balance: { fieldNumber: 1, dataType: 'uint64', }, }, default: { balance: BigInt(0), }, }; public reducers = { credit: async (params: Record<string, unknown>, stateStore: StateStore): Promise<void> => { const { address, amount } = params; if (!Buffer.isBuffer(address)) { throw new Error('Address must be a buffer'); } if (typeof amount !== 'bigint') { throw new Error('Amount must be a bigint'); } if (amount <= BigInt(0)) { throw new Error('Amount must be a positive bigint.'); } const account = await stateStore.account.getOrDefault<TokenAccount>(address); account.token.balance += amount; if (account.token.balance < this._minRemainingBalance) { throw new Error( `Remaining balance must be greater than ${this._minRemainingBalance.toString()}`, ); } await stateStore.account.set(address, account); }, debit: async (params: Record<string, unknown>, stateStore: StateStore): Promise<void> => { const { address, amount } = params; if (!Buffer.isBuffer(address)) { throw new Error('Address must be a buffer'); } if (typeof amount !== 'bigint') { throw new Error('Amount must be a bigint'); } if (amount <= BigInt(0)) { throw new Error('Amount must be a positive bigint.'); } const account = await stateStore.account.getOrDefault<TokenAccount>(address); account.token.balance -= amount; if (account.token.balance < this._minRemainingBalance) { throw new Error( `Remaining balance must be greater than ${this._minRemainingBalance.toString()}`, ); } await stateStore.account.set(address, account); }, getBalance: async ( params: Record<string, unknown>, stateStore: StateStore, ): Promise<bigint> => { const { address } = params; if (!Buffer.isBuffer(address)) { throw new Error('Address must be a buffer'); } const account = await stateStore.account.getOrDefault<TokenAccount>(address); return account.token.balance; }, // eslint-disable-next-line @typescript-eslint/require-await getMinRemainingBalance: async (): Promise<bigint> => this._minRemainingBalance, }; private readonly _minRemainingBalance: bigint; public constructor(genesisConfig: GenesisConfig) { super(genesisConfig); const minRemainingBalance = this.config.minRemainingBalance ? this.config.minRemainingBalance : DEFAULT_MIN_REMAINING_BALANCE; if (typeof minRemainingBalance !== 'string') { throw new Error('minRemainingBalance in genesisConfig must be a string.'); } this._minRemainingBalance = BigInt(minRemainingBalance); this.transactionAssets = [new TransferAsset(this._minRemainingBalance)]; } public async beforeTransactionApply({ transaction, stateStore, }: TransactionApplyContext): Promise<void> { // Deduct transaction fee from sender balance const sender = await stateStore.account.get<TokenAccount>(transaction.senderAddress); sender.token.balance -= transaction.fee; await stateStore.account.set(transaction.senderAddress, sender); } public async afterTransactionApply({ transaction, stateStore, }: TransactionApplyContext): Promise<void> { // Verify sender has minimum remaining balance const sender = await stateStore.account.getOrDefault<TokenAccount>(transaction.senderAddress); if (sender.token.balance < this._minRemainingBalance) { throw new Error( `Account ${sender.address.toString( 'hex', )} does not meet the minimum remaining balance requirement: ${this._minRemainingBalance.toString()}.`, ); } } public async afterBlockApply({ block, stateStore }: AfterBlockApplyContext): Promise<void> { // Credit reward and fee to generator const generatorAddress = getAddressFromPublicKey(block.header.generatorPublicKey); const generator = await stateStore.account.get<TokenAccount>(generatorAddress); generator.token.balance += block.header.reward; // If there is no transactions, no need to give fee if (!block.payload.length) { await stateStore.account.set(generatorAddress, generator); return; } const { totalFee, totalMinFee } = getTotalFees( block, BigInt(this.config.minFeePerByte), this.config.baseFees, ); // Generator only gets total fee - min fee const givenFee = totalFee - totalMinFee; generator.token.balance += givenFee; const totalFeeBurntBuffer = await stateStore.chain.get(CHAIN_STATE_BURNT_FEE); let totalFeeBurnt = totalFeeBurntBuffer ? totalFeeBurntBuffer.readBigInt64BE() : BigInt(0); totalFeeBurnt += givenFee > 0 ? totalMinFee : BigInt(0); // Update state store const updatedTotalBurntBuffer = Buffer.alloc(8); updatedTotalBurntBuffer.writeBigInt64BE(totalFeeBurnt); await stateStore.account.set(generatorAddress, generator); await stateStore.chain.set(CHAIN_STATE_BURNT_FEE, updatedTotalBurntBuffer); } // eslint-disable-next-line @typescript-eslint/require-await public async afterGenesisBlockApply({ genesisBlock, }: AfterGenesisBlockApplyContext<TokenAccount>): Promise<void> { // Validate genesis accounts balance let totalBalance = BigInt(0); for (const account of genesisBlock.header.asset.accounts) { totalBalance += BigInt(account.token.balance); } if (totalBalance > GENESIS_BLOCK_MAX_BALANCE) { throw new Error('Total balance exceeds the limit (2^63)-1'); } } }
<gh_stars>1-10 package model func NewErrorOnlyIterator(err error) Iterator { return &ErrorOnlyIterator{err} } type ErrorOnlyIterator struct { err error } func (self *ErrorOnlyIterator) Next(resultRef interface{}) bool { return false } func (self *ErrorOnlyIterator) Err() error { return self.err }
<reponame>tsmvision/spring-security-examples package com.example.corespringsecurity.controller.user; import com.example.corespringsecurity.domain.dto.AccountDto; import com.example.corespringsecurity.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller @RequiredArgsConstructor public class UserController { private final UserService userService; // private final PasswordEncoder passwordEncoder; @GetMapping("/myPage") public String getMessages() { return "user/myPage"; } @GetMapping("/users") public String createUser() { return "user/login/register"; } @PostMapping(value = "/users") public String createUser(AccountDto accountDto) throws Exception { // userService.createUser( // new Account( // accountDto.getUsername(), // passwordEncoder.encode( // accountDto.getPassword() // ), // accountDto.getEmail(), // accountDto.getAge(), // accountDto.getRole() // ) // ); // return "redirect:/"; return null; } }
.upper-right { position: fixed; top: 0; right: 0; font-size: 12px; color: #fff; padding: 10px; }
<reponame>YoucanyoudoIcanido/newsBeijing package com.example.zhongweikang.beijingnew.newsDetailPage; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.example.zhongweikang.beijingnew.R; import butterknife.BindView; import butterknife.ButterKnife; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.onekeyshare.OnekeyShare; /** * webView界面 */ public class News extends Activity implements View.OnClickListener { String URL; @BindView(R.id.tittle) TextView tittle; @BindView(R.id.image_back) ImageButton imageback; @BindView(R.id.image_Share) ImageButton imageShare; @BindView(R.id.image_TextSize) ImageButton imageTextSize; @BindView(R.id.webview) WebView webview; @BindView(R.id.image_prograbase) ProgressBar imagePrograbase; private int CurrentChecked = 2; // 当前选中的 private int tempChecked; WebSettings set; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ShareSDK.initSDK(this); setContentView(R.layout.new_item_intent); ButterKnife.bind(this); Intent intent = getIntent(); String newURL = intent.getStringExtra("url"); Log.d("newURL", newURL); String starUrl = "http://172.17.1.35"; URL = starUrl + newURL.substring(15); Log.d("URL", URL); imageback.setOnClickListener(this); imageShare.setOnClickListener(this); imageTextSize.setOnClickListener(this); webview.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { imagePrograbase.setVisibility(View.GONE); } }); // 获取WebView的辅助类 set = webview.getSettings(); set.setJavaScriptEnabled(true); // 设置支持javaScript,网页中更多可以点击 set.setBuiltInZoomControls(true); // 设置 放大缩小的功能 set.setUseWideViewPort(true); // 设置双击放大缩小功能 webview.loadUrl(URL); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.image_back: finish(); break; case R.id.image_Share: showShare(); break; case R.id.image_TextSize: ChangeTextSize(); break; } } private void ChangeTextSize() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("设置字体大小"); builder.setIcon(R.drawable.setting_press); final String[] item = {"超大号字体", "大号字体", "中号字体", "小号字体", "超小号字体"}; builder.setSingleChoiceItems(item, CurrentChecked, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.d("字体", item[which]); tempChecked = which; } }); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CurrentChecked=tempChecked; TextSize(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.show(); } public void TextSize() { switch (CurrentChecked) { case 0: set.setTextSize(WebSettings.TextSize.LARGEST); break; case 1: set.setTextSize(WebSettings.TextSize.LARGER); break; case 2: set.setTextSize(WebSettings.TextSize.NORMAL); break; case 3: set.setTextSize(WebSettings.TextSize.SMALLER); break; case 4: set.setTextSize(WebSettings.TextSize.SMALLEST); break; } } private void showShare() { OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize(); // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间等使用 oks.setTitle("这是我集成的分享"); // text是分享文本,所有平台都需要这个字段 oks.setText("我是分享文本"); // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片 // 启动分享GUI oks.show(this); } }
#!/bin/sh # install_agent.sh # create xbaydns user and generate the ssh key. # Created by Razor <bg1tpt AT gmail.com> on 2008-03-24. # Copyright (c) 2008 xBayDNS Team. All rights reserved. USER="xbaydns" GROUP="xbaydns" UID=60190 GID=60190 OSTYPE="`uname`" KEYBITS=2048 INSTALLPATH="/data0/xbaydns" MASTER_PUB="ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEAvU9ro9cXksNrwrApyRjKgNFpjyqU7f/TWpLDbUXjzgXFR7MRJs+6HoCEU7aRoupwvzXOstA/0Hsl0EqE+Sb8CtFYNcYxDfjDRMObJYf4JS7zK3TAvRIdrAosdNcehhH2sOexc1emyaE4E8xnqAy3OKA8ATzCRpmHJqpjpPX9bZ/o8NAZn0o+E3VGysLzi5GvOwe4v20Uzj6hcIZyWeBzrpYQ8S2m24XWDE9c4PMNm7XnULYznMG2+2GZWn1x87EWKJMZ1BGizIFSdzV58tbI8f5+hlIgWRn40S+2JYBIja9w0hcGAmGChsEaS9VFchqmUi4DQyM/cXkVU3KkFpBpOHeEPUK68mmnP+IzYQ4Gwkkfmrdf7hr9eC0DE5GP0/W6r+eHI6Hk0Opv5GpJxW2n6Lyupo99iexg4lySLXWdLiV5DrnE4zpNexeh5SbfVJ+TTFUdW77OupsQoWfu+vFUe78DtFhkWXcinJAEqUx2hHMR0WqIbT34JLhvGPh2l7uqntrv7LdoRZIrP5bLgo3ud2nUQMhHDmsccMmTUqEoMe1imq+dvRIFnJuA6JZsX+Oca3hqcv+sy8QZBKlFyVlIyuzWhcDFgHrhKQqUgYw0j5vcX5F+QM2aEir2pgfoFIUrwk4UZvAHeR9ra5U0E2BG4ChUcGu9dFpNBJlRpePpsp8= root@november.sysdev.sina.com.cn" KNOWN_MASTER="10.210.132.70 ssh-dss AAAAB3NzaC1kc3MAAACBAJDkyyiXLub85a741dYGe6dY2k9rQqUP/HH+MLiEV8Yk11F4tYzP28ByDjtM60BZzaQztjAT96+ZrsHIc3rPgua8TkJ92zyu8UqNp+cz7QZemJMYY4ysWav5OOJM6VkSmFHugr0zR3AIIV9/hFQuPmOeDR7NvDJEwrWnPYzISdghAAAAFQCfJr9dI26UIkrGbP2gxwJbmEhSuwAAAIBkD39AlTA9e+UjzjPyBMqBFjdOY6T1tqB3DjvtmXQg5W3+lheXnVvasQZdhQyeMHw0bDXxgcpJDNFtHcoyqaKgvVtnuGu1xMBNj1BlJJkEG7IY/z4tJHMZVihJXNzMNPlcWlQS8DfxIL8hgwqDeuZNY7OQsbGaVhmWB3ZOxfYiBQAAAIAx/vRc6PPdwhP16+xogNqqgfIf/rdH2IxJAC2WMHCFJd1BvZZU5jRNWIq16F2nMycHV8EFmK3CZbnBa28quZQYmGCcqa/6YxgjWxVRFX7gVSbriBbrIhl7emy5t15clRLXQBinOJbiPUaGn6DxEoAaowFPKufro3etnEJeVLNkBQ==" MASTERIP="10.210.132.70" if [ "`id -u`" != "0" ]; then echo "Run this script using root user." exit 1 fi # create user and group case ${OSTYPE} in FreeBSD) pw groupadd ${GROUP} -g${GID} pw useradd ${USER} -u${UID} -s/usr/libexec/smrsh -d${INSTALLPATH} ln -s `which rsync` /usr/libexec/sm.bin/rsync ;; *) echo "Not implement";; esac # generate ssh key mkdir -p ${INSTALLPATH}/.ssh ssh-keygen -t rsa -b ${KEYBITS} -f ${INSTALLPATH}/.ssh/id_rsa -N '' echo "Please paste the public key to the master's authorized_keys (the line below):" cat ${INSTALLPATH}/.ssh/id_rsa.pub read -p "Be sure the public key is pasted, then press any key to continue" nouse # add the master's public key to authorized echo ${MASTER_PUB} > ${INSTALLPATH}/.ssh/authorized_keys echo ${KNOWN_MASTER} > ${INSTALLPATH}/.ssh/known_hosts # rsync agent mkdir -p ${INSTALLPATH}/iplatency rsync -az -e "ssh -i ${INSTALLPATH}/.ssh/id_rsa" ${USER}@${MASTERIP}:${INSTALLPATH}/agent/\* ${INSTALLPATH}/iplatency chown -R xbaydns:xbaydns ${INSTALLPATH} chown -R xbaydns:xbaydns ${INSTALLPATH}/.ssh # add to cron grep -v iplatency /etc/crontab > /tmp/crontab.xbaydns echo "* */1 * * * ${USER} /bin/sh ${INSTALLPATH}/iplatency/iplatency_agent.sh" >> /tmp/crontab.xbaydns mv /tmp/crontab.xbaydns /etc/crontab
/* THIS FILE AUTO-GENERATED FROM astra_plugin_service_delegate.hpp.lpp. DO NOT EDIT. */ // This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015 Orbbec 3D // // 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. // // Be excellent to each other. #ifndef ASTRA_PLUGIN_SERVICE_DELEGATE_H #define ASTRA_PLUGIN_SERVICE_DELEGATE_H #include <astra_core/capi/astra_types.h> #include <stdarg.h> #include "astra_context.hpp" namespace astra { class plugin_service_delegate { public: static astra_status_t register_stream_registered_callback(void* pluginService, stream_registered_callback_t callback, void* clientTag, astra_callback_id_t* callbackId) { return static_cast<plugin_service*>(pluginService)->register_stream_registered_callback(callback, clientTag, *callbackId); } static astra_status_t register_stream_unregistering_callback(void* pluginService, stream_unregistering_callback_t callback, void* clientTag, astra_callback_id_t* callbackId) { return static_cast<plugin_service*>(pluginService)->register_stream_unregistering_callback(callback, clientTag, *callbackId); } static astra_status_t register_host_event_callback(void* pluginService, host_event_callback_t callback, void* clientTag, astra_callback_id_t* callbackId) { return static_cast<plugin_service*>(pluginService)->register_host_event_callback(callback, clientTag, *callbackId); } static astra_status_t unregister_host_event_callback(void* pluginService, astra_callback_id_t callback) { return static_cast<plugin_service*>(pluginService)->unregister_host_event_callback(callback); } static astra_status_t unregister_stream_registered_callback(void* pluginService, astra_callback_id_t callback) { return static_cast<plugin_service*>(pluginService)->unregister_stream_registered_callback(callback); } static astra_status_t unregister_stream_unregistering_callback(void* pluginService, astra_callback_id_t callback) { return static_cast<plugin_service*>(pluginService)->unregister_stream_unregistering_callback(callback); } static astra_status_t create_stream_set(void* pluginService, const char* setUri, astra_streamset_t& setHandle) { return static_cast<plugin_service*>(pluginService)->create_stream_set(setUri, setHandle); } static astra_status_t destroy_stream_set(void* pluginService, astra_streamset_t& setHandle) { return static_cast<plugin_service*>(pluginService)->destroy_stream_set(setHandle); } static astra_status_t get_streamset_uri(void* pluginService, astra_streamset_t setHandle, const char** uri) { return static_cast<plugin_service*>(pluginService)->get_streamset_uri(setHandle, *uri); } static astra_status_t create_stream(void* pluginService, astra_streamset_t setHandle, astra_stream_desc_t desc, astra_stream_t* handle) { return static_cast<plugin_service*>(pluginService)->create_stream(setHandle, desc, *handle); } static astra_status_t register_stream(void* pluginService, astra_stream_t handle, stream_callbacks_t pluginCallbacks) { return static_cast<plugin_service*>(pluginService)->register_stream(handle, pluginCallbacks); } static astra_status_t unregister_stream(void* pluginService, astra_stream_t handle) { return static_cast<plugin_service*>(pluginService)->unregister_stream(handle); } static astra_status_t destroy_stream(void* pluginService, astra_stream_t& handle) { return static_cast<plugin_service*>(pluginService)->destroy_stream(handle); } static astra_status_t create_stream_bin(void* pluginService, astra_stream_t streamHandle, size_t lengthInBytes, astra_bin_t* binHandle, astra_frame_t** binBuffer) { return static_cast<plugin_service*>(pluginService)->create_stream_bin(streamHandle, lengthInBytes, *binHandle, *binBuffer); } static astra_status_t destroy_stream_bin(void* pluginService, astra_stream_t streamHandle, astra_bin_t* binHandle, astra_frame_t** binBuffer) { return static_cast<plugin_service*>(pluginService)->destroy_stream_bin(streamHandle, *binHandle, *binBuffer); } static astra_status_t bin_has_connections(void* pluginService, astra_bin_t binHandle, bool* hasConnections) { return static_cast<plugin_service*>(pluginService)->bin_has_connections(binHandle, *hasConnections); } static astra_status_t cycle_bin_buffers(void* pluginService, astra_bin_t binHandle, astra_frame_t** binBuffer) { return static_cast<plugin_service*>(pluginService)->cycle_bin_buffers(binHandle, *binBuffer); } static astra_status_t link_connection_to_bin(void* pluginService, astra_streamconnection_t connection, astra_bin_t binHandle) { return static_cast<plugin_service*>(pluginService)->link_connection_to_bin(connection, binHandle); } static astra_status_t get_parameter_bin(void* pluginService, size_t byteSize, astra_parameter_bin_t* binHandle, astra_parameter_data_t* parameterData) { return static_cast<plugin_service*>(pluginService)->get_parameter_bin(byteSize, *binHandle, *parameterData); } static astra_status_t log(void* pluginService, const char* channel, astra_log_severity_t logLevel, const char* fileName, int lineNo, const char* func, const char* format, va_list args) { return static_cast<plugin_service*>(pluginService)->log(channel, logLevel, fileName, lineNo, func, format, args); } }; } #endif /* ASTRA_PLUGIN_SERVICE_DELEGATE_H */
#!/bin/sh echo "Updating files" git pull echo "Installing/Upgrading requirements" pip install -U -r requirements.txt echo "Setting env vars" # enter you own variables here # discord bot key export KEY_DISCORD="YOUR_KEY" # fnbr.co api key export KEY_FNBR="YOUR_KEY" # fortnite tracker network api key export KEY_TRACKERNETWORK="YOUR_KEY" # your postgresql access url (see README for details on setting up) export DATABASE_URL="postgresql://my.database" echo "Starting..." python ./bot.py
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fantasy.nacos.test.base; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import java.net.URL; /** * Http client for test module * * @author nkorange * @since 1.2.0 */ public class HttpClient4Test { protected URL base; @Autowired protected TestRestTemplate restTemplate; protected <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz) { HttpHeaders headers = new HttpHeaders(); HttpEntity<?> entity = new HttpEntity<T>(headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) .queryParams(params); return this.restTemplate.exchange( builder.toUriString(), HttpMethod.GET, entity, clazz); } protected <T> ResponseEntity<T> request(String path, MultiValueMap<String, String> params, Class<T> clazz, HttpMethod httpMethod) { HttpHeaders headers = new HttpHeaders(); HttpEntity<?> entity = new HttpEntity<T>(headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.base.toString() + path) .queryParams(params); return this.restTemplate.exchange( builder.toUriString(), httpMethod, entity, clazz); } }
func deleteLocalCounters(countersIds: [String], _ completion: (Result<Void, Error>) -> Void) { guard let managedContext = CounterWorker.getManagedContext() else { completion(.failure(AppError(id: .coreData))) return } let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: CounterModel.counterEntityName) fetchRequest.predicate = NSPredicate(format: "id IN %@", countersIds) let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) deleteRequest.resultType = .resultTypeObjectIDs do { try managedContext.executeAndMergeChanges(using: deleteRequest) completion(.success(())) } catch { completion(.failure(error)) } }
arr = [[ 8, 1, 6], [ 3, 5, 7], [ 4, 9, 2]] print("Following is a 3x3 matrix :") # printing given matrix in 3x3 format for i in range(0, 3): for j in range(0, 3): print(arr[i][j], end = " ") print() # calculating sum of matrix total = 0 for i in range(0, 3): total += arr[i][i] print("Sum of matrix:", total)
<filename>src/planner/binder/query_node/bind_setop_node.cpp #include "duckdb/parser/expression/columnref_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression_map.hpp" #include "duckdb/parser/query_node/select_node.hpp" #include "duckdb/parser/query_node/set_operation_node.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/query_node/bound_set_operation_node.hpp" using namespace duckdb; using namespace std; static void GatherAliases(QueryNode &node, unordered_map<string, idx_t> &aliases, expression_map_t<idx_t> &expressions) { if (node.type == QueryNodeType::SET_OPERATION_NODE) { // setop, recurse auto &setop = (SetOperationNode &)node; GatherAliases(*setop.left, aliases, expressions); GatherAliases(*setop.right, aliases, expressions); } else { // query node assert(node.type == QueryNodeType::SELECT_NODE); auto &select = (SelectNode &)node; // fill the alias lists for (idx_t i = 0; i < select.select_list.size(); i++) { auto &expr = select.select_list[i]; auto name = expr->GetName(); // first check if the alias is already in there auto entry = aliases.find(name); if (entry != aliases.end()) { // the alias already exists // check if there is a conflict if (entry->second != i) { // there is a conflict // we place "-1" in the aliases map at this location // "-1" signifies that there is an ambiguous reference aliases[name] = INVALID_INDEX; } } else { // the alias is not in there yet, just assign it aliases[name] = i; } // now check if the node is already in the set of expressions auto expr_entry = expressions.find(expr.get()); if (expr_entry != expressions.end()) { // the node is in there // repeat the same as with the alias: if there is an ambiguity we insert "-1" if (expr_entry->second != i) { expressions[expr.get()] = INVALID_INDEX; } } else { // not in there yet, just place it in there expressions[expr.get()] = i; } } } } unique_ptr<BoundQueryNode> Binder::Bind(SetOperationNode &statement) { auto result = make_unique<BoundSetOperationNode>(); result->setop_type = statement.setop_type; // first recursively visit the set operations // both the left and right sides have an independent BindContext and Binder assert(statement.left); assert(statement.right); result->setop_index = GenerateTableIndex(); vector<idx_t> order_references; if (statement.orders.size() > 0) { // handle the ORDER BY // NOTE: we handle the ORDER BY in SET OPERATIONS before binding the children // we do so we can perform expression comparisons BEFORE type resolution/binding // we recursively visit the children of this node to extract aliases and expressions that can be referenced in // the ORDER BY unordered_map<string, idx_t> alias_map; expression_map_t<idx_t> expression_map; GatherAliases(statement, alias_map, expression_map); // now we perform the actual resolution of the ORDER BY expressions for (idx_t i = 0; i < statement.orders.size(); i++) { auto &order = statement.orders[i].expression; if (order->type == ExpressionType::VALUE_CONSTANT) { // ORDER BY a constant auto &constant = (ConstantExpression &)*order; if (TypeIsIntegral(constant.value.type)) { // INTEGER constant: we use the integer as an index into the select list (e.g. ORDER BY 1) order_references.push_back(constant.value.GetValue<int64_t>() - 1); continue; } } if (order->type == ExpressionType::COLUMN_REF) { // ORDER BY column, check if it is an alias reference auto &colref = (ColumnRefExpression &)*order; if (colref.table_name.empty()) { auto entry = alias_map.find(colref.column_name); if (entry != alias_map.end()) { // found a matching entry if (entry->second == INVALID_INDEX) { // ambiguous reference throw BinderException("Ambiguous alias reference \"%s\"", colref.column_name.c_str()); } else { order_references.push_back(entry->second); continue; } } } } // check if the ORDER BY clause matches any of the columns in the projection list of any of the children auto expr_ref = expression_map.find(order.get()); if (expr_ref == expression_map.end()) { // not found throw BinderException("Could not ORDER BY column: add the expression/function to every SELECT, or move " "the UNION into a FROM clause."); } if (expr_ref->second == INVALID_INDEX) { throw BinderException("Ambiguous reference to column"); } order_references.push_back(expr_ref->second); } } result->left_binder = make_unique<Binder>(context, this); result->left = result->left_binder->Bind(*statement.left); result->right_binder = make_unique<Binder>(context, this); result->right = result->right_binder->Bind(*statement.right); result->names = result->left->names; // move the correlated expressions from the child binders to this binder MoveCorrelatedExpressions(*result->left_binder); MoveCorrelatedExpressions(*result->right_binder); // now both sides have been bound we can resolve types if (result->left->types.size() != result->right->types.size()) { throw Exception("Set operations can only apply to expressions with the " "same number of result columns"); } // figure out the types of the setop result by picking the max of both for (idx_t i = 0; i < result->left->types.size(); i++) { auto result_type = MaxSQLType(result->left->types[i], result->right->types[i]); result->types.push_back(result_type); } // if there are ORDER BY entries we create the BoundColumnRefExpressions assert(order_references.size() == statement.orders.size()); for (idx_t i = 0; i < statement.orders.size(); i++) { auto entry = order_references[i]; if (entry >= result->types.size()) { throw BinderException("ORDER term out of range - should be between 1 and %d", (int)result->types.size()); } BoundOrderByNode node; node.expression = make_unique<BoundColumnRefExpression>(GetInternalType(result->types[entry]), ColumnBinding(result->setop_index, entry)); node.type = statement.orders[i].type; result->orders.push_back(move(node)); } return move(result); }
<gh_stars>0 # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import goloco_pb2 as goloco__pb2 class LocationServiceStub(object): """---------------Location service---------- """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SaveLocation = channel.unary_unary( '/goloco.LocationService/SaveLocation', request_serializer=goloco__pb2.LocationRequest.SerializeToString, response_deserializer=goloco__pb2.LocationResponse.FromString, ) self.GetLocation = channel.unary_unary( '/goloco.LocationService/GetLocation', request_serializer=goloco__pb2.GetLocationLocationRequest.SerializeToString, response_deserializer=goloco__pb2.LocationResponse.FromString, ) self.UpdateLocation = channel.unary_unary( '/goloco.LocationService/UpdateLocation', request_serializer=goloco__pb2.LocationRequest.SerializeToString, response_deserializer=goloco__pb2.LocationResponse.FromString, ) self.DeleteLocation = channel.unary_unary( '/goloco.LocationService/DeleteLocation', request_serializer=goloco__pb2.DeleteLocationLocationRequest.SerializeToString, response_deserializer=goloco__pb2.DeletedLocationId.FromString, ) self.GetAllLocations = channel.unary_unary( '/goloco.LocationService/GetAllLocations', request_serializer=goloco__pb2.EmptyMessageRequest.SerializeToString, response_deserializer=goloco__pb2.AllLocationsResponse.FromString, ) self.GetAllLocationsStream = channel.unary_stream( '/goloco.LocationService/GetAllLocationsStream', request_serializer=goloco__pb2.EmptyMessageRequest.SerializeToString, response_deserializer=goloco__pb2.LocationResponse.FromString, ) class LocationServiceServicer(object): """---------------Location service---------- """ def SaveLocation(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetLocation(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def UpdateLocation(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DeleteLocation(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetAllLocations(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetAllLocationsStream(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_LocationServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'SaveLocation': grpc.unary_unary_rpc_method_handler( servicer.SaveLocation, request_deserializer=goloco__pb2.LocationRequest.FromString, response_serializer=goloco__pb2.LocationResponse.SerializeToString, ), 'GetLocation': grpc.unary_unary_rpc_method_handler( servicer.GetLocation, request_deserializer=goloco__pb2.GetLocationLocationRequest.FromString, response_serializer=goloco__pb2.LocationResponse.SerializeToString, ), 'UpdateLocation': grpc.unary_unary_rpc_method_handler( servicer.UpdateLocation, request_deserializer=goloco__pb2.LocationRequest.FromString, response_serializer=goloco__pb2.LocationResponse.SerializeToString, ), 'DeleteLocation': grpc.unary_unary_rpc_method_handler( servicer.DeleteLocation, request_deserializer=goloco__pb2.DeleteLocationLocationRequest.FromString, response_serializer=goloco__pb2.DeletedLocationId.SerializeToString, ), 'GetAllLocations': grpc.unary_unary_rpc_method_handler( servicer.GetAllLocations, request_deserializer=goloco__pb2.EmptyMessageRequest.FromString, response_serializer=goloco__pb2.AllLocationsResponse.SerializeToString, ), 'GetAllLocationsStream': grpc.unary_stream_rpc_method_handler( servicer.GetAllLocationsStream, request_deserializer=goloco__pb2.EmptyMessageRequest.FromString, response_serializer=goloco__pb2.LocationResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'goloco.LocationService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) class SuggestionServiceStub(object): """---------------Suggestions service---------- """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.ListSuggestions = channel.unary_unary( '/goloco.SuggestionService/ListSuggestions', request_serializer=goloco__pb2.ListSuggestionsRequest.SerializeToString, response_deserializer=goloco__pb2.ListSuggestionsResponse.FromString, ) class SuggestionServiceServicer(object): """---------------Suggestions service---------- """ def ListSuggestions(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_SuggestionServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'ListSuggestions': grpc.unary_unary_rpc_method_handler( servicer.ListSuggestions, request_deserializer=goloco__pb2.ListSuggestionsRequest.FromString, response_serializer=goloco__pb2.ListSuggestionsResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'goloco.SuggestionService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) class AdServiceStub(object): """---------------Ad service---------- """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetAds = channel.unary_unary( '/goloco.AdService/GetAds', request_serializer=goloco__pb2.AdRequest.SerializeToString, response_deserializer=goloco__pb2.AdResponse.FromString, ) class AdServiceServicer(object): """---------------Ad service---------- """ def GetAds(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_AdServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'GetAds': grpc.unary_unary_rpc_method_handler( servicer.GetAds, request_deserializer=goloco__pb2.AdRequest.FromString, response_serializer=goloco__pb2.AdResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'goloco.AdService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) class SearchServiceStub(object): """---------------Search service---------- """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SearchLocation = channel.unary_unary( '/goloco.SearchService/SearchLocation', request_serializer=goloco__pb2.SearchRequest.SerializeToString, response_deserializer=goloco__pb2.SearchResponse.FromString, ) class SearchServiceServicer(object): """---------------Search service---------- """ def SearchLocation(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_SearchServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'SearchLocation': grpc.unary_unary_rpc_method_handler( servicer.SearchLocation, request_deserializer=goloco__pb2.SearchRequest.FromString, response_serializer=goloco__pb2.SearchResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'goloco.SearchService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
var num1 = 4; var num2 = 5; var num3 = 3; // Find the maximum of the three numbers var max = Math.max(num1, num2, num3); // Print the max number console.log('The maximum number is ' + max);
<reponame>yamozha/discord-bots import discord import asyncio from discord.ext import commands import youtube_dl import os, glob, sys, re from youtube_search import YoutubeSearch import TenGiphPy from config import TOKEN g = TenGiphPy.Giphy(token='token for giphy')# yes i accidentally leaked mine here but it has been reset bot = commands.Bot(command_prefix='#', description='''multi-tool bot made by Yamozha''') queue = [] def youtubeDown(url): ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': 'downloadedsongs/%(title)s.%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) filename = ydl.prepare_filename(info) if ".webm" in filename: filename = filename.replace(".webm", ".mp3") elif ".mp4" in filename: filename = filename.replace(".mp4", ".mp3") elif ".m4a" in filename: filename = filename.replace(".m4a", ".mp3") return filename @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') game = discord.Game("#help") await bot.change_presence(activity=game, status=discord.Status.dnd) @bot.command(aliases=["sus","drip"]) async def amongus(ctx): em = discord.Embed(colour=discord.Colour(0xFF0000)) em.set_image(url=f"{g.random(tag='amongus')['data']['images']['downsized_large']['url']}") return await ctx.send(embed=em) @bot.command() async def ping(ctx): """ Pong """ await ctx.send("pong") @bot.command() async def top3league(ctx, username=None, region=None): """| Checks your top 3 champions in league""" # Check if user has provided username if not username: await ctx.send("Please give me a LoL username") await ctx.send("`usage: #top3league username region`") return # If user provides info as input, print information about the command elif not region: await ctx.send("Please give me a LoL region") await ctx.send("`usage: #top3league username region`") else: # Check if the account exists or not em = discord.Embed(title=f"{username}'s top 3") em.set_image(url=f"https://www.masterypoints.com/image/profile/{username}/{region}") return await ctx.send(embed=em) @bot.command(aliases=["p","paly"]) async def play(ctx, *, url): """| Plays a song or adds it to queue""" print(url) print(str(url)) is_url = re.search("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", url) if is_url: print("it's an url!") if "www" in url: url_thumbnail = url.replace("https://www.youtube.com/watch?v=", "http://i3.ytimg.com/vi/") + "/maxresdefault.jpg" else: url_thumbnail = url.replace("https://youtube.com/watch?v=", "http://i3.ytimg.com/vi/") + "/maxresdefault.jpg" print(url_thumbnail) pass else: url_dict = YoutubeSearch(url, max_results=1).to_dict() print(url_dict) url = f"https://youtube.com/{url_dict[0]['url_suffix']}" files = glob.glob("downloadedsongs/*") if len(files) > 10: for i in files: os.remove(i) print(len(files)) channel = ctx.author.voice.channel try: vc = await channel.connect() except Exception as e: vc = ctx.message.guild.voice_client print(e) pass if vc.is_playing(): queue.append(url) if not is_url: em = discord.Embed(title=f"Added {url_dict[0]['title']} to queue", colour=discord.Colour(0x8c0303)) em.set_image(url=url_dict[0]['thumbnails'][0]) em.add_field(name=f"{url_dict[0]['channel']}", value=f"{url_dict[0]['views']}", inline=False) await ctx.send(embed=em) else: with youtube_dl.YoutubeDL() as ydl: object = ydl.extract_info(url, download=False) print(object["title"]) em = discord.Embed(title=f"Added {object['title']} to queue", colour=discord.Colour(0x8c0303)) em.set_image(url=url_thumbnail) await ctx.send(embed=em) # em = discord.Embed(title/ elif not vc.is_playing() and len(queue) == 0: player = vc.play(discord.FFmpegPCMAudio(f"{youtubeDown(url)}")) if not is_url: em = discord.Embed(title=f"Playing {url_dict[0]['title']}", colour=discord.Colour(0x8c0303)) em.set_image(url=url_dict[0]['thumbnails'][0]) em.add_field(name=f"{url_dict[0]['channel']}",value=f"{url_dict[0]['views']}", inline=False) await ctx.send(embed=em) else: with youtube_dl.YoutubeDL() as ydl: object = ydl.extract_info(url, download=False) print(object["title"]) em = discord.Embed(title=f"Playing {object['title']} ", colour = discord.Colour(0x8c0303)) em.set_image(url=url_thumbnail) await ctx.send(embed=em) return @bot.command(aliases=["s","sikp"]) async def skip(ctx): """| Skip song""" channel = ctx.author.voice.channel try: vc = await channel.connect() except Exception as e: vc = ctx.message.guild.voice_client print(e) pass if vc.is_playing() and len(queue) != 0: vc.stop() print(queue) url = queue[0] if "www" in url: url_thumbnail = url.replace("https://www.youtube.com/watch?v=", "http://i3.ytimg.com/vi/") + "/maxresdefault.jpg" else: url_thumbnail = url.replace("https://youtube.com//watch?v=", "http://i3.ytimg.com/vi/") + "/maxresdefault.jpg" with youtube_dl.YoutubeDL() as ydl: object = ydl.extract_info(url, download=False) print(object["title"]) em = discord.Embed(title=f"Playing {object['title']} ", colour=discord.Colour(0x8c0303)) em.set_image(url=url_thumbnail) await ctx.send(embed=em) player = vc.play(discord.FFmpegPCMAudio(f"{youtubeDown(url)}")) queue.pop(0) @bot.command(aliases=["queue","que"]) async def q(ctx): """| Show queue""" em = discord.Embed(title=f"Queue") number = 0 for i in queue: number += 1 em.add_field(name=f"{number}.", value=i, inline=False) await ctx.send(embed=em) @bot.command(aliases=["l","begai"]) async def leave(ctx): """ | Makes the bot leave the voice channel its in""" server = ctx.message.guild.voice_client return await server.disconnect() @bot.command() async def stop(ctx): """| Stop current song """ server = ctx.message.guild.voice_client return await server.stop() @bot.command() async def dababy(ctx): """| Dababy """ em = discord.Embed(title=f"🚗 🚗 🚗") em.set_image(url=f"{g.random(tag='dababy')['data']['images']['downsized_large']['url']}") await ctx.send(embed=em) loop = asyncio.get_event_loop() try: loop.run_until_complete(bot.start(TOKEN)) except KeyboardInterrupt: loop.run_until_complete(bot.logout()) finally: loop.close()
<gh_stars>0 import React from 'react'; import { Grid, LinearProgress, Card } from '@material-ui/core'; export default function LivePreviewExample() { return ( <> <div className="mb-spacing-6"> <Grid container spacing={6}> <Grid item md={6} xl={3}> <Card className="p-3"> <div className="align-box-row"> <div className="text-first font-size-xl font-weight-bold pr-2"> 55% </div> <div className="flex-grow-1"> <LinearProgress variant="determinate" className="progress-animated-alt progress-bar-rounded progress-sm progress-bar-first" value={55} /> </div> </div> <div className="text-black-50 pt-2">Expenses target</div> </Card> </Grid> <Grid item md={6} xl={3}> <Card className="p-3"> <div className="align-box-row"> <div className="text-success font-size-xl font-weight-bold pr-2"> 76% </div> <div className="flex-grow-1"> <LinearProgress variant="determinate" className="progress-animated-alt progress-bar-rounded progress-sm progress-bar-success" value={76} /> </div> </div> <div className="text-black-50 pt-2">Sales target</div> </Card> </Grid> <Grid item md={6} xl={3}> <Card className="p-3 bg-asteroid"> <div className="align-box-row"> <div className="text-danger font-size-xl font-weight-bold pr-2"> 61% </div> <div className="flex-grow-1"> <LinearProgress variant="determinate" className="progress-animated-alt progress-bar-rounded bg-white-50 progress-sm progress-bar-danger" value={61} /> </div> </div> <div className="text-white-50 pt-2">Income target</div> </Card> </Grid> <Grid item md={6} xl={3}> <Card className="p-3 bg-midnight-bloom"> <div className="align-box-row"> <div className="text-warning font-size-xl font-weight-bold pr-2"> 83% </div> <div className="flex-grow-1"> <LinearProgress variant="determinate" className="progress-animated-alt progress-bar-rounded bg-white-50 progress-sm progress-bar-warning" value={83} /> </div> </div> <div className="text-white-50 pt-2">Spendings target</div> </Card> </Grid> </Grid> </div> </> ); }
#include <stdio.h> // I apologize I know i did really bad on this lab it just broke and I couldt work on it any more. int main(void) { char p,q,r ; int i = 0;int j = 0;int k = 0; int input = 0; printf( "truth table\n" ); printf( "P \t Q \t R \t | f (p,q,r)\n" ); printf( "--------------------------\n"); for (i = 0; i <= 1 ; i++) { for (j = 0; j <= 1 ; j++) { for ( k= 0; k <= 1 ; k++) { if ( i == 0) { p = '1'; } else { p = '0'; } if (j == 0) { q = '1'; } else { q = '0'; } if (k == 0) { r = '1'; } else { r = '0'; } printf("%d\t%d\t%d\n", p,q,r); } } } int Array[8]; for(int a = 0; a < 8; a++){ printf(" Enter 0 or 1 : \n"); scanf("%d",&input); if (input == 0 || input == 1){ Array[a] = input; }else if(input > 1){ printf("Invalid input\n"); break; }else if(input < 0){ printf("Invalid input\n"); break; } } return 0; }
'use strict'; module.exports = function (grunt) { require('time-grunt')(grunt); require('jit-grunt')(grunt); grunt.initConfig({ /*less: { options: { plugins: [new (require('../less-plugin-lists'))()] }, regression: { expand: true, flatten: true, src: 'test/less/*.less', dest: 'test/tmp/css', ext: '.css' } }, compare: { src: 'test/css/*.css', dest: 'test/tmp/css', },*/ jshint: { options: { jshintrc: 'test/.jshintrc' }, src: [ 'lib/*.js', 'Gruntfile.js' ], }, // clean: ['test/tmp'] }); /* grunt.registerTask('compare', require('./test/compare')(grunt)); grunt.registerTask('regression', [ 'clean', 'less:regression', 'compare' ]);*/ grunt.registerTask('test', [ 'jshint', // 'regression' ]); grunt.registerTask('default', ['test']); };
<reponame>hapramp/1Rramp-Android package com.hapramp.views.post; import android.content.Context; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.ScaleAnimation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.hapramp.R; import com.hapramp.api.ProgressRequestBody; import com.hapramp.api.RetrofitServiceGenerator; import com.hapramp.models.response.FileUploadReponse; import com.hapramp.utils.ImageCacheClearUtils; import com.hapramp.utils.ImageHandler; import com.hapramp.utils.ImageRotationHandler; import java.io.File; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import okhttp3.MultipartBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Ankit on 2/5/2018. */ public class PostImageView extends FrameLayout implements ImageRotationHandler.ImageRotationOperationListner, ProgressRequestBody.UploadCallbacks { private final int MAX_RETRY_COUNT = 5; @BindView(R.id.image) ImageView image; @BindView(R.id.informationTv) TextView informationTv; @BindView(R.id.actionContainer) RelativeLayout actionContainer; @BindView(R.id.progressBar) ProgressBar progressBar; @BindView(R.id.removeBtn) TextView removeBtn; private View mainView; private String downloadUrl; private ImageActionListener imageActionListener; private Context mContext; private int retryCount = 0; private Handler mHandler; private ImageRotationHandler imageRotationHandler; private String currentFilePath; private Call<FileUploadReponse> fileUploadReponseCall; private long currentImageUID; public PostImageView(@NonNull Context context) { super(context); init(context); } private void init(Context context) { this.mContext = context; mHandler = new Handler(); mainView = LayoutInflater.from(context).inflate(R.layout.post_image_view, this); ButterKnife.bind(this, mainView); imageRotationHandler = new ImageRotationHandler(context); imageRotationHandler.setImageRotationOperationListner(this); attachListeners(); invalidateView(); } private void attachListeners() { image.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (downloadUrl != null) { showAndhideActionContainer(); } } }); removeBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { scaleAndHideMainView(); try { if (imageActionListener != null) { imageActionListener.onImageRemoved(); currentFilePath = null; cancelUploadIfAny(); } } catch (Exception e) { e.printStackTrace(); } } }); } private void invalidateView() { progressBar.setVisibility(VISIBLE); informationTv.setVisibility(GONE); } private void showAndhideActionContainer() { actionContainer.setVisibility(VISIBLE); new Handler().postDelayed(new Runnable() { @Override public void run() { actionContainer.setVisibility(GONE); } }, 2000); } public void scaleAndHideMainView() { Animation anim = new ScaleAnimation( 1f, 1f, // Start and end values for the X axis scaling 1f, 0f, // Start and end values for the Y axis scaling Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling Animation.RELATIVE_TO_SELF, 0f); // Pivot point of Y scaling anim.setFillAfter(false); // Needed to keep the result of the animation anim.setDuration(200); anim.setInterpolator(new DecelerateInterpolator(1f)); mainView.startAnimation(anim); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { mainView.setVisibility(GONE); } @Override public void onAnimationRepeat(Animation animation) { } }); } private void cancelUploadIfAny() { if (fileUploadReponseCall != null) { fileUploadReponseCall.cancel(); } } public PostImageView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public PostImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public void setImageSource(String filePath) { invalidateView(); currentFilePath = filePath; mainView.setVisibility(VISIBLE); ImageHandler.loadFilePath(mContext, image, filePath); informationTv.setVisibility(VISIBLE); informationTv.setText("Processing..."); currentImageUID = System.currentTimeMillis(); actionContainer.setVisibility(VISIBLE); imageRotationHandler.checkOrientationAndFixImage(filePath, currentImageUID); } private void retryUpload(String filePath, boolean fileNeedsToBeDeleted, long uid) { if (informationTv != null && !isImageRemoved(filePath)) { retryCount++; if (retryCount > MAX_RETRY_COUNT) return; progressBar.setVisibility(VISIBLE); informationTv.setText("Retrying image upload..."); actionContainer.setVisibility(VISIBLE); startUploading(filePath, fileNeedsToBeDeleted, uid); } } @Override public void onImageRotationFixed(final String filePath, final boolean fileShouldBeDeleted, final long uid) { mHandler.post(new Runnable() { @Override public void run() { if (uid == currentImageUID) { startUploading(filePath, fileShouldBeDeleted, uid); } } }); } private void startUploading(final String filePath, final boolean fileShouldBeDeleted, final long imageUID) { try { final File file = new File(filePath); ProgressRequestBody fileBody = new ProgressRequestBody(file, this); MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), fileBody); fileUploadReponseCall = RetrofitServiceGenerator.getService().uploadFile(body); fileUploadReponseCall.enqueue(new Callback<FileUploadReponse>() { @Override public void onResponse(Call<FileUploadReponse> call, Response<FileUploadReponse> response) { //ignore failure action if image is replaced by another image. if (currentImageUID == imageUID) { if (response.isSuccessful()) { downloadUrl = response.body().getDownloadUrl(); progressBar.setVisibility(GONE); informationTv.setText("Uploaded"); if (imageActionListener != null) { imageActionListener.onImageUploaded(downloadUrl); } showAndhideActionContainer(); } else { Crashlytics.log(response.errorBody().toString()); downloadUrl = null; progressBar.setVisibility(GONE); retryUpload(filePath, fileShouldBeDeleted, imageUID); } } if (fileShouldBeDeleted) { ImageCacheClearUtils.deleteImage(filePath); } } @Override public void onFailure(Call<FileUploadReponse> call, Throwable t) { //ignore failure action if image is replaced by another image. if (currentImageUID == imageUID) { Crashlytics.logException(t); progressBar.setVisibility(GONE); downloadUrl = null; retryUpload(filePath, fileShouldBeDeleted, imageUID); } } }); } catch (Exception e) { Log.d("FilePathUtils", "" + e.toString()); informationTv.setText("Failed to load image."); Crashlytics.logException(e); progressBar.setVisibility(GONE); downloadUrl = null; } } private boolean isImageRemoved(String filePath) { return !filePath.equals(currentFilePath); } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { if (downloadUrl != null) { this.downloadUrl = downloadUrl; invalidateView(); mainView.setVisibility(VISIBLE); informationTv.setVisibility(VISIBLE); informationTv.setText("Uploaded"); actionContainer.setVisibility(VISIBLE); ImageHandler.load(mContext, image, downloadUrl); } } public void setImageActionListener(ImageActionListener imageActionListener) { this.imageActionListener = imageActionListener; } @Override public void onProgressUpdate(int percentage) { if (informationTv != null) { informationTv.setText(String.format(Locale.US, "Uploaded %d%%", percentage)); progressBar.setProgress(percentage); } } @Override public void onError() { } @Override public void onProcessing() { } @Override public void onFinish() { } public interface ImageActionListener { void onImageRemoved(); void onImageUploaded(String downloadUrl); } }
<gh_stars>0 package com.myproject.framework.mvp.ui.feed; import com.myproject.framework.mvp.ui.base.BaseView; import com.myproject.framework.mvp.ui.base.MvpPresenter; /** * Created by Nhat on 12/13/17. */ public interface FeedMvpPresenter<V extends BaseView> extends MvpPresenter<V> { }
#ifndef CROW_CONSTEXPR_HEXER_H #define CROW_CONSTEXPR_HEXER_H #include <array> #include <crow/hexer.h> #include <ctype.h> #include <igris/util/hexascii.h> namespace crow { template <size_t N> constexpr std::pair<std::array<char, N>, int> constexpr_hexer(const std::array<char, N> &arr) { std::array<char, N> ret = {}; int sz = 0; auto it = arr.begin(); auto dst = ret.begin(); while (it != arr.end()) { if (*it == '\r') return {ret, 0}; else if (*it == '\n') return {ret, 0}; else if (*it == '0') return {ret, 0}; else if (*it == '.') { uint8_t byte = 0; int cnt = 0; while (isdigit(*++it)) { byte *= 10; byte += hex2half(*it); cnt++; } ++sz; *dst++ = byte; if (cnt > 3) return {ret, CROW_HEXER_MORE3_DOT}; } else if (*it == ':') { uint16_t twobyte = 0; while (isdigit(*++it)) { twobyte *= 10; twobyte += hex2half(*it); } *dst++ = (twobyte & 0xFF00) >> 8; *dst++ = twobyte & 0x00FF; sz += 2; } else if (*it == '_') ++it; else return {ret, CROW_HEXER_UNDEFINED_SYMBOL}; } return {ret, sz}; } } #endif
<reponame>hamdouni/agoutidemo<filename>main.go package main import ( "log" "net/http" "strconv" ) func StartApp(p int) { a := ":" + strconv.Itoa(p) log.Fatal(http.ListenAndServe(a, http.FileServer(http.Dir("./")))) } func main() { // Simple static webserver: StartApp(8888) }
<reponame>Zurdge/react-bootstrap import { mount } from 'enzyme'; import Form from '../src/Form'; import FormGroup from '../src/FormGroup'; describe('<Form>', () => { it('should support custom `as`', () => { mount( <Form as="fieldset" className="my-form"> <FormGroup /> </Form>, ) .assertSingle('fieldset.my-form') .assertSingle('FormGroup'); }); it('Should have form as default component', () => { mount(<Form />).assertSingle('form'); }); it('should have form class `was-validated` if validated', () => { mount(<Form validated />).assertSingle('form.was-validated'); }); });
#!/bin/sh # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # # Called with following variables set: # - CORE_PATH is absolute path to @apache-mynewt-core # - BSP_PATH is absolute path to hw/bsp/bsp_name # - BIN_BASENAME is the path to prefix to target binary, # .elf appended to name is the ELF file # - FEATURES holds the target features string # - EXTRA_JTAG_CMD holds extra parameters to pass to jtag software # - RESET set if target should be reset when attaching # - NO_GDB set if we should not start gdb to debug # . $CORE_PATH/hw/scripts/openocd.sh FILE_NAME=$BIN_BASENAME.elf CFG="-s $BSP_PATH -f b-l072z-lrwan1.cfg" # Exit openocd when gdb detaches. EXTRA_JTAG_CMD="$EXTRA_JTAG_CMD; stm32l0.cpu configure -event gdb-detach {if {[stm32l0.cpu curstate] eq \"halted\"} resume;shutdown}" openocd_debug
/* Author: <NAME> Controls: Down: 2 | Rotate: R | Triangle: T | Leaf: M Left: 4 | AntiRotate: E | Quad: Q | Quit: X Right: 6 | ScaleUp: S | Polygon1: O | Up: 8 | ScaleDown: D | Polygon2: P | */ #include <windows.h> #include <stdio.h> #include <GL/glut.h> void Keyboard(unsigned char c, int x, int y); void Keyboard1(unsigned char c, int x, int y); void Keyboard2(unsigned char c, int x, int y); void Keyboard3(unsigned char c, int x, int y); void Keyboard4(unsigned char c, int x, int y); void display(); void display1(); void display2(); void display3(); void display4(); void triangle(){ glBegin(GL_TRIANGLES); glColor3f(0.0, 0.0, 1.0); glVertex2f(-0.3*0.152, 0.31*0.4); glColor3f(1.0, 0.0, 0.0); glVertex2f(0.0*0.152, 0.0*0.4); glColor3f(0.0, 1.0, 0.0); glVertex2f(0.3*0.152, 0.31*0.4); glEnd(); } void quad(){ glBegin(GL_POLYGON); glColor3f(1.0, 0.0, 0.0); glVertex2f(-0.59*0.152, 0.61*0.4); glColor3f(1.0, 0.0, 0.0); glVertex2f(0.0*0.152, 0.31*0.4); glColor3f(0.0, 1.0, 0.0); glVertex2f(0.59*0.152, 0.61*0.4); glColor3f(0.0, 0.0, 1.0); glVertex2f(0.0*0.152, 0.91*0.4); glEnd(); } void polygon1(){ glBegin(GL_POLYGON); glColor3f(0.0, 1.0, 0.0); glVertex2f(0.0*0.152, 0.91*0.4); glColor3f(1.0, 0.0, 0.0); glVertex2f(1.07*0.152, 1.1*0.4); glColor3f(0.0, 0.0, 1.0); glVertex2f(0.37*0.152, 1.33*0.4); glColor3f(0.0, 1.0, 0.0); glVertex2f(-0.37*0.152, 1.33*0.4); glColor3f(1.0, 0.0, 0.0); glVertex2f(-1.07*0.152, 1.1*0.4); glEnd(); } void polygon2(){ glBegin(GL_POLYGON); glColor3f(0.0, 0.0, 1.0); glVertex2f(0.37*0.152, 1.33*0.4); glColor3f(1.0, 0.0, 0.0); glVertex2f(0.6*0.152, 1.51*0.4); glColor3f(0.0, 1.0, 0.0); glVertex2f(0.0*0.152, 1.94*0.4); glColor3f(0.0, 0.0, 1.0); glVertex2f(-0.6*0.152, 1.51*0.4); glColor3f(1.0, 0.0, 0.0); glVertex2f(-0.37*0.152, 1.33*0.4); glEnd(); } void display() { triangle(); quad(); polygon1(); polygon2(); glFlush(); } void display1(){ triangle(); glFlush(); } void display2() { quad(); glFlush(); } void display3(){ polygon1(); glFlush(); } void display4(){ polygon2(); glFlush(); } void Keyboard(unsigned char c, int x, int y) { printf("%d\n",c); switch(c) { case 50: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,-.1,0); glutDisplayFunc(display); glutPostRedisplay(); break; case 52: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(-.1,0,0); glutDisplayFunc(display); glutPostRedisplay(); break; case 54: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(.1,0,0); glutDisplayFunc(display); glutPostRedisplay(); break; case 56: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,.1,0); glutDisplayFunc(display); glutPostRedisplay(); break; case 114: glClear(GL_COLOR_BUFFER_BIT); glRotatef(15,0,0,1); glutDisplayFunc(display); glutPostRedisplay(); break; case 101: glClear(GL_COLOR_BUFFER_BIT); glRotatef(-15,0,0,1); glutDisplayFunc(display); glutPostRedisplay(); break; case 115: glClear(GL_COLOR_BUFFER_BIT); glScalef(1.5,1.5,0); glutDisplayFunc(display); glutPostRedisplay(); break; case 100: glClear(GL_COLOR_BUFFER_BIT); glScalef(1/1.5,1/1.5,0); glutDisplayFunc(display); glutPostRedisplay(); break; case 116: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display1); glutPostRedisplay(); glutKeyboardFunc(Keyboard1); break; case 113: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display2); glutPostRedisplay(); glutKeyboardFunc(Keyboard2); break; case 111: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display3); glutPostRedisplay(); glutKeyboardFunc(Keyboard3); break; case 112: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display4); glutPostRedisplay(); glutKeyboardFunc(Keyboard4); break; case 109: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display); glutPostRedisplay(); glutKeyboardFunc(Keyboard); break; case 120: exit(1); } } void Keyboard1(unsigned char c, int x, int y) { printf("%d\n",c); switch(c) { case 50: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,-.1,0); glutDisplayFunc(display1); glutPostRedisplay(); break; case 52: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(-.1,0,0); glutDisplayFunc(display1); glutPostRedisplay(); break; case 54: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(.1,0,0); glutDisplayFunc(display1); glutPostRedisplay(); break; case 56: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,.1,0); glutDisplayFunc(display1); glutPostRedisplay(); break; case 114: glClear(GL_COLOR_BUFFER_BIT); glRotatef(15,0,0,1); glutDisplayFunc(display1); glutPostRedisplay(); break; case 101: glClear(GL_COLOR_BUFFER_BIT); glRotatef(-15,0,0,1); glutDisplayFunc(display1); glutPostRedisplay(); break; case 115: glClear(GL_COLOR_BUFFER_BIT); glScalef(1.5,1.5,0); glutDisplayFunc(display1); glutPostRedisplay(); break; case 100: glClear(GL_COLOR_BUFFER_BIT); glScalef(1/1.5,1/1.5,0); glutDisplayFunc(display1); glutPostRedisplay(); break; case 116: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display1); glutPostRedisplay(); glutKeyboardFunc(Keyboard1); break; case 113: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display2); glutPostRedisplay(); glutKeyboardFunc(Keyboard2); break; case 111: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display3); glutPostRedisplay(); glutKeyboardFunc(Keyboard3); break; case 112: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display4); glutPostRedisplay(); glutKeyboardFunc(Keyboard4); break; case 109: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display); glutPostRedisplay(); glutKeyboardFunc(Keyboard); break; case 120: exit(1); } } void Keyboard2(unsigned char c, int x, int y) { printf("%d\n",c); switch(c) { case 50: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,-.1,0); glutDisplayFunc(display2); glutPostRedisplay(); break; case 52: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(-.1,0,0); glutDisplayFunc(display2); glutPostRedisplay(); break; case 54: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(.1,0,0); glutDisplayFunc(display2); glutPostRedisplay(); break; case 56: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,.1,0); glutDisplayFunc(display2); glutPostRedisplay(); break; case 114: glClear(GL_COLOR_BUFFER_BIT); glRotatef(15,0,0,1); glutDisplayFunc(display2); glutPostRedisplay(); break; case 101: glClear(GL_COLOR_BUFFER_BIT); glRotatef(-15,0,0,1); glutDisplayFunc(display2); glutPostRedisplay(); break; case 115: glClear(GL_COLOR_BUFFER_BIT); glScalef(1.5,1.5,0); glutDisplayFunc(display2); glutPostRedisplay(); break; case 100: glClear(GL_COLOR_BUFFER_BIT); glScalef(1/1.5,1/1.5,0); glutDisplayFunc(display2); glutPostRedisplay(); break; case 116: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display1); glutPostRedisplay(); glutKeyboardFunc(Keyboard1); break; case 113: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display2); glutPostRedisplay(); glutKeyboardFunc(Keyboard2); break; case 111: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display3); glutPostRedisplay(); glutKeyboardFunc(Keyboard3); break; case 112: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display4); glutPostRedisplay(); glutKeyboardFunc(Keyboard4); break; case 109: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display); glutPostRedisplay(); glutKeyboardFunc(Keyboard); break; case 120: exit(1); } } void Keyboard3(unsigned char c, int x, int y) { printf("%d\n",c); switch(c) { case 50: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,-.1,0); glutDisplayFunc(display3); glutPostRedisplay(); break; case 52: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(-.1,0,0); glutDisplayFunc(display3); glutPostRedisplay(); break; case 54: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(.1,0,0); glutDisplayFunc(display3); glutPostRedisplay(); break; case 56: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,.1,0); glutDisplayFunc(display3); glutPostRedisplay(); break; case 114: glClear(GL_COLOR_BUFFER_BIT); glRotatef(15,0,0,1); glutDisplayFunc(display3); glutPostRedisplay(); break; case 101: glClear(GL_COLOR_BUFFER_BIT); glRotatef(-15,0,0,1); glutDisplayFunc(display3); glutPostRedisplay(); break; case 115: glClear(GL_COLOR_BUFFER_BIT); glScalef(1.5,1.5,0); glutDisplayFunc(display3); glutPostRedisplay(); break; case 100: glClear(GL_COLOR_BUFFER_BIT); glScalef(1/1.5,1/1.5,0); glutDisplayFunc(display3); glutPostRedisplay(); break; case 116: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display1); glutPostRedisplay(); glutKeyboardFunc(Keyboard1); break; case 113: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display2); glutPostRedisplay(); glutKeyboardFunc(Keyboard2); break; case 111: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display3); glutPostRedisplay(); glutKeyboardFunc(Keyboard3); break; case 112: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display4); glutPostRedisplay(); glutKeyboardFunc(Keyboard4); break; case 109: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display); glutPostRedisplay(); glutKeyboardFunc(Keyboard); break; case 120: exit(1); } } void Keyboard4(unsigned char c, int x, int y) { printf("%d\n",c); switch(c) { case 50: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,-.1,0); glutDisplayFunc(display4); glutPostRedisplay(); break; case 52: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(-.1,0,0); glutDisplayFunc(display4); glutPostRedisplay(); break; case 54: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(.1,0,0); glutDisplayFunc(display4); glutPostRedisplay(); break; case 56: glClear(GL_COLOR_BUFFER_BIT); glTranslatef(0,.1,0); glutDisplayFunc(display4); glutPostRedisplay(); break; case 114: glClear(GL_COLOR_BUFFER_BIT); glRotatef(15,0,0,1); glutDisplayFunc(display4); glutPostRedisplay(); break; case 101: glClear(GL_COLOR_BUFFER_BIT); glRotatef(-15,0,0,1); glutDisplayFunc(display4); glutPostRedisplay(); break; case 115: glClear(GL_COLOR_BUFFER_BIT); glScalef(1.5,1.5,0); glutDisplayFunc(display4); glutPostRedisplay(); break; case 100: glClear(GL_COLOR_BUFFER_BIT); glScalef(1/1.5,1/1.5,0); glutDisplayFunc(display4); glutPostRedisplay(); break; case 116: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display1); glutPostRedisplay(); glutKeyboardFunc(Keyboard1); break; case 113: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display2); glutPostRedisplay(); glutKeyboardFunc(Keyboard2); break; case 111: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display3); glutPostRedisplay(); glutKeyboardFunc(Keyboard3); break; case 112: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display4); glutPostRedisplay(); glutKeyboardFunc(Keyboard4); break; case 109: glClear(GL_COLOR_BUFFER_BIT); glutDisplayFunc(display); glutPostRedisplay(); glutKeyboardFunc(Keyboard); break; case 120: exit(1); } } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE); glutInitWindowSize(700,700); glutInitWindowPosition(500,0); glutCreateWindow("Lab-4, Code-1: Keyboard Interaction"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glutDisplayFunc(display); glutKeyboardFunc(Keyboard); glutMainLoop(); return 0; }
<reponame>navikt/nav-analytics<filename>src/versioning/signature.js const rules = require('./rules'); const createChecksum = require('./create-checksum'); const os = require('os'); class Signature { constructor() { this.checksums = new Map(); } add(what, rule) { const checksum = createChecksum(what); if (Object.values(rules).includes(rule)) { this.checksums.set(checksum, rule); } else { throw Error('Can\'t add to signature, rule doesn\'t exist'); } } list() { return new Map([...this.checksums].sort()); } compact() { const output = []; this.list().forEach((rule, checksum) => { output.push(`${checksum}${rule}`); }); return output.join(os.EOL); } } module.exports = Signature;
#!/bin/bash testrpc &
TERMUX_PKG_HOMEPAGE=https://mariadb.org TERMUX_PKG_DESCRIPTION="A drop-in replacement for mysql server" TERMUX_PKG_LICENSE="GPL-2.0" TERMUX_PKG_MAINTAINER="@termux" TERMUX_PKG_VERSION=2:10.6.4 TERMUX_PKG_SRCURL=http://ftp.hosteurope.de/mirror/archive.mariadb.org/mariadb-${TERMUX_PKG_VERSION:2}/source/mariadb-${TERMUX_PKG_VERSION:2}.tar.gz TERMUX_PKG_SHA256=75bf9b147a95d38160d01a73b098d50a1960563b46d16a235971fff64d99643c TERMUX_PKG_DEPENDS="libc++, libiconv, liblzma, ncurses, libedit, openssl, pcre2, libcrypt, libandroid-support, libandroid-glob, zlib, liblz4" TERMUX_PKG_BREAKS="mariadb-dev" TERMUX_PKG_REPLACES="mariadb-dev" TERMUX_PKG_SERVICE_SCRIPT=("mysqld" 'exec mysqld --basedir=$PREFIX --datadir=$PREFIX/var/lib/mysql 2>&1') TERMUX_PKG_EXTRA_CONFIGURE_ARGS=" -DBISON_EXECUTABLE=$(which bison) -DGETCONF=$(which getconf) -DBUILD_CONFIG=mysql_release -DCAT_EXECUTABLE=$(which cat) -DGIT_EXECUTABLE=$(which git) -DGSSAPI_FOUND=NO -DGRN_WITH_LZ4=yes -DENABLED_LOCAL_INFILE=ON -DHAVE_UCONTEXT_H=False -DIMPORT_EXECUTABLES=$TERMUX_PKG_HOSTBUILD_DIR/import_executables.cmake -DINSTALL_LAYOUT=DEB -DINSTALL_UNIX_ADDRDIR=$TERMUX_PREFIX/tmp/mysqld.sock -DINSTALL_SBINDIR=$TERMUX_PREFIX/bin -DMYSQL_DATADIR=$TERMUX_PREFIX/var/lib/mysql -DPLUGIN_AUTH_GSSAPI_CLIENT=OFF -DPLUGIN_AUTH_GSSAPI=NO -DPLUGIN_AUTH_PAM=NO -DPLUGIN_CONNECT=NO -DPLUGIN_DAEMON_EXAMPLE=NO -DPLUGIN_EXAMPLE=NO -DPLUGIN_GSSAPI=OFF -DPLUGIN_ROCKSDB=NO -DPLUGIN_TOKUDB=NO -DPLUGIN_SERVER_AUDIT=NO -DSTACK_DIRECTION=-1 -DTMPDIR=$TERMUX_PREFIX/tmp -DWITH_EXTRA_CHARSETS=complex -DWITH_JEMALLOC=OFF -DWITH_MARIABACKUP=OFF -DWITH_PCRE=system -DWITH_LZ4=system -DWITH_READLINE=OFF -DWITH_SSL=system -DWITH_WSREP=False -DWITH_ZLIB=system -DWITH_INNODB_BZIP2=OFF -DWITH_INNODB_LZ4=ON -DWITH_INNODB_LZMA=ON -DWITH_INNODB_LZO=OFF -DWITH_INNODB_SNAPPY=OFF -DWITH_UNIT_TESTS=OFF -DINSTALL_SYSCONFDIR=$TERMUX_PREFIX/etc " TERMUX_PKG_HOSTBUILD=true TERMUX_PKG_CONFLICTS="mysql" TERMUX_PKG_RM_AFTER_INSTALL=" bin/mysqltest* share/man/man1/mysql-test-run.pl.1 share/mysql/mysql-test mysql-test sql-bench " # i686 build fails due to: # /home/builder/.termux-build/mariadb/src/include/my_pthread.h:822:10: error: use of undeclared identifier 'my_atomic_add32' # (void) my_atomic_add32_explicit(value, 1, MY_MEMORY_ORDER_RELAXED); TERMUX_PKG_BLACKLISTED_ARCHES="i686" termux_step_host_build() { termux_setup_cmake sed -i 's/^\s*END[(][)]/ENDIF()/g' $TERMUX_PKG_SRCDIR/libmariadb/cmake/ConnectorName.cmake cmake -G "Unix Makefiles" \ $TERMUX_PKG_SRCDIR \ -DWITH_SSL=bundled \ -DCMAKE_BUILD_TYPE=Release make -j $TERMUX_MAKE_PROCESSES import_executables } termux_step_pre_configure() { # Certain packages are not safe to build on device because their # build.sh script deletes specific files in $TERMUX_PREFIX. if $TERMUX_ON_DEVICE_BUILD; then termux_error_exit "Package '$TERMUX_PKG_NAME' is not safe for on-device builds." fi CPPFLAGS+=" -Dushort=u_short" if [ $TERMUX_ARCH_BITS = 32 ]; then CPPFLAGS+=" -D__off64_t_defined" fi if [ $TERMUX_ARCH = "i686" ]; then # Avoid undefined reference to __atomic_load_8: CFLAGS+=" -latomic" fi sed -i 's/^\s*END[(][)]/ENDIF()/g' $TERMUX_PKG_SRCDIR/libmariadb/cmake/ConnectorName.cmake } termux_step_post_massage() { mkdir -p $TERMUX_PKG_MASSAGEDIR/$TERMUX_PREFIX/etc/my.cnf.d } termux_step_create_debscripts() { echo "if [ ! -e "$TERMUX_PREFIX/var/lib/mysql" ]; then" > postinst echo " echo 'Initializing mysql data directory...'" >> postinst echo " mkdir -p $TERMUX_PREFIX/var/lib/mysql" >> postinst echo " $TERMUX_PREFIX/bin/mysql_install_db --user=\$(whoami) --datadir=$TERMUX_PREFIX/var/lib/mysql --basedir=$TERMUX_PREFIX" >> postinst echo "fi" >> postinst echo "exit 0" >> postinst chmod 0755 postinst }
/* * This file is part of inertia, licensed under the MIT License (MIT). * * Copyright (c) vectrix.space <https://vectrix.space/> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package space.vectrix.inertia.entity; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import space.vectrix.inertia.Universe; import space.vectrix.inertia.util.CustomIterator; /* package */ final class EntityStashImpl implements EntityStash { private final IntSet stash = new IntOpenHashSet(); private final Universe universe; /* package */ EntityStashImpl(final @NonNull Universe universe) { this.universe = universe; } @Override public boolean contains(final @NonNegative int index) { return this.stash.contains(index); } @Override public @Nullable Entity get(final @NonNegative int index) { if(!this.stash.contains(index)) return null; return this.universe.getEntity(index); } @Override public <T extends Entity> @Nullable T get(final @NonNegative int index, final @NonNull Class<T> target) { if(!this.stash.contains(index)) return null; return this.universe.getEntity(index, target); } @Override public boolean add(final @NonNegative int index) { return this.stash.add(index); } @Override public boolean remove(final @NonNegative int index) { return this.stash.remove(index); } @Override public void clear() { this.stash.clear(); } @Override public @NonNull CustomIterator<Entity> iterator() { return CustomIterator.of(this.stash.iterator(), this.universe::getEntity, entity -> this.remove(entity.index())); } }
#!/bin/sh docker run \ --detach \ --hostname ${JENKINS_HOSTNAME:=`hostname -f`} \ --restart always \ --name ${JENKINS_CONTAINER_NAME:=jenkins} \ --publish ${JENKINS_HTTP_PORT:=8080}:8080 \ --publish ${JENKINS_SLAVE_PORT:=50000}:50000 \ --volume ${JENKINS_HOME_DIR:=/srv/jenkins}:/var/jenkins_home:Z \ dralog/jenkins:latest
/* * File: ServantServerRegister.cpp * Author: <NAME> * * Created on 2010_9_6 PM 3:23 */ #include "Log.h" #include "NodeDefines.h" #include "AppConfig.h" #include "ServantServerRegister.h" #include "ServantStubImp.h" #include "ProcessStatus.h" #include "ServantModule.h" using namespace mdl; using namespace evt; using namespace util; using namespace thd; CServantServerRegister::CServantServerRegister() { } CServantServerRegister::~CServantServerRegister() { } void CServantServerRegister::InitStatusCallback() { CServantStubImp::PTR_T pServantStubImp(CServantStubImp::Pointer()); CAutoPointer<GlobalMethodRS> pCPUUsageMethod(new GlobalMethodRS(GetCPUUsageStr)); pServantStubImp->AddInfoMethod("CPU", pCPUUsageMethod); CAutoPointer<GlobalMethodRS> pMemoryUsageMethod(new GlobalMethodRS(GetMemoryUsageStr)); pServantStubImp->AddInfoMethod("MemoryKB", pMemoryUsageMethod); CAutoPointer<GlobalMethodRS> pVirtualMemMethod(new GlobalMethodRS(GetVirtualMemoryUsageStr)); pServantStubImp->AddInfoMethod("VirtualMemoryKB", pVirtualMemMethod); CAutoPointer<GlobalMethodRS> pIOReadMethod(new GlobalMethodRS(GetIOReadKBStr)); pServantStubImp->AddInfoMethod("TotalIOReadKB", pIOReadMethod); CAutoPointer<GlobalMethodRS> pIOWriteMethod(new GlobalMethodRS(GetIOWriteKBStr)); pServantStubImp->AddInfoMethod("TotalIOWriteKB", pIOWriteMethod); } void CServantServerRegister::InitTemplate() { } void CServantServerRegister::RegisterCommand() { } void CServantServerRegister::RegistModule() { CFacade::PTR_T pFacade(CFacade::Pointer()); //register module AppConfig::PTR_T pConfig(AppConfig::Pointer()); uint16_t u16ServerId = (uint16_t)pConfig->GetInt(APPCONFIG_SERVERID); CAutoPointer<CServantModule> pServantModule( new CServantModule(SERVANT_MODEL_NAME, u16ServerId)); pFacade->RegisterModule(pServantModule); } void CServantServerRegister::UnregistModule() { CFacade::PTR_T pFacade(CFacade::Pointer()); //unregister module pFacade->RemoveModule(SERVANT_MODEL_NAME); }
<reponame>insad/jworkflow package net.jworkflow.kernel.services.test; import net.jworkflow.kernel.services.MemoryPersistenceService; import net.jworkflow.kernel.services.abstractions.PersistenceServiceTest; import org.junit.Test; import net.jworkflow.kernel.interfaces.PersistenceService; public class MemoryPersistenceServiceTest extends PersistenceServiceTest { @Override public PersistenceService createService() { return new MemoryPersistenceService(); } }
""" Generate a program using Python which collects environmental data from a list of cities and organizes it in a table. """ import requests # API key for openweathermap KEY = '123456789' def get_weather_data(cities): weather_data = [] for city in cities: url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city +'&APPID='+KEY response = requests.get(url) data = response.json() city_data = { 'name': city, 'temperature': data['main']['temp'], 'humidity': data['main']['humidity'], 'wind speed': data['wind']['speed'] } weather_data.append(city_data) return weather_data if __name__ == '__main__': cities = ['New York', 'Los Angeles', 'San Francisco', 'Chicago'] data = get_weather_data(cities) for city_data in data: print('Name:', city_data['name']) print('Temperature:', city_data['temperature']) print('Humidity:', city_data['humidity']) print('Wind speed:', city_data['wind speed'], '\n')
// Copyright 2006, 2007, 2010, 2014 The Apache Software 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.apache.tapestry5.integration.app1.pages.nested; import org.apache.tapestry5.Asset; import org.apache.tapestry5.ComponentResources; import org.apache.tapestry5.annotations.Environmental; import org.apache.tapestry5.annotations.Import; import org.apache.tapestry5.annotations.Path; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.AssetSource; import org.apache.tapestry5.services.javascript.JavaScriptSupport; import org.apache.tapestry5.services.javascript.StylesheetLink; import org.apache.tapestry5.services.javascript.StylesheetOptions; /** * Primarily used to demonstrate that assets can be localized and exposed to the client, this has grown to also * demonstrate the use of the {@link Import} annotation. */ @Import(library = {"//:${d3.url}", "AssetDemo.js"}) public class AssetDemo { @Property @Inject @Path("context:images/tapestry_banner.gif") private Asset icon; @Property @Inject @Path("tapestry-button.png") private Asset button; @Property @Inject @Path("AssetDemo.properties") private Asset properties; @Inject @Path("context:css/ie-only.css") private Asset ieOnly; @Property @Inject @Path("http://${d3.url}") private Asset httpAsset; @Property @Inject @Path("https://${d3.url}") private Asset httpsAsset; @Property @Inject @Path("//${d3.url}") private Asset protocolRelativeAsset; @Property @Inject @Path("ftp://${d3.url}") private Asset ftpAsset; @Environmental private JavaScriptSupport javascriptSupport; @Property @Inject @Path("tapestry.png") private Asset logo; @Inject private ComponentResources resources; @Inject private AssetSource assetSource; @Import(stylesheet = "context:css/via-import.css") void afterRender() { javascriptSupport.importStylesheet(new StylesheetLink(ieOnly, new StylesheetOptions(null, "IE"))); javascriptSupport.importJavaScriptLibrary(getAssetWithWrongChecksumUrl()); } public String getAssetWithWrongChecksumUrl() { final Asset asset = getAssetWithCorrectChecksum(); return asset.toClientURL().replaceAll("[0-9a-f]{8}", "00000000"); } public Asset getAssetWithCorrectChecksum() { return assetSource.getComponentAsset(resources, "AssetWithWrongChecksum.js", ""); } }
#!/bin/bash . $(dirname "${BASH_SOURCE[0]}")/common.sh DOCKER_RUN_ARGS="run --rm -i -e RUMP_VERBOSE=1 -e DEBUG=1 --runtime=runu-dev --net=none $DOCKER_RUN_ARGS_ARCH" # prepare RUNU_AUX_DIR create_runu_aux_dir # update daemon.json fold_start test.dockerd.0 "boot dockerd" if [ $TRAVIS_OS_NAME = "linux" ] ; then (sudo cat /etc/docker/daemon.json 2>/dev/null || echo '{}') | \ jq '.runtimes."runu-dev" |= {"path":"'${TRAVIS_HOME}'/gopath/bin/'${RUNU_PATH}'runu","runtimeArgs":[]}' | \ jq '. |= .+{"experimental":true}' | \ jq '. |= .+{"ipv6":true}' | \ jq '. |= .+{"fixed-cidr-v6": "2001:db8::/64"}' | \ tee /tmp/tmp.json sudo mv /tmp/tmp.json /etc/docker/daemon.json sudo service docker restart elif [ $TRAVIS_OS_NAME = "osx" ] ; then sudo mkdir -p /etc/docker/ git clone https://gist.github.com/aba357f73da4e14bc3f5cbeb00aeaea4.git \ /tmp/containerd-config-dockerd || true sudo cp /tmp/containerd-config-dockerd/daemon.json /etc/docker/ # prepare dockerd mkdir -p /tmp/containerd-shim sudo killall containerd || true sudo dockerd --config-file /etc/docker/daemon.json > $HOME/dockerd.log 2>&1 & sleep 3 sudo chmod 666 /tmp/var/run/docker.sock sudo chmod 777 /tmp/var/run/ sudo ln -sf /tmp/var/run/docker.sock /var/run/docker.sock # build docker (client) if [ -z "$(which docker)" ] ; then curl -O https://download.docker.com/mac/static/stable/x86_64/docker-18.09.0.tgz tar xfz docker-18.09.0.tgz cp -f docker/docker ~/.local/bin chmod +x ~/.local/bin/docker fi DOCKER_RUN_EXT_ARGS="--platform=linux/amd64 -e LKL_USE_9PFS=1" # XXX: this is required when we use 9pfs rootfs (e.g., on mac) # see #3 issue more detail https://github.com/ukontainer/runu/issues/3 ALPINE_PREFIX="/bin/busybox" fi fold_end test.dockerd.0 "" # test hello-world fold_start test.docker.0 "docker hello" docker $DOCKER_RUN_ARGS thehajime/runu-base:$DOCKER_IMG_VERSION hello fold_end test.docker.0 # test ping fold_start test.docker.1 "docker ping" docker $DOCKER_RUN_ARGS thehajime/runu-base:$DOCKER_IMG_VERSION \ ping -c5 127.0.0.1 fold_end test.docker.1 # test python # XXX: PYTHONHASHSEED=1 is workaround for slow read of getrandom() on 4.19 # (4.16 doesn't have such) fold_start test.docker.2 "docker python" docker $DOCKER_RUN_ARGS -e HOME=/ \ -e PYTHONHOME=/python -e LKL_ROOTFS=imgs/python.img \ -e PYTHONHASHSEED=1 \ thehajime/runu-base:$DOCKER_IMG_VERSION \ python -c "print(\"hello world from python(docker-runu)\")" fold_end test.docker.2 # test nginx fold_start test.docker.3 "docker nginx" CID=`docker $DOCKER_RUN_ARGS -d \ -e LKL_ROOTFS=imgs/data.iso \ thehajime/runu-base:$DOCKER_IMG_VERSION \ nginx` sleep 2 docker ps -a docker logs $CID docker kill $CID fold_end test.docker.3 # alipine image test fold_start test.docker.4 "docker alpine" docker $DOCKER_RUN_ARGS $DOCKER_RUN_EXT_ARGS \ -e RUNU_AUX_DIR=$RUNU_AUX_DIR alpine $ALPINE_PREFIX uname -a docker $DOCKER_RUN_ARGS $DOCKER_RUN_EXT_ARGS \ -e RUNU_AUX_DIR=$RUNU_AUX_DIR alpine $ALPINE_PREFIX \ ping -c 5 127.0.0.1 docker $DOCKER_RUN_ARGS $DOCKER_RUN_EXT_ARGS \ -e RUNU_AUX_DIR=$RUNU_AUX_DIR alpine $ALPINE_PREFIX dmesg | head docker $DOCKER_RUN_ARGS $DOCKER_RUN_EXT_ARGS \ -e RUNU_AUX_DIR=$RUNU_AUX_DIR alpine $ALPINE_PREFIX ls -l / if [ $TRAVIS_OS_NAME = "linux" ] ; then # XXX: df -ha gives core dumps. remove above if statement this once fixed docker $DOCKER_RUN_ARGS $DOCKER_RUN_EXT_ARGS \ -e RUNU_AUX_DIR=$RUNU_AUX_DIR alpine $ALPINE_PREFIX df -ha fi fold_end test.docker.4 # test named fold_start test.docker.5 "docker named" CID=named-docker docker $DOCKER_RUN_ARGS -d --name $CID \ -e LKL_ROOTFS=imgs/named.img \ thehajime/runu-base:$DOCKER_IMG_VERSION \ named -c /etc/bind/named.conf -g sleep 10 docker ps -a docker logs $CID docker kill $CID fold_end test.docker.5
from typing import List def extract_unique_parameters(parameter_list: List[str]) -> List[str]: unique_parameters = [] seen = set() for param in parameter_list: if param not in seen: unique_parameters.append(param) seen.add(param) return unique_parameters
#!/bin/bash -e # VARIABLES PASSED FROM JENKINS: # # # SOURCE_FILE=$NAME-$VERSION.tar.gz module load ci echo $SOFT_DIR echo $WORKSPACE echo $SRC_DIR echo $NAME echo $VERSION #module load gcc/4.8.2 if [[ ! -s $SRC_DIR/$SOURCE_FILE ]] then echo "getting the file from the web" mkdir -p $SRC_DIR wget http://www.hdfgroup.org/ftp/HDF5/releases/$NAME-$VERSION/src/$SOURCE_FILE -O $SRC_DIR/$SOURCE_FILE tar -xvzf $SRC_DIR/$SOURCE_FILE -C $WORKSPACE else echo "the file is local, untarring it" ls -lht $SRC_DIR/$SOURCE_FILE tar -xvzf $SRC_DIR/$SOURCE_FILE -C $WORKSPACE fi ls $WORKSPACE cd $WORKSPACE/$NAME-$VERSION module add zlib module add openmpi # pull in the built code for zlib rm -rf $ZLIB_DIR tar -xvzf /repo/$SITE/$OS/$ARCH/zlib/$ZLIB_VERSION/build.tar.gz -C / # ... and openmpi rm -rf $OPENMPI_DIR tar xvfz /repo/$SITE/$OS/$ARCH/openmpi/$OPENMPI_VERSION/build.tar.gz -C / ./configure --prefix=$SOFT_DIR make -j 8 make check make install DESTDIR=$WORKSPACE/build # At this point, we should have built OpenMPI mkdir -p $REPO_DIR rm -rf $REPO_DIR/* tar -cvzf $REPO_DIR/build.tar.gz -C $WORKSPACE/build apprepo mkdir -p modules ( cat <<MODULE_FILE #%Module1.0 ## $NAME modulefile ## proc ModulesHelp { } { puts stderr " This module does nothing but alert the user" puts stderr " that the [module-info name] module is not available" } module-whatis "$NAME $VERSION." module load zlib openmpi prereq zlib prereq openmpi setenv HDF5_VERSION $VERSION # # # setenv HDF5_DIR /apprepo/$::env(SITE)/$::env(OS)/$::env(ARCH)/$NAME/$VERSION prepend-path LD_LIBRARY_PATH $::env(HDF5_DIR)/lib MODULE_FILE ) > modules/$VERSION mkdir -p $LIBRARIES_MODULES/$NAME cp -v modules/$VERSION $LIBRARIES_MODULES/$NAME module avail
# frozen_string_literal: true require_relative "../support/command_testing" using CommandTesting describe "bootsnap compatibility" do it "works" do skip if defined? JRUBY_VERSION cache_path = File.join(__dir__, "fixtures", "bootsnap", "tmp") if File.directory?(cache_path) FileUtils.rm_rf(cache_path) end run_ruby( File.join(__dir__, "fixtures", "bootsnap", "test.rb").to_s ) do |_status, output, _err| output.should include("PERFORM: ruby_next#test\n") output.should include("UNKNOWN: perform\n") end end end
<filename>src/components/Card/index.tsx import styled from 'styled-components' export const Card = styled.div` display: flex; flex-flow: column nowrap; justify-content: flex-start; overflow: hidden; background: ${({ theme }) => theme.bg0}; box-shadow: ${({ theme }) => theme.boxShadow1}; border-radius: 15px; padding: 1.25rem; `
<gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ic_chrome_reader_mode = void 0; var ic_chrome_reader_mode = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M-74 29h48v48h-48V29zM0 0h24v24H0V0zm0 0h24v24H0V0z", "fill": "none" }, "children": [] }, { "name": "path", "attribs": { "d": "M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z" }, "children": [] }] }; exports.ic_chrome_reader_mode = ic_chrome_reader_mode;
# This is the custom theme template for gitprompt.sh # These are the defaults from the "Default" theme # You just need to override what you want to have changed override_git_prompt_colors() { GIT_PROMPT_THEME_NAME="Custom" Time12a="\$(date +%H:%M:%S)" # PathShort="\w"; REMOTE_USER="\u" # Username REMOTE_HOST="\h" # Host ## These are the color definitions used by gitprompt.sh GIT_PROMPT_PREFIX="( " # start of the git info string GIT_PROMPT_SUFFIX=" )" # the end of the git info string GIT_PROMPT_SEPARATOR=" | " # separates each item GIT_PROMPT_BRANCH="${BoldYellow}" # the git branch that is active in the current directory GIT_PROMPT_STAGED="${Cyan}S" # the number of staged files/directories GIT_PROMPT_CONFLICTS="${Red}C" # the number of files in conflict GIT_PROMPT_CHANGED="${Green}M" # the number of changed files GIT_PROMPT_REMOTE=" " # the remote branch name (if any) and the symbols for ahead and behind GIT_PROMPT_UNTRACKED="${White}U" # the number of untracked files/dirs GIT_PROMPT_STASHED="${BoldMagenta}⚑ " # the number of stashed files/dir GIT_PROMPT_CLEAN="${BoldGreen}✔" # a colored flag indicating a "clean" repo ## For the command indicator, the placeholder _LAST_COMMAND_STATE_ ## will be replaced with the exit code of the last command ## e.g. ## GIT_PROMPT_COMMAND_OK="${Green}✔-_LAST_COMMAND_STATE_ " # indicator if the last command returned with an exit code of 0 ## GIT_PROMPT_COMMAND_FAIL="${Red}✘-_LAST_COMMAND_STATE_ " # indicator if the last command returned with an exit code of other than 0 GIT_PROMPT_COMMAND_OK="${Green}[${Time12a}]${ResetColor}" # indicator if the last command returned with an exit code of 0 GIT_PROMPT_COMMAND_FAIL="${Red}[${Time12a}]${ResetColor}" # indicator if the last command returned with an exit code of other than 0 ## template for displaying the current virtual environment ## use the placeholder _VIRTUALENV_ will be replaced with ## the name of the current virtual environment (currently CONDA and VIRTUAL_ENV) # GIT_PROMPT_VIRTUALENV="(${Blue}_VIRTUALENV_${ResetColor}) " ## _LAST_COMMAND_INDICATOR_ will be replaced by the appropriate GIT_PROMPT_COMMAND_OK OR GIT_PROMPT_COMMAND_FAIL if [ -z "$SSH_TTY" ]; then GIT_PROMPT_START_USER="_LAST_COMMAND_INDICATOR_ ${BoldBlue}${PathShort}${ResetColor}" else GIT_PROMPT_START_USER="_LAST_COMMAND_INDICATOR_ ${Yellow}\u${ResetColor}@${Red}\h${ResetColor} ${BoldBlue}${PathShort}${ResetColor}" fi # GIT_PROMPT_START_ROOT="_LAST_COMMAND_INDICATOR_ ${GIT_PROMPT_START_USER}" GIT_PROMPT_END_USER=" \n$ " # GIT_PROMPT_END_ROOT=" \n${White}${Time12a}${ResetColor} # " ## Please do not add colors to these symbols GIT_PROMPT_SYMBOLS_AHEAD="${BoldMagenta}↑${ResetColor}·" # The symbol for "n versions ahead of origin" GIT_PROMPT_SYMBOLS_BEHIND="${BoldCyan}↓${ResetColor}·" # The symbol for "n versions behind of origin" GIT_PROMPT_SYMBOLS_PREHASH=":" # Written before hash of commit, if no name could be found GIT_PROMPT_SYMBOLS_NO_REMOTE_TRACKING="L" # This symbol is written after the branch, if the branch is not tracked } reload_git_prompt_colors "Custom"
import React, { Component } from 'react' import TransitionGroup from 'react-transition-group/TransitionGroup' import Transition from 'react-transition-group/Transition' import sizeMe from 'react-sizeme' import uuid from 'uuid' import AngelElement from '../components/AngelElement.js' import AngelExpanded from '../components/AngelExpanded.js' const HEIGHT_GAP = 10 const ANGEL_TEMPLATE = { color: 'white', photo: '#', name: '...', dates: '', bio: [] } const assignId = a => a.hasOwnProperty('_id') ? a : Object.assign(a, { _id: uuid() }) const parseNums = ({ x, y, w, h, ...data }) => ({ x: parseInt(x), y: parseInt(y), w: parseInt(w), h: parseInt(h), ...data }) export default sizeMe()(class AngelDisplay extends Component { state = { selectedId: null, triggered: false, angels: [] } constructor(props) { super(props) const { angels } = this.props if (typeof angels === 'function') angels() .then(data => data.map(assignId).map(parseNums)) .then(data => this.setState({ angels: data })) .catch(err => console.error('Error getting angels -', err)) else this.state = Object.assign(this.state, { angels: angels.map(assignId).map(parseNums) }) this.selectId = this.selectId.bind(this) this.trigger = this.trigger.bind(this) } selectId(_id) { this.setState({ selectedId: _id, triggered: false }) } trigger() { this.setState({ triggered: true }) } render() { const { angels, selectedId } = this.state const { width, height } = this.props const columns = +(this.props.columns || Math.max(...angels.map(a => +a.w + +a.x - 1)) || 4) const rows = +(this.props.rows || Math.max(...angels.map(a => +a.h + +a.y - 1)) || 3) const WIDTH_GAP = (this.props.size.width - columns * width) / (columns - 1) if (this.state.triggered) { const angel = Object.assign(ANGEL_TEMPLATE, angels.find(a => a._id === selectedId)) /* render fully expanded angel */ return <AngelExpanded angel={angel} height={`${rows * (height + HEIGHT_GAP) - HEIGHT_GAP}px`} exit={() => this.selectId(null)} /> } /* render grid */ return ( <div style={{ display: 'grid', gridTemplateColumns: `repeat(${columns}, ${width || 100}px)`, gridTemplateRows: `repeat(${rows}, ${height || 100}px)`, columnGap: `calc((100% - ${columns * width}px) / ${columns - 1})`, height: `${rows * (height + HEIGHT_GAP) - HEIGHT_GAP}px`, rowGap: `${HEIGHT_GAP}px` }}> <TransitionGroup component={null}> { angels .filter(a => a._id !== selectedId) .map(a => ( <Transition key={`angel-element-${a._id}`} timeout={{exit: 500}} unmountOnExit> {state => <AngelElement transitionState={state} onSelected={() => this.selectId(a._id)} expandMargin={{ top: `${(height + HEIGHT_GAP) * (1 - a.y)}px`, left: `${(width + WIDTH_GAP) * (1 - a.x)}px`, bottom: `${(height + HEIGHT_GAP) * (a.y + a.h - 1 - rows)}px`, right: `${(width + WIDTH_GAP) * (a.x + a.w - 1 - columns)}px`, }} trigger={() => this.trigger()} {...a} />} </Transition> )) } </TransitionGroup> </div> ) } })
<gh_stars>0 # Copyright (c) [2022] Huawei Technologies Co.,Ltd.ALL rights reserved. # This program is licensed under Mulan PSL v2. # You can use it according to the terms and conditions of the Mulan PSL v2. # http://license.coscl.org.cn/MulanPSL2 # THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. #################################### # @Author : # @email : # @Date : # @License : Mulan PSL v2 ##################################### from flask import jsonify from flask_restful import Resource from flask_pydantic import validate from server.utils.auth_util import auth from server.utils.response_util import RET from server.utils.response_util import response_collect from server.model.framework import Framework, GitRepo from server.model.template import Template from server.utils.db import Insert, Delete, Edit, Select from server.schema.framework import FrameworkBase, FrameworkQuery, GitRepoBase, GitRepoQuery from server.utils.resource_utils import ResourceManager from server.utils.permission_utils import GetAllByPermission from server import casbin_enforcer class FrameworkEvent(Resource): @auth.login_required() @response_collect @validate() def post(self, body: FrameworkBase): return ResourceManager("framework").add("api_infos.yaml", body.__dict__) @auth.login_required() @response_collect @validate() def get(self, query: FrameworkQuery): filter_params = GetAllByPermission(Framework).get_filter() if query.name: filter_params.append( Framework.name.like(f'%{query.name}%') ) if query.url: filter_params.append( Framework.url.like(f'%{query.url}%') ) if query.adaptive: filter_params.append( Framework.adaptive == query.adaptive ) frameworks = Framework.query.filter(*filter_params).all() if not frameworks: return jsonify(error_code=RET.OK, error_msg="OK", data=[]) return jsonify( error_code=RET.OK, error_msg="OK", data=[ _framework.to_json() for _framework in frameworks ] ) class FrameworkItemEvent(Resource): @auth.login_required @response_collect @validate() @casbin_enforcer.enforcer def delete(self, framework_id): return ResourceManager("framework").del_cascade_single(framework_id, GitRepo, [GitRepo.framework_id==framework_id], False) @auth.login_required @response_collect @validate() @casbin_enforcer.enforcer def put(self, framework_id, body: FrameworkQuery): _body = { **body.__dict__, "id": framework_id, } return Edit(Framework, _body).single(Framework, "/framework") @auth.login_required @response_collect @validate() @casbin_enforcer.enforcer def get(self, framework_id): framework = Framework.query.filter_by(id=framework_id).first() if not framework: return jsonify( error_code=RET.NO_DATA_ERR, error_msg="the framework does not exist" ) return jsonify( error_code=RET.OK, error_msg="OK", data=framework.to_json() ) class GitRepoEvent(Resource): @auth.login_required() @response_collect @validate() def post(self, body: GitRepoBase): return ResourceManager("git_repo").add_v2("framework/api_infos.yaml", body.__dict__) @auth.login_required() @response_collect @validate() def get(self, query: GitRepoQuery): filter_params = GetAllByPermission(GitRepo).get_filter() if query.name: filter_params.append( GitRepo.name.like(f'%{query.name}%') ) if query.git_url: filter_params.append( GitRepo.git_url.like(f'%{query.git_url}%') ) if query.sync_rule: filter_params.append( GitRepo.sync_rule == query.sync_rule ) if query.framework_id: filter_params.append( GitRepo.framework_id == query.framework_id ) git_repos = GitRepo.query.filter(*filter_params).all() if not git_repos: return jsonify(error_code=RET.OK, error_msg="OK", data=[]) return jsonify( error_code=RET.OK, error_msg="OK", data=[ _git_repo.to_json() for _git_repo in git_repos ] ) class GitRepoItemEvent(Resource): @auth.login_required @response_collect @validate() @casbin_enforcer.enforcer def delete(self, git_repo_id): return ResourceManager("git_repo").del_cascade_single(git_repo_id, Template, [Template.git_repo_id==git_repo_id], False) @auth.login_required @response_collect @validate() @casbin_enforcer.enforcer def put(self, git_repo_id, body: GitRepoQuery): _body = { **body.__dict__, "id": git_repo_id, } return Edit(GitRepo, _body).single(GitRepo, "/git_repo") @auth.login_required @response_collect @casbin_enforcer.enforcer def get(self, git_repo_id): git_repo = GitRepo.query.filter_by(id=git_repo_id).first() if not git_repo: return jsonify( error_code=RET.NO_DATA_ERR, error_msg="the git repo does not exist" ) return jsonify( error_code=RET.OK, error_msg="OK", data=git_repo.to_json() )
<p>The quick brown fox jumped over the lazy dog.</p>
<reponame>dailynodejs/ice-scripts<filename>packages/ice-plugin-dll/index.js const webpack = require('webpack'); const path = require('path'); const buildDll = require('./lib/buildDll'); module.exports = async ({ chainWebpack, context, log }) => { const { rootDir, command, pkg } = context; // only active in dev mode if (command === 'dev') { const htmlTemplate = path.join(rootDir, 'public', 'index.html'); await buildDll({ webpackConfig: context.getWebpackConfig(), rootDir, pkg, htmlTemplate, log, }); const join = path.join.bind(path, rootDir); log.info('Dll build complete'); chainWebpack((config) => { config .devServer .contentBase([ rootDir, join('node_modules', 'plugin-dll', 'public'), ]) .end() .plugin('DllReferencePlugin') .use(webpack.DllReferencePlugin, [{ context: join('node_modules', 'plugin-dll'), manifest: join('node_modules', 'plugin-dll', 'vendor-manifest.json'), }]) .end() .plugin('CopyWebpackPlugin') .tap(([args]) => [[{ ...(args[0] || {}), from: join('node_modules', 'plugin-dll', 'public'), }]]); // Handle multi entry config const entry = config.toConfig().entry; const entryNames = Object.keys(entry); const isMultiEntry = entryNames.length > 1; if (isMultiEntry) { // remove default HtmlWebpackPlugin config.plugins.delete('HtmlWebpackPlugin'); // generate multiple html file // webpack-chain entry must be [name]: [...values] entryNames.forEach((entryName) => { if (isMultiEntry) { const pluginKey = `HtmlWebpackPlugin_${entryName}`; config .plugin(pluginKey) .tap(([options]) => [{ ...options, template: join('node_modules', 'plugin-dll', 'public', 'index.html'), }]); } }); } else { // Use template index.html config .plugin('HtmlWebpackPlugin') .tap(([options]) => [{ ...options, template: join('node_modules', 'plugin-dll', 'public', 'index.html'), }]); } }); } };
#!/bin/bash ./node_modules/protractor/bin/protractor tests/protractor_config.js
#!/bin/bash source tests/helpers.bash function setUp(){ _make deploy_elasticsearch 1>/dev/null _getProtocol 1>/dev/null _elasticsearchHealth 1>/dev/null } function tearDown(){ _debug _make undeploy_elasticsearch 1>/dev/null } function test_only_static_fields(){ description="[${BASHT_TEST_FILENAME##*/}] acceptance-tests (v${CLIENT_VERSION}): $BASHT_TEST_NUMBER - only static fields are logged" echo "$description" name="${BASHT_TEST_FILENAME##*/}.${BASHT_TEST_NUMBER}" message="$((RANDOM)) $description" basht_run docker run --rm -ti \ --log-driver rchicoli/docker-log-elasticsearch:development \ --log-opt elasticsearch-url="${ELASTICSEARCH_URL}" \ --log-opt elasticsearch-version="${CLIENT_VERSION}" \ --name "$name" \ --log-opt elasticsearch-fields='none' \ alpine echo -n "$message" sleep "${SLEEP_TIME}" basht_run curl -s -G --connect-timeout 5 \ "${ELASTICSEARCH_URL}/${ELASTICSEARCH_INDEX}/${ELASTICSEARCH_TYPE}/_search?pretty=true&size=1" \ --data-urlencode "q=message:\"$message\"" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '1 p'" == "message" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '2 p'" == "partial" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '3 p'" == "source" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '4 p'" == "timestamp" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | wc -l" == 4 } function test_all_fields_except_container_labels(){ description="[${BASHT_TEST_FILENAME##*/}] acceptance-tests (v${CLIENT_VERSION}): $BASHT_TEST_NUMBER - all fields are logged, except of containerLabels" echo "$description" name="${BASHT_TEST_FILENAME##*/}.${BASHT_TEST_NUMBER}" message="$((RANDOM)) $description" basht_run docker run --rm -ti \ --log-driver rchicoli/docker-log-elasticsearch:development \ --log-opt elasticsearch-url="${ELASTICSEARCH_URL}" \ --log-opt elasticsearch-version="${CLIENT_VERSION}" \ --name "$name" \ --log-opt elasticsearch-fields='config,containerID,containerName,containerArgs,containerImageID,containerImageName,containerCreated,containerEnv,daemonName' \ alpine echo -n "$message" sleep "${SLEEP_TIME}" basht_run curl -s -G --connect-timeout 5 \ "${ELASTICSEARCH_URL}/${ELASTICSEARCH_INDEX}/${ELASTICSEARCH_TYPE}/_search?pretty=true&size=1" \ --data-urlencode "q=message:\"$message\"" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '1 p'" == "config" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '2 p'" == "containerArgs" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '3 p'" == "containerCreated" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '4 p'" == "containerEnv" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '5 p'" == "containerID" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '6 p'" == "containerImageID" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '7 p'" == "containerImageName" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '8 p'" == "containerName" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '9 p'" == "daemonName" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '10 p'" == "message" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '11 p'" == "partial" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '12 p'" == "source" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '13 p'" == "timestamp" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | wc -l" == 13 } function test_all_available_fields(){ description="[${BASHT_TEST_FILENAME##*/}] acceptance-tests (v${CLIENT_VERSION}): $BASHT_TEST_NUMBER - all available fields are logged" echo "$description" # TODO: label is not support on elasticsearch version 2, because of the dots "com.docker.compose.container-number" # basht_assert ${CLIENT_VERSION} -eq 2 && skip "MapperParsingException[Field name [com.docker.compose.config-hash] cannot contain '.']" name="${BASHT_TEST_FILENAME##*/}.${BASHT_TEST_NUMBER}" message="$((RANDOM)) $description" basht_run docker run --rm -ti \ --log-driver rchicoli/docker-log-elasticsearch:development \ --log-opt elasticsearch-url="${ELASTICSEARCH_URL}" \ --log-opt elasticsearch-version="${CLIENT_VERSION}" \ --name "$name" \ --log-opt elasticsearch-fields='config,containerID,containerName,containerArgs,containerImageID,containerImageName,containerCreated,containerEnv,containerLabels,daemonName' \ --label environment=testing \ alpine echo -n "$message" sleep "${SLEEP_TIME}" basht_run curl -s -G --connect-timeout 5 \ "${ELASTICSEARCH_URL}/${ELASTICSEARCH_INDEX}/${ELASTICSEARCH_TYPE}/_search?pretty=true&size=1" \ --data-urlencode "q=message:\"$message\"" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '1 p'" == "config" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '2 p'" == "containerArgs" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '3 p'" == "containerCreated" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '4 p'" == "containerEnv" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '5 p'" == "containerID" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '6 p'" == "containerImageID" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '7 p'" == "containerImageName" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '8 p'" == "containerLabels" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '9 p'" == "containerName" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '10 p'" == "daemonName" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '11 p'" == "message" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '12 p'" == "partial" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '13 p'" == "source" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | sed -n '14 p'" == "timestamp" basht_assert "echo '${output}' | jq '.hits.hits[0]._source' | jq -r 'keys[]' | wc -l" == 14 }
#!/bin/bash mkdir build cd build python_path=$(which python) # Configure step cmake -GNinja .. -DPYTHON_EXECUTABLE:FILEPATH=$python_path \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_LIBDIR=lib # Build step ninja install
<reponame>janis-jenny/The-Jungle-Game import Phaser from 'phaser'; import BootScene from './scenes/BootScene'; import PreloaderScene from './scenes/PreloaderScene'; import MainScene from './scenes/MainScene'; import GameOver from './scenes/GameOver'; import ScoreBoard from './scenes/ScoreBoard'; import './css/stylesheet.css'; import ApiScore from './scenes/ApiScore'; const config = { type: Phaser.AUTO, width: 1260, height: 585, physics: { default: 'arcade', arcade: { gravity: { y: 500 }, enableBody: true, }, }, scene: [BootScene, PreloaderScene, MainScene, GameOver, ScoreBoard], }; // eslint-disable-next-line no-unused-vars const api = new ApiScore(); const game = new Phaser.Game(config); game.globals = { score: 0, api }; export default game;
#!/usr/bin/env bash set -e usage() { echo "$0 <repo> <tag> [<release name>]" >&2; } if [ "$1" = "-h" -o "$1" = "--help" ]; then usage exit 1; fi if [ -z "$1" ] then REPO=$(git ls-remote --get-url origin | \ sed -u 's/git@//g; s/https:\/\///g; s/github.com\///g; s/\.git//g') else REPO=$1 fi if [ -z "$2" ] then TAG=$(git describe --tags $(git rev-list --tags --max-count=1)) else TAG=$2 fi BODY=$(awk "/$TAG/ {print; exit}" RS="\n\n" ORS="\n\n" CHANGELOG.md | tail -n+2) PAYLOAD=$( jq --null-input \ --arg t "$TAG" \ --arg n "$TAG" \ --arg b "$BODY" \ '{ tag_name: $t, name: $n, body: $b}' ) TAG_ID=$(curl -s "https://api.github.com/repos/$REPO/releases/tags/$TAG" | jq -r '.id') curl --fail \ --netrc \ --silent \ --location \ --request PATCH \ --data "$PAYLOAD" \ "https://api.github.com/repos/${REPO}/releases/${TAG_ID}"
<reponame>agrista/playframework<filename>documentation/manual/javaGuide/main/global/code/javaguide/global/onerror/Global.java /* * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com> */ package javaguide.global.onerror; import javaguide.global.views; //#global import play.*; import play.mvc.*; import play.mvc.Http.*; import play.libs.F.*; import static play.mvc.Results.*; public class Global extends GlobalSettings { public Promise<Result> onError(RequestHeader request, Throwable t) { return Promise.<Result>pure(internalServerError( views.html.errorPage.render(t) )); } } //#global
<gh_stars>10-100 /** * */ package jframe.pay.http.handler; import java.util.Map; import io.netty.handler.codec.http.HttpHeaders; import jframe.pay.domain.http.RspCode; /** * @author dzh * @date Aug 15, 2014 7:42:11 PM * @since 1.0 */ public abstract class SafeHandler extends AbstractHandler { /** * @param plugin */ protected SafeHandler() { super(); } protected Map<String, String> parseHttpReq(String content) throws Exception { return super.parseHttpReq(content); } @Override protected boolean isValidData(String data) { return true; } @Override public boolean isValidHeaders(HttpHeaders headers) { if (!isValidToken(headers)) { RspCode.setRspCode(rspMap, RspCode.FAIL_HTTP_TOKAN); return false; } return true; } @Override protected Map<String, Object> filterRspMap(Map<String, Object> rsp) { return rsp; } @Override public void service(Map<String, String> req, Map<String, Object> rsp) throws PayException { calcSignContent(req); } /** * TODO throw exception * * @param req */ private void calcSignContent(Map<String, String> req) { // HttpHeaders headers = this.getHttpHeaders(); // String signK = headers.get(PayFields.F_Pay_SignK); // String signV = headers.get(PayFields.F_Pay_SignV); // if (req == null || signK == null || signV == null) { // isValidContent = false; // return; // } // isValidContent = SecurityUtil.payDigest(signK, JsonUtil.encode(req)) // .equals(signV) ? true : false; } /** * * @param req * @return */ public boolean isValidContent() { return true; } public boolean isValidToken(HttpHeaders headers) { if (Boolean.parseBoolean(Plugin.getConfig("token.disable", "false"))) { return true; } return false; } }