text
stringlengths
1
1.05M
<filename>captcha.go package vaptcha import ( "bytes" "errors" "io" "net/http" "net/url" "strings" ) var ( ErrIllegalServer = errors.New("illegal server") ErrWrongUserID = errors.New("userid error") ErrEmptyID = errors.New("id empty") ErrWrongID = errors.New("id error") ErrWrongScene = errors.New("scene error") ErrWrongToken = errors.New("token error") ErrExpiredToken = errors.New("token expired") ErrOverrun = errors.New("frequency overrun") ErrBadRequest = errors.New("bad request") ErrIllegalParams = errors.New("params error") ErrUnknown = errors.New("unknown error") ErrInvalidResponse = errors.New("invalid response") ) type CaptchaRequest struct { VID string `json:"id"` Key string `json:"secretkey"` Server string `json:"-"` Scene int `json:"scene"` Token string `json:"token"` ClientIP string `json:"ip"` UserID string `json:"userid,omitempty"` } // validateServer will validate verify server's url, if illegal, return error, otherwise nil func (request *CaptchaRequest) validateServer() error { u, err := url.Parse(request.Server) if err != nil { return ErrIllegalServer } host := u.Hostname() if strings.HasSuffix(host, ".vaptcha.com") || strings.HasSuffix(host, ".vaptcha.net") { return nil } return ErrIllegalServer } type CaptchaResponse struct { Success int `json:"success"` Score int `json:"score"` Msg string `json:"msg"` } // Request will send request to verify server and get response, if server is illegal, returns ErrIllegalServer, func (request *CaptchaRequest) Request() (*CaptchaResponse, error) { // validate server err := request.validateServer() if err != nil { return nil, err } // post request buf := bytes.NewReader(mustToJson(request)) resp, err := http.Post(request.Server, "application/json", buf) if err != nil { return nil, err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } // bind data to response struct var response CaptchaResponse err = json.Unmarshal(body, &response) if err != nil { return nil, err } return &response, nil } var errMsg = map[string]error{ "userid error": ErrWrongUserID, "id empty": ErrEmptyID, "id error": ErrWrongID, "scene error": ErrWrongScene, "token error": ErrWrongToken, "token expired": ErrExpiredToken, "frequency overrun": ErrOverrun, "bad request": ErrBadRequest, "param-error": ErrIllegalParams, } // Verify will verify the response and return nil if pass, otherwise errors with details // For example, ErrWrongUserID, ErrIllegalParams, etc. You can find these errors in defined variables. func (response *CaptchaResponse) Verify() error { if response == nil { return ErrInvalidResponse } if response.Success == 1 { return nil } else { v, ok := errMsg[response.Msg] if ok { return v } else { return ErrUnknown } } } // RequestAndVerify will request and verify captcha info, return true if pass, otherwise false func RequestAndVerify(request *CaptchaRequest) bool { resp, err := request.Request() if err != nil { return false } err = resp.Verify() if err != nil { return false } return true }
#!/bin/bash set -ex export AWS_DEFAULT_REGION=us-west-2 services="cart \ catalogue \ dispatch \ load-gen \ mongo \ mysql \ payment \ ratings \ shipping \ user \ web" for service in $services; do aws ecr create-repository \ --repository-name robot-shop/$service \ --image-tag-mutability IMMUTABLE \ --image-scanning-configuration scanOnPush=true \ --region us-west-2 || true done
<reponame>garrylachman/GoodDAPP import { first, omit } from 'lodash' import Config from '../../../../config/config' import logger from '../../../../lib/logger/pino-logger' import Torus from './torus' import { Auth0Strategy, FacebookStrategy, GoogleLegacyStrategy, GoogleStrategy, PaswordlessEmailStrategy, PaswordlessSMSStrategy, } from './strategies' class TorusSDK { strategies = {} static factory() { const sdk = new TorusSDK(Config, logger.child({ from: 'TorusSDK' })) sdk.addStrategy('facebook', FacebookStrategy) sdk.addStrategy('google-old', GoogleLegacyStrategy) sdk.addStrategy('google', GoogleStrategy) sdk.addStrategy('auth0', Auth0Strategy) sdk.addStrategy('auth0-pwdless-email', PaswordlessEmailStrategy) sdk.addStrategy('auth0-pwdless-sms', PaswordlessSMSStrategy) return sdk } constructor(config, logger) { const { env, torusProxyContract, torusNetwork } = config this.torus = new Torus(config, { proxyContractAddress: torusProxyContract, // details for test net network: torusNetwork, // details for test net enableLogging: env === 'development', }) this.config = config this.logger = logger } // eslint-disable-next-line require-await async initialize() { const { torus } = this return torus.init() } async triggerLogin(verifier, customLogger = null) { const { logger, strategies } = this const log = customLogger || logger let withVerifier = verifier log.debug('triggerLogin', { verifier }) if (!verifier || !(verifier in strategies)) { withVerifier = 'facebook' } const response = await strategies[withVerifier].triggerLogin() return this.fetchTorusUser(response, customLogger) } addStrategy(verifier, strategyClass) { const { config, torus, strategies } = this strategies[verifier] = new strategyClass(torus, config) } fetchTorusUser(response, customLogger = null) { const { logger, config } = this const log = customLogger || logger let torusUser = response let { userInfo, ...otherResponse } = torusUser if (userInfo) { // aggregate login returns an array with user info userInfo = first(userInfo) || userInfo torusUser = { ...otherResponse, ...userInfo } } const { name, email } = torusUser const isLoginPhoneNumber = /\+[0-9]+$/.test(name) if (isLoginPhoneNumber) { torusUser = { ...torusUser, mobile: name } } if (isLoginPhoneNumber || name === email) { torusUser = omit(torusUser, 'name') } if ('production' !== config.env) { log.debug('Received torusUser:', torusUser) } return torusUser } } export default TorusSDK.factory()
#!/bin/bash ( cd $(dirname "${BASH_SOURCE[0]}") ../../build/MoonGen perf-mac.lua 14 15 )
import {execVim} from "./exec_vim"; export type RTPProvider = () => string[]; export class VimHelp { helplang: string[]; rtpProvider?: () => string[]; constructor( public vimBin = "vim", ) { this.vimBin = vimBin; this.helplang = []; } search(word: string): Promise<string> { const safeWord = word.replace(/\|/g, "bar"); const commands = [ `verbose silent help ${safeWord}`, [ "?\\%(^\\s*$\\|[^*]$\\)?", "/\\*\\S\\+\\*/", ";", "/^*\\|[^*]$/", "-1", "/^\\s*\\*\\S\\+\\*\\|\\*\\S\\+\\*\\s*\\%(>\\)\\=$/", "?^[^=-].*[^=-]$?", "print" ].join("") ]; const runtimepaths = this.rtpProvider?.() || []; const preCommands = runtimepaths.map((rtp) => `set runtimepath+=${rtp.replace(/[\\, ]/, "\\\0")}` ); preCommands.push(`set helplang=${this.helplang.join(",")}`); return this._execVim(preCommands.concat(commands)); } _execVim(commands: string[]): Promise<string> { return execVim(this.vimBin, [...commands, "qall!"]); } setRTPProvider(provider: () => string[]): void { this.rtpProvider = provider; } }
import random def rock_paper_scissors(): choices = ['rock', 'paper', 'scissors'] user_choice = input("Enter your choice (rock, paper, scissors): ").lower() while user_choice not in choices: user_choice = input("Invalid choice. Please enter rock, paper, or scissors: ").lower() computer_choice = random.choice(choices) print(f"User's choice: {user_choice}") print(f"Computer's choice: {computer_choice}") if user_choice == computer_choice: print("Result: It's a draw!") elif (user_choice == 'rock' and computer_choice == 'scissors') or (user_choice == 'scissors' and computer_choice == 'paper') or (user_choice == 'paper' and computer_choice == 'rock'): print("Result: You win!") else: print("Result: Computer wins!") rock_paper_scissors()
import useSWR from 'swr' import { get } from 'lib/common/fetch' import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events' import { API_URL } from 'lib/constants' export function useJwtSecretUpdateStatus(projectRef: string | string[] | undefined) { const url = `${API_URL}/props/project/${projectRef}/jwt-secret-update-status` const { data, error, mutate } = useSWR<any>(url, get, { refreshInterval: (data) => data?.jwtSecretUpdateStatus?.meta?.status === JwtSecretUpdateStatus.Updating ? 1_000 : 0, }) const anyError = data?.error || error const meta = data?.jwtSecretUpdateStatus?.meta return { changeTrackingId: meta?.change_tracking_id, isError: !!anyError, isLoading: !anyError && !data, jwtSecretUpdateError: meta?.error, jwtSecretUpdateProgress: meta?.progress, jwtSecretUpdateStatus: meta?.status, mutateJwtSecretUpdateStatus: mutate, } }
import * as NS from '../../namespace'; import { ITwoFactorInfo } from 'shared/types/models'; export function setTwoFactorInfo(data: ITwoFactorInfo): NS.ISetTwoFactorInfo { return { type: 'AUTH:SET_TWO_FACTOR_INFO', payload: data }; }
<gh_stars>10-100 import React from "react"; import CardBody from "../CardBody"; import CardBtn from "../CardBtn"; import CardImg from "../CardImage"; import CardHeading from "../CardHeading"; import "./style.css"; function Card() { return ( <div> <CardHeading /> <CardImg /> <CardBody /> <CardBtn style={{ opacity: 1 }} data-value="back" /> <CardBtn style={{ opacity: 1 }} data-value="next" /> </div> ); } export default Card;
const Component = require('./component'); class Diode extends Component { constructor(key) { super('diode', `D_${key.compositeName}`, 2); this.setPad(1, `col${key.col}`); } getAdditionalData(x, y, options) { return { x: ((x + 0.5) * 1905) / 100, y: ((y + 0.5) * 1905) / 100, }; } } module.exports = Diode;
<reponame>AustinSanders/usgscsm<filename>tests/EigenUtilitiesTests.cpp #include "EigenUtilities.h" #include <gtest/gtest.h> #include <cmath> // See if fitting a projective transform to points which were created // with such a transform to start with can recover it. TEST(EigenUtilitiesTests, createProjectiveApproximation) { // Create a projective transform with coeffs stored in a vector. // The exact values are not important. std::vector<double> u(14); for (size_t it = 0; it < u.size(); it++) u[it] = sin(it); // why not // Create inputs and outputs std::vector<csm::ImageCoord> imagePts; std::vector<csm::EcefCoord> groundPts; for (int r = 0; r < 5; r++) { for (int c = 0; c < 5; c++) { // Create some 3D points. The precise values are not important // as long as they are well-distributed double x = c, y = r, z = 0.3 * x + 2 * y + 0.04 * x * y; // Find corresponding 2D points double p = (u[0] + u[1] * x + u[2] * y + u[3] * z) / (1 + u[4] * x + u[5] * y + u[6] * z); double q = (u[7] + u[8] * x + u[9] * y + u[10] * z) / (1 + u[11] * x + u[12] * y + u[13] * z); imagePts.push_back(csm::ImageCoord(p, q)); groundPts.push_back(csm::EcefCoord(x, y, z)); } } // Find the transform std::vector<double> transformCoeffs; usgscsm::computeBestFitProjectiveTransform(imagePts, groundPts, transformCoeffs); // Verify that we recover the transform double err = 0.0; for (size_t it = 0; it < u.size(); it++) err = std::max(err, std::abs(u[it] - transformCoeffs[it])); EXPECT_NEAR(0.0, err, 1e-12); }
x86_64-w64-mingw32-gcc -Os -shared -std=c99 src/dllmain.c -o DINPUT8.dll.2016 -DHITMAN2016 -Wall -Wno-missing-braces -static-libstdc++ -static-libgcc #-static -lpthread
<filename>lc0041_first_missing_positive.py """Leetcode 41. First Missing Positive Hard URL: https://leetcode.com/problems/first-missing-positive/ Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: Input: [3,4,-1,1] Output: 2 Example 3: Input: [7,8,9,11,12] Output: 1 Note: Your algorithm should run in O(n) time and uses constant extra space. """ class SolutionSwapToCorrectPos(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int Time complexity: O(n). Space complexity: O(1). """ n = len(nums) # Iterate through all positions, continue swapping # nums[i]'s to their correct position (i + 1)'s. for i in range(n): while 0 < nums[i] <= n and nums[i] != nums[nums[i] - 1]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] # Check each updated elements in nums with true positive integer. for i in range(n): if i + 1 != nums[i]: return i + 1 # If all elements in nums are correct, return the last one plus one. return n + 1 def main(): # Output: 3 nums = [1,2,0] print SolutionSwapToCorrectPos().firstMissingPositive(nums) # Output: 2 nums = [3,4,-1,1] print nums print SolutionSwapToCorrectPos().firstMissingPositive(nums) # # Output: 1 nums = [7,8,9,11,12] print SolutionSwapToCorrectPos().firstMissingPositive(nums) if __name__ == '__main__': main()
#!/usr/bin/env bash # read-menu: a menu driven system information program clear cat << EOF Please Select: 1. Display System Information 2. Display Disk Space 3. Display Home Space Utilization 0. Quit EOF echo -n 'Enter selection [0-3]: ' read -r sel case $sel in 0) echo "Program terminated.";; 1) echo "Hostname: $HOSTNAME"; uptime;; 2) df -h;; 3) if [ "$UID" = 0 ]; then echo "Home Space Utilization (All Users)" du -sh /home/* else echo "Home Space Utilization ($USER)" du -sh "$HOME" fi ;; *) echo "Invalid entry." >&2 exit 1 esac
int linearSearch(int data[], int size, int key) { for (int i=0; i<size; i++) { if (data[i] == key) { return i; } } return -1; }
module.exports = (api) => ({ presets: [ [ '@babel/env', { bugfixes: true, loose: true, modules: api.env() === 'esm' ? false : 'commonjs', }, ], ], });
#!/bin/bash python -m py_compile multicursor.py && ./install.sh && gedit test.txt
/* tslint:disable */ export type NetSuiteResponseLog = { name: string; type: string; externalId: string; internalId: string; success: boolean; };
<reponame>mattiolato98/reservation-ninja # Generated by Django 3.2.7 on 2021-10-01 10:11 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('reservation_management', '0002_alter_classroom_name'), ] operations = [ migrations.CreateModel( name='Timetable', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('day', models.PositiveSmallIntegerField()), ('start_time', models.TimeField()), ('end_time', models.TimeField()), ('classroom', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='timetables', to='reservation_management.classroom')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='timetables', to=settings.AUTH_USER_MODEL)), ], ), ]
<gh_stars>10-100 import { StyleSheet, Dimensions } from 'react-native'; const styles = StyleSheet.create({ container: { minHeight: 40, alignItems: 'flex-start', justifyContent: 'center', margin: 15, marginHorizontal: 5, }, inputLabelWrapper: { height: 56, width: '92%', alignItems: 'center', justifyContent: 'center', backgroundColor: '#41E1FD', marginHorizontal: 10, borderColor: '#D9D5DC', borderWidth: 1, borderRadius: 4, }, inputLabel: { height: 50, width: '99%', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', elevation: 4, borderRadius: 4, shadowColor: '#000', shadowOpacity: 0.2, shadowRadius: 4, backgroundColor: 'white', shadowOffset: { width: 0, height: 0 }, paddingLeft:5 }, labelTextWrapper: { height: 50, flex: 1, alignItems: 'center', justifyContent: 'center' }, valueWrapper: { width: '60%', flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', }, iconWrapper: { height: 50, flexDirection: 'row', width: '7%', alignItems: 'center', justifyContent: 'flex-start', }, labelText: { fontSize: 18, lineHeight: 20, minHeight: 20, color: '#ADADAD', fontFamily: 'roboto', textAlign: 'left', fontWeight: '300', paddingStart: 5, flex:1 }, iconStyle: { fontFamily: 'roboto', alignSelf: 'center', fontSize: 18, lineHeight: 20, height: 20, color: '#41E1FD', }, inputText: { fontSize: 15, lineHeight: 20, minHeight: 20, color: '#575757', fontFamily: 'roboto', alignSelf: 'center', fontWeight: '100', }, button: { height: 50, backgroundColor: '#48BBEC', margin: 0, alignSelf: 'stretch', justifyContent: 'center', }, buttonText: { fontSize: 18, color: 'white', alignSelf: 'center', }, selectedContainer: { height: 40, width: '50%', }, selectedStatusOuter: { height: 30, flexDirection: 'row', width: '100%', backgroundColor: '#6AD97B', borderRadius: 15, borderColor: 'white', borderWidth: 1, justifyContent: 'center', alignItems: 'center', margin: 5, }, selectedText: { color: 'white', fontFamily: 'roboto', paddingLeft: 10, paddingRight: 10, alignItems: 'center', fontSize: 12, width: '70%', }, removeFilterIcon: { alignItems: 'center', justifyContent: 'center', height: 30, width: 30, marginEnd: 10, }, noDataWrapper: { height: 80, justifyContent: 'center', alignItems: 'center', }, nodataText: { height: 30, lineHeight: 20, color: '#989898', fontFamily: 'roboto', width: '100%', fontSize: 14, padding: 5, fontWeight: '700', alignSelf: 'center', textAlign: 'center', }, }); export default styles;
/** * Created by <NAME> on 9/16/2021. */ var execSync = require('./execSync'); var prepareCommandOptions = require('./prepareCommandOptions'); /** * @module GitSync * @param {object} options * @param {string} options.cwd - Working path to set git to work in * @param {string} options.dryRun - Do not run command, only logs them * @param {string} options.logging - Logs all commands * @param {string} options.forceExit - Forces the app to exit when an error occurs */ function GitSync(options) { options = options || {}; this.cwd = options.cwd || '.'; this.dryRun = options.dryRun || false; this.logging = options.logging || false; this.forceExit = options.forceExit || false; } /** * Gets the options * @access private * @returns {object} */ GitSync.prototype.getOptions = function () { return { cwd: this.cwd, dryRun: this.dryRun, logging: this.logging, forceExit: this.forceExit }; } /** * Executes 'git add ' * @method add * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.add = function (commandOptions, execOptions, options) { return execSync('git add ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git bisect ' * @method bisect * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.bisect = function (commandOptions, execOptions, options) { return execSync('git bisect ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git branch ' * @method branch * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.branch = function (commandOptions, execOptions, options) { return execSync('git branch ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git checkout ' * @method checkout * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.checkout = function (commandOptions, execOptions, options) { return execSync('git checkout ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git clean ' * @method clean * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.clean = function (commandOptions, execOptions, options) { return execSync('git clean ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git clone ' * @method clone * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.clone = function (commandOptions, execOptions, options) { return execSync('git clone ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git commit ' * @method commit * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.commit = function (commandOptions, execOptions, options) { return execSync('git commit ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git config ' * @method config * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.config = function (commandOptions, execOptions, options) { return execSync('git config ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git diff ' * @method diff * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.diff = function (commandOptions, execOptions, options) { return execSync('git diff ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git fetch ' * @method fetch * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.fetch = function (commandOptions, execOptions, options) { return execSync('git fetch ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git grep ' * @method grep * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.grep = function (commandOptions, execOptions, options) { return execSync('git grep ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git init ' * @method init * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.init = function (commandOptions, execOptions, options) { return execSync('git init ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git log ' * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.log = function (commandOptions, execOptions, options) { return execSync('git log ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git merge ' * @method merge * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.merge = function (commandOptions, execOptions, options) { return execSync('git merge ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git mv ' * @method mv * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.mv = function (commandOptions, execOptions, options) { return execSync('git mv ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git pull' * @method pull * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.pull = function (commandOptions, execOptions, options) { return execSync('git pull ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'hub pull-request ' * @method pullRequest * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.pullRequest = function (commandOptions, execOptions, options) { return execSync('hub pull-request ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git push ' * @method push * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.push = function (commandOptions, execOptions, options) { return execSync('git push ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git rebase ' * @method rebase * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.rebase = function (commandOptions, execOptions, options) { return execSync('git rebase ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git remote ' * @method remote * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.remote = function (commandOptions, execOptions, options) { return execSync('git remote ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git reset ' * @method reset * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.reset = function (commandOptions, execOptions, options) { return execSync('git reset ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git rm ' * @method rm * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.rm = function (commandOptions, execOptions, options) { return execSync('git rm ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git show ' * @method show * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.show = function (commandOptions, execOptions, options) { return execSync('git show ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git stash ' * @method stash * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} * @see https://git-scm.com/docs/git-stash */ GitSync.prototype.stash = function (commandOptions, execOptions, options) { return execSync('git stash ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git status ' * @method status * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.status = function (commandOptions, execOptions, options) { return execSync('git status ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes 'git tag ' * @method tag * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.tag = function (commandOptions, execOptions, options) { return execSync('git tag ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes a method over git directly. Like 'git [commandOptions]' * @method git * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.git = function(commandOptions, execOptions, options) { return execSync('git ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; /** * Executes a method over hub directly. Like 'hub [commandOptions]' * @method hub * @param {string} [commandOptions] * @param {object} [execOptions] * @returns {string} */ GitSync.prototype.hub = function(commandOptions, execOptions, options) { return execSync('hub ' + prepareCommandOptions(commandOptions), execOptions, options || this.getOptions()); }; module.exports = GitSync;
<gh_stars>0 const mongoose = require("mongoose"); const Schema = mongoose.Schema; const movieSchema = new Schema({ backdrop_path: { type: String }, genre_ids: { type: Number }, id: { type: Number }, original_title: { type: String }, overview: { type: String }, poster_path: { type: String }, vote_average: { type: Number }, vote_count: { type: Number }, }); const movie = mongoose.model("movieDB", movieSchema); module.exports = movie;
<filename>doxall/search/files_1.js<gh_stars>0 var searchData= [ ['barriermodelregion_2ecpp',['BarrierModelRegion.cpp',['../_barrier_model_region_8cpp.html',1,'']]], ['barriermodelregion_2ehpp',['BarrierModelRegion.hpp',['../_barrier_model_region_8hpp.html',1,'']]] ];
<filename>src/www/src/views/projection_item_view.js 'use strict'; /* * @Author: <NAME>, Design Research Lab, Universität der Künste Berlin * @Date: 2016-05-04 11:38:41 * @Last Modified by: lutzer * @Last Modified time: 2016-07-14 17:06:19 */ import Marionette from 'marionette' import _ from 'underscore' import Config from 'config' import template from 'text!templates/projection_item_tmpl.html'; class BaseView extends Marionette.ItemView { /* properties */ get template() { return _.template(template) } get templateHelpers() { return { backgroundImage : this.getBackgroundImageString() } } /* methods */ initialize(options) { //listen to model events this.listenTo(this.model,'change',this.render); //listen to socket events this.listenTo(Backbone,'submission:changed', this.onSubmissionChanged); } onRender() { if (this.model.get('device') == "letterbox") this.$('.background').addClass("invert"); } getBackgroundImageString() { var filesUrl = Config.files_url + this.model.get('_id') + '/'; var files = this.model.get('files') if (files.length > 0) return "style=\"background-image: url('"+filesUrl+files[0].name+"')\""; else return ""; } onSubmissionChanged() { this.model.fetch(); } } export default BaseView
def avg(a, b, c): return (a + b + c)/3 a = 21 b = 15 c = 10 average = avg(a, b, c) print("Average of three numbers is:", average)
wsk -i action invoke --result fat-go --param name Jack
<reponame>nkmrshn/jquery.ganttView<gh_stars>1-10 const Holidays = [ // // 2010年 { name: "元旦", at: new Date(2010,00,01), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "成人の日", at: new Date(2010,00,11), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "建国記念日", at: new Date(2010,01,11), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "春分の日", at: new Date(2010,02,21), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "振替休日", at: new Date(2010,02,22), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "昭和の日", at: new Date(2010,03,29), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "憲法記念日", at: new Date(2010,04,03), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "みどりの日", at: new Date(2010,04,04), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "こどもの日", at: new Date(2010,04,05), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "海の日", at: new Date(2010,06,19), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "敬老の日", at: new Date(2010,08,20), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "秋分の日", at: new Date(2010,08,23), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "体育の日", at: new Date(2010,09,11), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "文化の日", at: new Date(2010,10,03), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "勤労感謝の日", at: new Date(2010,10,23), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "天皇誕生日", at: new Date(2010,11,23), color: "#777777", backgroundColor: "#ffe4e1" }, // // 2011年 { name: "元旦", at: new Date(2011,00,01), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "成人の日", at: new Date(2011,00,10), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "建国記念日", at: new Date(2011,01,11), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "春分の日", at: new Date(2011,02,21), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "昭和の日", at: new Date(2011,03,29), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "憲法記念日", at: new Date(2011,04,03), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "みどりの日", at: new Date(2011,04,04), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "こどもの日", at: new Date(2011,04,05), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "海の日", at: new Date(2011,06,18), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "敬老の日", at: new Date(2011,08,19), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "秋分の日", at: new Date(2011,08,23), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "体育の日", at: new Date(2011,09,10), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "文化の日", at: new Date(2011,10,03), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "勤労感謝の日", at: new Date(2011,10,23), color: "#777777", backgroundColor: "#ffe4e1" }, { name: "天皇誕生日", at: new Date(2011,11,23), color: "#777777", backgroundColor: "#ffe4e1" } ];
#!/bin/sh # This is a generated file; do not edit or check into version control. export "FLUTTER_ROOT=/Users/hututu/Dev/AndroidStudio/flutter" export "FLUTTER_APPLICATION_PATH=/Users/hututu/Dev/AndroidStudio/WorkFlutter/facebook_audience_IOS_Android/example" export "FLUTTER_TARGET=/Users/hututu/Dev/AndroidStudio/WorkFlutter/facebook_audience_IOS_Android/example/lib/main.dart" export "FLUTTER_BUILD_DIR=build" export "SYMROOT=${SOURCE_ROOT}/../build/ios" export "FLUTTER_FRAMEWORK_DIR=/Users/hututu/Dev/AndroidStudio/flutter/bin/cache/artifacts/engine/ios" export "TRACK_WIDGET_CREATION=true"
def find_primes(numb): for i in range(2, numb + 1): for j in range(2, i): if i%j == 0: break else: print(i) find_primes(100)
<gh_stars>1-10 import {FETCH, GET} from '../actions/types'; export interface IRootState { salutation: string; } const initialState: IRootState = { // Add properties to the initial state. salutation: '' }; export default function(state: IRootState = initialState, action: { type: string; payload: any }) { switch (action.type) { case FETCH: return { ...state, // ..., } case GET: return { ...state, salutation: action.payload } default: return state; } }
import { RemoteData } from './RemoteData'; import { isDefined } from './internal/isDefined'; import { MaybeCancel } from './internal/MaybeCancel'; export interface RemoteDataStore<T> { readonly triggerUpdate: () => MaybeCancel; readonly invalidate: () => void; readonly current: RemoteData<T>; // you can supply this through `Options` parameter to `useRemoteData` readonly storeName: string | undefined; } export namespace RemoteDataStore { // get a completely static store. Perfect for storybook and so on export const always = <T>(current: RemoteData<T>, storeName?: string): RemoteDataStore<T> => ({ triggerUpdate: () => undefined, current, storeName, invalidate: () => {}, }); // get a version of the store which can be rendered immediately export const orNull = <T>(store: RemoteDataStore<T>): RemoteDataStore<T | null> => { return { get current() { return RemoteData.Yes(RemoteData.orNull(store.current)); }, invalidate: store.invalidate, triggerUpdate: store.triggerUpdate, storeName: store.storeName, }; }; export type ValuesFrom<Stores extends [...RemoteDataStore<unknown>[]]> = { [K in keyof Stores]: Stores[K] extends RemoteDataStore<infer O> ? O : never; }; // combine many stores into one which will produce a tuple with all values when we have them. // think of this as `sequence` from FP export const all = <Stores extends RemoteDataStore<unknown>[]>( ...stores: Stores ): RemoteDataStore<ValuesFrom<Stores>> => new All(stores); class All<Stores extends RemoteDataStore<unknown>[]> implements RemoteDataStore<ValuesFrom<Stores>> { readonly #stores: Stores; constructor(stores: Stores) { this.#stores = stores; } triggerUpdate = (): MaybeCancel => { // if the product of all stores is a failure, dont invalidate any successful stores where we won't see the result if (this.current.type === 'no') { return undefined; } return MaybeCancel.all(this.#stores.map((store) => store.triggerUpdate())); }; get current() { const combined = RemoteData.all(...this.#stores.map((store) => store.current)); // didn't bother to prove this, but we could return combined as RemoteData<RemoteDataStore.ValuesFrom<Stores>>; } get storeName() { return this.#stores .map((store) => store.storeName) .filter(isDefined) .join(', '); } invalidate = () => this.#stores.forEach((store) => store.invalidate()); } }
<filename>src/admin/admin.controller.ts import { Controller, Get, Render } from '@nestjs/common'; import { config } from '../config.service'; @Controller('admin') export class AdminController { @Get() @Render('admin/index') index() { return { title: 'P' }; } @Get('login') @Render(config.PAGE_LANDING) login() { return { title: 'P' }; } }
function generateCardStyles(theme, elevation) { const { palette, typography, shadows } = theme; const { text, divider } = palette; const { fontSize } = typography.body1; let styles = ` color: ${text.primary}; font-size: ${fontSize}; display: flex; justify-content: center; align-items: center; box-shadow: ${shadows[elevation]}; border-radius: 4px; `; if (elevation === 0) { styles += ` border: 1px solid ${divider}; `; } return styles; }
const axios = require('axios'); async function convertCurrency(amount, fromCurrency, toCurrency) { const response = await axios.get(`https://api.exchangeratesapi.io/latest?base=${fromCurrency}&symbols=${toCurrency}`); const exchangeRate = response.data.rates[toCurrency]; const convertedAmout = (amount * exchangeRate).toFixed(2); return convertedAmout; } const convertedAmout = convertCurrency(120, 'GBP', 'USD'); console.log(convertedAmout);// Outputs 161.32
import CoreGraphics struct SizeRange { var min: CGSize var max: CGSize init(min: CGSize, max: CGSize) { self.min = min self.max = max } init(width: CGFloat, height: CGFloat) { let size = CGSize(width: width, height: height) self.init(min: size, max: size) } }
let data = [ {id: 1, name: "John", score: 50}, {id: 2, name: "Bob", score: 80}, {id: 3, name: "Alice", score: 70} ]; let property = 'score'; // Sort the data in descending order based on the given property data.sort((a,b) => b[property] - a[property]); console.log(data); // [ {id: 2, name: "Bob", score: 80}, {id: 3, name: "Alice", score: 70}, {id: 1, name: "John", score: 50} ]
package com.jdc.app.entity; import lombok.Data; @Data public class Category { private int id; private String name; public Category() {} public Category(String name) { this.name = name; } @Override public String toString() { return name; } }
<reponame>xcfox/react-tile-pane import React, { useEffect, useState } from 'react' import './App.css' import '../static/style.css' import { LeftTabDemo, SimpleDemo } from './demo' const demos = { 'tab-bar in left demo': <LeftTabDemo />, 'simple demo': <SimpleDemo />, } const color: Record<keyof typeof demos, [string, string]> = { 'tab-bar in left demo': ['#161718', '#ffffff'], 'simple demo': ['#ffffff', '#000000'], } const App: React.FC = () => { const [demo, setDemo] = useState<keyof typeof demos>('tab-bar in left demo') useEffect(() => { document.body.style.background = color[demo][0] document.body.style.color = color[demo][1] }, [demo]) return ( <div style={{ width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <div style={{ height: 30, display: 'flex' }}> {(Object.keys(demos) as (keyof typeof demos)[]).map((key) => ( <div style={{ marginLeft: 20, marginRight: 20 }} key={key} onClick={() => setDemo(key)} > {key} </div> ))} </div> {demos[demo]} </div> ) } export default App
import * as observable from '@nativescript/core/data/observable'; import * as builder from '@nativescript/core/ui/builder'; import * as app from '@nativescript/core/application'; import * as utils from "@nativescript/core/utils"; export class ChartExamplesDataModel { private _categoricalSource; private _categoricalSource2; private _categoricalSource3; private _areaSource; private _areaSource2; private _bubbleCategoricalSource; private _pieSource; private _pieSource2; private _pieSource3; private _areaTypes; private _pieTypes; private _lineTypes; private _barTypes; private selectedItem: ChartTypeItem; private _views; private _useCache; constructor(useCache: boolean) { this._useCache = useCache; this._views = {}; } public clearCache() { for (var i = 0; i < this._views.length; i++) { delete this._views[i]; } this._views = {}; } public loadGalleryFragment(item: ChartTypeItem, viewHolder, pathToModuleXML: string, exampleXmlName: string) { if (this.selectedItem) { this.selectedItem.isSelected = false; } item.isSelected = true; this.selectedItem = item; var useCache = this._useCache && viewHolder.android !== undefined; var exampleView = useCache ? this._views[pathToModuleXML + exampleXmlName] : null; if (!exampleView) { exampleView = builder.load({ path: pathToModuleXML, name: exampleXmlName }); if (useCache) { this._views[pathToModuleXML + exampleXmlName] = exampleView; } } if (viewHolder.getChildrenCount() > 0) { var child = viewHolder.getChildAt(0); viewHolder.removeChild(child); child = null; if (viewHolder.ios) { utils.GC(); } } // The following reset of binding context fixes a glitch in iOS with series animations // which occurs due to chart loading data before being properly measured if (app.ios) { let context = viewHolder.bindingContext; viewHolder.bindingContext = null; viewHolder.addChild(exampleView); setTimeout(() => { viewHolder.bindingContext = context; }, 100); } else { viewHolder.addChild(exampleView); } } get categoricalSource() { if (this._categoricalSource) { return this._categoricalSource; } return this._categoricalSource = [ { Category: "Mar", Amount: 65.0 }, { Category: "Apr", Amount: 62.0 }, { Category: "May", Amount: 55.0 }, { Category: "Jun", Amount: 71.0 } ]; } get categoricalSource2() { if (this._categoricalSource2) { return this._categoricalSource2; } return this._categoricalSource2 = [ { Category: "Mar", Amount: 5 }, { Category: "Apr", Amount: 15 }, { Category: "May", Amount: 3 }, { Category: "Jun", Amount: 45 } ]; } get categoricalSource3() { if (this._categoricalSource3) { return this._categoricalSource3; } return this._categoricalSource3 = [ { Category: "Mar", Amount: 65 }, { Category: "Apr", Amount: 56 }, { Category: "May", Amount: 89 }, { Category: "Jun", Amount: 68 } ]; } get areaSource() { if (this._areaSource) { return this._areaSource; } return this._areaSource = [ { Category: "Mar", Amount: 51 }, { Category: "Apr", Amount: 81 }, { Category: "May", Amount: 89 }, { Category: "Jun", Amount: 60 } ]; } get areaSource2() { if (this._areaSource2) { return this._areaSource2; } return this._areaSource2 = [ { Category: "Mar", Amount: 60 }, { Category: "Apr", Amount: 87 }, { Category: "May", Amount: 91 }, { Category: "Jun", Amount: 95 } ]; } get bubbleCategoricalSource() { if (this._bubbleCategoricalSource) { return this._bubbleCategoricalSource; } return this._bubbleCategoricalSource = [ { Country: "Germany", Amount: Math.random() * 10, Impact: 1 }, { Country: "France", Amount: Math.random() * 10, Impact: 7 }, { Country: "Bulgaria", Amount: Math.random() * 10, Impact: 10 }, { Country: "Spain", Amount: Math.random() * 10, Impact: 3 }, { Country: "USA", Amount: Math.random() * 10, Impact: 4 } ]; } get pieSource() { if (this._pieSource) { return this._pieSource; } return this._pieSource = [ { Country: "Belgium", Amount: 20.0 }, { Country: "Germany", Amount: 50.0 }, { Country: "UK", Amount: 30.0 } ]; } get pieSource2() { if (this._pieSource2) { return this._pieSource2; } return this._pieSource2 = [ { Company: "Google", Amount: 20.0 }, { Company: "Apple", Amount: 30.0 }, { Company: "Microsoft", Amount: 10.0 }, { Company: "Oracle", Amount: 8.0 } ]; } get pieSource3() { if (this._pieSource3) { return this._pieSource3; } return this._pieSource3 = [ { Level: "Elementary", Amount: 180.0 }, { Level: "Higher", Amount: 120.0 }, { Level: "Training", Amount: 60.0 } ]; } private getPictureResourcePath(groupName: string, exampleName: string) { if (app.ios) { return "res://chart/" + groupName + "/" + exampleName; } var resourcePath = "res://" + exampleName; return resourcePath; } get areaTypes() { if (this._areaTypes) { return this._areaTypes; } return this._areaTypes = [ new ChartTypeItem(true, this.getPictureResourcePath("area", "area1"), "area1"), new ChartTypeItem(false, this.getPictureResourcePath("area", "area2"), "area2"), new ChartTypeItem(false, this.getPictureResourcePath("area", "area3"), "area3"), new ChartTypeItem(false, this.getPictureResourcePath("area", "area4"), "area4"), new ChartTypeItem(false, this.getPictureResourcePath("area", "area5"), "area5"), new ChartTypeItem(false, this.getPictureResourcePath("area", "area6"), "area6") ]; } get barTypes() { if (this._barTypes) { return this._barTypes; } return this._barTypes = [ new ChartTypeItem(true, this.getPictureResourcePath("bar", "bar1"), "bar1"), new ChartTypeItem(false, this.getPictureResourcePath("bar", "bar2"), "bar2"), new ChartTypeItem(false, this.getPictureResourcePath("bar", "bar3"), "bar3"), new ChartTypeItem(false, this.getPictureResourcePath("bar", "bar4"), "bar4"), new ChartTypeItem(false, this.getPictureResourcePath("bar", "bar5"), "bar5"), new ChartTypeItem(false, this.getPictureResourcePath("bar", "bar6"), "bar6") ]; } get lineTypes() { if (this._lineTypes) { return this._lineTypes; } return this._lineTypes = [ new ChartTypeItem(true, this.getPictureResourcePath("line", "line1"), "line1"), new ChartTypeItem(false, this.getPictureResourcePath("line", "line2"), "line2"), new ChartTypeItem(false, this.getPictureResourcePath("line", "line3"), "line3"), new ChartTypeItem(false, this.getPictureResourcePath("line", "line4"), "line4") ]; } get pieTypes() { if (this._pieTypes) { return this._pieTypes; } return this._pieTypes = [ new ChartTypeItem(true, this.getPictureResourcePath("pie", "pie1"), "pie1"), new ChartTypeItem(false, this.getPictureResourcePath("pie", "pie2"), "pie2"), new ChartTypeItem(false, this.getPictureResourcePath("pie", "pie3"), "pie3"), ]; } } export class ChartTypeItem extends observable.Observable { constructor(selected, imageResource, xmlResource) { super(); this.isSelected = selected; this.imageRes = imageResource; this.exampleXml = xmlResource; } get isSelected() { return this.get("selected"); } set isSelected(value) { this.set("selected", value); } get imageRes() { return this.get("imgRes"); } set imageRes(value) { this.set("imgRes", value); } get selectedImageRes() { var suffix = app.ios ? "s" : ""; return this.get("imgRes") + suffix; } get exampleXml() { return this.get("exXml"); } set exampleXml(value) { this.set("exXml", value); } }
import pytest from mixer.backend.django import mixer from projects.models import Project, ProjectMembership from users.models import User @pytest.mark.django_db class TestProject: def test_project_create(self): user = mixer.blend(User, username='test') proj = mixer.blend(Project, owner = user) assert proj.owner == user def test_project_str(self): proj = mixer.blend(Project) assert str(proj) == proj.title @pytest.mark.django_db class TestProjectMembers: def test_member(self): proj = mixer.blend(Project) user = mixer.blend(User, username='test') mixer.blend(ProjectMembership, member=user, project=proj) assert proj.members.get(username='test') == user def test_proj_member_str(self): pmem = mixer.blend(ProjectMembership) assert str(pmem) == f'{pmem.member.full_name} , {pmem.project.title}'
#!/bin/sh export IP=$(ifconfig en0 | grep inet | awk '$1=="inet" {print $2}') echo "host is $IP" echo "starting nixos container..." # enable for GUI apps # xhost + $IP docker run -it --rm \ -e DISPLAY=$IP:0 \ -e NIXPKGS_ALLOW_BROKEN=1 \ -e ROBOT_SSH_KEY="$ROBOT_SSH_KEY" \ -v "$(pwd):/app" \ -v "nix:/nix" \ -v "nix-19.09-root:/root" \ -w "/app" nixos/nix:2.3 sh -c " ./nix/bootstrap.sh && nix-shell ./nix/shell.nix --pure \ -I ssh-config-file=/tmp/.ssh/config \ --argstr hexOrganization $HEX_ORGANIZATION \ --argstr hexApiKey $HEX_API_KEY \ --argstr robotSshKey $ROBOT_SSH_KEY \ --option sandbox false \ -v --show-trace "
"""Top-level package for ACM DL HCI Searcher.""" from acm_dl_searcher.__main__ import _search from acm_dl_searcher import search_operations __author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ = '0.1.0-alpha.3' search = _search __all__ = [search, search_operations]
/** * Created by liubinbin on 16/08/2016. */ import emitter from "../functions/emitter"; import * as React from "react"; import {IArticle} from "../../definitions/storage/article"; import * as HistoryStorage from "../storage/history" import * as ArticleStorage from "../storage/article" import History from "../storage/history" import {IHistory} from "../storage/history"; export interface HistoryListProps { } export interface HistoryListState { entries: IArticle[]; } export class HistoryList extends React.Component<HistoryListProps, {}> { state: HistoryListState = { entries: [], }; componentWillMount() { emitter.on("open_in_detail", (entry: IArticle) => { History.AddAsync({id: 0, articleId: entry.id}) .then(()=> this.update()) }); this.update() } private update() { History.FindAsync() .then((data)=> { this.setState({ entries: data }); }) } open_in_detail(link: string) { } styles = { columnReverse: { display: 'flex', flexDirection: 'column-reverse', overflow: 'scroll' } } renderItem = (entry: IArticle) => { return ( <li key={entry.id}><a onClick={this.open_in_detail.bind(this,entry.link)}>{entry.title}</a></li> ); } render() { return ( <ul style={this.styles.columnReverse}> {this.state.entries.map((entry: IArticle) => { return this.renderItem(entry); })} </ul> ); } }
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require('./bootFOAMNode.js'); var env = foam.box.Context.create(); env.me = foam.box.NamedBox.create({ name: '/ca/vany/adam' }, env); // Force services to start. env.socketService; env.webSocketService; var dao = foam.dao.MDAO.create({ of: boxmail.Message }); env.registry.register( 'INBOX', null, foam.box.SkeletonBox.create({ data: dao.orderBy(boxmail.Message.ID) })); var text = ('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.').split(' '); function word() { return text[Math.floor(Math.random() * text.length)]; } function words() { return word() + ' ' + word() + ' ' + word() + ' ' + word(); } for ( var i = 0 ; i < 10000 ; i++ ) { dao.put(boxmail.Message.create({ id: i, subject: "[" + i + "] " + word(), body: words() })); }
<reponame>schinmayee/nimbus //##################################################################### // Copyright 2004-2009, <NAME>, <NAME>. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Grids_Uniform_Arrays/ARRAYS_ND.h> #include <PhysBAM_Tools/Read_Write/Arrays/READ_WRITE_ARRAY.h> #include <PhysBAM_Tools/Read_Write/Data_Structures/READ_WRITE_PAIR.h> #include <PhysBAM_Tools/Read_Write/Grids_Uniform_Arrays/READ_WRITE_ARRAYS.h> #include <PhysBAM_Tools/Read_Write/Utilities/FILE_UTILITIES.h> #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_GRID_2D.h> #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL_Components/OPENGL_COMPONENT_SCALAR_FIELD_2D.h> using namespace PhysBAM; template<class T,class T2,class RW> OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: OPENGL_COMPONENT_SCALAR_FIELD_2D(GRID<TV> &grid_input, const std::string &scalar_field_filename_input,OPENGL_COLOR_MAP<T2>* color_map_input,bool is_moving_grid_input,const std::string rigid_grid_frame_filename_input) : OPENGL_COMPONENT("Scalar Field 2D"), opengl_scalar_field(grid_input,*new ARRAY<T2,VECTOR<int,2> >,color_map_input,OPENGL_SCALAR_FIELD_2D<T,T2>::DRAW_TEXTURE,is_moving_grid_input),scalar_field_filename(scalar_field_filename_input), frame_loaded(-1), valid(false),is_moving_grid(is_moving_grid_input),rigid_grid_frame_filename(rigid_grid_frame_filename_input),print_weights_i(false),print_weights_j(false) { is_animation = FILE_UTILITIES::Is_Animated(scalar_field_filename); } template<class T,class T2,class RW> OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: OPENGL_COMPONENT_SCALAR_FIELD_2D(GRID<TV> &grid_input, const std::string &scalar_field_filename_input,OPENGL_COLOR_MAP<T2>* color_map_input,typename OPENGL_SCALAR_FIELD_2D<T,T2>::DRAW_MODE draw_mode_input,bool is_moving_grid_input,const std::string rigid_grid_frame_filename_input) : OPENGL_COMPONENT("Scalar Field 2D"), opengl_scalar_field(grid_input,*new ARRAY<T2,VECTOR<int,2> >,color_map_input,draw_mode_input,is_moving_grid_input),scalar_field_filename(scalar_field_filename_input), frame_loaded(-1), valid(false),is_moving_grid(is_moving_grid_input),rigid_grid_frame_filename(rigid_grid_frame_filename_input),print_weights_i(false),print_weights_j(false) { is_animation = FILE_UTILITIES::Is_Animated(scalar_field_filename); } template<class T,class T2,class RW> OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: ~OPENGL_COMPONENT_SCALAR_FIELD_2D() { delete &opengl_scalar_field.values; } template<class T,class T2,class RW> bool OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Valid_Frame(int frame_input) const { return FILE_UTILITIES::Frame_File_Exists(scalar_field_filename, frame_input); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Set_Frame(int frame_input) { OPENGL_COMPONENT::Set_Frame(frame_input); Reinitialize(); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Set_Draw(bool draw_input) { OPENGL_COMPONENT::Set_Draw(draw_input); Reinitialize(); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Display(const int in_color) const { if (valid && draw) opengl_scalar_field.Display(in_color); } template<class T,class T2,class RW> RANGE<VECTOR<float,3> > OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Bounding_Box() const { if (valid && draw) return opengl_scalar_field.Bounding_Box(); else return RANGE<VECTOR<float,3> >::Centered_Box(); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Print_Weights_I(std::ostream& stream,const VECTOR<int,2>& cell) const { ARRAY<PAIR<TV_INT,T> >& local_weights=const_cast<ARRAY<PAIR<TV_INT,T> >&>(weights_to(cell)); for(int i=1;i<=local_weights.m;i++){ stream<<" "<<local_weights(i).y<<" to "<<local_weights(i).x<<std::endl;} } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Print_Weights_J(std::ostream& stream,const VECTOR<int,2>& cell) const { ARRAY<PAIR<TV_INT,int> >& local_weights=const_cast<ARRAY<PAIR<TV_INT,int> >&>(weights_from(cell)); for(int i=1;i<=local_weights.m;i++){ stream<<" "<<weights_to(local_weights(i).x)(local_weights(i).y).y<<" to "<<local_weights(i).x<<std::endl;} } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Print_Selection_Info(std::ostream& output_stream,OPENGL_SELECTION* current_selection) const { if(Is_Up_To_Date(frame)){ output_stream<<component_name<<": "; opengl_scalar_field.Print_Selection_Info(output_stream,current_selection); if(print_weights_i && ((OPENGL_SELECTION_GRID_CELL_2D<T>*)current_selection)){ VECTOR<int,2> index=((OPENGL_SELECTION_GRID_CELL_2D<T>*)current_selection)->index; output_stream<<"w_i"<<std::endl; Print_Weights_I(output_stream,index);} if(print_weights_j && ((OPENGL_SELECTION_GRID_CELL_2D<T>*)current_selection)){ VECTOR<int,2> index=((OPENGL_SELECTION_GRID_CELL_2D<T>*)current_selection)->index; output_stream<<"w_j"<<std::endl; Print_Weights_J(output_stream,index);}} } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Reinitialize() { if (draw){ if ((is_animation && frame_loaded != frame) || (!is_animation && frame_loaded < 0)){ valid = false; if(print_weights_i){ std::string tmp_i_filename=FILE_UTILITIES::Get_Frame_Filename(weights_i_filename.c_str(), frame); if (FILE_UTILITIES::File_Exists(tmp_i_filename)) FILE_UTILITIES::Read_From_File<RW>(tmp_i_filename,weights_to); else return;} if(print_weights_j){ std::string tmp_j_filename=FILE_UTILITIES::Get_Frame_Filename(weights_j_filename.c_str(), frame); if (FILE_UTILITIES::File_Exists(tmp_j_filename)) FILE_UTILITIES::Read_From_File<RW>(tmp_j_filename,weights_from); else return;} if(is_moving_grid){ std::string grid_filename=STRING_UTILITIES::string_sprintf(rigid_grid_frame_filename.c_str(),frame); if(FILE_UTILITIES::File_Exists(grid_filename)) FILE_UTILITIES::Read_From_File<T>(grid_filename,opengl_scalar_field.rigid_grid_frame);} std::string filename = FILE_UTILITIES::Get_Frame_Filename(scalar_field_filename, frame); if (FILE_UTILITIES::File_Exists(filename)) FILE_UTILITIES::Read_From_File<RW>(filename,opengl_scalar_field.values); else return; opengl_scalar_field.Update(); frame_loaded = frame; valid = true;}} } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Toggle_Smooth() { opengl_scalar_field.Toggle_Smooth_Texture(); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Toggle_Draw_Mode() { opengl_scalar_field.Toggle_Draw_Mode(); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Toggle_Color_Map() { opengl_scalar_field.Toggle_Color_Map(); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Toggle_Increase_Color_Map_Range() { opengl_scalar_field.Increase_Scale_Range(); } template<class T,class T2,class RW> void OPENGL_COMPONENT_SCALAR_FIELD_2D<T,T2,RW>:: Toggle_Decrease_Color_Map_Range() { opengl_scalar_field.Decrease_Scale_Range(); } template class OPENGL_COMPONENT_SCALAR_FIELD_2D<float,int,float>; template class OPENGL_COMPONENT_SCALAR_FIELD_2D<float,bool,float>; template class OPENGL_COMPONENT_SCALAR_FIELD_2D<float,float,float>; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class OPENGL_COMPONENT_SCALAR_FIELD_2D<double,int,double>; template class OPENGL_COMPONENT_SCALAR_FIELD_2D<double,bool,double>; template class OPENGL_COMPONENT_SCALAR_FIELD_2D<double,double,double>; #endif
@@ -1,12 +1,12 @@ jQuery(window).load(function($) { var $ = jQuery; $('img').each(function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { // image was broken, replace with your new image this.src = "http://placehold.it/" + ($(this).attr('width') || this.width || $(this).naturalWidth()) + "x" + (this.naturalHeight || $(this).attr('height') || $(this).height()); } }); $('img').each(function () { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { // image was broken, replace with your new image this.src = "http://placehold.it/" + ($(this).attr('width') || this.width || $(this).naturalWidth()) + "x" + (this.naturalHeight || $(this).attr('height') || $(this).height()); } }); }); //Radio, Checkbox and Select @@ -19,7 +19,7 @@ function formStylization() { $('input[type="checkbox"]:checked').parent('.new-checkbox').addClass('checked'); $('input[type="radio"]:checked').parent('.new-radio').addClass('checked'); $('input[type="radio"]:disabled, input[type="checkbox"]:disabled').parent().addClass('disabled'); $('html').click(function(){ $('html').click(function () { $('input[type="radio"]').parent('.new-radio').removeClass('checked'); $('input[type="radio"]:checked').parent('.new-radio').addClass('checked'); $('input[type="checkbox"]').parent('.new-checkbox').removeClass('checked'); @@ -28,129 +28,129 @@ function formStylization() { $('input[type="radio"]:disabled, input[type="checkbox"]:disabled').parent().addClass('disabled'); }); $('select').selectbox(); $('.home-filter .sbHolder, .ibr-properties-filter .sbHolder').each(function () { var element = $(this).find('ul.sbOptions li:first a'); var text = element.text(); var text = element.text(); element.html('- Any -'); }); $('body').on('change', 'select', function() { $('body').on('change', 'select', function () { $('#sbSelector_' + $(this).attr('sb')).text($(this).find('option:selected').text()); }); } //Home (Map) function optionHomeMap() { var $ = jQuery, filter = $('#main .home-filter'), filterContent = $('#main .home-filter .filter-content'), filterButton = $('#main .home-filter .filter-button'), filterHeight = $('#main .home-filter .filter-content').outerHeight(), filterWidth = $('#main .home-filter .filter-content').outerWidth(), filterButtonWidth = $('#main .home-filter .filter-button').outerWidth(), windowHeight = $('body').height(), windowWidth = $('body').width(), headerHeight = $('#site-header').outerHeight(), tabHeight = $('#main .home-tabs').outerHeight(), mapHeight = windowHeight - headerHeight - tabHeight, var $ = jQuery, filter = $('#main .home-filter'), filterContent = $('#main .home-filter .filter-content'), filterButton = $('#main .home-filter .filter-button'), filterHeight = $('#main .home-filter .filter-content').outerHeight(), filterWidth = $('#main .home-filter .filter-content').outerWidth(), filterButtonWidth = $('#main .home-filter .filter-button').outerWidth(), windowHeight = $('body').height(), windowWidth = $('body').width(), headerHeight = $('#site-header').outerHeight(), tabHeight = $('#main .home-tabs').outerHeight(), mapHeight = windowHeight - headerHeight - tabHeight, marginTop; if ((filter.hasClass('filter-position-right')) || ( windowHeight < ( headerHeight + filterHeight + tabHeight + 60 ))) { if ((filter.hasClass('filter-position-right')) || (windowHeight < (headerHeight + filterHeight + tabHeight + 60))) { marginTop = headerHeight + 30; } else { marginTop = ( mapHeight - filterHeight) / 2 + headerHeight; marginTop = (mapHeight - filterHeight) / 2 + headerHeight; } $('#map-canvas').css({ height : windowHeight, minHeight : headerHeight + filterHeight + tabHeight + 75, height: windowHeight, minHeight: headerHeight + filterHeight + tabHeight + 75, }); $('.overlay-filter').css({ top : headerHeight, bottom : filterHeight + tabHeight + 10, left : filterWidth - filterButtonWidth top: headerHeight, bottom: filterHeight + tabHeight + 10, left: filterWidth - filterButtonWidth }); if (filter.hasClass('open')) { if (filter.hasClass('filter-position-right') && $('body').width() >= 768) { filter.css({ left : windowWidth - filterButtonWidth - 30, top : headerHeight + 30 left: windowWidth - filterButtonWidth - 30, top: headerHeight + 30 }); } else { filter.css({ left : (windowWidth / 2) + (filterWidth / 2) - filterButtonWidth, top : marginTop left: (windowWidth / 2) + (filterWidth / 2) - filterButtonWidth, top: marginTop }); } } else { filterButton.html('Show filter <div class="flip"><span>+</span></div>'); filter.css({ left : windowWidth - 136, top : windowHeight - 109 left: windowWidth - 136, top: windowHeight - 109 }); } $(filterButton).click(function() { var windowHeight = $('body').height(), windowWidth = $('body').width(); $(filterButton).click(function () { var windowHeight = $('body').height(), windowWidth = $('body').width(); if (filter.hasClass('open')) { filterContent.fadeOut('400', function() { filterContent.fadeOut('400', function () { filter.animate({ left : windowWidth - 136, top : windowHeight - 109 }, 400); left: windowWidth - 136, top: windowHeight - 109 }, 400); filterButton.html('Show filter <div class="flip"><span>+</span></div>'); filter.removeClass('open', 400 ); filter.removeClass('open', 400); }); } else { filterButton.html('Hide <div class="flip"><span>&#8211;</span></div>'); if (filter.hasClass('filter-position-right')) { filter.animate({ left : windowWidth - filterButtonWidth - 30, top : headerHeight + 30 left: windowWidth - filterButtonWidth - 30, top: headerHeight + 30 }, 400, function(){ filterContent.fadeIn('400'); }); function () { filterContent.fadeIn('400'); }); } else { filter.animate({ left : (windowWidth / 2) + (filterWidth / 2) - filterButtonWidth, top : marginTop left: (windowWidth / 2) + (filterWidth / 2) - filterButtonWidth, top: marginTop }, 400, function(){ filterContent.fadeIn('400'); }); function () { filterContent.fadeIn('400'); }); } $(filter).addClass('open', 400 ); $(filter).addClass('open', 400); } return false; }); if ($('body').width() >= 980 ) { if ($('body').width() >= 980) { $("#main .home-filter").draggable({ containment: '.overlay-filter', cursor: 'move', handle: '.move', }); } } //Home (Best Agents) function optionHomeAgents() { var $ = jQuery, windowHeight = $('body').height(), carouselWidth = $('#main .home-agents .row').width(), siteHeader = $('#site-header').outerHeight(), agentsSize = $('#main .home-content .agent').length, gridMargim = $('#main .home-content .span4').css('margin-left'), marginTop = $('#main .home-agents .row'), var $ = jQuery, windowHeight = $('body').height(), carouselWidth = $('#main .home-agents .row').width(), siteHeader = $('#site-header').outerHeight(), agentsSize = $('#main .home-content .agent').length, gridMargim = $('#main .home-content .span4').css('margin-left'), marginTop = $('#main .home-agents .row'), contentHeight; if ($('body').hasClass('main-menu-visible') && $('body').width() >= 980 ) { if ($('body').hasClass('main-menu-visible') && $('body').width() >= 980) { contentHeight = windowHeight - siteHeader - 109; } else { contentHeight = windowHeight - siteHeader - 109; @@ -167,23 +167,23 @@ function optionHomeAgents() { if (marginTop621 < 0) { marginTop621 = 0; } $('#main .home-content .home-agents').css('height', contentHeight); if (carouselWidth > 1199) { if ( contentHeight > 700) { if (contentHeight > 700) { if (agentsSize > 6) { $('#main .home-content .home-carousel .span4:nth-child(3n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(3n)').each(function () { $(this).children('.agent').appendTo($(this).prev().prev()); $(this).remove(); }); $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); marginTop.css('marginTop', marginTop621); } else if (agentsSize < 7 && agentsSize > 3) { $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); @@ -193,7 +193,7 @@ function optionHomeAgents() { } } else if (contentHeight < 701 && contentHeight > 483) { if (agentsSize > 3) { $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); @@ -205,19 +205,19 @@ function optionHomeAgents() { marginTop.css('marginTop', marginTop187); } } else if (carouselWidth < 1200 && carouselWidth > 779) { if ( contentHeight > 700) { if (contentHeight > 700) { if (agentsSize > 4) { $('#main .home-content .home-carousel .span4:nth-child(3n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(3n)').each(function () { $(this).children('.agent').appendTo($(this).prev().prev()); $(this).remove(); }); $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); marginTop.css('marginTop', marginTop621); } else if (agentsSize < 5 && agentsSize > 2) { $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); @@ -227,7 +227,7 @@ function optionHomeAgents() { } } else if (contentHeight < 701 && contentHeight > 483) { if (agentsSize > 2) { $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); @@ -239,18 +239,18 @@ function optionHomeAgents() { marginTop.css('marginTop', marginTop187); } } else { if ( contentHeight > 700) { $('#main .home-content .home-carousel .span4:nth-child(3n)').each(function(){ if (contentHeight > 700) { $('#main .home-content .home-carousel .span4:nth-child(3n)').each(function () { $(this).children('.agent').appendTo($(this).prev().prev()); $(this).remove(); }); $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); marginTop.css('marginTop', marginTop621); } else if (contentHeight < 701 && contentHeight > 483) { $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function(){ $('#main .home-content .home-carousel .span4:nth-child(2n)').each(function () { $(this).children('.agent').appendTo($(this).prev()); $(this).remove(); }); @@ -263,16 +263,16 @@ function optionHomeAgents() { //Home (Best Properties) function optionHomeProperties() { var $ = jQuery, windowHeight = $('body').height(), var $ = jQuery, windowHeight = $('body').height(), carouselWidth = $('#main .properties .row').width(), siteHeader = $('#site-header').outerHeight(), propertySize = $('#main .home-content .property').length, gridMargim = $('#main .home-content .span3').css('margin-left'), marginTop = $('#main .home-content .properties .row'), siteHeader = $('#site-header').outerHeight(), propertySize = $('#main .home-content .property').length, gridMargim = $('#main .home-content .span3').css('margin-left'), marginTop = $('#main .home-content .properties .row'), contentHeight; if ($('body').hasClass('main-menu-visible') && $('body').width() >= 980 ) { if ($('body').hasClass('main-menu-visible') && $('body').width() >= 980) { contentHeight = windowHeight - siteHeader - 109; } else { contentHeight = windowHeight - siteHeader - 109; @@ -285,11 +285,11 @@ function optionHomeProperties() { if (marginTop620 < 0) { marginTop620 = 0; } $('#main .home-content .properties').css('height', contentHeight); if (carouselWidth > 1199) { if ( contentHeight >= 698 && propertySize > 4) { $('.home-content .home-carousel .span3:odd').each(function(){ if (contentHeight >= 698 && propertySize > 4) { $('.home-content .home-carousel .span3:odd').each(function () { $(this).children('.property').appendTo($(this).prev()); $(this).remove(); }); @@ -298,8 +298,8 @@ function optionHomeProperties() { marginTop.css('marginTop', marginTop296); } } else if (carouselWidth < 1200 && carouselWidth > 869) { if ( contentHeight >= 698 && propertySize > 3) { $('.home-content .home-carousel .span3:odd').each(function(){ if (contentHeight >= 698 && propertySize > 3) { $('.home-content .home-carousel .span3:odd').each(function () { $(this).children('.property').appendTo($(this).prev()); $(this).remove(); }); @@ -308,8 +308,8 @@ function optionHomeProperties() { marginTop.css('marginTop', marginTop296); } } else if (carouselWidth < 870 && carouselWidth > 559) { if ( contentHeight >= 698 && propertySize > 2) { $('.home-content .home-carousel .span3:odd').each(function(){ if (contentHeight >= 698 && propertySize > 2) { $('.home-content .home-carousel .span3:odd').each(function () { $(this).children('.property').appendTo($(this).prev()); $(this).remove(); }); @@ -318,8 +318,8 @@ function optionHomeProperties() { marginTop.css('marginTop', marginTop296); } } else { if ( contentHeight >= 698) { $('.home-content .home-carousel .span3:odd').each(function(){ if (contentHeight >= 698) { $('.home-content .home-carousel .span3:odd').each(function () { $(this).children('.property').appendTo($(this).prev()); $(this).remove(); }); @@ -333,58 +333,58 @@ function optionHomeProperties() { //Home (Best Property) function optionHomeProperty() { var $ = jQuery, windowHeight = $('body').height(), siteHeader = $('#site-header').outerHeight(), contentWidth = $('body').width(), contentHeight = windowHeight - siteHeader - 109; if (contentWidth/contentHeight > 1.8) { var $ = jQuery, windowHeight = $('body').height(), siteHeader = $('#site-header').outerHeight(), contentWidth = $('body').width(), contentHeight = windowHeight - siteHeader - 109; if (contentWidth / contentHeight > 1.8) { if ((contentHeight * 1.8) < 320) { $('#main .home-content .property-one .property').css('width', 320); } else { $('#main .home-content .property-one .property').css('width', contentHeight * 1.78); } } var propertyWidth = $('.property-one .property').outerWidth(), var propertyWidth = $('.property-one .property').outerWidth(), propertyHeight = $('.property-one .property').outerHeight(), propertyClass, marginTop; if (((contentHeight - (propertyWidth/1.8) - 50) / 2) > 0) { marginTop = (contentHeight - (propertyWidth/1.8) - 50) / 2; if (((contentHeight - (propertyWidth / 1.8) - 50) / 2) > 0) { marginTop = (contentHeight - (propertyWidth / 1.8) - 50) / 2; } else { marginTop = 0; } if (propertyWidth/propertyHeight < 1.8) { if (propertyWidth / propertyHeight < 1.8) { $('#main .home-content .property-one .property').css({ height : propertyWidth/1.8, marginTop : marginTop height: propertyWidth / 1.8, marginTop: marginTop }); } $('#main .home-content .property-one').css({ height : contentHeight, minHeight : contentHeight height: contentHeight, minHeight: contentHeight }); if (propertyWidth < 980 && propertyWidth > 768) { propertyClass = 'property-768'; } else if (propertyWidth < 768) { propertyClass = 'property-320'; } $('.property-one .property').addClass(propertyClass); $('.tooltip-link').tooltip(); } //Video Pley function playVideo() { var $ = jQuery; if ($('body').hasClass('ibr-tab-slider')) { var $ = jQuery; if ($('body').hasClass('ibr-tab-slider')) { $('.slider-slides .slide').each(function (i) { if ($(this).find('video').length) { if (i === 0) { @@ -395,173 +395,170 @@ function playVideo() { } } }); } } } //Home (Sliders) function optionHomeSliders() { var $ = jQuery, windowHeight = $('body').height(), siteHeader = $('#site-header').outerHeight(), contentWidth = $('body').width(), contentHeight = windowHeight - siteHeader, slider = $('#main .slider-content'), slide = $('#main .home-slider .slide'), slideContent = $('#main .home-slider.type-content .slide'), slideProperty = $('#main .home-slider.type-property .slide'); var $ = jQuery, windowHeight = $('body').height(), siteHeader = $('#site-header').outerHeight(), contentWidth = $('body').width(), contentHeight = windowHeight - siteHeader, slider = $('#main .slider-content'), slide = $('#main .home-slider .slide'), slideContent = $('#main .home-slider.type-content .slide'), slideProperty = $('#main .home-slider.type-property .slide'); $('#main .home-content .home-slider').css({ height : windowHeight, height: windowHeight, }); if (windowHeight < 700) { $('#main .home-content .home-slider').addClass('mini'); } else { $('#main .home-content .home-slider').removeClass('mini'); } if (slideContent.length) { $('#main .home-slider.type-content .slider-slides').carouFredSel({ responsive : true, auto : false, pagination : slider.find('.pagination'), next : slider.find('.next'), prev : slider.find('.prev'), swipe : { responsive: true, auto: false, pagination: slider.find('.pagination'), next: slider.find('.next'), prev: slider.find('.prev'), swipe: { onMouse: true, onTouch: true, }, height : 'auto', items : { height: 'auto', items: { visible: 1, }, scroll : { onAfter :function () { playVideo(); } scroll: { onAfter: function () { playVideo(); } } }); } if (slideProperty.length) { $('#main .home-slider.type-property .slider-slides').carouFredSel({ responsive : true, auto : { progress : { bar : slider.find('.timer'), responsive: true, auto: { progress: { bar: slider.find('.timer'), }, timeoutDuration : 4000, timeoutDuration: 4000, }, next : slider.find('.next'), prev : slider.find('.prev'), swipe : { next: slider.find('.next'), prev: slider.find('.prev'), swipe: { onMouse: true, onTouch: true, }, height : 'auto', items : { height: 'auto', items: { visible: 1, }, }); if ($('#main .home-slider.type-property .slide').length === 1) { $('#main .home-slider.type-property .timer').addClass('hidden'); } } //Natural width/height images var props = ['Width', 'Height'], prop; while (prop = props.pop()) { while (prop = props.pop()) { (function (natural, prop) { $.fn[natural] = (natural in new Image()) ? function () { return this[0][natural]; } : function () { var node = this[0], img, value; if (node.tagName.toLowerCase() === 'img') { img = new Image(); img.src = node.src; value = img[prop]; } return value; }; $.fn[natural] = (natural in new Image()) ? function () { return this[0][natural]; } : function () { var node = this[0], img, value; if (node.tagName.toLowerCase() === 'img') { img = new Image(); img.src = node.src; value = img[prop]; } return value; }; }('natural' + prop, prop.toLowerCase())); } var slideHeight = slide.outerHeight(), slideWidth = slide.outerWidth(); slide.each(function() { var slideImg = $(this).children('.slide-image').children('img'); } var slideHeight = slide.outerHeight(), slideWidth = slide.outerWidth(); slide.each(function () { var slideImg = $(this).children('.slide-image').children('img'); if (slideImg.length) { var slideImgWidthN = slideImg.naturalWidth(), slideImgHeightN = slideImg.naturalHeight(), var slideImgWidthN = slideImg.naturalWidth(), slideImgHeightN = slideImg.naturalHeight(), slideImgWidth, imgMarginLeft; if ((slideWidth / slideHeight) < (slideImgWidthN / slideImgHeightN)) { if ((slideWidth / slideHeight) < (slideImgWidthN / slideImgHeightN)) { slideImg.css({ height : '100%', maxWidth : 'inherit', minWidth : '100%', width : 'auto' height: '100%', maxWidth: 'inherit', minWidth: '100%', width: 'auto' }); slideImgWidth = slideImg.width(); slideImgWidth = slideImg.width(); imgMarginLeft = (slideWidth - slideImgWidth) / 2; slideImg.css({ marginLeft : imgMarginLeft marginLeft: imgMarginLeft }); } else { else { slideImg.css({ height : 'auto', maxWidth : '100%', width : '100%' height: 'auto', maxWidth: '100%', width: '100%' }); slideImgWidth = slideImg.width(); slideImgWidth = slideImg.width(); imgMarginLeft = (slideWidth - slideImgWidth) / 2; slideImg.css({ marginLeft : 0 marginLeft: 0 }); } } }); slide.each(function() { var slideVideo = $(this).children('.slide-image').children('video'), slideVideoHeight = slideVideo.height(), slideVideoWidth = slideVideo.width(), slide.each(function () { var slideVideo = $(this).children('.slide-image').children('video'), slideVideoHeight = slideVideo.height(), slideVideoWidth = slideVideo.width(), videoMarginLeft; if (slideVideoWidth > slideWidth) { slideVideo.css({ marginLeft : (slideWidth - slideVideoWidth) /2 marginLeft: (slideWidth - slideVideoWidth) / 2 }); } if (slideVideoWidth < slideWidth) { slideVideo.css({ height : 'auto', width : '100%', marginLeft : 0 height: 'auto', width: '100%', marginLeft: 0 }); } else { else { slideVideo.css({ height : '100%', width : 'auto', height: '100%', width: 'auto', }); } }); @@ -574,12 +571,12 @@ function homeCarousel() { $(this).carouFredSel({ scroll: 1, auto: false, infinite : false, infinite: false, height: 'auto', next: $(this).closest('.home-content').find('.next'), prev: $(this).closest('.home-content').find('.prev'), items: { width : 'variable' width: 'variable' }, pagination: { container: $(this).closest('.home-content').find('.scroll'), @@ -600,20 +597,20 @@ function carousel() { var $ = jQuery; $('.carousel-box .carousel').each(function () { var widget = $(this).parents('.carousel-box'); if ($(widget).hasClass('features-first') && $('body').width() <= 979) { $(this).closest('.carousel-box').find('.next').hide(); $(this).closest('.carousel-box').find('.prev').hide(); $('.carousel-box.features-first .carousel').trigger("destroy", true); } else { $(this).carouFredSel({ auto : false, infinite : false, scroll : 1, height : 'auto', next : $(this).closest('.carousel-box').find('.next'), prev : $(this).closest('.carousel-box').find('.prev'), swipe : { auto: false, infinite: false, scroll: 1, height: 'auto', next: $(this).closest('.carousel-box').find('.next'), prev: $(this).closest('.carousel-box').find('.prev'), swipe: { onMouse: true, onTouch: true, easing: 'linear' @@ -631,7 +628,7 @@ function properties() { $(this).carouFredSel({ responsive: true, auto: false, infinite : false, infinite: false, pagination: $(this).closest('.property').find('.pagination'), }).parents('.images-box').css("overflow", "visible"); } @@ -640,16 +637,16 @@ function properties() { //Property Carousel function propertyCarousel(selector) { var $ = jQuery; var $ = jQuery; if ((selector.find('a').length > 1) ){ if ((selector.find('a').length > 1)) { selector.carouFredSel({ responsive: true, auto: false, infinite : false, infinite: false, pagination: selector.closest('.property').find('.pagination'), }); } } } //Home Property @@ -659,14 +656,14 @@ function homeProperty() { $(this).carouFredSel({ responsive: true, auto: false, infinite : false, infinite: false, pagination: $(this).closest('.property').find('.pagination'), swipe: { onMouse: true, onTouch: true, easing: 'linear' }, height : 'auto', height: 'auto', items: { visible: 1, } @@ -679,45 +676,44 @@ function propertyView() { var $ = jQuery, thumbsDirection, thumbsVisible; if ($('body').width() >= 980) { thumbsDirection = 'up'; thumbsVisible = 4; } else { thumbsDirection = 'left'; thumbsVisible = null; } if ( $('body').width() >= 980 ) { $('#thumbs > div:odd').each(function(){ if ($('body').width() >= 980) { $('#thumbs > div:odd').each(function () { if ($(this).prev().find('a').length < 2) { $(this).children('a').addClass('two'); $(this).children('a').appendTo($(this).prev()); $(this).remove(); } }); } else { $('#thumbs > div').each(function(){ else { $('#thumbs > div').each(function () { if ($(this).find('a').length > 1) { $(this).children('a').removeClass('two'); $(this).before('<div></div>'); $(this).children('a:first').appendTo($(this).prev()); } }); } $('#thumbs a:first').addClass('selected'); $('#thumbs a').click(function() { $('.property-view .galery .images').trigger('slideTo', '#' + this.href.split('#').pop() ); $('#thumbs a').click(function () { $('.property-view .galery .images').trigger('slideTo', '#' + this.href.split('#').pop()); $('#thumbs a').removeClass('selected'); $(this).addClass('selected'); return false; }); $('.property-view .galery .images').each(function () { $(this).carouFredSel({ responsive: true, @@ -733,15 +729,15 @@ function propertyView() { }, }).parents('.galery').addClass('onload'); }); $('#thumbs').each(function () { $(this).carouFredSel({ circular: false, infinite: false, auto: false, prev: $('.thumbs-box .prev'), next: $('.thumbs-box .next'), direction : thumbsDirection, direction: thumbsDirection, items: { visible: thumbsVisible, }, @@ -756,48 +752,48 @@ function propertyView() { //Bg Sidebar function bgSidebar() { var $ = jQuery, pageHeader = $('.page-header').outerHeight(), windowWidth = $('body').width(), var $ = jQuery, pageHeader = $('.page-header').outerHeight(), windowWidth = $('body').width(), containerWidth = $('.container').width(), sidebarWidth = $('#sidebar').width(); sidebarWidth = $('#sidebar').width(); $('#sidebar .widget-area .aside-border').css('width', (windowWidth / 2) - (containerWidth / 2) + sidebarWidth); $('#sidebar .bg-sidebar').css({ 'top' : pageHeader, 'width' : (windowWidth / 2) - (containerWidth / 2) + sidebarWidth 'top': pageHeader, 'width': (windowWidth / 2) - (containerWidth / 2) + sidebarWidth }); } //Sidebar (width < 980) function sidebar() { var $ = jQuery, pageHeader = $('.page-header').outerHeight(), var $ = jQuery, pageHeader = $('.page-header').outerHeight(), primaryHeight = $('#sidebar .widget-area').height(); $('#primary').css('minHeight', primaryHeight - 50); if ($('body').width() <= 979 ) { if ($('body').width() <= 979) { $('#sidebar').css('marginTop', pageHeader); } else { $('#sidebar').css('marginTop', 0); } } function sidebarOpen() { var $ = jQuery, siteHeader = $('#site-header').outerHeight(), pageHeader = $('.page-header').outerHeight(), bodyHeight = $('#page').outerHeight(), footerHeight = $('#site-footer').outerHeight(), var $ = jQuery, siteHeader = $('#site-header').outerHeight(), pageHeader = $('.page-header').outerHeight(), bodyHeight = $('#page').outerHeight(), footerHeight = $('#site-footer').outerHeight(), primaryHeight = $('#sidebar .widget-area').height(); $('#primary').css('minHeight', primaryHeight - 50); if ($('body').width() <= 979 ) { if ($('body').width() <= 979) { $('#sidebar').css('marginTop', pageHeader); } $(window).scroll(function(){ if ($('body').width() <= 979 ) { $(window).scroll(function () { if ($('body').width() <= 979) { if ($(this).scrollTop() > siteHeader + pageHeader) { $('#sidebar .sidebar-button').addClass('scroll'); } else { @@ -808,48 +804,48 @@ function sidebarOpen() { } } }); $('#sidebar .sidebar-button').click(function(){ if ($('body').width() <= 979 ) { $('#sidebar .sidebar-button').click(function () { if ($('body').width() <= 979) { if ($('#sidebar').hasClass('open')) { $('#sidebar').removeClass('open'); if ($('#primary').hasClass('right-sidebar')) { $('#sidebar').animate({ marginRight: '-292' }, 500 ); if ($('body').width() >= 768 ) { $('#content').animate({ marginLeft: '20' }, 500 ); $('#sidebar').animate({ marginRight: '-292' }, 500); if ($('body').width() >= 768) { $('#content').animate({ marginLeft: '20' }, 500); } else { $('#content').animate({ marginLeft: '0' }, 500 ); $('#content').animate({ marginLeft: '0' }, 500); } } else { $('#sidebar').animate({ marginLeft: '-292' }, 500 ); if ($('body').width() >= 768 ) { $('#content').animate({ marginRight: '0' }, 500 ); $('#sidebar').animate({ marginLeft: '-292' }, 500); if ($('body').width() >= 768) { $('#content').animate({ marginRight: '0' }, 500); } else { $('#content').animate({ marginRight: '0' }, 500 ); $('#content').animate({ marginRight: '0' }, 500); } } } else { $('#sidebar').addClass('open'); if ($('#primary').hasClass('right-sidebar')) { $('#sidebar').animate({ marginRight: '0' }, 500 ); if ($('body').width() >= 768 ) { $('#content').animate({ marginLeft: '-292' }, 500 ); $('#sidebar').animate({ marginRight: '0' }, 500); if ($('body').width() >= 768) { $('#content').animate({ marginLeft: '-292' }, 500); } else { $('#content').animate({ marginLeft: '-312' }, 500 ); $('#content').animate({ marginLeft: '-312' }, 500); } } else { $('#sidebar').animate({ marginLeft: '0' }, 500 ); if ($('body').width() >= 768 ) { $('#content').animate({ marginRight: '-292' }, 500 ); $('#sidebar').animate({ marginLeft: '0' }, 500); if ($('body').width() >= 768) { $('#content').animate({ marginRight: '-292' }, 500); } else { $('#content').animate({ marginRight: '-312' }, 500 ); $('#content').animate({ marginRight: '-312' }, 500); } } } } return false; }); $('#sidebar > .close').click(function(){ $('#sidebar > .close').click(function () { $("#sidebar .sidebar-button").click(); return false; }); @@ -860,14 +856,14 @@ function moreMenu() { var $ = jQuery, moreWidth, menuWidth; if ($('body').width() >= 980) { var totalWidth = 0, closeWidth = $('#main-menu .close').outerWidth(), bodyWidth = $('body').width(); if ($('body').hasClass('main-menu-visible')) { $('#second-menu .menu > li').each( function () { $('#second-menu .menu > li').each(function () { totalWidth = totalWidth + $(this).width(); if (totalWidth > bodyWidth) { $(this).addClass('more-li'); @@ -876,7 +872,7 @@ function moreMenu() { } }); } else { $('#main-menu .main-navigation .menu > li').each( function () { $('#main-menu .main-navigation .menu > li').each(function () { totalWidth = totalWidth + $(this).outerWidth(); if (totalWidth > (bodyWidth - closeWidth)) { $(this).addClass('more-li'); @@ -885,33 +881,33 @@ function moreMenu() { } }); } if ($('body').hasClass('main-menu-visible')) { moreWidth = $('#second-menu .more-a').outerWidth(); menuWidth = $('#second-menu .menu').outerWidth(); if (bodyWidth < (menuWidth + moreWidth)) { $('#second-menu .menu li:last').addClass('more-li'); $('#second-menu .menu li:last').prependTo('#second-menu .more-ul'); } } else { moreWidth = $('#main-menu .more-a').outerWidth(); menuWidth = $('#main-menu .menu').outerWidth(); if (bodyWidth < (menuWidth + moreWidth + closeWidth)) { $('#main-menu .main-navigation .menu li:last').addClass('more-li'); $('#main-menu .main-navigation .menu li:last').prependTo('#main-menu .more-ul'); } } } else { if ($('body').hasClass('main-menu-visible')) { $('#second-menu .more-ul .more-li').each( function () { $('#second-menu .more-ul .more-li').each(function () { $('#second-menu .more').removeClass('visible'); $(this).appendTo('#second-menu .menu'); $(this).removeClass('more-li'); }); } else { $('#main-menu .more-ul .more-li').each( function () { $('#main-menu .more-ul .more-li').each(function () { $('#main-menu .more').removeClass('visible'); $(this).appendTo('#main-menu .menu'); $(this).removeClass('more-li'); @@ -922,46 +918,76 @@ function moreMenu() { } function imgProperies() { var $ = jQuery, imgBox = $('.properties-list .property .images-box'), var $ = jQuery, imgBox = $('.properties-list .property .images-box'), imgBoxWidth = imgBox.width(), img = $('.properties-list .property .images-box .images img'), imgWidth = img.width(); img = $('.properties-list .property .images-box .images img'), imgWidth = img.width(); if (imgWidth > imgBoxWidth) { img.each( function () { img.each(function () { img.css('marginLeft', (imgBoxWidth - imgWidth) / 2); }); } } // Search form function getPosition() { // If geolocation is available, try to get the visitor's position if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(successCallback, errorCallback); console.log("Getting the position information..."); } else { alert("Sorry, your browser does not support HTML5 geolocation."); } }; // Define callback function for successful attempt function successCallback(position) { console.log("Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")"); } // Define callback function for failed attempt function errorCallback(error) { if (error.code == 1) { console.log("User did not give permission to access location."); } else if (error.code == 2) { alert("The network is down or the positioning service can't be reached."); } else if (error.code == 3) { alert("The attempt timed out before it could get the location data."); } else { alert("Geolocation failed due to unknown error."); } } //Home Map function geocodePosition(pos, element) { var $ = jQuery; geocoder = new google.maps.Geocoder(); geocoder.geocode( {latLng: pos}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { { latLng: pos }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { var key = Math.floor(results['length'] / 2); $(element).parent().attr('title', results[key].formatted_address); $(element).replaceWith(results[key].formatted_address); } else { } else { $(element).replaceWith(ibr.adressError + ' ' + status); } } ); } jQuery(document).ready(function() { "use strict"; var $ = jQuery; jQuery(document).ready(function () { "use strict"; var $ = jQuery; $('body').on('click', 'video.slide-video', function () { if (this.paused) { this.play(); @@ -970,24 +996,24 @@ jQuery(document).ready(function() { this.pause(); } }); if ($('body').width() <= 1198 ) { if ($('body').width() <= 1198) { $('#main .home-slider .slide .slide-image video').remove(); } //Functions /* Radio, Checkbox and Select */ formStylization(); /* Home Tabs */ optionHomeMap(); optionHomeAgents(); optionHomeProperties(); optionHomeProperty(); optionHomeSliders(); /* Carousel */ $(window).bind({ load : function() { load: function () { carousel(); properties(); homeProperty(); @@ -998,19 +1024,19 @@ jQuery(document).ready(function() { } }); $(window).load(function() { $(window).load(function () { $('.home-tabs-overlay').css('display', 'none'); }); //Bootstrap Elements $('.tooltip-demo a').tooltip(); $('.tooltip-link').tooltip(); $('.nav-tabs a').click(function () { e.preventDefault(); $(this).tab('show'); }); $('.btn-loading').click(function () { var btn = $(this); btn.button('loading'); @@ -1021,133 +1047,133 @@ jQuery(document).ready(function() { $('.disabled').click(function () { return false; }); if ($('body').width() >= 980) { $('.fancybox').fancybox({ openEffect : 'fade', closeEffect : 'fade', prevEffect : 'fade', nextEffect : 'fade', helpers : { title : { type : 'inside' openEffect: 'fade', closeEffect: 'fade', prevEffect: 'fade', nextEffect: 'fade', helpers: { title: { type: 'inside' }, } }); } else { $('.property-view #content .galery .images a').click(function(){ $('.property-view #content .galery .images a').click(function () { return false; }); } //Accordion $('.accordion-group .accordion-body.in').parent().addClass('active'); $('.accordion-group .accordion-heading').click( function(e){ $('.accordion-group .accordion-heading').click(function (e) { var accordion = $(this).parent(); if ( accordion.hasClass('active')) { if (accordion.hasClass('active')) { accordion.removeClass('active'); } else { $('.accordion-group').removeClass('active'); accordion.addClass('active'); } }).dblclick(function(){ $(this).trigger( "click" ); }).dblclick(function () { $(this).trigger("click"); return false; }); $('.accordion-toggle').bind('touchstart', function(){ $('.accordion-toggle').bind('touchstart', function () { $(this).addClass('not-hover'); }); //Properties Options $('#main .property .options .bedrooms').each(function(){ $('#main .property .options .bedrooms').each(function () { $(this).css('right', $(this).next().width() + 40); }); $('#main .properties-list .property .options .bedrooms').each(function(){ $('#main .properties-list .property .options .bedrooms').each(function () { $(this).css('right', $(this).next().width() + 50); }); // Scroll to Top $('#up').click(function() { $('#up').click(function () { $('html, body').animate({ scrollTop: $('body').offset().top }, 500); return false; }); //Header Icons $('#site-header .header-icons-buttons a').click(function(){ $('#site-header .header-icons-buttons a').click(function () { $(this).effect('pulsate', { times: 1 }, 5); var $class = $(this).attr('href'), var $class = $(this).attr('href'), iconCount = $('#site-header .header-icons-buttons > a').length; if ($(this).hasClass('active')) { return false; } else { $('#site-header .header-icons-buttons a').removeClass('active prev'); $(this).addClass( 'active', 10, 'easeOutBounce'); $(this).addClass('active', 10, 'easeOutBounce'); if (iconCount < 3) { $(this).next().addClass( 'prev', 10, 'easeOutBounce'); $(this).prev().addClass( 'prev', 10, 'easeOutBounce'); $(this).next().addClass('prev', 10, 'easeOutBounce'); $(this).prev().addClass('prev', 10, 'easeOutBounce'); } else { if ($(this).hasClass('email')) { $('#site-header .header-icons-buttons .phone').addClass( 'prev', 10, 'easeOutBounce'); $('#site-header .header-icons-buttons .phone').addClass('prev', 10, 'easeOutBounce'); } else { $(this).prev().addClass('prev'); } } $('#site-header .header-icons-body > div').css('display', 'none'); $('#site-header .header-icons-body > div').removeClass('active'); $('#site-header .header-icons-body .' +$class).fadeIn('15000'); $('#site-header .header-icons-body .' +$class).addClass('active'); $('#site-header .header-icons-body .' + $class).fadeIn('15000'); $('#site-header .header-icons-body .' + $class).addClass('active'); return false; } }); //Main Menu $('#site-header .menu-button').click(function(){ $('#site-header .menu-button').click(function () { $('#main-menu .main-navigation, #second-menu').show('500'); $('#main-menu .bg-color, .second-bg').fadeIn('1000'); return false; }); $('#main-menu .close, #main-menu .bg-color').click(function(){ $('#main-menu .close, #main-menu .bg-color').click(function () { $('#main-menu .main-navigation').hide('500'); $('#main-menu .bg-color').fadeOut('1000'); return false; }); $('#second-menu .close, .second-bg').click(function(){ $('#second-menu .close, .second-bg').click(function () { $('#second-menu').hide('500'); $('.second-bg').fadeOut('1000'); return false; }); $('#main-menu .sub-menu, #second-menu .sub-menu').parent('li').addClass('parent'); if ($('body').width() <= 979 ) { if ($('body').width() <= 979) { $('#main-menu .sub-menu, #second-menu .sub-menu').prev('a').append('<span class="open-sub">+</span>'); } //Main Menu More moreMenu(); if (!$('body').hasClass('main-menu-visible')) { $('#site-header .menu-button').click(function(){ $('#site-header .menu-button').click(function () { moreMenu(); }); } $('#main-menu .open-sub , #second-menu .open-sub').toggle(function(){ if ($('body').width() <= 979 ) { $('#main-menu .open-sub , #second-menu .open-sub').toggle(function () { if ($('body').width() <= 979) { if ($(this).parent().next().hasClass('sub-menu') && $(this).parents('.parent').not('active')) { $(this).html('&#8211;'); $(this).parent().next('.sub-menu').slideDown(600); $(this).parents('.parent').addClass('active'); } } return false; }, function(){ if ($('body').width() <= 979 ) { }, function () { if ($('body').width() <= 979) { if ($(this).parent().next().hasClass('sub-menu')) { $(this).html('+'); $(this).parent().next('.sub-menu').slideUp(600); @@ -1156,11 +1182,11 @@ jQuery(document).ready(function() { } return false; }); //Sidebar menu $('#sidebar .sub-menu, #sidebar .children').prev('a').append('<span class="open-sub">+</span>'); $('#sidebar .sub-menu, #sidebar .children').parent('li').addClass('parent'); $('#sidebar a > .open-sub').toggle(function(){ $('#sidebar a > .open-sub').toggle(function () { if ($(this).parent().next().hasClass('sub-menu') && $(this).parents('.parent').not('active')) { $(this).html('&#8211;'); $(this).parent().next('.sub-menu').slideDown(600); @@ -1172,7 +1198,7 @@ jQuery(document).ready(function() { $(this).parents('.parent').addClass('active'); } return false; }, function(){ }, function () { if ($(this).parent().next().hasClass('sub-menu')) { $(this).html('+'); $(this).parent().next('.sub-menu').slideUp(600); @@ -1185,198 +1211,198 @@ jQuery(document).ready(function() { } return false; }); bgSidebar(); sidebar(); sidebarOpen(); //Meta Head if (document.width > 768) { $('.viewport').remove(); $('.viewport').remove(); } //Team $('body').bind('touchstart', function(e){ $('body').bind('touchstart', function (e) { if (!$(e.target).closest('.team-shortcode .team-member .worker-info').length) { $('.team-shortcode .team-member .worker-info').removeClass('hover'); } }); $('.team-shortcode .team-member .worker-info').bind('touchstart', function(){ $('.team-shortcode .team-member .worker-info').bind('touchstart', function () { if ($(this).hasClass('hover')) { $(this).removeClass('hover'); } else { $('.team-shortcode .team-member .worker-info').removeClass('hover'); $(this).addClass('hover'); } }); $('.team-shortcode .team-member .worker-info').mouseenter(function(){ $('.team-shortcode .team-member .worker-info').mouseenter(function () { $(this).addClass('hover'); }).mouseleave(function(){ }).mouseleave(function () { $(this).removeClass('hover'); }); }); //Carousel next/prev button (not active) $('.prev-next').bind('touchstart', function(){ $('.prev-next').bind('touchstart', function () { $(this).removeClass('not-hover'); }); $('.prev-next').bind('touchend', function(){ $('.prev-next').bind('touchend', function () { $(this).addClass('not-hover'); }); //Chart if ($('.graph-params .praph-param').length) { var line, lineX, lineY; var lineOne = []; $('.graph-params .praph-param').each( function () { $('.graph-params .praph-param').each(function () { lineX = $(this).attr('id'); lineY = $(this).attr('value'); lineOne.push([lineX, parseFloat(lineY)]); }); line = lineOne; var xtitle = $('#chart-param .title-x').attr('value'), ytitle = $('#chart-param .title-y').attr('value'), lineColor = $('#chart-param .linecolor').attr('value'); var plot1 = $.jqplot('chart', [line], { axes : { xaxis : { renderer : $.jqplot.DateAxisRenderer, label : xtitle, labelRenderer : $.jqplot.CanvasAxisLabelRenderer, tickOptions : { formatString:'%b.' axes: { xaxis: { renderer: $.jqplot.DateAxisRenderer, label: xtitle, labelRenderer: $.jqplot.CanvasAxisLabelRenderer, tickOptions: { formatString: '%b.' } }, yaxis : { tickOptions : { formatString : '' yaxis: { tickOptions: { formatString: '' }, label : ytitle, labelRenderer : $.jqplot.CanvasAxisLabelRenderer, label: ytitle, labelRenderer: $.jqplot.CanvasAxisLabelRenderer, } }, highlighter : { show : true, sizeAdjust : 10 highlighter: { show: true, sizeAdjust: 10 }, cursor : { show : false cursor: { show: false }, series : [ series: [ { lineWidth : 1, color : lineColor, lineWidth: 1, color: lineColor, }, ], grid : { drawGridLines : false, gridLineColor : 'none', background : 'none', borderColor : '#999999', borderWidth : 2, shadow : false, renderer : $.jqplot.CanvasGridRenderer, grid: { drawGridLines: false, gridLineColor: 'none', background: 'none', borderColor: '#999999', borderWidth: 2, shadow: false, renderer: $.jqplot.CanvasGridRenderer, }, }); } //Resize Window $( window ).resize(function() { delay( function() { $(window).resize(function () { delay(function () { if (document.width > 768) { $('.viewport').remove(); } else { $('head').append('<meta class="viewport" name="viewport" content="width=device-width, initial-scale=1.0">'); } //Chart if ($('.graph-params .praph-param').length) { plot1.replot( { resetAxes: true } ); plot1.replot({ resetAxes: true }); } //Sidebar sidebar(); bgSidebar(); if ($('body').width() >= 979 ) { if ($('body').width() >= 979) { $('#content').removeAttr('style', 'margin-left'); $('#sidebar').removeClass('open'); $('#sidebar').removeAttr('style', 'margin-right'); } //Home restructured carousel $('#main .home-content .home-carousel .span4').each(function(){ $(this).children('.agent').each( function(){ $('#main .home-content .home-carousel .span4').each(function () { $(this).children('.agent').each(function () { $(this).appendTo($(this).parent().parent()).wrap('<div class="span4"></div>'); }); }); $('#main .home-content .home-carousel .span4').each(function(){ $('#main .home-content .home-carousel .span4').each(function () { if ($(this).children('.agent').length == 0) { $(this).remove(); } }); $('#main .home-content .home-carousel .span3').each(function(){ $(this).children('.property').each( function(){ $('#main .home-content .home-carousel .span3').each(function () { $(this).children('.property').each(function () { $(this).appendTo($(this).parent().parent()).wrap('<div class="span3"></div>'); }); }); $('#main .home-content .home-carousel .span3').each(function(){ $('#main .home-content .home-carousel .span3').each(function () { if ($(this).children('.property').length == 0) { $(this).remove(); } }); //Home Tabs optionHomeMap(); optionHomeAgents(); optionHomeProperties(); optionHomeProperty(); optionHomeSliders(); //Carousel carousel(); properties(); homeProperty(); propertyView(); homeCarousel(); imgProperies(); //Menu if ($('body').width() >= 979 ) { if ($('body').width() >= 979) { $('#second-menu').removeAttr('style', 'display'); $('.second-bg').css('display', 'none'); } moreMenu(); if (!$('body').hasClass('main-menu-visible')) { $('#site-header .menu-button').click(function(){ $('#site-header .menu-button').click(function () { moreMenu(); }); } $('#main-menu .open-sub, #second-menu .open-sub').remove(); if ($('body').width() <= 979 ) { if ($('body').width() <= 979) { $('#main-menu .sub-menu, #second-menu .sub-menu').prev('a').append('<span class="open-sub">+</span>'); } $('#main-menu .open-sub , #second-menu .open-sub').toggle(function(){ if ($('body').width() <= 979 ) { $('#main-menu .open-sub , #second-menu .open-sub').toggle(function () { if ($('body').width() <= 979) { if ($(this).parent().next().hasClass('sub-menu') && $(this).parents('.parent').not('active')) { $(this).html('&#8211;'); $(this).parent().next('.sub-menu').slideDown(600); $(this).parents('.parent').addClass('active'); } } return false; }, function(){ if ($('body').width() <= 979 ) { }, function () { if ($('body').width() <= 979) { if ($(this).parent().next().hasClass('sub-menu')) { $(this).html('+'); $(this).parent().next('.sub-menu').slideUp(600); @@ -1385,19 +1411,19 @@ jQuery(document).ready(function() { } return false; }); }, 'resize' ); }, 'resize'); }); var delay = ( function() { var timeout = { }; return function( callback, id, time ) { if( id !== null ) { time = ( time !== null ) ? time : 100; clearTimeout( timeout[ id ] ); timeout[ id ] = setTimeout( callback, time ); var delay = (function () { var timeout = {}; return function (callback, id, time) { if (id !== null) { time = (time !== null) ? time : 100; clearTimeout(timeout[id]); timeout[id] = setTimeout(callback, time); } }; })();
<reponame>MultiDigital/gatsby-starter-default import React from "react" import { useStaticQuery, graphql } from "gatsby" import { LanguageSwitcherContext } from "../context/languageSwitcherContext" export const useFooter = () => { const menu = useStaticQuery(graphql` query FooterQuery { allDatoCmsFooter( filter: { root: { eq: true }, anchor: { ne: null } } sort: { fields: position, order: ASC } ) { nodes { id locale root anchor link { ... on DatoCmsInternalLink { id anchor locale model { apiKey } link { ... on DatoCmsBlogPage { ...BlogDetails } ... on DatoCmsPage { ...PageDetails ...PageTreeParent ...AllSlugLocales } ... on DatoCmsArticle { ...ArticleDetails ...ArticleAllSlugLocales } ... on DatoCmsArticleCategory { ...ArticleCategoryDetails ...ArticleCategoryAllSlugLocales } } } ... on DatoCmsExternalLink { id anchor url model { apiKey } } } treeChildren { id locale root anchor position link { ... on DatoCmsInternalLink { id anchor locale model { apiKey } link { ... on DatoCmsBlogPage { ...BlogDetails } ... on DatoCmsPage { ...PageDetails ...PageTreeParent ...AllSlugLocales } ... on DatoCmsArticle { ...ArticleDetails ...ArticleAllSlugLocales } ... on DatoCmsArticleCategory { ...ArticleCategoryDetails ...ArticleCategoryAllSlugLocales } } } ... on DatoCmsExternalLink { id anchor url model { apiKey } } } treeChildren { id locale root anchor link { ... on DatoCmsInternalLink { id anchor locale model { apiKey } link { ... on DatoCmsBlogPage { ...BlogDetails } ... on DatoCmsPage { ...PageDetails ...PageTreeParent ...AllSlugLocales } ... on DatoCmsArticle { ...ArticleDetails ...ArticleAllSlugLocales } ... on DatoCmsArticleCategory { ...ArticleCategoryDetails ...ArticleCategoryAllSlugLocales } } } ... on DatoCmsExternalLink { id anchor url model { apiKey } } } } } } } } `) const locale = React.useContext(LanguageSwitcherContext).activeLocale const i18nFooter = menu.allDatoCmsFooter.nodes.filter( link => link.locale === locale ) return i18nFooter }
(function() { 'use strict'; angular .module('app.services') .factory('stationVideos', stationVideos); stationVideos.$inject = ['$resource']; function stationVideos($resource) { var customInterceptor = { response: function(response) { return response; } }; return { getVideoUrls: getVideoUrls, getVideoUrlsAscendingByLimit: getVideoUrlsAscendingByLimit, getVideoUrlsDescendingByLimit: getVideoUrlsDescendingByLimit }; function getVideoUrls(stationId, fromTimestamp, toTimestamp, limit) { var resource = $resource('/api/video_urls_by_station/:station_id/:from_timestamp/:to_timestamp/:limit', {}, { query: { method: 'GET', params: { station_id: stationId, from_timestamp: fromTimestamp, to_timestamp: toTimestamp, limit: limit }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, from_timestamp: fromTimestamp, to_timestamp: toTimestamp, limit: limit }).$promise .then(getVideoUrlsComplete) .catch(getVideoUrlsFailed); function getVideoUrlsComplete(response) { return response; } function getVideoUrlsFailed(error) { console.log(error); } } function getVideoUrlsToTimestamp(stationId, toTimestamp, limit) { var resource = $resource('/api/video_urls_by_station/:station_id/:to_timestamp/:limit', {}, { query: { method: 'GET', params: { station_id: stationId, to_timestamp: toTimestamp, limit: limit }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, to_timestamp: toTimestamp, limit: limit }).$promise .then(getVideoUrlsComplete) .catch(getVideoUrlsFailed); function getVideoUrlsComplete(response) { return response; } function getVideoUrlsFailed(error) { console.log(error); } } function getVideoUrlsAscendingByLimit(stationId, limit) { var resource = $resource('/api/video_urls_by_station_asc_limit/:station_id/:limit', {}, { query: { method: 'GET', params: { station_id: stationId, limit: limit }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, limit: limit }).$promise .then(getVideoUrlsAscendingByLimitComplete) .catch(getVideoUrlsAscendingByLimitFailed); function getVideoUrlsAscendingByLimitComplete(response) { return response; } function getVideoUrlsAscendingByLimitFailed(error) { console.log(error); } } function getVideoUrlsDescendingByLimit(stationId, limit) { var resource = $resource('/api/video_urls_by_station_desc_limit/:station_id/:limit', {}, { query: { method: 'GET', params: { station_id: stationId, limit: limit }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, limit: limit }).$promise .then(getVideoUrlsDescendingByLimitComplete) .catch(getVideoUrlsDescendingByLimitFailed); function getVideoUrlsDescendingByLimitComplete(response) { return response; } function getVideoUrlsDescendingByLimitFailed(error) { console.log(error); } } } })();
<gh_stars>0 // // ModesInfoViewController.h // raspberryCar // // Created by <NAME> on 29.02.2016. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "TCPConnection.h" @interface ModesInfoViewController : UIViewController @property TCPConnection* tcpConnection; @property (strong, nonatomic) IBOutlet UITextView *info; @property NSInteger chosenInfo; @end
HTTP_PORT=3004 P2P_PORT=6004 PEERS=ws://localhost:6001 npm start
// Code to convert from Fahrenheit to Celsius #include <iostream> int main() { float fahrenheit; std::cout << "Enter temperature in fahrenheit: "; std::cin >> fahrenheit; float celsius = (fahrenheit - 32.0) / 1.8; std::cout << celsius << " C"; return 0; }
<reponame>ojcastaneda/osu-stamina-trainer-web import {faCheck, faTrashAlt} from '@fortawesome/free-solid-svg-icons'; import LanguageContext from '../../../contexts/languageContext'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import {Button, Card, Col, Row, Table} from 'react-bootstrap'; import SessionContext from '../../../contexts/sessionContext'; import {refreshPage} from '../../sharedResources'; import {toast} from 'react-toastify'; import {useContext} from 'react'; const Submission = props => { const {submission, page, setPage} = props; const session = useContext(SessionContext); const language = useContext(LanguageContext); const approveSubmission = async event => { const response = await fetch(`${process.env.REACT_APP_SERVER_API}web/submissions/${submission.id}/approve`, { method: 'PUT', headers: { Authorization: session.token, Accept: 'application/json', 'Content-Type': 'text/plain' } }); if (response.ok) { toast.success(language.submissionListUpdated); refreshPage(page, setPage); } else { toast.warning(language.serverOverloaded); } }; const removeSubmission = async () => { const response = await fetch(`${process.env.REACT_APP_SERVER_API}web/submissions/${submission.id}`, { method: 'DELETE', headers: { Authorization: session.token, Accept: 'application/json', 'Content-Type': 'application/json' } }); if (response.ok) { toast.success(language.submissionListUpdated); refreshPage(page, setPage); } }; return (<Row> <Card className="shadow mb-3"> <Card.Body> <Row> <Col className="d-block d-md-none"> <Table> <tbody> <tr> <td>{language.beatmapId}:</td> <td>{submission.id}</td> </tr> <tr> <td>{language.status}:</td> <td>{language[submission.status]}</td> </tr> </tbody> </Table> </Col> <Col className="select-cursor m-auto d-none d-md-block text-center" onClick={() => window.open(`https://osu.ppy.sh/beatmaps/${submission.id}`)}> {submission.id} </Col> <Col className="m-auto d-none d-md-block text-center"> {submission.approved !== 'waiting_processing' && language[submission.approved]} {submission.approved === 'waiting_processing' && language.waitingForProcessing} </Col> {submission.approved !== 'pending' && <Col className="d-none d-md-block"/>} {submission.approved === 'pending' && (<> <Col className="mb-3 mb-md-0 col-12 col-md"> <Button className="container-fluid" variant="success" onClick={approveSubmission}> <FontAwesomeIcon icon={faCheck}/> </Button> </Col> </>)} <Col className="mb-3 mb-md-0 col-12 col-md"> <Button className="container-fluid" variant="danger" onClick={removeSubmission}> <FontAwesomeIcon icon={faTrashAlt}/> </Button> </Col> </Row> </Card.Body> </Card> </Row>); }; export default Submission;
package com.ashok.csv.typeinference; import org.junit.Assert; import org.junit.Test; public class InferTypeImplTest { @Test public void inferTypeTest() throws Exception { String [] firstDataRow = {"2019-05-15 09:15:02","2105","2125.55","2084.6","2090.2"}; InferType inferType = new InferTypeImpl(); Assert.assertEquals(inferType.inferType(firstDataRow[0]),"String"); Assert.assertEquals(inferType.inferType(firstDataRow[1]),"Double"); Assert.assertEquals(inferType.inferType(firstDataRow[2]),"Double"); Assert.assertEquals(inferType.inferType(firstDataRow[3]),"Double"); Assert.assertEquals(inferType.inferType(firstDataRow[4]),"Double"); } }
#!/bin/sh -x # Change Me: base directory configuation # SDK Release ID export RELEASE_ID=SDK10.0-PR2003 # Platform ID (cn83xx,cn81xx,cn913x etc) export SOC_PLATFORM=cn83xx # TODO: delete me # Build directory; place all tarballs here #export BASE_HOME=$HOME/build_${SOC_PLATFORM} # Work directory ; change this according to builds (armada/cn83xx etc) export BUILD_DIR_HOME=$HOME/work_${SOC_PLATFORM}_${RELEASE_ID} # Main SDK tarball export SDK_TARBALL=$HOME/base_sdk-${RELEASE_ID}.zip # toolchain export MARVELL_TOOLCHAIN_HOME=marvell-tools-238.0 export TOOLCHAIN_TARBALL=${HOME}/toolchain-238.tar.bz2 # Env Variables export TOOLS_HOME=$HOME/marvell export BASE_SRC=base-sources-${RELEASE_ID} export BASE_SRC_TARBALL=${BUILD_DIR_HOME}/${BASE_SRC}.tar.bz2 export SRC_BUILDROOT=sources-buildroot-${RELEASE_ID} export SRC_BUILDROOT_TARBALL=${BUILD_DIR_HOME}/${SRC_BUILDROOT}.tar.bz2 export SRC_BUILDROOT_EXT=sources-buildroot-external-marvell-${RELEASE_ID} export SRC_BUILDROOT_EXT_TARBALL=${BUILD_DIR_HOME}/${SRC_BUILDROOT_EXT}.tar.bz2 export DPDK_VERSION=dpdk-18.11-rc export LINUX_VERSION=linux-4.14.76-rc export TFTPBOOT_DIR=/tftpboot export MUSDK_INSTALL_DIR=$TFTPBOOT_DIR/lib/modules/4.14.76-devel-19.02.1/kernel/drivers/musdk export BASE_SOURCE=sources-buildroot-SDK10.0 export DATAPLANE_SOURCE=dataplane-sources-rc export SOURCES_LINUX=sources-$LINUX_VERSION export SOURCES_DPDK=sources-$DPDK_VERSION export SOURCES_MUSDK=sources-musdk-marvell-rc export ARCH=arm64 export CROSS_COMPILE=aarch64-marvell-linux-gnu- export CROSS=$CROSS_COMPILE export KDIR=$BUILD_DIR_HOME/$LINUX_VERSION-$RELEASE_ID export RTE_KERNELDIR=$KDIR export RTE_TARGET=arm64-armada-linuxapp-gcc export LIBMUSDK_HOME_PATH=$BUILD_DIR_HOME/musdk-marvell-rc-$RELEASE_ID export LIBMUSDK_PATH=$LIBMUSDK_HOME_PATH/usr/local if [[ x$SOC_PLATFORM =~ ^xcn8[1,3]xx$ ]] ; then export DPDK_HOME=$BUILD_DIR_HOME/$SOC_PLATFORM-release-output/build/dpdk else export DPDK_HOME=$BUILD_DIR_HOME/$DPDK_VERSION-$RELEASE_ID fi export DPDK_SHARE_FOR_EXAMPLES=$TFTPBOOT_DIR/usr/local/dpdk/share/dpdk if [[ ! -d $DPDK_SHARE_FOR_EXAMPLES ]] ; then mkdir -p $DPDK_SHARE_FOR_EXAMPLES fi export OVS_VERSION=2.11.1 export OVS_DIR=openvswitch-$OVS_VERSION export OVS_TARBALL_PATH=https://www.openvswitch.org/releases/$OVS_DIR.tar.gz #export OVS_MOUNT_DISK_PATH=$TFTPBOOT_DIR export OVS_MOUNT_DISK_PATH=$HOME/marvell/disk # Set the path to access Toolchain export PATH=$HOME:$BUILD_DIR_HOME/$MARVELL_TOOLCHAIN_HOME/bin:$PATH
<filename>test/fragments/custom/nowarn/obsolete/deprecated-usage.d.ts /** * @deprecated use something else */ interface I {} type T = string | I;
#!/bin/bash JBMC_PATH=$1 shift JQ_COMMAND=$1 shift $JBMC_PATH "$@" | jq -c "$JQ_COMMAND"
import sys import atexit def override_exception_hooks(): def excepthook(*args): import traceback traceback.print_exception(*args) sys.excepthook = excepthook def restrict_module_access(): if 'PyQt4.QtGui' in sys.modules: sys.modules['PyQt4.QtGui'].QApplication = None sys.modules.pop('PyQt4.QtGui', None) sys.modules.pop('PyQt4.QtCore', None) def sabotage_atexit_callbacks(): atexit._exithandlers = [(func, args, kwargs) for func, args, kwargs in atexit._exithandlers if 'sensitive_cleanup' not in str(func)]
<reponame>yuansfer/yuansfer-payment-android package com.yuansfer.paysdk.model; import android.os.Parcel; import android.text.TextUtils; import java.util.HashMap; /** * @Author Fly * @CreateDate 2019/5/29 15:44 * @Desciption 订单状态 */ public class DetailInfo extends SignInfo { private String reference; private String transactionNo; public DetailInfo() { } public DetailInfo(Parcel in) { super(in); this.setReference(in.readString()); this.setTransactionNo(in.readString()); } public String getReference() { return reference; } /** * reference和transactionNo二选一 * * @param reference 流水号 */ public void setReference(String reference) { this.reference = reference; } public String getTransactionNo() { return transactionNo; } /** * reference和transactionNo二选一 * * @param transactionNo 订单号 */ public void setTransactionNo(String transactionNo) { this.transactionNo = transactionNo; } @Override public HashMap<String, String> toHashMap() { HashMap<String, String> paramMap = super.toHashMap(); if (!TextUtils.isEmpty(reference)) { paramMap.put("reference", reference); } if (!TextUtils.isEmpty(transactionNo)) { paramMap.put("transactionNo", transactionNo); } return paramMap; } public static final Creator<DetailInfo> CREATOR = new Creator<DetailInfo>() { public DetailInfo createFromParcel(Parcel source) { return new DetailInfo(source); } public DetailInfo[] newArray(int size) { return new DetailInfo[size]; } }; @Override public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(getReference()); dest.writeString(getTransactionNo()); } }
#!/usr/bin/env bash function helm_package() { chart_dir="$1" chart_name="$(basename "${chart_dir}")" echo "==> Packaging chart: ${chart_name}" ${HELM} package \ --debug \ --destination ./archives \ ${chart_dir} } function main() { echo "==> Helm version: ${HELM_VERSION}" export -f helm_package find ./charts/ \ -mindepth 1 \ -maxdepth 1 \ -type d \ -exec bash -c 'helm_package "$0"' {} \; } main
def preOrder(root): if root: # First print the data of node print(root.val) # Then recur on left child preOrder(root.left) # Finally recur on right child preOrder(root.right)
def words = ["level", "radar", "giraffe", "kayak"] words.each { word -> def reversedWord = word.reverse() if (word == reversedWord) { println(word) } }
<reponame>Spark-DS/logic-schema-demo package sparkDS.logicSchema.demo.dataSpec import org.scalatest._ import sparkDS.logicSchema.demo.dataSpec.dataFiles.OrderFile import sparkDS.logicSchema.demo.testData.TestDataFile class DataValidationTest extends FlatSpec with Matchers with BeforeAndAfterAll { "========================================================================================================================" + "\nCase 1 - Data validation of valid order file" should "return true" in { val orderDF = TestDataFile.validOrderDF val validatedOrderDF = OrderFile.validateData(orderDF) validatedOrderDF.printSchema() validatedOrderDF.show(999, truncate = false) val invalidDF = validatedOrderDF.filter("size(logic_validation_result) > 0") println("\n\ninvalidDF:") invalidDF.show(999, truncate = false) println("\n\n") val isValidDF = invalidDF.isEmpty // Force to materialize assert(isValidDF, "Validation of valid order file failed") } "\nCase 2 - Data validation of invalid order file" should "return false" in { val orderDF = TestDataFile.invalidOrderDF val validatedOrderDF = OrderFile.validateData(orderDF) validatedOrderDF.printSchema() validatedOrderDF.show(999, truncate = false) val invalidDF = validatedOrderDF.filter("size(logic_validation_result) > 0") println("\n\ninvalidDF:") invalidDF.show(999, truncate = false) println("\n\n") val isValidDF = invalidDF.isEmpty // Force to materialize assert(!isValidDF, "Validation of invalid order file failed") assert(invalidDF.count() == 2, "Count of invalid records did not match") } }
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../shared/to_i', __FILE__) require File.expand_path('../shared/integer_rounding', __FILE__) describe "Integer#ceil" do it_behaves_like(:integer_to_i, :ceil) it_behaves_like(:integer_rounding_positive_precision, :ceil) ruby_version_is "2.4" do context "precision argument specified as part of the ceil method is negative" do it "returns the smallest integer greater than self with at least precision.abs trailing zeros" do 18.ceil(-1).should eql(20) 18.ceil(-2).should eql(100) 18.ceil(-3).should eql(1000) -1832.ceil(-1).should eql(-1830) -1832.ceil(-2).should eql(-1800) -1832.ceil(-3).should eql(-1000) end end end end
#ifndef INCLUDED_PLATFORM_SERIALIZE_VEC4_H #define INCLUDED_PLATFORM_SERIALIZE_VEC4_H #include "platform/i_platform.h" namespace boost { namespace serialization { template<class Archive> void serialize( Archive & ar, glm::vec4 & g, const unsigned int version ) { ar & g.x; ar & g.y; ar & g.z; ar & g.w; } template<class Archive> void serialize( Archive & ar, glm::vec3 & g, const unsigned int version ) { ar & g.x; ar & g.y; ar & g.z; } template<class Archive> void serialize( Archive & ar, glm::vec2 & g, const unsigned int version ) { ar & g.x; ar & g.y; } } // namespace serialization } // namespace boost #endif // INCLUDED_PLATFORM_SERIALIZE_VEC4_H
function replacePlaceholders(string $template, array $values): string { foreach ($values as $key => $value) { $placeholder = '{$' . $key . '}'; $template = str_replace($placeholder, $value, $template); } return $template; }
#include <stdio.h> #include <drivers/gpio.h> #include "gpio.h" static const struct device *dev = NULL; void dutchess_gpio_init () { #ifdef CONFIG_BOARD_MIMXRT1020_EVK dev = device_get_binding("GPIO_1"); #endif } void dutchess_gpio_configure (int pin) { #ifdef CONFIG_BOARD_MIMXRT1020_EVK gpio_pin_configure(dev, pin, GPIO_OUTPUT_ACTIVE); #endif } void dutchess_gpio_set (int pin, int value) { #ifdef CONFIG_BOARD_MIMXRT1020_EVK gpio_pin_set(dev, pin, value); #endif } int dutchess_gpio_get (int pin) { int value = 0; #ifdef CONFIG_BOARD_MIMXRT1020_EVK value = gpio_pin_get(dev, pin); #endif return value; }
import React from 'react'; import { FaFacebook, FaInstagram, FaYoutube, FaTwitter, FaLinkedin } from 'react-icons/fa'; import { FooterContainer, SocialMedia, SocialMediaWrap, WebsiteRights, SocialIcons, SocialIconLink } from './footerElement'; function Footer() { return ( <FooterContainer> <SocialMedia> <SocialMediaWrap> <WebsiteRights>Hack Odisha © {new Date().getFullYear()} All rights reserved.</WebsiteRights> <SocialIcons> <SocialIconLink href='https://www.facebook.com/hackodisha' target='_blank' aria-label='Facebook'> <FaFacebook /> </SocialIconLink> <SocialIconLink href='https://www.instagram.com/webwiz.nitr/' target='_blank' aria-label='Instagram'> <FaInstagram /> </SocialIconLink> <SocialIconLink href='https://twitter.com/hackodisha' target='_blank' aria-label='Twitter'> <FaTwitter /> </SocialIconLink> <SocialIconLink href='https://www.linkedin.com/company/hackodisha/' target='_blank' aria-label='LinkedIn'> <FaLinkedin /> </SocialIconLink> </SocialIcons> </SocialMediaWrap> </SocialMedia> </FooterContainer> ); } export default Footer;
# NOTE - the arguments: $1 should be the serverId and $2 should be the number of servers cd .. && mvn clean package sudo -u postgres psql -d sec$1 -a -f secure-server/src/main/java/META-INF/drop-tables.sql java -jar secure-server/target/secure-server-1.0.jar --server.port=920$1 $1 $2 --spring.datasource.url=jdbc:postgresql://localhost:5432/sec$1 | tee deploy/logs/server$1_log.txt & # Wait for the server to initiate the database before inserting the data sleep 15 sudo -u postgres psql -d sec$1 -a -f secure-server/src/main/java/META-INF/load-script.sql echo "SERVERs DEPLOY DONE, START CLIENTS NOW" read CONT ps axf | grep secure-server | grep -v grep | awk '{print "kill -9 " $1}' | sh
#!/bin/sh F=/tmp/delivery_count if [ ! -f $F ] ; then echo "1" > $F else i=`cat $F` i=$(($i+1)) echo $i > $F fi
<gh_stars>1-10 package cucumber.runtime.io; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; public class FileResourceTest { @Test public void get_path_should_return_short_path_when_root_same_as_file() { // setup FileResource toTest = new FileResource(new File("test1/test.feature"), new File("test1/test.feature")); // test assertEquals("test1" + File.separator + "test.feature", toTest.getPath()); } @Test public void get_path_should_return_truncated_path_when_absolute_file_paths_are_input() { // setup FileResource toTest = new FileResource(new File("/testPath/test1"), new File("/testPath/test1/test.feature")); // test assertEquals("test.feature", toTest.getPath()); } }
<filename>src/api/interfaces/IConfig.ts interface IConfig { ip: string; port: string; environment: string; mongodb: { uri: string; }, auth: { secret: string; }, email: { host: string; port: number; secure: boolean; pool: boolean; secureConnection: boolean; auth: { user: string; pass: string; } tls: { rejectUnauthorized: boolean; } }, firebase: { apiKey: string; authDomain: string; projectId: string; storageBucket: string; messagingSenderId: string; appId: string; measurementId: string; serviceAccount: string; } } export type { IConfig };
<reponame>domagojlatecki/fnc-lab package at.doml.fnc.lab1 import java.text.DecimalFormat import at.doml.fnc.lab1.domain.{Domain, DomainElement} import at.doml.fnc.lab1.set.FuzzySet object Debug { private val formatter = new DecimalFormat("0.000000") def print(domain: Domain, heading: String): Unit = { this.printHeadingAndDomainElements(heading, domain) { e => println(s"Domain element: $e") } println(s"Cardinality: ${domain.cardinality}") println() } def print(set: FuzzySet, heading: String): Unit = { this.printHeadingAndDomainElements(heading, set.domain) { e => println(s"d($e) = ${this.formatter.format(set.getValueAt(e))}") } println() } private def printHeadingAndDomainElements(heading: String, domain: Domain)(printFn: DomainElement => Unit): Unit = { if (heading != null) { println(heading) } for (e <- domain) { printFn(e) } } }
<reponame>tanishq-arya/Rotten-Scripts import os import platform if(platform.system()[1].lower() == 'windows'): # For Windows Operating System. try: os.system("pip install -r Windows/requirements.txt") except Exception: print("Something went Wrong.!") else: # Unix Based Systems i.e include (Linux/Mac OSX) etc try: os.system("pip3 install -r Unix/requirements.txt") except Exception: print("Something went Wrong.!")
#!/bin/bash ########################################################################## #Aqueduct - Compliance Remediation Content #Copyright (C) 2011,2012 # Vincent C. Passaro (vincent.passaro@gmail.com) # Shannon Mitchell (shannon.mitchell@fusiontechnology-llc.com) # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; either version 2 #of the License, or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, #Boston, MA 02110-1301, USA. ########################################################################## ###################### Fotis Networks LLC ############################### # By Vincent C. Passaro # # Fotis Networks LLC # # Vincent[.]Passaro[@]fotisnetworks[.]com # # www.fotisnetworks.com # ###################### Fotis Networks LLC ############################### # # _____________________________________________________________________ # | Version | Change Information | Author | Date | # |__________|_______________________|____________________|____________| # | 1.0 | Initial Script | Vincent C. Passaro | 1-Aug-2012 | # | | Creation | | | # |__________|_______________________|____________________|____________| # #######################DISA INFORMATION################################## # Group ID (Vulid): V-1026 # Group Title: GEN006080 # Rule ID: SV-37870r1_rule # Severity: medium # Rule Version (STIG-ID): GEN006080 # Rule Title: The Samba Web Administration Tool (SWAT) must be restricted # to the local host or require SSL. # # Vulnerability Discussion: SWAT is a tool used to configure Samba. It # modifies Samba configuration, which can impact system security, and must # be protected from unauthorized access. SWAT authentication may involve # the root password, which must be protected by encryption when traversing # the network. # Restricting access to the local host allows for the use of SSH TCP # forwarding, if configured, or administration by a web browser on the # local system. # # Responsibility: System Administrator # IAControls: EBRP-1, ECCT-1, ECCT-2 # # Check Content: # # SWAT is a tool for configuring Samba and should only be found on a # system with a requirement for Samba. If SWAT is used, it must be utilized # with SSL to ensure a secure connection between the client and the server. # Procedure: # grep -H "bin/swat" /etc/xinetd.d/*|cut -d: -f1 |xargs grep "only_from" # If the value of the "only_from" line in the "xinetd.d" file which starts # "/usr/sbin/swat" is not "localhost" or the equivalent, this is a finding. # # Fix Text: # # Disable SWAT or require SWAT is only accessed via SSH. # Procedure: # If SWAT is not needed for operation of the system remove the SWAT package: # rpm -qa|grep swat # Remove "samba-swat" or "samba3x-swat" depending on which one is installed # rpm --erase samba-swat # or # rpm --erase samba3x-swat # If SWAT is required but not at all times disable it when it is not needed. # Modify the /etc/xinetd.d file for "swat" to contain a "disable = yes" # line. # To access using SSH: # Follow vendor configuration documentation to create an stunnel for SWAT. #######################DISA INFORMATION################################## # Global Variables PDI=GEN006080 # Start-Lockdown
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-shuffled/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-shuffled/512+512+512-NER-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_named_entities_first_third_sixth --eval_function penultimate_sixth_eval
#!/bin/bash # Copyright 2017-2020 Authors of Cilium # SPDX-License-Identifier: Apache-2.0 set -o errexit set -o pipefail set -o nounset MAKER_IMAGE="${MAKER_IMAGE:-quay.io/cilium/image-maker:ca3f9135c0c8cb88c979f829d93a167838776615@sha256:b64f9168f52dae5538cd8ca06922e522eb84e36d3f727583c352266e3ed15894}" root_dir="$(git rev-parse --show-toplevel)" if [ -z "${MAKER_CONTAINER+x}" ] ; then exec docker run --rm --volume "${root_dir}:/src" --workdir /src/images "${MAKER_IMAGE}" "/src/images/scripts/$(basename "${0}")" fi # shellcheck disable=SC2207 scripts=($(find . -name '*.sh' -executable)) for script in "${scripts[@]}" ; do shellcheck --external-source --source-path="$(dirname "${script}")" "${script}" done
#!/bin/bash # De DEM wordt uitgeknipt uit de gebiedsdekkende DEM, de verrasterde watervlakken worden gebruikt om de DEM # dicht te smeren. # Een masker wordt gemaakt van de DEM om data/nodata pixels te onderscheiden. Gebiedsdekkende bodemberging # (ghg, glg, ggg), frictie en infiltratie raster worden op dit masker geprojecteerd en gecomprimeerd. PS=$(python /code/modelbuilder/pixelsize.py "/code/tmp/rasters/tmp/channelsurface.tif") echo $PS gdalwarp -cutline /code/tmp/rasters/tmp/polder.shp -tr $PS $PS -tap -crop_to_cutline -srcnodata -9999 -dstnodata -9999 -co "COMPRESS=DEFLATE" /code/data/fixed_data/DEM/dem.vrt /code/tmp/rasters/tmp/raw_dem_clipped.tif echo INFO smeer watergangen dicht gdalwarp -ot Float32 -dstnodata -9999 -tr $PS $PS -tap /code/tmp/rasters/tmp/raw_dem_clipped.tif /code/tmp/rasters/tmp/channelsurface.tif /code/tmp/rasters/tmp/temp.tif echo INFO pas compressie toe op DEM gdal_translate -ot Float32 -co "COMPRESS=DEFLATE" /code/tmp/rasters/tmp/temp.tif /code/tmp/rasters/dem_$2.tif echo INFO Knip bodemberging, frictie en infiltratie uit gebiedsbrede rasters echo ----------------------------------- echo INFO maak raster met enen voor extent gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/dem_$2.tif --outfile /code/tmp/rasters/tmp/enenraster_ongec.tif --calc="1" echo INFO maak rasters om te vullen gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/dem_$2.tif --outfile /code/tmp/rasters/tmp/vulraster_ghg_ongec.tif --calc="0" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/dem_$2.tif --outfile /code/tmp/rasters/tmp/vulraster_glg_ongec.tif --calc="0" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/dem_$2.tif --outfile /code/tmp/rasters/tmp/vulraster_ggg_ongec.tif --calc="0" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/dem_$2.tif --outfile /code/tmp/rasters/tmp/vulraster_friction.tif --calc="0.2" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/dem_$2.tif --outfile /code/tmp/rasters/tmp/vulraster_infiltration.tif --calc="0" echo INFO plak de waarden voor bodemberging hier in gdalwarp /code/data/fixed_data/other/bodemberging_verhard_hhnk.tif /code/data/fixed_data/other/bodemberging_hhnk_ghg_m.tif /code/tmp/rasters/tmp/vulraster_ghg_ongec.tif gdalwarp /code/data/fixed_data/other/bodemberging_verhard_hhnk.tif /code/data/fixed_data/other/bodemberging_hhnk_ggg_m.tif /code/tmp/rasters/tmp/vulraster_ggg_ongec.tif gdalwarp /code/data/fixed_data/other/bodemberging_verhard_hhnk.tif /code/data/fixed_data/other/bodemberging_hhnk_glg_m.tif /code/tmp/rasters/tmp/vulraster_glg_ongec.tif gdalwarp /code/data/fixed_data/other/friction_hhnk.tif /code/tmp/rasters/tmp/vulraster_friction.tif gdalwarp /code/data/fixed_data/other/infiltratie_hhnk.tif /code/tmp/rasters/tmp/vulraster_infiltration.tif echo INFO pas extent toe op gevulde rasters gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/tmp/enenraster_ongec.tif -B /code/tmp/rasters/tmp/vulraster_ghg_ongec.tif --outfile /code/tmp/rasters/tmp/vulraster_ghg_ongec_ext.tif --calc="A*B" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/tmp/enenraster_ongec.tif -B /code/tmp/rasters/tmp/vulraster_ggg_ongec.tif --outfile /code/tmp/rasters/tmp/vulraster_ggg_ongec_ext.tif --calc="A*B" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/tmp/enenraster_ongec.tif -B /code/tmp/rasters/tmp/vulraster_glg_ongec.tif --outfile /code/tmp/rasters/tmp/vulraster_glg_ongec_ext.tif --calc="A*B" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/tmp/enenraster_ongec.tif -B /code/tmp/rasters/tmp/vulraster_friction.tif --outfile /code/tmp/rasters/tmp/vulraster_friction_ext.tif --calc="A*B" gdal_calc.py --co="COMPRESS=DEFLATE" --NoDataValue -9999 -A /code/tmp/rasters/tmp/enenraster_ongec.tif -B /code/tmp/rasters/tmp/vulraster_infiltration.tif --outfile /code/tmp/rasters/tmp/vulraster_infiltration_ext.tif --calc="A*B" echo INFO comprimeer eindresultaat gdal_translate -co "COMPRESS=DEFLATE" /code/tmp/rasters/tmp/vulraster_ghg_ongec_ext.tif /code/tmp/rasters/storage_ghg_$2.tif gdal_translate -co "COMPRESS=DEFLATE" /code/tmp/rasters/tmp/vulraster_ggg_ongec_ext.tif /code/tmp/rasters/storage_ggg_$2.tif gdal_translate -co "COMPRESS=DEFLATE" /code/tmp/rasters/tmp/vulraster_glg_ongec_ext.tif /code/tmp/rasters/storage_glg_$2.tif gdal_translate -co "COMPRESS=DEFLATE" /code/tmp/rasters/tmp/vulraster_friction_ext.tif /code/tmp/rasters/friction_$2.tif gdal_translate -co "COMPRESS=DEFLATE" /code/tmp/rasters/tmp/vulraster_infiltration_ext.tif /code/tmp/rasters/infiltration_$2.tif echo INFO verwijder tijdelijke bestanden rm /code/tmp/rasters/tmp -rf cp -r /code/tmp/rasters/ /code/data/output/models/rasters rm /code/tmp -rf echo Klaar tmp_data
<gh_stars>1-10 import should from 'should' import BigNumber from 'bignumber.js' import jibrelContractsApi from '../index.js' if (process.env.JSON_PATH == null) { throw (new Error('JSON_PATH env variable not found')) } const testParams = require(process.env.JSON_PATH) const controller = jibrelContractsApi.contracts.controller const erc20Mintable = jibrelContractsApi.contracts.erc20Mintable const rpcaddr = process.env.RPCADDR || '127.0.0.1' const rpcport = process.env.RPCPORT || 8545 const contractAddressController = testParams.contracts.JNTController const contractAddress = testParams.contracts.JNTViewERC20 const privateKey = testParams.privateKeys[4] // privateKey of managerMint const account = testParams.accounts[7] // address of testInvestor1 const value = new BigNumber(1, 10) describe('ERC20Mintable API', function() { // timeout should be increased to wait while transaction was mined this.timeout(100000) describe('MintEvent', function() { let isDone it('returns event emitter for MintEvent event', function(done) { erc20Mintable.MintEvent({ rpcaddr, rpcport, contractAddress, }).then((result) => { const eeMint = result eeMint.on('data', (event) => { event.should.be.an.Object() event.logIndex.should.be.a.Number() event.transactionIndex.should.be.a.Number() event.transactionHash.should.be.a.String() event.transactionHash.length.should.be.equal(66) event.transactionHash.should.match(/^0x[a-fA-F0-9]+/) event.blockHash.should.be.a.String() event.blockNumber.should.be.a.Number() event.address.should.be.a.String() event.type.should.be.a.String() event.event.should.be.equal('MintEvent') event.args.should.be.an.Object() event.args.owner.should.be.equal(account) event.args.value.equals(new BigNumber(value)).should.be.equal(true) // ignore, if this test has already done if (isDone) { return } isDone = true done() }) eeMint.on('error', (err) => { done(err) }) controller.mint({ rpcaddr, rpcport, privateKey, account, value, contractAddress: contractAddressController, }).catch(done) }).catch(done) }) it('wait while "mint" transaction was mined', function(done) { this.timeout(30000); setTimeout(done, 25000); }); describe('returns error', function() { describe('because options', function(done) { it('is invalid (wrong type)', function(done) { erc20Mintable.MintEvent({ rpcaddr, rpcport, contractAddress, options: 123, }).then(() => { done(new Error('Exception was not thrown')) }).catch((err) => { err.should.be.an.Object() err.message.should.be.equal( 'ValidationError: child "options" fails because ["options" must be an object]' ) done() }) }) // MintEvent returns error because options is invalid (wrong type) it('is invalid (wrong key of object)', function(done) { erc20Mintable.MintEvent({ rpcaddr, rpcport, contractAddress, options: { foo: 'bar' }, }).then(() => { done(new Error('Exception was not thrown')) }).catch((err) => { err.should.be.an.Object() err.message.should.be.equal( 'ValidationError: child "options" fails because ["foo" is not allowed]' ) done() }) }) // MintEvent returns error because options is invalid (wrong key of object) }) // MintEvent returns error because options describe('because callback', function(done) { it('is invalid (wrong type)', function(done) { erc20Mintable.MintEvent({ rpcaddr, rpcport, contractAddress, callback: 123, }).then(() => { done(new Error('Exception was not thrown')) }).catch((err) => { err.should.be.an.Object() err.message.should.be.equal( 'ValidationError: child "callback" fails because ["callback" must be a Function]' ) done() }) }) // MintEvent returns error because callback is invalid (wrong type) }) // MintEvent returns error because callback }) // MintEvent returns error }) /** * NOTE: burn of tokens is not working * TODO: investigate an issue and unskip these tests */ describe.skip('BurnEvent', function() { let isDone it('returns event emitter for BurnEvent event', function(done) { erc20Mintable.BurnEvent({ rpcaddr, rpcport, contractAddress, }).then((result) => { const eeMint = result eeMint.on('data', (event) => { event.should.be.an.Object() event.logIndex.should.be.a.Number() event.transactionIndex.should.be.a.Number() event.transactionHash.should.be.a.String() event.transactionHash.length.should.be.equal(66) event.transactionHash.should.match(/^0x[a-fA-F0-9]+/) event.blockHash.should.be.a.String() event.blockNumber.should.be.a.Number() event.address.should.be.a.String() event.type.should.be.a.String() event.event.should.be.equal('BurnEvent') event.args.should.be.an.Object() event.args.owner.should.be.equal(account) event.args.value.equals(new BigNumber(value)).should.be.equal(true) // ignore, if this test has already done if (isDone) { return } isDone = true done() }) eeMint.on('error', (err) => { done(err) }) controller.burn({ rpcaddr, rpcport, privateKey, account, value, contractAddress: contractAddressController, }).catch(done) }).catch(done) }) it('wait while "burn" transaction was mined', function(done) { this.timeout(30000); setTimeout(done, 25000); }); describe('returns error', function() { describe('because options', function(done) { it('is invalid (wrong type)', function(done) { erc20Mintable.BurnEvent({ rpcaddr, rpcport, contractAddress, options: 123, }).then(() => { done(new Error('Exception was not thrown')) }).catch((err) => { err.should.be.an.Object() err.message.should.be.equal( 'ValidationError: child "options" fails because ["options" must be an object]' ) done() }) }) // BurnEvent returns error because options is invalid (wrong type) it('is invalid (wrong key of object)', function(done) { erc20Mintable.BurnEvent({ rpcaddr, rpcport, contractAddress, options: { foo: 'bar' }, }).then(() => { done(new Error('Exception was not thrown')) }).catch((err) => { err.should.be.an.Object() err.message.should.be.equal( 'ValidationError: child "options" fails because ["foo" is not allowed]' ) done() }) }) // BurnEvent returns error because options is invalid (wrong key of object) }) // BurnEvent returns error because options describe('because callback', function(done) { it('is invalid (wrong type)', function(done) { erc20Mintable.BurnEvent({ rpcaddr, rpcport, contractAddress, callback: 123, }).then(() => { done(new Error('Exception was not thrown')) }).catch((err) => { err.should.be.an.Object() err.message.should.be.equal( 'ValidationError: child "callback" fails because ["callback" must be a Function]' ) done() }) }) // BurnEvent returns error because callback is invalid (wrong type) }) // BurnEvent returns error because callback }) // BurnEvent returns error }) describe('allEvents', function() { let isDone it('returns event emitter for all events', function(done) { erc20Mintable.allEvents({ rpcaddr, rpcport, contractAddress, }).then((result) => { const eeAllEvents = result eeAllEvents.on('data', (event) => { event.should.be.an.Object() event.logIndex.should.be.a.Number() event.transactionIndex.should.be.a.Number() event.transactionHash.should.be.a.String() event.transactionHash.length.should.be.equal(66) event.transactionHash.should.match(/^0x[a-fA-F0-9]+/) event.blockHash.should.be.a.String() event.blockNumber.should.be.a.Number() event.address.should.be.a.String() event.type.should.be.a.String() event.event.should.be.equal('MintEvent') event.args.should.be.an.Object() event.args.owner.should.be.equal(account) event.args.value.equals(new BigNumber(value)).should.be.equal(true) // ignore, if this test has already done if (isDone) { return } isDone = true done() }) eeAllEvents.on('error', (err) => { done(err) }) controller.mint({ rpcaddr, rpcport, privateKey, account, value, contractAddress: contractAddressController, }).catch(done) }).catch(done) }) it('wait while "mint" transaction was mined', function(done) { this.timeout(30000); setTimeout(done, 25000); }); }) describe('getPastEvents', function() { const eventName = 'MintEvent' it('returns past MintEvent events', function(done) { erc20Mintable.getPastEvents({ rpcaddr, rpcport, contractAddress, event: eventName, }).then((result) => { const logs = result result.should.be.an.Array() result.length.should.be.greaterThan(0) const event = result[0] event.should.be.an.Object() event.logIndex.should.be.a.Number() event.transactionIndex.should.be.a.Number() event.transactionHash.should.be.a.String() event.transactionHash.length.should.be.equal(66) event.transactionHash.should.match(/^0x[a-fA-F0-9]+/) event.blockHash.should.be.a.String() event.blockNumber.should.be.a.Number() event.address.should.be.a.String() event.type.should.be.a.String() event.event.should.be.equal(eventName) event.args.should.be.an.Object() event.args.owner.should.be.equal(account) event.args.value.equals(new BigNumber(value)).should.be.equal(true) done() }).catch(done) }) }) })
<gh_stars>0 import React from "react"; import styled from "styled-components"; const Overlay = ({ show, closeSideDrawer }) => show ? <Container onClick={closeSideDrawer} /> : null; const Container = styled.div` position: fixed; top: 0; left: 0; height: 100%; width: 100%; background-color: rgba(0, 0, 0, 0.3); z-index: 9998; `; export default Overlay;
<filename>vendor/plugins/geocoder/lib/geocoder/lookups/yandex.rb require 'geocoder/lookups/base' require "geocoder/results/yandex" module Geocoder::Lookup class Yandex < Base def map_link_url(coordinates) "http://maps.yandex.ru/?ll=#{coordinates.reverse.join(',')}" end private # --------------------------------------------------------------- def results(query, reverse = false) return [] unless doc = fetch_data(query, reverse) if err = doc['error'] warn "Yandex Geocoding API error: #{err['status']} (#{err['message']})." return [] end if doc = doc['response']['GeoObjectCollection'] meta = doc['metaDataProperty']['GeocoderResponseMetaData'] return meta['found'].to_i > 0 ? doc['featureMember'] : [] else warn "Yandex Geocoding API error: unexpected response format." return [] end end def query_url(query, reverse = false) query = query.split(",").reverse.join(",") if reverse params = { :geocode => query, :format => "json", :plng => "#{Geocoder::Configuration.language}", # supports ru, uk, be :key => Geocoder::Configuration.api_key } "http://geocode-maps.yandex.ru/1.x/?" + hash_to_query(params) end end end
import UIKit class WaterViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Set up UI elements setupUI() } func setupUI() { // Create text fields to record water intake let waterIntake = UITextField(frame: CGRect(x: 10, y: 50, width: 300, height: 40)) waterIntake.text = "Enter water intake" waterIntake.borderStyle = .roundedRect self.view.addSubview(waterIntake) // Create button to save water intake let saveButton = UIButton(frame: CGRect(x: 10, y: 100, width: 300, height: 40)) saveButton.setTitle("Save", for: .normal) saveButton.backgroundColor = UIColor.blue saveButton.addTarget(self, action: #selector(saveWaterIntake), for: .touchUpInside) self.view.addSubview(saveButton) } @objc func saveWaterIntake() { // Save water intake } }
package registrationclass; import products.Product; import products.dumplings.Salmon; import products.pasta.Bolognese; import products.pizza.Italiana; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; public class ReflectionFactory { private static ReflectionFactory instance; private Map<String, Class<? extends Product>> registeredTypes = new HashMap() {{ put("salmon", Salmon.class); put("italiana", Italiana.class); put("Bolognese", Bolognese.class); }}; private ReflectionFactory() { } public static ReflectionFactory getInstance() { if (instance == null) instance = new ReflectionFactory(); return instance; } public void registerProduct(String type, Class<? extends Product> _class) { registeredTypes.put(type, _class); } public Product getProduct(String type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<?> clazz = registeredTypes.get(type); if (clazz == null){ throw new IllegalArgumentException(); } Constructor productConstructor = clazz.getDeclaredConstructor(); return (Product) productConstructor.newInstance(new Object[]{}); } public String orderProduct(String type) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { return getProduct(type).order(); } }
#! /usr/bin/env bash set -e # # The follow block is based on code from tiangolo/gunicorn-uvicorn-docker # MIT License: https://github.com/tiangolo/gunicorn-uvicorn-docker/blob/master/LICENSE # if [ -f /app/app/worker.py ]; then DEFAULT_MODULE_NAME=app.worker elif [ -f /app/worker.py ]; then DEFAULT_MODULE_NAME=worker fi MODULE_NAME=${MODULE_NAME:-$DEFAULT_MODULE_NAME} VARIABLE_NAME=${VARIABLE_NAME:-celery} export APP_MODULE=${APP_MODULE:-"$MODULE_NAME.$VARIABLE_NAME"} # If there's a prestart.sh script in the /app directory or other path specified, run it before starting PRE_START_PATH=${PRE_START_PATH:-/app/prestart.sh} echo "Checking for script in $PRE_START_PATH" if [ -f $PRE_START_PATH ] ; then echo "Running prestart script $PRE_START_PATH" . "$PRE_START_PATH" else echo "There is no prestart script at $PRE_START_PATH" fi # # End of tiangolo/gunicorn-uvicorn-docker block # if [[ "$ENABLE_BEAT" == "true" ]]; then COMMAND="python -m celery -A $APP_MODULE beat -s /var/celery/celerybeat-schedule" else POOL=${POOL:-prefork} if [[ "$POOL" = "gevent" ]] || [[ "$POOL" = "eventlet" ]] ; then CONCURRENCY=${CONCURRENCY:-100} else CONCURRENCY=${CONCURRENCY:-2} fi COMMAND="python -m celery -A $APP_MODULE worker \ --pool=$POOL \ --concurrency=$CONCURRENCY \ --prefetch-multiplier=${PREFETCH_MULTIPLIER:-4}" if [[ ! -z "$QUEUES" ]]; then COMMAND="$COMMAND --queues=$QUEUES" fi fi COMMAND="$COMMAND --loglevel=${LOG_LEVEL:-INFO}" echo $COMMAND $COMMAND
<gh_stars>0 import React from 'react'; import { storiesOf } from '@storybook/react'; import { Title } from './Title'; import { BlueTitle } from './BlueTitle'; const stories = storiesOf('Button', module); stories.add('Default', () => <Title>Title</Title>); stories.add('Blue Title', () => <BlueTitle>Title</BlueTitle>);
module Travis module Addons module Sqwiggle require 'travis/addons/sqwiggle/instruments' require 'travis/addons/sqwiggle/event_handler' class Task < ::Travis::Task; end end end end
<reponame>blkmajik/hyperglass<filename>hyperglass/ui/components/table/main.tsx<gh_stars>100-1000 // This rule isn't needed because react-table does this for us, for better or worse. /* eslint react/jsx-key: 0 */ import dynamic from 'next/dynamic'; import { Flex, Icon, Text } from '@chakra-ui/react'; import { usePagination, useSortBy, useTable } from 'react-table'; import { useMobile } from '~/context'; import { CardBody, CardFooter, CardHeader, If } from '~/components'; import { TableMain } from './table'; import { TableCell } from './cell'; import { TableHead } from './head'; import { TableRow } from './row'; import { TableBody } from './body'; import { TableIconButton } from './button'; import { TableSelectShow } from './pageSelect'; import type { TableOptions, PluginHook } from 'react-table'; import type { TCellRender } from '~/types'; import type { TTable } from './types'; const ChevronRight = dynamic<MeronexIcon>(() => import('@meronex/icons/fa').then(i => i.FaChevronRight), ); const ChevronLeft = dynamic<MeronexIcon>(() => import('@meronex/icons/fa').then(i => i.FaChevronLeft), ); const ChevronDown = dynamic<MeronexIcon>(() => import('@meronex/icons/fa').then(i => i.FaChevronDown), ); const DoubleChevronRight = dynamic<MeronexIcon>(() => import('@meronex/icons/fi').then(i => i.FiChevronsRight), ); const DoubleChevronLeft = dynamic<MeronexIcon>(() => import('@meronex/icons/fi').then(i => i.FiChevronsLeft), ); export const Table: React.FC<TTable> = (props: TTable) => { const { data, columns, heading, Cell, rowHighlightBg, striped = false, rowHighlightProp, bordersVertical = false, bordersHorizontal = false, } = props; const isMobile = useMobile(); const defaultColumn = { minWidth: 100, width: 150, maxWidth: 300, }; const hiddenColumns = [] as string[]; for (const col of columns) { if (col.hidden) { hiddenColumns.push(col.accessor); } } const options = { columns, defaultColumn, data, initialState: { hiddenColumns }, } as TableOptions<TRoute>; const plugins = [useSortBy, usePagination] as PluginHook<TRoute>[]; const instance = useTable<TRoute>(options, ...plugins); const { page, gotoPage, nextPage, pageCount, prepareRow, canNextPage, pageOptions, setPageSize, headerGroups, previousPage, getTableProps, canPreviousPage, state: { pageIndex, pageSize }, } = instance; return ( <CardBody> {heading && <CardHeader>{heading}</CardHeader>} <TableMain {...getTableProps()}> <TableHead> {headerGroups.map((headerGroup, i) => ( <TableRow index={i} {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map(column => ( <TableCell as="th" align={column.align} {...column.getHeaderProps()} {...column.getSortByToggleProps()} > <Text fontSize="sm" fontWeight="bold" display="inline-block"> {column.render('Header')} </Text> <If c={column.isSorted}> <If c={typeof column.isSortedDesc !== 'undefined'}> <Icon as={ChevronDown} boxSize={4} ml={1} /> </If> <If c={!column.isSortedDesc}> <Icon as={ChevronRight} boxSize={4} ml={1} /> </If> </If> <If c={!column.isSorted}>{''}</If> </TableCell> ))} </TableRow> ))} </TableHead> <TableBody> {page.map((row, key) => { prepareRow(row); return ( <TableRow index={key} doStripe={striped} highlightBg={rowHighlightBg} doHorizontalBorders={bordersHorizontal} highlight={row.values[rowHighlightProp ?? ''] ?? false} {...row.getRowProps()} > {row.cells.map((cell, i) => { const { column, row, value } = cell as TCellRender; return ( <TableCell align={cell.column.align} bordersVertical={[bordersVertical, i]} {...cell.getCellProps()} > {typeof Cell !== 'undefined' ? ( <Cell column={column} row={row} value={value} /> ) : ( cell.render('Cell') )} </TableCell> ); })} </TableRow> ); })} </TableBody> </TableMain> <CardFooter> <Flex direction="row"> <TableIconButton mr={2} onClick={() => gotoPage(0)} isDisabled={!canPreviousPage} icon={<Icon as={DoubleChevronLeft} boxSize={4} />} /> <TableIconButton mr={2} onClick={() => previousPage()} isDisabled={!canPreviousPage} icon={<Icon as={ChevronLeft} boxSize={3} />} /> </Flex> <Flex justifyContent="center" alignItems="center"> <Text fontSize="sm" mr={4} whiteSpace="nowrap"> Page{' '} <strong> {pageIndex + 1} of {pageOptions.length} </strong>{' '} </Text> {!isMobile && ( <TableSelectShow value={pageSize} onChange={e => { setPageSize(Number(e.target.value)); }} /> )} </Flex> <Flex direction="row"> <TableIconButton ml={2} onClick={nextPage} isDisabled={!canNextPage} icon={<Icon as={ChevronRight} boxSize={3} />} /> <TableIconButton ml={2} isDisabled={!canNextPage} icon={<Icon as={DoubleChevronRight} boxSize={4} />} onClick={() => gotoPage(pageCount ? pageCount - 1 : 1)} /> </Flex> </CardFooter> </CardBody> ); };
# Action: # Kill clients by ssh-ing into client machines export APT=1 if [ $APT -eq 1 ] then for i in `seq 2 110`; do ssh -oStrictHostKeyChecking=no node-$i.RDMA.fawn.apt.emulab.net "cd HERD; ./local-kill.sh" & done else for i in `seq 2 20`; do ssh anuj$i.RDMA.fawn.susitna.pdl.cmu.local "cd HERD; ./local-kill.sh" done fi
mkdir -p ~/facs-seq_test/joined/models nohup python ~/facs-seq/models/model_trainer.py train_model_joined_CV.cfg 5 > ~/facs-seq_test/joined/models/train.log &
<reponame>wkma/bk-sops # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. """ from __future__ import absolute_import from django.test import TestCase from pipeline_web.constants import PWE from pipeline_web.drawing_new.order import order class TestOrder(TestCase): def setUp(self): self.pipeline = { 'all_nodes': { 'node0': { PWE.id: 'node0', PWE.incoming: '', PWE.outgoing: ['flow0', 'flow1', 'flow2'] }, 'node1': { PWE.id: 'node1', PWE.incoming: 'flow0', PWE.outgoing: ['flow3', 'flow4'] }, 'node2': { PWE.id: 'node2', PWE.incoming: 'flow1', PWE.outgoing: ['flow5', 'flow6', 'flow7'] }, 'node3': { PWE.id: 'node3', PWE.incoming: 'flow2', PWE.outgoing: ['flow8', 'flow9', 'flow10'] }, 'node4': { PWE.id: 'node4', PWE.incoming: ['flow3', 'flow5', 'flow8'], PWE.outgoing: '' }, 'node5': { PWE.id: 'node5', PWE.incoming: ['flow4'], PWE.outgoing: '' }, 'node6': { PWE.id: 'node6', PWE.incoming: ['flow6'], PWE.outgoing: '' }, 'node7': { PWE.id: 'node7', PWE.incoming: ['flow7', 'flow9'], PWE.outgoing: '' }, 'node8': { PWE.id: 'node8', PWE.incoming: ['flow10'], PWE.outgoing: '' } }, 'flows': { 'flow0': { PWE.id: 'flow0', PWE.source: 'node0', PWE.target: 'node1' }, 'flow1': { PWE.id: 'flow1', PWE.source: 'node0', PWE.target: 'node2' }, 'flow2': { PWE.id: 'flow2', PWE.source: 'node0', PWE.target: 'node3' }, 'flow3': { PWE.id: 'flow3', PWE.source: 'node1', PWE.target: 'node4' }, 'flow4': { PWE.id: 'flow4', PWE.source: 'node1', PWE.target: 'node5' }, 'flow5': { PWE.id: 'flow5', PWE.source: 'node2', PWE.target: 'node4' }, 'flow6': { PWE.id: 'flow6', PWE.source: 'node2', PWE.target: 'node6' }, 'flow7': { PWE.id: 'flow7', PWE.source: 'node2', PWE.target: 'node7' }, 'flow8': { PWE.id: 'flow8', PWE.source: 'node3', PWE.target: 'node4' }, 'flow9': { PWE.id: 'flow9', PWE.source: 'node3', PWE.target: 'node7' }, 'flow10': { PWE.id: 'flow10', PWE.source: 'node3', PWE.target: 'node8' } } } self.ranks = { 'node0': 0, 'node1': 1, 'node2': 1, 'node3': 1, 'node4': 2, 'node5': 2, 'node6': 2, 'node7': 2, 'node8': 2 } def test_init_order(self): orders = order.init_order(self.pipeline, self.ranks) self.assertEqual(orders, { 0: ['node0'], 1: ['node1', 'node2', 'node3'], 2: ['node4', 'node5', 'node6', 'node7', 'node8'] }) def test_crossing_count(self): orders = { 0: ['node0'], 1: ['node1', 'node2', 'node3'], 2: ['node4', 'node5', 'node6', 'node7', 'node8'] } self.assertEqual(order.crossing_count(self.pipeline, orders), 4) def test_sort_layer(self): layer_order = ['a', 'b', 'c', 'd', 'e', 'f'] weight = [3, 6, 2, 1, 5, 4] self.assertEqual(order.sort_layer(layer_order, weight), ['d', 'c', 'a', 'f', 'e', 'b']) layer_order = ['a', 'b'] weight = [-1, -1] self.assertEqual(order.sort_layer(layer_order, weight), ['a', 'b']) layer_order = ['a', 'b', 'c', 'd', 'e', 'f'] weight = [3, -1, 2, -1, 5, 4] self.assertEqual(order.sort_layer(layer_order, weight), ['c', 'b', 'a', 'd', 'f', 'e']) def test_median_value(self): refer_layer_orders = ['node1', 'node2', 'node3', 'node4'] refer_nodes = ['node1'] self.assertEqual(order.median_value(refer_nodes, refer_layer_orders), 0) refer_nodes = ['node1', 'node4'] self.assertEqual(order.median_value(refer_nodes, refer_layer_orders), 1.5) refer_nodes = ['node1', 'node4', 'node2'] self.assertEqual(order.median_value(refer_nodes, refer_layer_orders), 1) def test_refer_node_ids(self): self.assertEqual(order.refer_node_ids(self.pipeline, 'node1', PWE.outgoing), ['node4', 'node5']) self.assertEqual(order.refer_node_ids(self.pipeline, 'node4', PWE.incoming), ['node1', 'node2', 'node3']) def test_ordering(self): best_orders = { 0: ['node0'], 1: ['node1', 'node2', 'node3'], 2: ['node5', 'node4', 'node6', 'node7', 'node8'] } self.assertEqual(order.ordering(self.pipeline, self.ranks), best_orders)
<filename>pkg/version/version.go package version var Version="UNKNOWN"
class MetricManager: def __init__(self): self.metrics = set() def add_metric(self, metric): self.metrics.add(metric) def clear(self): self.metrics.clear() def delete_metric(self, metric): if metric in self.metrics: self.metrics.remove(metric) else: print(f"Metric '{metric}' not found in the set.") # Example usage manager = MetricManager() manager.add_metric('jac_metric') manager.add_metric('grad_logdet_metric') manager.add_metric('metric') # Clear all metrics manager.clear() # Delete a specific metric manager.delete_metric('metric')
<reponame>glowroot/glowroot-instrumentation /* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.glowroot.instrumentation.test.harness.agent.spans; import java.util.Deque; import java.util.Map; import java.util.Queue; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.google.common.collect.Queues; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.glowroot.instrumentation.api.Getter; import org.glowroot.instrumentation.api.MessageSupplier; import org.glowroot.instrumentation.api.Setter; import org.glowroot.instrumentation.api.ThreadContext.ServletRequestInfo; import org.glowroot.instrumentation.api.internal.ReadableMessage; import org.glowroot.instrumentation.engine.bytecode.api.ThreadContextThreadLocal; import org.glowroot.instrumentation.engine.util.TwoPartCompletion; import org.glowroot.instrumentation.test.harness.ImmutableIncomingSpan; import org.glowroot.instrumentation.test.harness.ImmutableIncomingSpanError; import org.glowroot.instrumentation.test.harness.IncomingSpan.IncomingSpanError; import org.glowroot.instrumentation.test.harness.ThrowableInfo; import org.glowroot.instrumentation.test.harness.agent.Global; import org.glowroot.instrumentation.test.harness.agent.TimerImpl; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; public class IncomingSpanImpl implements org.glowroot.instrumentation.api.Span, ParentSpanImpl { private final MessageSupplier messageSupplier; private final ThreadContextThreadLocal.Holder threadContextHolder; private final long startNanoTime; private final TimerImpl mainThreadTimer; private final Deque<ParentSpanImpl> currParentSpanStack; private final Queue<TimerImpl> auxThreadTimers = Queues.newConcurrentLinkedQueue(); private final Queue<TimerImpl> asyncTimers = Queues.newConcurrentLinkedQueue(); private final Queue<SpanImpl> childSpans = Queues.newConcurrentLinkedQueue(); private volatile @Nullable ServletRequestInfo servletRequestInfo; private volatile String transactionType; private volatile int transactionTypePriority = Integer.MIN_VALUE; private volatile String transactionName; private volatile int transactionNamePriority = Integer.MIN_VALUE; private volatile @MonotonicNonNull String user; private volatile int userPriority = Integer.MIN_VALUE; private volatile long syncTotalNanos = -1; private volatile long totalNanos = -1; private volatile @MonotonicNonNull IncomingSpanError error; private volatile @MonotonicNonNull Long locationStackTraceMillis; private volatile @MonotonicNonNull TwoPartCompletion asyncCompletion; private final Map<Object, Boolean> resourcesAcquired = Maps.newConcurrentMap(); public IncomingSpanImpl(String transactionType, String transactionName, MessageSupplier messageSupplier, ThreadContextThreadLocal.Holder threadContextHolder, TimerImpl mainThreadTimer, Deque<ParentSpanImpl> currParentSpanStack, long startNanoTime) { this.transactionType = transactionType; this.transactionName = transactionName; this.messageSupplier = messageSupplier; this.threadContextHolder = threadContextHolder; this.mainThreadTimer = mainThreadTimer; this.currParentSpanStack = currParentSpanStack; this.startNanoTime = startNanoTime; } @Override public void end() { endInternal(); } @Override public void endWithLocationStackTrace(long thresholdNanos) { locationStackTraceMillis = NANOSECONDS.toMillis(thresholdNanos); endInternal(); } @Override public void endWithError(Throwable t) { if (error == null) { error = ImmutableIncomingSpanError.builder() .exception(ThrowableInfo.create(t)) .build(); } endInternal(); } @Override public org.glowroot.instrumentation.api.Timer extend() { throw new UnsupportedOperationException("extend() shouldn't be called on incoming span"); } @Override public Object getMessageSupplier() { return messageSupplier; } @Override @Deprecated public <R> void propagateToResponse(R response, Setter<R> setter) {} @Override @Deprecated public <R> void extractFromResponse(R response, Getter<R> getter) {} @Override public void addChildSpan(SpanImpl childSpan) { childSpans.add(childSpan); } @Override public ImmutableIncomingSpan toImmutable() { ImmutableIncomingSpan.Builder builder = ImmutableIncomingSpan.builder() .totalNanos(totalNanos) .transactionType(transactionType) .transactionName(transactionName) .user(Strings.nullToEmpty(user)) .mainThreadTimer(mainThreadTimer.toImmutable()); for (TimerImpl auxThreadTimer : auxThreadTimers) { builder.addAuxThreadTimers(auxThreadTimer.toImmutable()); } for (TimerImpl asyncTimer : asyncTimers) { builder.addAsyncTimers(asyncTimer.toImmutable()); } ReadableMessage message = (ReadableMessage) messageSupplier.get(); builder.message(message.getText()); setDetail(builder, message.getDetail()); builder.error(error) .locationStackTraceMillis(locationStackTraceMillis); for (SpanImpl childSpan : childSpans) { builder.addChildSpans(childSpan.toImmutable()); } if (resourcesAcquired.isEmpty()) { builder.resourceLeakDetected(false); builder.resourceLeakDetectedWithLocation(false); } else { builder.resourceLeakDetected(true); boolean withLocation = false; for (boolean value : resourcesAcquired.values()) { if (value) { withLocation = true; } } builder.resourceLeakDetectedWithLocation(withLocation); } return builder.build(); } public @Nullable ServletRequestInfo getServletRequestInfo() { return servletRequestInfo; } public void setServletRequestInfo(@Nullable ServletRequestInfo servletRequestInfo) { this.servletRequestInfo = servletRequestInfo; } public void setAsync() { asyncCompletion = new TwoPartCompletion(); } public void setAsyncComplete() { checkNotNull(asyncCompletion); if (asyncCompletion.completePart1()) { totalNanos = System.nanoTime() - startNanoTime; Global.report(toImmutable()); } } public void setTransactionType(@Nullable String transactionType, int priority) { if (priority > transactionTypePriority && !Strings.isNullOrEmpty(transactionType)) { this.transactionType = transactionType; transactionTypePriority = priority; } } public void setTransactionName(@Nullable String transactionName, int priority) { if (priority > transactionNamePriority && !Strings.isNullOrEmpty(transactionName)) { this.transactionName = transactionName; transactionNamePriority = priority; } } public void setUser(@Nullable String user, int priority) { if (priority > userPriority && !Strings.isNullOrEmpty(user)) { this.user = user; userPriority = priority; } } public void setError(Throwable t) { if (error == null) { error = ImmutableIncomingSpanError.builder() .exception(ThrowableInfo.create(t)) .build(); } } public void setError(@Nullable String message) { if (error == null) { error = ImmutableIncomingSpanError.builder() .message(message) .build(); } } public void setError(@Nullable String message, @Nullable Throwable t) { if (error == null) { if (t == null) { error = ImmutableIncomingSpanError.builder() .message(message) .build(); } else { error = ImmutableIncomingSpanError.builder() .message(message) .exception(ThrowableInfo.create(t)) .build(); } } } public void addAuxThreadTimer(TimerImpl auxThreadTimer) { auxThreadTimers.add(auxThreadTimer); } public void addAsyncTimer(TimerImpl asyncTimer) { asyncTimers.add(asyncTimer); } public void trackResourceAcquired(Object resource, boolean withLocationStackTrace) { resourcesAcquired.put(resource, withLocationStackTrace); } public void trackResourceReleased(Object resource) { resourcesAcquired.remove(resource); } private void endInternal() { endInternalPart1(); endInternalPart2(); } private long endInternalPart1() { if (syncTotalNanos == -1) { threadContextHolder.set(null); long nanoTime = System.nanoTime(); mainThreadTimer.stop(nanoTime); if (currParentSpanStack.pop() != this) { throw new IllegalStateException( "Unexpected value at the top of current parent span stack"); } syncTotalNanos = nanoTime - startNanoTime; } return syncTotalNanos; } private void endInternalPart2() { if (asyncCompletion == null || asyncCompletion.completePart2()) { totalNanos = syncTotalNanos; Global.report(toImmutable()); } } // this suppression is needed for checker framework because the immutables method signature // takes Map<String, ? extends Object> instead of/ Map<String, ? extends /*@Nullable*/ Object> @SuppressWarnings("argument.type.incompatible") private static void setDetail(ImmutableIncomingSpan.Builder builder, Map<String, ?> detail) { builder.detail(detail); } }
#!/usr/bin/env bash cd $(dirname $0) && source ./.env if ! docker ps | grep -q "${CONTAINER_NAME}"; then if docker ps -a | grep -q "${CONTAINER_NAME}"; then docker start ${CONTAINER_NAME} else ./networks/setup.sh docker run -d \ --name ${CONTAINER_NAME} \ --network=${BACKEND_NETWORK_NAME} --hostname=${CONTAINER_NAME} \ -p ${HOST_PORT}:${PORT} \ ${IMAGE_FULL_NAME} fi fi
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" elif [ -L "${binary}" ]; then echo "Destination binary is symlinked..." dirname="$(dirname "${binary}")" binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Copies the bcsymbolmap files of a vendored framework install_bcsymbolmap() { local bcsymbolmap_path="$1" local destination="${BUILT_PRODUCTS_DIR}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" install_framework "${BUILT_PRODUCTS_DIR}/YSNetworkDemo/YSNetworkDemo.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" install_framework "${BUILT_PRODUCTS_DIR}/YSNetworkDemo/YSNetworkDemo.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
class BaseAbility include CanCan::Ability cattr_accessor :precondition attr_reader :user def initialize(user, **options) @user = user @options = options create_action_aliases user ? draw(user) : draw_guest end protected def draw(user) if precondition.nil? || precondition.call(user) || @options[:skip_precondition] logged_in(user) for role in user.roles m = method(role) m.arity == 1 ? m.call(user) : m.call end end end def logged_in(user); end def draw_guest; end def create_action_aliases clear_aliased_actions alias_actions(action_aliases) end def action_aliases; end # Allow hash style aliases, like: alias_action :modify => [:update, :destroy] # which is the same as: alias_action :update, :destroy, to: :modify def alias_action(*args) return super(*args) if args.length > 1 to, from = args[0].first super(*from, to: to) end def alias_actions(aliases) aliases.each { |from, to| alias_action from => to } end def banned_actions # Format = 'action_name: "Reason to ban"' { new: "It doesn't make sense to allow :new, but deny :create - use :create instead of :new", edit: "It doesn't make sense to allow :edit but deny :update - use :update instead of :edit" } end def can(action = nil, *args) banned_action = (banned_actions.keys & [action].flatten.map(&:to_sym)).first raise "Action :#{banned_action} is banned; you can't use it when defining abilities. Reason: #{banned_actions[banned_action]}." if banned_action super(action, *args) end end
pathToData=$1 company=$2 seq=$3 params=$4 reverseComplement=$5 makePlots=$6 for region in LOW-chr2 AVG-chr20 AVG-chr7 AVG-chr8; do #HIGH-chr12 ## Removing HIGH region cos broken for hifi time ../scripts/phaseTest.sh ${pathToData} ${region} ${company} ${seq} $params $reverseComplement $makePlots >&out_${company}_${seq}_${params}_${region}_phased.txt & done wait trap 'kill $(jobs -p)' EXIT
SELECT Name, Price FROM Table ORDER BY Price LIMIT 3;
#!/bin/bash # ... source /$PROJECT/.env/$PROJECT/bin/activate cd /$PROJECT ./manage.py syncdb ./manage.py migrate
#!/bin/bash set -e echo "===Pull & Run postgres container" docker run --rm --name pg-docker -e POSTGRES_USER=user -e POSTGRES_PASSWORD=docker -d -p 5432:5432 -v c:/Docker/postgres postgres:11 echo "===Copy SQL DB scheme to postgres container" docker cp final.SQL pg-docker:/final.SQL echo "===Waiting for database up" sleep 5s winpty docker exec -it pg-docker psql -U user -c 'create database thesis_db;' winpty docker exec -it pg-docker psql -U user -c 'grant all privileges on database "thesis_db" to "user";' echo "===Run SQL scheme" winpty docker exec -it pg-docker psql -U user -d thesis_db -f final.SQL
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package brooklyn.entity.basic; import brooklyn.entity.Entity; import brooklyn.event.AttributeSensor; import brooklyn.event.basic.DependentConfiguration; import brooklyn.management.Task; import brooklyn.util.collections.CollectionFunctionals; import brooklyn.util.time.Duration; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; /** Generally useful tasks related to entities */ public class EntityTasks { /** creates an (unsubmitted) task which waits for the attribute to satisfy the given predicate, * returning false if it times out or becomes unmanaged */ public static <T> Task<Boolean> testingAttributeEventually(Entity entity, AttributeSensor<T> sensor, Predicate<T> condition, Duration timeout) { return DependentConfiguration.builder().attributeWhenReady(entity, sensor) .readiness(condition) .postProcess(Functions.constant(true)) .timeout(timeout) .onTimeoutReturn(false) .onUnmanagedReturn(false) .build(); } /** creates an (unsubmitted) task which waits for the attribute to satisfy the given predicate, * throwing if it times out or becomes unmanaged */ public static <T> Task<Boolean> requiringAttributeEventually(Entity entity, AttributeSensor<T> sensor, Predicate<T> condition, Duration timeout) { return DependentConfiguration.builder().attributeWhenReady(entity, sensor) .readiness(condition) .postProcess(Functions.constant(true)) .timeout(timeout) .onTimeoutThrow() .onUnmanagedThrow() .build(); } /** as {@link #testingAttributeEventually(Entity, AttributeSensor, Predicate, Duration) for multiple entities */ public static <T> Task<Boolean> testingAttributeEventually(Iterable<Entity> entities, AttributeSensor<T> sensor, Predicate<T> condition, Duration timeout) { return DependentConfiguration.builder().attributeWhenReadyFromMultiple(entities, sensor, condition) .postProcess(Functions.constant(true)) .timeout(timeout) .onTimeoutReturn(false) .onUnmanagedReturn(false) .postProcessFromMultiple(CollectionFunctionals.all(Predicates.equalTo(true))) .build(); } /** as {@link #requiringAttributeEventually(Entity, AttributeSensor, Predicate, Duration) for multiple entities */ public static <T> Task<Boolean> requiringAttributeEventually(Iterable<Entity> entities, AttributeSensor<T> sensor, Predicate<T> condition, Duration timeout) { return DependentConfiguration.builder().attributeWhenReadyFromMultiple(entities, sensor, condition) .postProcess(Functions.constant(true)) .timeout(timeout) .onTimeoutThrow() .onUnmanagedThrow() .postProcessFromMultiple(CollectionFunctionals.all(Predicates.equalTo(true))) .build(); } }