text stringlengths 1 1.05M |
|---|
#!/bin/bash
for ((; i<=9;))
do
let i++
echo -n "$i "
done |
<reponame>james54068/engine_monitoring_system
/**
* Timer properties for all STM32F4xx timers
*
* @author <NAME>
* @email <EMAIL>
* @website http://stm32f4-discovery.com
* @link
* @version v1.0
* @ide Keil uVision
* @license GNU GPL v3
*
* |----------------------------------------------------------------------
* | Copyright (C) <NAME>, 2014
* |
* | 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 3 of the License, or
* | 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, see <http://www.gnu.org/licenses/>.
* |----------------------------------------------------------------------
*
* This library allows you to enable/disable clock for specific timer,
* and returns you settings for timer, ex. max period, max prescaler and timer's clock
*
* Also, it is used in every library where timers are used.
*/
#ifndef TM_TIMER_PROPERTIES_H
#define TM_TIMER_PROPERTIES_H 100
/**
* Dependencies
* - STM32F4xx
* - STM32F4xx RCC
* - STM32F4xx TIM
* - defines.h
*/
/**
* Includes
*/
#include "stm32f4xx.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_tim.h"
#include "defines.h"
/**
* Result enumeration
*
* Parameters:
* - TM_TIMER_PROPERTIES_Result_Ok:
* Everything OK
* - TM_TIMER_PROPERTIES_Result_Error:
* An error occured
* - TM_TIMER_PROPERTIES_Result_TimerNotValid:
* Timer is not valid
* - TM_TIMER_PROPERTIES_Result_FrequencyTooHigh:
* Frequency for timer is too high
* - TM_TIMER_PROPERTIES_Result_FrequencyTooLow
* Frequency for timer is too low
*/
typedef enum {
TM_TIMER_PROPERTIES_Result_Ok,
TM_TIMER_PROPERTIES_Result_Error,
TM_TIMER_PROPERTIES_Result_TimerNotValid,
TM_TIMER_PROPERTIES_Result_FrequencyTooHigh,
TM_TIMER_PROPERTIES_Result_FrequencyTooLow
} TM_TIMER_PROPERTIES_Result_t;
/**
* Struct for timer data
*
* Parameters:
* - uint32_t TimerFrequency:
* timer's working frequency
* - uint32_t MaxPeriod:
* Max timer period
* - uint32_t MaxPrescaler:
* Max timer prescaler
* - uint32_t Period:
* Timer's working period:
* - uint32_t Prescaler:
* Timer's working prescaler
* - uint32_t Frequency:
* Timer's reload frequency
*/
typedef struct {
uint32_t TimerFrequency;
uint32_t MaxPeriod;
uint32_t MaxPrescaler;
uint32_t Period;
uint32_t Prescaler;
uint32_t Frequency;
} TM_TIMER_PROPERTIES_t;
/**
* Returns you a timer properties
*
* Parameters:
* - TIM_TypeDef* TIMx:
* Timer used to get settings for
* - TM_TIMER_PROPERTIES_t* Timer_Data
* Pointer to TM_TIMER_PROPERTIES_t struct to store data to
*
* Member of TM_TIMER_PROPERTIES_Result_t is returned
*/
extern TM_TIMER_PROPERTIES_Result_t TM_TIMER_PROPERTIES_GetTimerProperties(TIM_TypeDef* TIMx, TM_TIMER_PROPERTIES_t* Timer_Data);
/**
* Generate period and prescaller for given timer frequency
*
* Parameters:
* - TM_TIMER_PROPERTIES_t* Timer_Data:
* Pointer for timer data
* - uint32_t frequency
* Frequency used
*
* Member of TM_TIMER_PROPERTIES_Result_t is returned
*/
extern TM_TIMER_PROPERTIES_Result_t TM_TIMER_PROPERTIES_GenerateDataForWorkingFrequency(TM_TIMER_PROPERTIES_t* Timer_Data, double frequency);
/**
* Enable timer's clock
*
* Parameters:
* - TIM_TypeDef* TIMx
* Timer to enable clock for
*
* Member of TM_TIMER_PROPERTIES_Result_t is returned
*/
extern TM_TIMER_PROPERTIES_Result_t TM_TIMER_PROPERTIES_EnableClock(TIM_TypeDef* TIMx);
/**
* Disable timer's clock
*
* Parameters:
* - TIM_TypeDef* TIMx
* Timer to disable clock for
*
* Member of TM_TIMER_PROPERTIES_Result_t is returned
*/
extern TM_TIMER_PROPERTIES_Result_t TM_TIMER_PROPERTIES_DisableClock(TIM_TypeDef* TIMx);
#endif
|
<reponame>kocyigitkim/fastapi-next<gh_stars>0
import { NextFunction, Request, Response } from 'express'
export interface INextContextBase {
//#region Express Parameters
req: Request;
res: Response;
next: NextFunction;
//#endregion
//#region Request Parameters
body: any;
query: any;
params: any;
cookies: any;
headers: any;
protocol: string;
ip: string;
ipv4: boolean;
ipv6: boolean;
method: string;
url: string;
path: string;
files?: Array<Express.Multer.File>;
fileCount?: number;
//#endregion
//#region Session Parameters
session: Object;
sessionId: string;
//#endregion
get token(): string | null;
}
export class NextContextBase implements INextContextBase {
//#region Express Parameters
public req: Request;
public res: Response;
public next: NextFunction;
//#endregion
//#region Request Parameters
public all: any;
public body: any;
public query: any;
public params: any;
public cookies: any;
public headers: any;
public protocol: string;
public ip: string;
public ipv4: boolean;
public ipv6: boolean;
public method: string;
public url: string;
public path: string;
public files?: Array<Express.Multer.File>;
public fileCount?: number;
//#endregion
//#region Session Parameters
public session: Object;
public sessionId: string;
//#endregion
//#region Session Parameters
public items: Object;
//#endregion
public get token(): string | null {
return (this.req as any).token || (this.req as any).access_token || (this.req as any).accessToken || null;
}
constructor(req: Request, res: Response, next: NextFunction) {
this.req = req;
this.res = res;
this.next = next;
this.body = req.body;
this.query = req.query;
this.params = req.params;
this.all = { ...req.params, ...req.query, ...req.body };
this.cookies = req.cookies;
this.headers = req.headers;
this.protocol = req.protocol;
this.files = (req as any).files;
this.fileCount = (req as any).fileCount;
this.ip = ((req as any).clientIp) || req.ip;
this.ipv4 = ((req.ip || "").split(":")[0]) === req.ip;
this.ipv6 = !this.ipv4;
this.method = req.method;
this.url = req.url;
this.path = req.path;
this.session = (req as any).session;
this.sessionId = (this.session && (this.session as any).id) || (req as any).sessionId;
this.items = {};
}
}
export interface NextContext<TBODY, TQUERY = TBODY, TPARAMS = TBODY> extends INextContextBase {
body: TBODY;
query: TQUERY;
params: TPARAMS;
}
|
import java.util.HashSet;
import java.util.Random;
public class RandomSetGenerator {
public static void randomSet(int min, int max, int n, HashSet<Integer> set) {
if (n > (max - min + 1) || max < min) {
return; // Unable to generate n distinct integers within the given range
}
Random random = new Random();
set.clear(); // Clear the set before generating new random integers
while (set.size() < n) {
int randomNumber = random.nextInt((max - min) + 1) + min; // Generate a random number within the range [min, max]
set.add(randomNumber); // Add the random number to the set (HashSet ensures distinct values)
}
}
public static void main(String[] args) {
HashSet<Integer> resultSet = new HashSet<>();
randomSet(1, 10, 5, resultSet);
System.out.println("Random Set: " + resultSet);
}
} |
#!/bin/bash
#
# Copyright 2015 Delft University of Technology
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -e
# Ensure the configuration file exists
#rootdir=$(dirname $(readlink -f ${0}))/../..
rootdir=$(pwd)
config="${rootdir}/config"
if [ ! -f "$config/platform.properties" ]; then
echo "Missing mandatory configuration file: $config/platform.properties" >&2
exit 1
fi
# Construct the classpath
PLATFORM_HOME=$(grep -E "^platform.gunrock.home[ ]*[:=]" $config/platform.properties | sed 's/platform.gunrock.home[\t ]*[:=][\t ]*\([^\t ]*\).*/\1/g' | head -n 1)
if [ -z $PLATFORM_HOME ]; then
echo "Error: Gunrock home directory not specified."
echo "Define variable platform.gunrock.home in $config/platform.properties"
exit 1
fi
# TODO Build binaries
# mkdir -p $rootdir/bin/exe
# (cd $rootdir/bin/exe && cmake -DCMAKE_BUILD_TYPE=Release ../../src/main/c -DPLATFORM_HOME=$PLATFORM_HOME && make all VERBOSE=1)
if [ $? -ne 0 ]
then
echo "Compilation failed"
exit 1
fi
|
<filename>app/src/main/java/com/oztaking/www/a16_brvahdemo/BRVADLoadMoreDemo/PullToRefreshUseActivity.java
package com.oztaking.www.a16_brvahdemo.BRVADLoadMoreDemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.oztaking.www.a16_brvahdemo.BRVADDemo.Status;
import com.oztaking.www.a16_brvahdemo.BRVADDemo.Utils;
import com.oztaking.www.a16_brvahdemo.R;
import java.util.List;
/**
* https://github.com/CymChad/BaseRecyclerViewAdapterHelper
*/
public class PullToRefreshUseActivity extends Activity {
private static final int PAGE_SIZE = 6;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private PullToRefreshAdapter mAdapter;
private int mNextRequestPage = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_brvah);
Utils.init(getApplicationContext());
mRecyclerView = (RecyclerView) findViewById(R.id.rv_list);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
setTitle("Pull TO Refresh Use");
// setBackBtn();
initAdapter();
// addHeadView();
initRefreshLayout();
mSwipeRefreshLayout.setRefreshing(true);
refresh();
}
private void initAdapter() {
mAdapter = new PullToRefreshAdapter();
mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
loadMore();
}
});
// mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
// mAdapter.setPreLoadNumber(3);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
@Override
public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {
Toast.makeText(PullToRefreshUseActivity.this, Integer.toString(position), Toast.LENGTH_LONG).show();
}
});
}
// private void addHeadView() {
// View headView = getLayoutInflater().inflate(R.layout.head_view_brvah, (ViewGroup) mRecyclerView.getParent(), false);
// headView.findViewById(R.id.iv).setVisibility(View.GONE);
// ((TextView) headView.findViewById(R.id.tv)).setText("change load view");
// headView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// mAdapter.setNewData(null);
// mAdapter.setLoadMoreView(new CustomLoadMoreView());
// mRecyclerView.setAdapter(mAdapter);
// Toast.makeText(PullToRefreshUseActivity.this, "change complete", Toast.LENGTH_LONG).show();
//
// mSwipeRefreshLayout.setRefreshing(true);
// refresh();
// }
// });
// mAdapter.addHeaderView(headView);
// }
private void initRefreshLayout() {
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refresh();
}
});
}
private void refresh() {
mNextRequestPage = 1;
mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
new Request(mNextRequestPage, new RequestCallBack() {
@Override
public void success(List<Status> data) {
setData(true, data);
mAdapter.setEnableLoadMore(true);
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void fail(Exception e) {
Toast.makeText(PullToRefreshUseActivity.this, "请检查网络...", Toast.LENGTH_LONG).show();
mAdapter.setEnableLoadMore(true);
mSwipeRefreshLayout.setRefreshing(false);
}
}).start();
}
private void loadMore() {
new Request(mNextRequestPage, new RequestCallBack() {
@Override
public void success(List<Status> data) {
setData(false, data);
}
@Override
public void fail(Exception e) {
mAdapter.loadMoreFail();
Toast.makeText(PullToRefreshUseActivity.this, "请检查网络...", Toast.LENGTH_LONG).show();
}
}).start();
}
private void setData(boolean isRefresh, List data) {
mNextRequestPage++;
final int size = data == null ? 0 : data.size();
if (isRefresh) {
mAdapter.setNewData(data);
} else {
if (size > 0) {
mAdapter.addData(data);
}
}
if (size < PAGE_SIZE) {
//第一页如果不够一页就不显示没有更多数据布局
mAdapter.loadMoreEnd(isRefresh);
Toast.makeText(this, "没有数据啦!", Toast.LENGTH_SHORT).show();
} else {
mAdapter.loadMoreComplete();
}
}
} |
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
Request,
UseGuards,
UsePipes,
} from '@nestjs/common';
import { ApiOperation, ApiResponse } from '@nestjs/swagger';
import { ValidationPipe } from 'src/common/validation/validation.pipe';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CreateUserDto } from '../dto/create-user.dto';
import { LoginUserDto } from '../dto/login-user.dto';
import { UpdateUserDto } from '../dto/update-user.dto';
import { UserService } from '../services/user.service';
@Controller('api')
export class UserController {
constructor(private userService: UserService) {}
@ApiOperation({ summary: 'All User' })
@ApiResponse({
status: 200,
description: 'OK',
})
@ApiResponse({
status: 422,
description: 'Unexpected error',
})
@Get('users')
async finAll(): Promise<any> {
return this.userService.findAll();
}
// Get current user
@ApiOperation({ summary: 'Get current user' })
@ApiResponse({
status: 200,
description: 'OK',
})
@ApiResponse({
status: 422,
description: 'Unexpected error',
})
@UseGuards(JwtAuthGuard)
@Get('user')
async getDetail(@Request() req): Promise<any> {
return this.userService.findOne(req.user.username);
}
// register new user
@ApiOperation({ summary: 'Register a new user' })
@ApiResponse({
status: 201,
description: 'OK',
})
@ApiResponse({
status: 422,
description: 'Unexpected error',
})
@UsePipes(new ValidationPipe())
@Post('users')
async create(@Body() user: CreateUserDto): Promise<any> {
return this.userService.create(user);
}
@ApiOperation({ summary: 'Existing user login' })
@ApiResponse({
status: 201,
description: 'OK',
})
@ApiResponse({
status: 422,
description: 'Unexpected error',
})
@Post('users/login')
async login(@Body() user: LoginUserDto): Promise<any> {
return this.userService.login(user);
}
@ApiOperation({ summary: 'Update current user' })
@ApiResponse({
status: 201,
description: 'OK',
})
@ApiResponse({
status: 422,
description: 'Unexpected error',
})
@UseGuards(JwtAuthGuard)
// @UsePipes(new ValidationPipe())
@Put('user')
async update(@Body() bodys: UpdateUserDto, @Request() req): Promise<any> {
let id = req.user.id;
return this.userService.update(id, bodys);
}
}
|
<reponame>process-this/process-this-android<filename>app/src/main/java/io/github/processthis/client/service/GoogleSignInService.java
/* Copyright [2019] [<NAME>, <NAME>, <NAME>, <NAME>]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.github.processthis.client.service;
import android.app.Application;
import android.net.Uri;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import io.github.processthis.client.BuildConfig;
/**
* This class contains the necessary methods for the Google Sign-In Service
*/
public class GoogleSignInService {
private static Application context;
private GoogleSignInAccount account;
private GoogleSignInClient client;
private GoogleSignInService() {
GoogleSignInOptions options = new GoogleSignInOptions.Builder()
.requestEmail()
.requestId()
.requestProfile()
.requestIdToken(BuildConfig.CLIENT_ID)
.build();
client = GoogleSignIn.getClient(context, options);
}
/**
* This method sets the Context object to the Google Sign-in activity
*/
public static void setContext(Application context) {
GoogleSignInService.context = context;
}
/**
* This method gets the client to be used in Sign-In
*/
public GoogleSignInClient getClient() {
return client;
}
/**
* Gets the google account to bu used in Sign-In
*/
public GoogleSignInAccount getAccount() {
return account;
}
/**
* Sets the google account to bu used in Sign-In
*/
public void setAccount(GoogleSignInAccount account) {
this.account = account;
}
/**
* Gets the instance of Goggle Sign-In service to bu used in Sign-In
*/
public static GoogleSignInService getInstance() {
return InstanceHolder.INSTANCE;
}
private static class InstanceHolder {
private static final GoogleSignInService INSTANCE = new GoogleSignInService();
}
}
|
<form action="#" method="post">
<label>Name</label>
<input type="text" name="name">
<label>Email</label>
<input type="email" name="email">
<label>Telephone</label>
<input type="tel" name="telephone">
<button type="submit">Submit</button>
</form> |
<gh_stars>100-1000
/**********************************************************************
Sneedacity: A Digital Audio Editor
SneedacityMessageBox.h
<NAME> split this out of ErrorDialog.h
**********************************************************************/
#ifndef __SNEEDACITY_MESSAGE_BOX__
#define __SNEEDACITY_MESSAGE_BOX__
#include <wx/msgdlg.h>
#include "Internat.h"
extern SNEEDACITY_DLL_API TranslatableString SneedacityMessageBoxCaptionStr();
// Do not use wxMessageBox!! Its default window title does not translate!
inline int SneedacityMessageBox(const TranslatableString& message,
const TranslatableString& caption = SneedacityMessageBoxCaptionStr(),
long style = wxOK | wxCENTRE,
wxWindow *parent = NULL,
int x = wxDefaultCoord, int y = wxDefaultCoord)
{
return ::wxMessageBox(message.Translation(), caption.Translation(),
style, parent, x, y);
}
#endif
|
import copy
dct = {"a": 1, "b": 2, "c": 3}
# clone the dictionary
dct_clone = copy.deepcopy(dct)
print(dct_clone) |
#!/usr/bin/env bash
echo '{"id": "foo", "command": "date"}'
echo '{"id": "uptime", "command": "uptime", "description": "Run uptime on a given machine"}'
echo '{"id": "uname", "command": "uname", "args": ["-a"]}'
echo '{"id": "ls", "command": "ls", "args": ["-l", "/"]}'
pgrep zsh | jq -cM '{id: ("vmmap." + (.|tostring)), command: "vmmap", args: [.|tostring]}' |
def move_player_and_box(grid, player_position, box_position, target_position, impassable_positions, move):
def is_valid_position(position):
row, col = position
return 0 <= row < len(grid) and 0 <= col < len(grid[0]) and grid[row][col] not in ['#', '2']
def move_position(position, direction):
row, col = position
if direction == 'U':
return row - 1, col
elif direction == 'D':
return row + 1, col
elif direction == 'L':
return row, col - 1
elif direction == 'R':
return row, col + 1
def is_win_state(box_position, target_position):
return box_position == target_position
new_player_position = move_position(player_position, move)
new_box_position = box_position
if new_player_position == box_position:
new_box_position = move_position(box_position, move)
if is_valid_position(new_player_position) and is_valid_position(new_box_position):
if is_win_state(new_box_position, target_position):
return new_player_position, new_box_position
elif grid[new_box_position[0]][new_box_position[1]] != '#':
return new_player_position, new_box_position
return player_position, box_position |
#!/bin/bash
# this shell script can install docker which supports the option SCMP_ACT_LOG of seccomp
sudo apt-get remove docker docker-engine docker.io containerd runc
sudo apt-get update
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable nightly test"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
sudo apt-get install docker-ce=5:19.03.6~3-0~ubuntu-xenial docker-ce-cli=5:19.03.6~3-0~ubuntu-xenial containerd.io
|
#!/usr/bin/env bash
set -e
trap 'echo exit at ${0}:${LINENO}, command was: ${BASH_COMMAND} 1>&2' ERR
#
# global defaults
#
REGISTRY_URL=registry1.dso.mil
FLUX_KUSTOMIZATION=base/flux
FLUX_SECRET=private-registry
WAIT_TIMEOUT=300
#
# helper functions
#
# script help message
function help {
cat << EOF
usage: $(basename "$0") <arguments>
-h|--help - print this help message and exit
-r|--registry-url - (optional, default: registry1.dso.mil) registry url to use for flux installation
-u|--registry-username - (required) registry username to use for flux installation
-p|--registry-password - (required) registry password to use for flux installation
-w|--wait-timeout - (optional, default: 120) how long to wait; in seconds, for each key flux resource component
EOF
}
#
# cli parsing
#
PARAMS=""
while (( "$#" )); do
case "$1" in
# registry username required argument
-u|--registry-username)
if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
REGISTRY_USERNAME=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
help; exit 1
fi
;;
# registry password required argument
-p|--registry-password)
if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
REGISTRY_PASSWORD=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
help; exit 1
fi
;;
# registry email required argument
-e|--registry-email)
if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
REGISTRY_EMAIL=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
help; exit 1
fi
;;
# registry url optional argument
-r|--registry-url)
if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
REGISTRY_URL=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
help; exit 1
fi
;;
# wait timeout optional argument
-w|--wait-timeout)
if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
WAIT_TIMEOUT=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
help; exit 1
fi
;;
# help flag
-h|--help)
help; exit 0
;;
# unsupported flags
-*|--*=)
echo "Error: Unsupported flag $1" >&2
help; exit 1
;;
# preserve positional arguments
*)
PARAMS="$PARAMS $1"
shift
;;
esac
done
# check required arguments
if [ -z "$REGISTRY_USERNAME" ] || [ -z "$REGISTRY_PASSWORD" ]; then
help; exit 1
fi
# debug print cli args
echo "REGISTRY_URL: $REGISTRY_URL"
echo "REGISTRY_USERNAME: $REGISTRY_USERNAME"
#
# install flux
#
kubectl create namespace flux-system || true
echo "Creating secret $FLUX_SECRET in namespace flux-system"
kubectl create secret docker-registry "$FLUX_SECRET" -n flux-system \
--docker-server="$REGISTRY_URL" \
--docker-username="$REGISTRY_USERNAME" \
--docker-password="$REGISTRY_PASSWORD" \
--docker-email="$REGISTRY_EMAIL" \
--dry-run=client -o yaml | kubectl apply -n flux-system -f -
echo "Installing flux from kustomization"
kustomize build "$FLUX_KUSTOMIZATION" | sed "s/registry1.dso.mil/${REGISTRY_URL}/g" | kubectl apply -f -
#
# verify flux
#
kubectl wait --for=condition=available --timeout "${WAIT_TIMEOUT}s" -n "flux-system" "deployment/helm-controller"
kubectl wait --for=condition=available --timeout "${WAIT_TIMEOUT}s" -n "flux-system" "deployment/source-controller"
kubectl wait --for=condition=available --timeout "${WAIT_TIMEOUT}s" -n "flux-system" "deployment/kustomize-controller"
kubectl wait --for=condition=available --timeout "${WAIT_TIMEOUT}s" -n "flux-system" "deployment/notification-controller"
|
package cyclops.reactor;
import cyclops.reactive.ReactiveSeq;
import cyclops.reactive.collection.container.mutable.SetX;
import cyclops.reactor.container.higherkinded.FluxAnyM;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Stream;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
public class ReactorTest {
@Test
public void amb() {
Stream<List<Integer>> stream = Stream.of(Arrays.asList(1,
2,
3),
Arrays.asList(10,
20,
30));
SetX.fromPublisher(Flux.first(ReactiveSeq.of(1,
2,
3),
Flux.just(10,
20,
30)));
}
@Test
public void anyMTest() {
System.out.println("Start");
//Flux.just(1,2,3,4,5).subscribeOn(Schedulers.fromExecutor(ForkJoinPool.commonPool())).subscribe(System.out::println);
FluxAnyM.anyM(Flux.just(1,
2,
3,
4,
5)
.subscribeOn(Schedulers.fromExecutor(ForkJoinPool.commonPool())))
.forEach(System.out::println,
System.err::println);
System.out.println("Set up");
}
static class LinkedList {
}
}
|
/*******************************************************/
/* "C" Language Integrated Production System */
/* */
/* CLIPS Version 6.30 08/16/14 */
/* */
/* OBJECT PATTERN MATCHER MODULE */
/*******************************************************/
/*************************************************************/
/* Purpose: RETE Network Parsing Interface for Objects */
/* */
/* Principal Programmer(s): */
/* <NAME> */
/* */
/* Contributing Programmer(s): */
/* */
/* Revision History: */
/* */
/* 6.24: Removed INCREMENTAL_RESET compilation flag. */
/* */
/* Converted INSTANCE_PATTERN_MATCHING to */
/* DEFRULE_CONSTRUCT. */
/* */
/* Renamed BOOLEAN macro type to intBool. */
/* */
/* 6.30: Changed integer type/precision. */
/* */
/* Removed conditional code for unsupported */
/* compilers/operating systems (IBM_MCW, */
/* MAC_MCW, and IBM_TBC). */
/* */
/* Support for long long integers. */
/* */
/* Added support for hashed comparisons to */
/* constants. */
/* */
/* Added support for hashed alpha memories. */
/* */
/* Added const qualifiers to remove C++ */
/* deprecation warnings. */
/* */
/*************************************************************/
/* =========================================
*****************************************
EXTERNAL DEFINITIONS
=========================================
***************************************** */
#include "setup.h"
#if DEFRULE_CONSTRUCT && OBJECT_SYSTEM
#if (! BLOAD_ONLY) && (! RUN_TIME)
#include <string.h>
#include <stdlib.h>
#include "classcom.h"
#include "classfun.h"
#include "cstrnutl.h"
#include "constrnt.h"
#include "cstrnchk.h"
#include "cstrnops.h"
#include "drive.h"
#include "envrnmnt.h"
#include "exprnpsr.h"
#include "inscom.h"
#include "insfun.h"
#include "insmngr.h"
#include "memalloc.h"
#include "network.h"
#include "object.h"
#include "pattern.h"
#include "reteutil.h"
#include "ruledef.h"
#include "rulepsr.h"
#include "scanner.h"
#include "symbol.h"
#include "utility.h"
#endif
#include "constrct.h"
#include "objrtmch.h"
#include "objrtgen.h"
#include "objrtfnx.h"
#include "reorder.h"
#include "router.h"
#if CONSTRUCT_COMPILER && (! RUN_TIME)
#include "objrtcmp.h"
#endif
#if BLOAD_AND_BSAVE || BLOAD || BLOAD_ONLY
#include "objrtbin.h"
#endif
#define _OBJRTBLD_SOURCE_
#include "objrtbld.h"
#if ! DEFINSTANCES_CONSTRUCT
#include "extnfunc.h"
#include "classfun.h"
#include "classcom.h"
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
/* =========================================
*****************************************
CONSTANTS
=========================================
***************************************** */
#define OBJECT_PATTERN_INDICATOR "object"
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTION HEADERS
=========================================
***************************************** */
static intBool PatternParserFind(SYMBOL_HN *);
static struct lhsParseNode *ObjectLHSParse(void *,const char *,struct token *);
static intBool ReorderAndAnalyzeObjectPattern(void *,struct lhsParseNode *);
static struct patternNodeHeader *PlaceObjectPattern(void *,struct lhsParseNode *);
static OBJECT_PATTERN_NODE *FindObjectPatternNode(OBJECT_PATTERN_NODE *,struct lhsParseNode *,
OBJECT_PATTERN_NODE **,unsigned,unsigned);
static OBJECT_PATTERN_NODE *CreateNewObjectPatternNode(void *,struct lhsParseNode *,OBJECT_PATTERN_NODE *,
OBJECT_PATTERN_NODE *,unsigned,unsigned);
static void DetachObjectPattern(void *,struct patternNodeHeader *);
static void ClearObjectPatternMatches(void *,OBJECT_ALPHA_NODE *);
static void RemoveObjectPartialMatches(void *,INSTANCE_TYPE *,struct patternNodeHeader *);
static intBool CheckDuplicateSlots(void *,struct lhsParseNode *,SYMBOL_HN *);
static struct lhsParseNode *ParseClassRestriction(void *,const char *,struct token *);
static struct lhsParseNode *ParseNameRestriction(void *,const char *,struct token *);
static struct lhsParseNode *ParseSlotRestriction(void *,const char *,struct token *,CONSTRAINT_RECORD *,int);
static CLASS_BITMAP *NewClassBitMap(void *,int,int);
static void InitializeClassBitMap(void *,CLASS_BITMAP *,int);
static void DeleteIntermediateClassBitMap(void *,CLASS_BITMAP *);
static void *CopyClassBitMap(void *,void *);
static void DeleteClassBitMap(void *,void *);
static void MarkBitMapClassesBusy(void *,BITMAP_HN *,int);
static intBool EmptyClassBitMap(CLASS_BITMAP *);
static intBool IdenticalClassBitMap(CLASS_BITMAP *,CLASS_BITMAP *);
static intBool ProcessClassRestriction(void *,CLASS_BITMAP *,struct lhsParseNode **,int);
static CONSTRAINT_RECORD *ProcessSlotRestriction(void *,CLASS_BITMAP *,SYMBOL_HN *,int *);
static void IntersectClassBitMaps(CLASS_BITMAP *,CLASS_BITMAP *);
static void UnionClassBitMaps(CLASS_BITMAP *,CLASS_BITMAP *);
static CLASS_BITMAP *PackClassBitMap(void *,CLASS_BITMAP *);
static struct lhsParseNode *FilterObjectPattern(void *,struct patternParser *,
struct lhsParseNode *,struct lhsParseNode **,
struct lhsParseNode **,struct lhsParseNode **);
static BITMAP_HN *FormSlotBitMap(void *,struct lhsParseNode *);
static struct lhsParseNode *RemoveSlotExistenceTests(void *,struct lhsParseNode *,BITMAP_HN **);
static struct lhsParseNode *CreateInitialObjectPattern(void *);
static EXPRESSION *ObjectMatchDelayParse(void *,EXPRESSION *,const char *);
static void MarkObjectPtnIncrementalReset(void *,struct patternNodeHeader *,int);
static void ObjectIncrementalReset(void *);
#endif
#if ! DEFINSTANCES_CONSTRUCT
static void ResetInitialObject(void *);
#endif
/* =========================================
*****************************************
EXTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
/********************************************************
NAME : SetupObjectPatternStuff
DESCRIPTION : Installs the parsers and other items
necessary for recognizing and processing
object patterns in defrules
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : Rete network interfaces for objects
initialized
NOTES : None
********************************************************/
globle void SetupObjectPatternStuff(
void *theEnv)
{
#if (! BLOAD_ONLY) && (! RUN_TIME)
struct patternParser *newPtr;
if (ReservedPatternSymbol(theEnv,"object",NULL) == TRUE)
{
SystemError(theEnv,"OBJRTBLD",1);
EnvExitRouter(theEnv,EXIT_FAILURE);
}
AddReservedPatternSymbol(theEnv,"object",NULL);
/* ===========================================================================
The object pattern parser needs to have a higher priority than deftemplates
or regular facts so that the "object" keyword is always recognized first
=========================================================================== */
newPtr = get_struct(theEnv,patternParser);
newPtr->name = "objects";
newPtr->priority = 20;
newPtr->entityType = &InstanceData(theEnv)->InstanceInfo;
newPtr->recognizeFunction = PatternParserFind;
newPtr->parseFunction = ObjectLHSParse;
newPtr->postAnalysisFunction = ReorderAndAnalyzeObjectPattern;
newPtr->addPatternFunction = PlaceObjectPattern;
newPtr->removePatternFunction = DetachObjectPattern;
newPtr->genJNConstantFunction = NULL;
newPtr->replaceGetJNValueFunction = ReplaceGetJNObjectValue;
newPtr->genGetJNValueFunction = GenGetJNObjectValue;
newPtr->genCompareJNValuesFunction = ObjectJNVariableComparison;
newPtr->genPNConstantFunction = GenObjectPNConstantCompare;
newPtr->replaceGetPNValueFunction = ReplaceGetPNObjectValue;
newPtr->genGetPNValueFunction = GenGetPNObjectValue;
newPtr->genComparePNValuesFunction = ObjectPNVariableComparison;
newPtr->returnUserDataFunction = DeleteClassBitMap;
newPtr->copyUserDataFunction = CopyClassBitMap;
newPtr->markIRPatternFunction = MarkObjectPtnIncrementalReset;
newPtr->incrementalResetFunction = ObjectIncrementalReset;
newPtr->initialPatternFunction = CreateInitialObjectPattern;
#if CONSTRUCT_COMPILER && (! RUN_TIME)
newPtr->codeReferenceFunction = ObjectPatternNodeReference;
#else
newPtr->codeReferenceFunction = NULL;
#endif
AddPatternParser(theEnv,newPtr);
EnvDefineFunction2(theEnv,"object-pattern-match-delay",'u',
PTIEF ObjectMatchDelay,"ObjectMatchDelay",NULL);
AddFunctionParser(theEnv,"object-pattern-match-delay",ObjectMatchDelayParse);
FuncSeqOvlFlags(theEnv,"object-pattern-match-delay",FALSE,FALSE);
#endif
InstallObjectPrimitives(theEnv);
#if CONSTRUCT_COMPILER && (! RUN_TIME)
ObjectPatternsCompilerSetup(theEnv);
#endif
#if ! DEFINSTANCES_CONSTRUCT
EnvAddResetFunction(theEnv,"reset-initial-object",ResetInitialObject,0);
#endif
#if BLOAD_AND_BSAVE || BLOAD || BLOAD_ONLY
SetupObjectPatternsBload(theEnv);
#endif
}
/* =========================================
*****************************************
INTERNALLY VISIBLE FUNCTIONS
=========================================
***************************************** */
#if ! DEFINSTANCES_CONSTRUCT
static void ResetInitialObject(
void *theEnv)
{
EXPRESSION *tmp;
DATA_OBJECT rtn;
tmp = GenConstant(theEnv,FCALL,(void *) FindFunction(theEnv,"make-instance"));
tmp->argList = GenConstant(theEnv,INSTANCE_NAME,(void *) DefclassData(theEnv)->INITIAL_OBJECT_SYMBOL);
tmp->argList->nextArg =
GenConstant(theEnv,DEFCLASS_PTR,(void *) LookupDefclassInScope(theEnv,INITIAL_OBJECT_CLASS_NAME));
EvaluateExpression(theEnv,tmp,&rtn);
ReturnExpression(theEnv,tmp);
}
#endif
#if (! BLOAD_ONLY) && (! RUN_TIME)
/*****************************************************
NAME : PatternParserFind
DESCRIPTION : Determines if a pattern CE is an
object pattern (i.e. the first field
is the constant symbol "object")
INPUTS : 1) The type of the first field
2) The value of the first field
RETURNS : TRUE if it is an object pattern,
FALSE otherwise
SIDE EFFECTS : None
NOTES : Used by AddPatternParser()
*****************************************************/
static intBool PatternParserFind(
SYMBOL_HN *value)
{
if (strcmp(ValueToString(value),OBJECT_PATTERN_INDICATOR) == 0)
return(TRUE);
return(FALSE);
}
/************************************************************************************
NAME : ObjectLHSParse
DESCRIPTION : Scans and parses an object pattern for a rule
INPUTS : 1) The logical name of the input source
2) A buffer holding the last token read
RETURNS : The address of struct lhsParseNodes, NULL on errors
SIDE EFFECTS : A series of struct lhsParseNodes are created to represent
the intermediate parse of the pattern
Pretty-print form for the pattern is saved
NOTES : Object Pattern Syntax:
(object [<class-constraint>] [<name-constraint>] <slot-constraint>*)
<class-constraint> ::= (is-a <constraint>)
<name-constraint> ::= (name <constraint>)
<slot-constraint> ::= (<slot-name> <constraint>*)
************************************************************************************/
static struct lhsParseNode *ObjectLHSParse(
void *theEnv,
const char *readSource,
struct token *lastToken)
{
struct token theToken;
struct lhsParseNode *firstNode = NULL,*lastNode = NULL,*tmpNode;
CLASS_BITMAP *clsset,*tmpset;
CONSTRAINT_RECORD *slotConstraints;
int ppbackupReqd = FALSE,multip;
/* ========================================================
Get a bitmap big enough to mark the ids of all currently
existing classes - and set all bits, since the initial
set of applicable classes is everything.
======================================================== */
clsset = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,1);
if (EmptyClassBitMap(clsset))
{
PrintErrorID(theEnv,"OBJRTBLD",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern.\n");
DeleteIntermediateClassBitMap(theEnv,clsset);
return(NULL);
}
tmpset = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,1);
IncrementIndentDepth(theEnv,7);
/* ===========================================
Parse the class, name and slot restrictions
=========================================== */
GetToken(theEnv,readSource,&theToken);
while (theToken.type != RPAREN)
{
ppbackupReqd = TRUE;
PPBackup(theEnv);
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken.printForm);
if (theToken.type != LPAREN)
{
SyntaxErrorMessage(theEnv,"object pattern");
goto ObjectLHSParseERROR;
}
GetToken(theEnv,readSource,&theToken);
if (theToken.type != SYMBOL)
{
SyntaxErrorMessage(theEnv,"object pattern");
goto ObjectLHSParseERROR;
}
if (CheckDuplicateSlots(theEnv,firstNode,(SYMBOL_HN *) theToken.value))
goto ObjectLHSParseERROR;
if (theToken.value == (void *) DefclassData(theEnv)->ISA_SYMBOL)
{
tmpNode = ParseClassRestriction(theEnv,readSource,&theToken);
if (tmpNode == NULL)
goto ObjectLHSParseERROR;
InitializeClassBitMap(theEnv,tmpset,0);
if (ProcessClassRestriction(theEnv,tmpset,&tmpNode->bottom,TRUE) == FALSE)
{
ReturnLHSParseNodes(theEnv,tmpNode);
goto ObjectLHSParseERROR;
}
IntersectClassBitMaps(clsset,tmpset);
}
else if (theToken.value == (void *) DefclassData(theEnv)->NAME_SYMBOL)
{
tmpNode = ParseNameRestriction(theEnv,readSource,&theToken);
if (tmpNode == NULL)
goto ObjectLHSParseERROR;
InitializeClassBitMap(theEnv,tmpset,1);
}
else
{
slotConstraints = ProcessSlotRestriction(theEnv,clsset,(SYMBOL_HN *) theToken.value,&multip);
if (slotConstraints != NULL)
{
InitializeClassBitMap(theEnv,tmpset,1);
tmpNode = ParseSlotRestriction(theEnv,readSource,&theToken,slotConstraints,multip);
if (tmpNode == NULL)
goto ObjectLHSParseERROR;
}
else
{
InitializeClassBitMap(theEnv,tmpset,0);
tmpNode = GetLHSParseNode(theEnv);
tmpNode->slot = (SYMBOL_HN *) theToken.value;
}
}
if (EmptyClassBitMap(tmpset))
{
PrintErrorID(theEnv,"OBJRTBLD",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy ");
EnvPrintRouter(theEnv,WERROR,ValueToString(tmpNode->slot));
EnvPrintRouter(theEnv,WERROR," restriction in object pattern.\n");
ReturnLHSParseNodes(theEnv,tmpNode);
goto ObjectLHSParseERROR;
}
if (EmptyClassBitMap(clsset))
{
PrintErrorID(theEnv,"OBJRTBLD",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern.\n");
ReturnLHSParseNodes(theEnv,tmpNode);
goto ObjectLHSParseERROR;
}
if (tmpNode != NULL)
{
if (firstNode == NULL)
firstNode = tmpNode;
else
lastNode->right = tmpNode;
lastNode = tmpNode;
}
PPCRAndIndent(theEnv);
GetToken(theEnv,readSource,&theToken);
}
if (firstNode == NULL)
{
if (EmptyClassBitMap(clsset))
{
PrintErrorID(theEnv,"OBJRTBLD",1,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern.\n");
goto ObjectLHSParseERROR;
}
firstNode = GetLHSParseNode(theEnv);
firstNode->type = SF_WILDCARD;
firstNode->slot = DefclassData(theEnv)->ISA_SYMBOL;
firstNode->slotNumber = ISA_ID;
firstNode->index = 1;
}
if (ppbackupReqd)
{
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,theToken.printForm);
}
DeleteIntermediateClassBitMap(theEnv,tmpset);
clsset = PackClassBitMap(theEnv,clsset);
firstNode->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset));
IncrementBitMapCount(firstNode->userData);
DeleteIntermediateClassBitMap(theEnv,clsset);
DecrementIndentDepth(theEnv,7);
return(firstNode);
ObjectLHSParseERROR:
DeleteIntermediateClassBitMap(theEnv,clsset);
DeleteIntermediateClassBitMap(theEnv,tmpset);
ReturnLHSParseNodes(theEnv,firstNode);
DecrementIndentDepth(theEnv,7);
return(NULL);
}
/**************************************************************
NAME : ReorderAndAnalyzeObjectPattern
DESCRIPTION : This function reexamines the object pattern
after constraint and variable analysis info
has been propagated from other patterns.
Any slots which are no longer applicable
to the pattern are eliminated from the
class set.
Also, the slot names are ordered according
to lexical value to aid in deteterming
sharing between object patterns. (The is-a
and name restrictions are always placed
first regardless of symbolic hash value.)
INPUTS : The pattern CE lhsParseNode
RETURNS : FALSE if all OK, otherwise TRUE
(e.g. all classes are eliminated as potential
matching candidates for the pattern)
SIDE EFFECTS : Slot restrictions are reordered (if necessary)
NOTES : Adds a default is-a slot if one does not
already exist
**************************************************************/
static intBool ReorderAndAnalyzeObjectPattern(
void *theEnv,
struct lhsParseNode *topNode)
{
CLASS_BITMAP *clsset,*tmpset;
EXPRESSION *rexp,*tmpmin,*tmpmax;
DEFCLASS *cls;
struct lhsParseNode *tmpNode,*subNode,*bitmap_node,*isa_node,*name_node;
register unsigned short i;
SLOT_DESC *sd;
CONSTRAINT_RECORD *crossConstraints, *theConstraint;
int incompatibleConstraint,clssetChanged = FALSE;
/* ==========================================================
Make sure that the bitmap marking which classes of object
can match the pattern is attached to the class restriction
(which will always be present and the last restriction
after the sort)
========================================================== */
topNode->right = FilterObjectPattern(theEnv,topNode->patternType,topNode->right,
&bitmap_node,&isa_node,&name_node);
if (EnvGetStaticConstraintChecking(theEnv) == FALSE)
return(FALSE);
/* ============================================
Allocate a temporary set for marking classes
============================================ */
clsset = (CLASS_BITMAP *) ValueToBitMap(bitmap_node->userData);
tmpset = NewClassBitMap(theEnv,(int) clsset->maxid,0);
/* ==========================================================
Check the allowed-values for the constraint on the is-a
slot. If there are any, make sure that only the classes
with those values as names are marked in the bitmap.
There will only be symbols in the list because the
original constraint on the is-a slot allowed only symbols.
========================================================== */
if ((isa_node == NULL) ? FALSE :
((isa_node->constraints == NULL) ? FALSE :
(isa_node->constraints->restrictionList != NULL)))
{
rexp = isa_node->constraints->restrictionList;
while (rexp != NULL)
{
cls = LookupDefclassInScope(theEnv,ValueToString(rexp->value));
if (cls != NULL)
{
if ((cls->id <= (unsigned) clsset->maxid) ? TestBitMap(clsset->map,cls->id) : FALSE)
SetBitMap(tmpset->map,cls->id);
}
rexp = rexp->nextArg;
}
clssetChanged = IdenticalClassBitMap(tmpset,clsset) ? FALSE : TRUE;
}
else
GenCopyMemory(char,tmpset->maxid / BITS_PER_BYTE + 1,tmpset->map,clsset->map);
/* ================================================================
For each of the slots (excluding name and is-a), check the total
constraints for the slot against the individual constraints
for each occurrence of the slot in the classes marked in
the bitmap. For any slot which is not compatible with
the overall constraint, clear its class's bit in the bitmap.
================================================================ */
tmpNode = topNode->right;
while (tmpNode != bitmap_node)
{
if ((tmpNode == isa_node) || (tmpNode == name_node))
{
tmpNode = tmpNode->right;
continue;
}
for (i = 0 ; i <= tmpset->maxid ; i++)
if (TestBitMap(tmpset->map,i))
{
cls = DefclassData(theEnv)->ClassIDMap[i];
sd = cls->instanceTemplate[FindInstanceTemplateSlot(theEnv,cls,tmpNode->slot)];
/* =========================================
Check the top-level lhsParseNode for type
and cardinality compatibility
========================================= */
crossConstraints = IntersectConstraints(theEnv,tmpNode->constraints,sd->constraint);
incompatibleConstraint = UnmatchableConstraint(crossConstraints);
RemoveConstraint(theEnv,crossConstraints);
if (incompatibleConstraint)
{
ClearBitMap(tmpset->map,i);
clssetChanged = TRUE;
}
else if (tmpNode->type == MF_WILDCARD)
{
/* ==========================================
Check the sub-nodes for type compatibility
========================================== */
for (subNode = tmpNode->bottom ; subNode != NULL ; subNode = subNode->right)
{
/* ========================================================
Temporarily reset cardinality of variables to
match slot so that no cardinality errors will be flagged
======================================================== */
if ((subNode->type == MF_WILDCARD) || (subNode->type == MF_VARIABLE))
{ theConstraint = subNode->constraints->multifield; }
else
{ theConstraint = subNode->constraints; }
tmpmin = theConstraint->minFields;
theConstraint->minFields = sd->constraint->minFields;
tmpmax = theConstraint->maxFields;
theConstraint->maxFields = sd->constraint->maxFields;
crossConstraints = IntersectConstraints(theEnv,theConstraint,sd->constraint);
theConstraint->minFields = tmpmin;
theConstraint->maxFields = tmpmax;
incompatibleConstraint = UnmatchableConstraint(crossConstraints);
RemoveConstraint(theEnv,crossConstraints);
if (incompatibleConstraint)
{
ClearBitMap(tmpset->map,i);
clssetChanged = TRUE;
break;
}
}
}
}
tmpNode = tmpNode->right;
}
if (clssetChanged)
{
/* =======================================================
Make sure that there are still classes of objects which
can satisfy this pattern. Otherwise, signal an error.
======================================================= */
if (EmptyClassBitMap(tmpset))
{
PrintErrorID(theEnv,"OBJRTBLD",3,TRUE);
DeleteIntermediateClassBitMap(theEnv,tmpset);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy pattern #");
PrintLongInteger(theEnv,WERROR,(long long) topNode->pattern);
EnvPrintRouter(theEnv,WERROR,".\n");
return(TRUE);
}
clsset = PackClassBitMap(theEnv,tmpset);
DeleteClassBitMap(theEnv,(void *) bitmap_node->userData);
bitmap_node->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset));
IncrementBitMapCount(bitmap_node->userData);
DeleteIntermediateClassBitMap(theEnv,clsset);
}
else
DeleteIntermediateClassBitMap(theEnv,tmpset);
return(FALSE);
}
/*****************************************************
NAME : PlaceObjectPattern
DESCRIPTION : Integrates an object pattern into the
object pattern network
INPUTS : The intermediate parse representation
of the pattern
RETURNS : The address of the new pattern
SIDE EFFECTS : Object pattern network updated
NOTES : None
*****************************************************/
static struct patternNodeHeader *PlaceObjectPattern(
void *theEnv,
struct lhsParseNode *thePattern)
{
OBJECT_PATTERN_NODE *currentLevel,*lastLevel;
struct lhsParseNode *tempPattern = NULL;
OBJECT_PATTERN_NODE *nodeSlotGroup, *newNode;
OBJECT_ALPHA_NODE *newAlphaNode;
unsigned endSlot;
BITMAP_HN *newClassBitMap,*newSlotBitMap;
struct expr *rightHash;
/*========================================================*/
/* Get the top of the object pattern network and prepare */
/* for the traversal to look for shareable pattern nodes. */
/*========================================================*/
currentLevel = ObjectNetworkPointer(theEnv);
lastLevel = NULL;
/*====================================================*/
/* Remove slot existence tests from the pattern since */
/* these are accounted for by the class bitmap and */
/* find the class and slot bitmaps. */
/*====================================================*/
rightHash = thePattern->rightHash;
newSlotBitMap = FormSlotBitMap(theEnv,thePattern->right);
thePattern->right = RemoveSlotExistenceTests(theEnv,thePattern->right,&newClassBitMap);
thePattern = thePattern->right;
/*=========================================================*/
/* Loop until all fields in the pattern have been added to */
/* the pattern network. Process the bitmap node ONLY if it */
/* is the only node in the pattern. */
/*=========================================================*/
do
{
if (thePattern->multifieldSlot)
{
tempPattern = thePattern;
thePattern = thePattern->bottom;
}
/*============================================*/
/* Determine if the last pattern field within */
/* a multifield slot is being processed. */
/*============================================*/
if (((thePattern->type == MF_WILDCARD) ||
(thePattern->type == MF_VARIABLE)) &&
(thePattern->right == NULL) && (tempPattern != NULL))
{ endSlot = TRUE; }
else
{ endSlot = FALSE; }
/*========================================*/
/* Is there a node in the pattern network */
/* that can be reused (shared)? */
/*========================================*/
newNode = FindObjectPatternNode(currentLevel,thePattern,&nodeSlotGroup,endSlot,FALSE);
/*================================================*/
/* If the pattern node cannot be shared, then add */
/* a new pattern node to the pattern network. */
/*================================================*/
if (newNode == NULL)
{ newNode = CreateNewObjectPatternNode(theEnv,thePattern,nodeSlotGroup,lastLevel,endSlot,FALSE); }
if (thePattern->constantSelector != NULL)
{
currentLevel = newNode->nextLevel;
lastLevel = newNode;
newNode = FindObjectPatternNode(currentLevel,thePattern,&nodeSlotGroup,endSlot,TRUE);
if (newNode == NULL)
{ newNode = CreateNewObjectPatternNode(theEnv,thePattern,nodeSlotGroup,lastLevel,endSlot,TRUE); }
}
/*=======================================================*/
/* Move on to the next field in the pattern to be added. */
/*=======================================================*/
if ((thePattern->right == NULL) && (tempPattern != NULL))
{
thePattern = tempPattern;
tempPattern = NULL;
}
lastLevel = newNode;
currentLevel = newNode->nextLevel;
thePattern = thePattern->right;
}
while ((thePattern != NULL) ? (thePattern->userData == NULL) : FALSE);
/*==================================================*/
/* Return the leaf node of the newly added pattern. */
/*==================================================*/
newAlphaNode = lastLevel->alphaNode;
while (newAlphaNode != NULL)
{
if ((newClassBitMap == newAlphaNode->classbmp) &&
(newSlotBitMap == newAlphaNode->slotbmp) &&
IdenticalExpression(newAlphaNode->header.rightHash,rightHash))
return((struct patternNodeHeader *) newAlphaNode);
newAlphaNode = newAlphaNode->nxtInGroup;
}
newAlphaNode = get_struct(theEnv,objectAlphaNode);
InitializePatternHeader(theEnv,&newAlphaNode->header);
newAlphaNode->header.rightHash = AddHashedExpression(theEnv,rightHash);
newAlphaNode->matchTimeTag = 0L;
newAlphaNode->patternNode = lastLevel;
newAlphaNode->classbmp = newClassBitMap;
IncrementBitMapCount(newClassBitMap);
MarkBitMapClassesBusy(theEnv,newClassBitMap,1);
newAlphaNode->slotbmp = newSlotBitMap;
if (newSlotBitMap != NULL)
IncrementBitMapCount(newSlotBitMap);
newAlphaNode->bsaveID = 0L;
newAlphaNode->nxtInGroup = lastLevel->alphaNode;
lastLevel->alphaNode = newAlphaNode;
newAlphaNode->nxtTerminal = ObjectNetworkTerminalPointer(theEnv);
SetObjectNetworkTerminalPointer(theEnv,newAlphaNode);
return((struct patternNodeHeader *) newAlphaNode);
}
/************************************************************************
NAME : FindObjectPatternNode
DESCRIPTION : Looks for a pattern node at a specified
level in the pattern network that can be reused (shared)
with a pattern field being added to the pattern network.
INPUTS : 1) The current layer of nodes being examined in the
object pattern network
2) The intermediate parse representation of the pattern
being added
3) A buffer for holding the first node of a group
of slots with the same name as the new node
4) An integer code indicating if this is the last
fiedl in a slot pattern or not
RETURNS : The old pattern network node matching the new node, or
NULL if there is none (nodeSlotGroup will hold the
place where to attach a new node)
SIDE EFFECTS : nodeSlotGroup set
NOTES : None
************************************************************************/
static OBJECT_PATTERN_NODE *FindObjectPatternNode(
OBJECT_PATTERN_NODE *listOfNodes,
struct lhsParseNode *thePattern,
OBJECT_PATTERN_NODE **nodeSlotGroup,
unsigned endSlot,
unsigned constantSelector)
{
struct expr *compareTest;
*nodeSlotGroup = NULL;
if (constantSelector)
{ compareTest = thePattern->constantValue; }
else if (thePattern->constantSelector != NULL)
{ compareTest = thePattern->constantSelector; }
else
{ compareTest = thePattern->networkTest; }
/*==========================================================*/
/* Loop through the nodes at the given level in the pattern */
/* network looking for a node that can be reused (shared). */
/*==========================================================*/
while (listOfNodes != NULL)
{
/*=========================================================*/
/* A object pattern node can be shared if the slot name is */
/* the same, the test is on the same field in the pattern, */
/* and the network test expressions are the same. */
/*=========================================================*/
if (((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE)) ?
listOfNodes->multifieldNode : (listOfNodes->multifieldNode == 0))
{
if ((thePattern->slotNumber == (int) listOfNodes->slotNameID) &&
(thePattern->index == (int) listOfNodes->whichField) &&
(thePattern->singleFieldsAfter == listOfNodes->leaveFields) &&
(endSlot == listOfNodes->endSlot) &&
IdenticalExpression(listOfNodes->networkTest,compareTest))
return(listOfNodes);
}
/*===============================================*/
/* Find the beginning of a group of nodes with */
/* the same slot name testing on the same field. */
/*===============================================*/
if ((*nodeSlotGroup == NULL) &&
(thePattern->index == (int) listOfNodes->whichField) &&
(thePattern->slotNumber == (int) listOfNodes->slotNameID))
*nodeSlotGroup = listOfNodes;
listOfNodes = listOfNodes->rightNode;
}
/*==============================================*/
/* A shareable pattern node could not be found. */
/*==============================================*/
return(NULL);
}
/*****************************************************************
NAME : CreateNewObjectPatternNode
DESCRIPTION : Creates a new pattern node and initializes
all of its values.
INPUTS : 1) The intermediate parse representation
of the new pattern node
2) A pointer to the network node after
which to add the new node
3) A pointer to the parent node on the
level above to link the new node
4) An integer code indicating if this is the last
fiedl in a slot pattern or not
RETURNS : A pointer to the new pattern node
SIDE EFFECTS : Pattern node allocated, initialized and
attached
NOTES : None
*****************************************************************/
static OBJECT_PATTERN_NODE *CreateNewObjectPatternNode(
void *theEnv,
struct lhsParseNode *thePattern,
OBJECT_PATTERN_NODE *nodeSlotGroup,
OBJECT_PATTERN_NODE *upperLevel,
unsigned endSlot,
unsigned constantSelector)
{
OBJECT_PATTERN_NODE *newNode,*prvNode,*curNode;
newNode = get_struct(theEnv,objectPatternNode);
newNode->blocked = FALSE;
newNode->multifieldNode = FALSE;
newNode->alphaNode = NULL;
newNode->matchTimeTag = 0L;
newNode->nextLevel = NULL;
newNode->rightNode = NULL;
newNode->leftNode = NULL;
newNode->bsaveID = 0L;
if ((thePattern->constantSelector != NULL) && (! constantSelector))
{ newNode->selector = TRUE; }
else
{ newNode->selector = FALSE; }
/*===========================================================*/
/* Install the expression associated with this pattern node. */
/*===========================================================*/
if (constantSelector)
{ newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantValue); }
else if (thePattern->constantSelector != NULL)
{ newNode->networkTest = AddHashedExpression(theEnv,thePattern->constantSelector); }
else
{ newNode->networkTest = AddHashedExpression(theEnv,thePattern->networkTest); }
newNode->whichField = thePattern->index;
newNode->leaveFields = thePattern->singleFieldsAfter;
/*=========================================*/
/* Install the slot name for the new node. */
/*=========================================*/
newNode->slotNameID = (unsigned) thePattern->slotNumber;
if ((thePattern->type == MF_WILDCARD) || (thePattern->type == MF_VARIABLE))
newNode->multifieldNode = TRUE;
newNode->endSlot = endSlot;
/*===============================================*/
/* Set the upper level pointer for the new node. */
/*===============================================*/
newNode->lastLevel = upperLevel;
if ((upperLevel != NULL) && (upperLevel->selector))
{ AddHashedPatternNode(theEnv,upperLevel,newNode,newNode->networkTest->type,newNode->networkTest->value); }
/*==============================================*/
/* If there are no nodes with this slot name on */
/* this level, simply prepend it to the front. */
/*==============================================*/
if (nodeSlotGroup == NULL)
{
if (upperLevel == NULL)
{
newNode->rightNode = ObjectNetworkPointer(theEnv);
SetObjectNetworkPointer(theEnv,newNode);
}
else
{
newNode->rightNode = upperLevel->nextLevel;
upperLevel->nextLevel = newNode;
}
if (newNode->rightNode != NULL)
newNode->rightNode->leftNode = newNode;
return(newNode);
}
/* ===========================================================
Group this node with other nodes of the same name
testing on the same field in the pattern
on this level. This allows us to do some optimization
with constant tests on a particular slots. If we put
all constant tests for a particular slot/field group at the
end of that group, then when one of those test succeeds
during pattern-matching, we don't have to test any
more of the nodes with that slot/field name to the right.
=========================================================== */
prvNode = NULL;
curNode = nodeSlotGroup;
while ((curNode == NULL) ? FALSE :
(curNode->slotNameID == nodeSlotGroup->slotNameID) &&
(curNode->whichField == nodeSlotGroup->whichField))
{
if ((curNode->networkTest == NULL) ? FALSE :
((curNode->networkTest->type != OBJ_PN_CONSTANT) ? FALSE :
((struct ObjectCmpPNConstant *) ValueToBitMap(curNode->networkTest->value))->pass))
break;
prvNode = curNode;
curNode = curNode->rightNode;
}
if (curNode != NULL)
{
newNode->leftNode = curNode->leftNode;
newNode->rightNode = curNode;
if (curNode->leftNode != NULL)
curNode->leftNode->rightNode = newNode;
else if (curNode->lastLevel != NULL)
curNode->lastLevel->nextLevel = newNode;
else
SetObjectNetworkPointer(theEnv,newNode);
curNode->leftNode = newNode;
}
else
{
newNode->leftNode = prvNode;
prvNode->rightNode = newNode;
}
return(newNode);
}
/********************************************************
NAME : DetachObjectPattern
DESCRIPTION : Removes a pattern node and all of its
parent nodes from the pattern network. Nodes are only
removed if they are no longer shared (i.e. a pattern
node that has more than one child node is shared). A
pattern from a rule is typically removed by removing
the bottom most pattern node used by the pattern and
then removing any parent nodes which are not shared by
other patterns.
Example:
Patterns (a b c d) and (a b e f) would be represented
by the pattern net shown on the left. If (a b c d)
was detached, the resultant pattern net would be the
one shown on the right. The '=' represents an
end-of-pattern node.
a a
| |
b b
| |
c--e e
| | |
d f f
| | |
= = =
INPUTS : The pattern to be removed
RETURNS : Nothing useful
SIDE EFFECTS : All non-shared nodes associated with the
pattern are removed
NOTES : None
********************************************************/
static void DetachObjectPattern(
void *theEnv,
struct patternNodeHeader *thePattern)
{
OBJECT_ALPHA_NODE *alphaPtr,*prv,*terminalPtr;
OBJECT_PATTERN_NODE *patternPtr,*upperLevel;
/*====================================================*/
/* Get rid of any matches stored in the alpha memory. */
/*====================================================*/
alphaPtr = (OBJECT_ALPHA_NODE *) thePattern;
ClearObjectPatternMatches(theEnv,alphaPtr);
/*========================================================*/
/* Unmark the classes to which the pattern is applicable */
/* and unmark the class and slot id maps so that they can */
/* become ephemeral. */
/*========================================================*/
MarkBitMapClassesBusy(theEnv,alphaPtr->classbmp,-1);
DeleteClassBitMap(theEnv,alphaPtr->classbmp);
if (alphaPtr->slotbmp != NULL)
{ DecrementBitMapCount(theEnv,alphaPtr->slotbmp); }
/*=========================================*/
/* Only continue deleting this pattern if */
/* this is the last alpha memory attached. */
/*=========================================*/
prv = NULL;
terminalPtr = ObjectNetworkTerminalPointer(theEnv);
while (terminalPtr != alphaPtr)
{
prv = terminalPtr;
terminalPtr = terminalPtr->nxtTerminal;
}
if (prv == NULL)
{ SetObjectNetworkTerminalPointer(theEnv,terminalPtr->nxtTerminal); }
else
{ prv->nxtTerminal = terminalPtr->nxtTerminal; }
prv = NULL;
terminalPtr = alphaPtr->patternNode->alphaNode;
while (terminalPtr != alphaPtr)
{
prv = terminalPtr;
terminalPtr = terminalPtr->nxtInGroup;
}
if (prv == NULL)
{
if (alphaPtr->nxtInGroup != NULL)
{
alphaPtr->patternNode->alphaNode = alphaPtr->nxtInGroup;
RemoveHashedExpression(theEnv,alphaPtr->header.rightHash);
rtn_struct(theEnv,objectAlphaNode,alphaPtr);
return;
}
}
else
{
prv->nxtInGroup = alphaPtr->nxtInGroup;
RemoveHashedExpression(theEnv,alphaPtr->header.rightHash);
rtn_struct(theEnv,objectAlphaNode,alphaPtr);
return;
}
alphaPtr->patternNode->alphaNode = NULL;
RemoveHashedExpression(theEnv,alphaPtr->header.rightHash);
rtn_struct(theEnv,objectAlphaNode,alphaPtr);
upperLevel = alphaPtr->patternNode;
if (upperLevel->nextLevel != NULL)
return;
/*==============================================================*/
/* Loop until all appropriate pattern nodes have been detached. */
/*==============================================================*/
while (upperLevel != NULL)
{
if ((upperLevel->leftNode == NULL) &&
(upperLevel->rightNode == NULL))
{
/*===============================================*/
/* Pattern node is the only node on this level. */
/* Remove it and continue detaching other nodes */
/* above this one, because no other patterns are */
/* dependent upon this node. */
/*===============================================*/
patternPtr = upperLevel;
upperLevel = patternPtr->lastLevel;
if (upperLevel == NULL)
SetObjectNetworkPointer(theEnv,NULL);
else
{
if (upperLevel->selector)
{ RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); }
upperLevel->nextLevel = NULL;
if (upperLevel->alphaNode != NULL)
upperLevel = NULL;
}
RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest);
rtn_struct(theEnv,objectPatternNode,patternPtr);
}
else if (upperLevel->leftNode != NULL)
{
/*====================================================*/
/* Pattern node has another pattern node which must */
/* be checked preceding it. Remove the pattern node, */
/* but do not detach any nodes above this one. */
/*====================================================*/
patternPtr = upperLevel;
if ((patternPtr->lastLevel != NULL) &&
(patternPtr->lastLevel->selector))
{ RemoveHashedPatternNode(theEnv,patternPtr->lastLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); }
upperLevel->leftNode->rightNode = upperLevel->rightNode;
if (upperLevel->rightNode != NULL)
{ upperLevel->rightNode->leftNode = upperLevel->leftNode; }
RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest);
rtn_struct(theEnv,objectPatternNode,patternPtr);
upperLevel = NULL;
}
else
{
/*====================================================*/
/* Pattern node has no pattern node preceding it, but */
/* does have one succeeding it. Remove the pattern */
/* node, but do not detach any nodes above this one. */
/*====================================================*/
patternPtr = upperLevel;
upperLevel = upperLevel->lastLevel;
if (upperLevel == NULL)
{ SetObjectNetworkPointer(theEnv,patternPtr->rightNode); }
else
{
if (upperLevel->selector)
{ RemoveHashedPatternNode(theEnv,upperLevel,patternPtr,patternPtr->networkTest->type,patternPtr->networkTest->value); }
upperLevel->nextLevel = patternPtr->rightNode;
}
patternPtr->rightNode->leftNode = NULL;
RemoveHashedExpression(theEnv,(EXPRESSION *) patternPtr->networkTest);
rtn_struct(theEnv,objectPatternNode,patternPtr);
upperLevel = NULL;
}
}
}
/***************************************************
NAME : ClearObjectPatternMatches
DESCRIPTION : Removes a pattern node alpha memory
from the list of partial matches
on all instances (active or
garbage collected)
INPUTS : The pattern node to remove
RETURNS : Nothing useful
SIDE EFFECTS : Pattern alpha memory removed
from all object partial match lists
NOTES : Used when a pattern is removed
***************************************************/
static void ClearObjectPatternMatches(
void *theEnv,
OBJECT_ALPHA_NODE *alphaPtr)
{
INSTANCE_TYPE *ins;
IGARBAGE *igrb;
/* =============================================
Loop through every active and queued instance
============================================= */
ins = InstanceData(theEnv)->InstanceList;
while (ins != NULL)
{
RemoveObjectPartialMatches(theEnv,(INSTANCE_TYPE *) ins,(struct patternNodeHeader *) alphaPtr);
ins = ins->nxtList;
}
/* ============================
Check for garbaged instances
============================ */
igrb = InstanceData(theEnv)->InstanceGarbageList;
while (igrb != NULL)
{
RemoveObjectPartialMatches(theEnv,(INSTANCE_TYPE *) igrb->ins,(struct patternNodeHeader *) alphaPtr);
igrb = igrb->nxt;
}
}
/***************************************************
NAME : RemoveObjectPartialMatches
DESCRIPTION : Removes a partial match from a
list of partial matches for
an instance
INPUTS : 1) The instance
2) The pattern node header
corresponding to the match
RETURNS : Nothing useful
SIDE EFFECTS : Match removed
NOTES : None
***************************************************/
static void RemoveObjectPartialMatches(
void *theEnv,
INSTANCE_TYPE *ins,
struct patternNodeHeader *phead)
{
struct patternMatch *match_before, *match_ptr;
match_before = NULL;
match_ptr = (struct patternMatch *) ins->partialMatchList;
/* =======================================
Loop through every match for the object
======================================= */
while (match_ptr != NULL)
{
if (match_ptr->matchingPattern == phead)
{
ins->busy--;
if (match_before == NULL)
{
ins->partialMatchList = (void *) match_ptr->next;
rtn_struct(theEnv,patternMatch,match_ptr);
match_ptr = (struct patternMatch *) ins->partialMatchList;
}
else
{
match_before->next = match_ptr->next;
rtn_struct(theEnv,patternMatch,match_ptr);
match_ptr = match_before->next;
}
}
else
{
match_before = match_ptr;
match_ptr = match_ptr->next;
}
}
}
/******************************************************
NAME : CheckDuplicateSlots
DESCRIPTION : Determines if a restriction has
already been defined in a pattern
INPUTS : The list of already built restrictions
RETURNS : TRUE if a definition already
exists, FALSE otherwise
SIDE EFFECTS : An error message is printed if a
duplicate is found
NOTES : None
******************************************************/
static intBool CheckDuplicateSlots(
void *theEnv,
struct lhsParseNode *nodeList,
SYMBOL_HN *slotName)
{
while (nodeList != NULL)
{
if (nodeList->slot == slotName)
{
PrintErrorID(theEnv,"OBJRTBLD",4,TRUE);
EnvPrintRouter(theEnv,WERROR,"Multiple restrictions on attribute ");
EnvPrintRouter(theEnv,WERROR,ValueToString(slotName));
EnvPrintRouter(theEnv,WERROR," not allowed.\n");
return(TRUE);
}
nodeList = nodeList->right;
}
return(FALSE);
}
/**********************************************************
NAME : ParseClassRestriction
DESCRIPTION : Parses the single-field constraint
on the class an object pattern
INPUTS : 1) The logical input source
2) A buffer for tokens
RETURNS : The intermediate pattern nodes
representing the class constraint
(NULL on errors)
SIDE EFFECTS : Intermediate pattern nodes allocated
NOTES : None
**********************************************************/
static struct lhsParseNode *ParseClassRestriction(
void *theEnv,
const char *readSource,
struct token *theToken)
{
struct lhsParseNode *tmpNode;
SYMBOL_HN *rln;
CONSTRAINT_RECORD *rv;
rv = GetConstraintRecord(theEnv);
rv->anyAllowed = 0;
rv->symbolsAllowed = 1;
rln = (SYMBOL_HN *) theToken->value;
SavePPBuffer(theEnv," ");
GetToken(theEnv,readSource,theToken);
tmpNode = RestrictionParse(theEnv,readSource,theToken,FALSE,rln,ISA_ID,rv,0);
if (tmpNode == NULL)
{
RemoveConstraint(theEnv,rv);
return(NULL);
}
if ((theToken->type != RPAREN) ||
(tmpNode->type == MF_WILDCARD) ||
(tmpNode->type == MF_VARIABLE))
{
PPBackup(theEnv);
if (theToken->type != RPAREN)
{
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken->printForm);
}
SyntaxErrorMessage(theEnv,"class restriction in object pattern");
ReturnLHSParseNodes(theEnv,tmpNode);
RemoveConstraint(theEnv,rv);
return(NULL);
}
tmpNode->derivedConstraints = 1;
return(tmpNode);
}
/**********************************************************
NAME : ParseNameRestriction
DESCRIPTION : Parses the single-field constraint
on the name of an object pattern
INPUTS : 1) The logical input source
2) A buffer for tokens
RETURNS : The intermediate pattern nodes
representing the name constraint
(NULL on errors)
SIDE EFFECTS : Intermediate pattern nodes allocated
NOTES : None
**********************************************************/
static struct lhsParseNode *ParseNameRestriction(
void *theEnv,
const char *readSource,
struct token *theToken)
{
struct lhsParseNode *tmpNode;
SYMBOL_HN *rln;
CONSTRAINT_RECORD *rv;
rv = GetConstraintRecord(theEnv);
rv->anyAllowed = 0;
rv->instanceNamesAllowed = 1;
rln = (SYMBOL_HN *) theToken->value;
SavePPBuffer(theEnv," ");
GetToken(theEnv,readSource,theToken);
tmpNode = RestrictionParse(theEnv,readSource,theToken,FALSE,rln,NAME_ID,rv,0);
if (tmpNode == NULL)
{
RemoveConstraint(theEnv,rv);
return(NULL);
}
if ((theToken->type != RPAREN) ||
(tmpNode->type == MF_WILDCARD) ||
(tmpNode->type == MF_VARIABLE))
{
PPBackup(theEnv);
if (theToken->type != RPAREN)
{
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken->printForm);
}
SyntaxErrorMessage(theEnv,"name restriction in object pattern");
ReturnLHSParseNodes(theEnv,tmpNode);
RemoveConstraint(theEnv,rv);
return(NULL);
}
tmpNode->derivedConstraints = 1;
return(tmpNode);
}
/***************************************************
NAME : ParseSlotRestriction
DESCRIPTION : Parses the field constraint(s)
on a slot of an object pattern
INPUTS : 1) The logical input source
2) A buffer for tokens
3) Constraint record holding the
unioned constraints of all the
slots which could match the
slot pattern
4) A flag indicating if any
multifield slots match the name
RETURNS : The intermediate pattern nodes
representing the slot constraint(s)
(NULL on errors)
SIDE EFFECTS : Intermediate pattern nodes
allocated
NOTES : None
***************************************************/
static struct lhsParseNode *ParseSlotRestriction(
void *theEnv,
const char *readSource,
struct token *theToken,
CONSTRAINT_RECORD *slotConstraints,
int multip)
{
struct lhsParseNode *tmpNode;
SYMBOL_HN *slotName;
slotName = (SYMBOL_HN *) theToken->value;
SavePPBuffer(theEnv," ");
GetToken(theEnv,readSource,theToken);
tmpNode = RestrictionParse(theEnv,readSource,theToken,multip,slotName,FindSlotNameID(theEnv,slotName),
slotConstraints,1);
if (tmpNode == NULL)
{
RemoveConstraint(theEnv,slotConstraints);
return(NULL);
}
if (theToken->type != RPAREN)
{
PPBackup(theEnv);
SavePPBuffer(theEnv," ");
SavePPBuffer(theEnv,theToken->printForm);
SyntaxErrorMessage(theEnv,"object slot pattern");
ReturnLHSParseNodes(theEnv,tmpNode);
RemoveConstraint(theEnv,slotConstraints);
return(NULL);
}
if ((tmpNode->bottom == NULL) && (tmpNode->multifieldSlot))
{
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,")");
}
tmpNode->derivedConstraints = 1;
return(tmpNode);
}
/********************************************************
NAME : NewClassBitMap
DESCRIPTION : Creates a new bitmap large enough
to hold all ids of classes in the
system and initializes all the bits
to zero or one.
INPUTS : 1) The maximum id that will be set
in the bitmap
2) An integer code indicating if all
the bits are to be set to zero or one
RETURNS : The new bitmap
SIDE EFFECTS : BitMap allocated and initialized
NOTES : None
********************************************************/
static CLASS_BITMAP *NewClassBitMap(
void *theEnv,
int maxid,
int set)
{
register CLASS_BITMAP *bmp;
unsigned size;
if (maxid == -1)
maxid = 0;
size = sizeof(CLASS_BITMAP) +
(sizeof(char) * (maxid / BITS_PER_BYTE));
bmp = (CLASS_BITMAP *) gm2(theEnv,size);
ClearBitString((void *) bmp,size);
bmp->maxid = (unsigned short) maxid;
InitializeClassBitMap(theEnv,bmp,set);
return(bmp);
}
/***********************************************************
NAME : InitializeClassBitMap
DESCRIPTION : Initializes a bitmap to all zeroes or ones.
INPUTS : 1) The bitmap
2) An integer code indicating if all
the bits are to be set to zero or one
RETURNS : Nothing useful
SIDE EFFECTS : The bitmap is initialized
NOTES : None
***********************************************************/
static void InitializeClassBitMap(
void *theEnv,
CLASS_BITMAP *bmp,
int set)
{
register int i,bytes;
DEFCLASS *cls;
struct defmodule *currentModule;
bytes = bmp->maxid / BITS_PER_BYTE + 1;
while (bytes > 0)
{
bmp->map[bytes - 1] = (char) 0;
bytes--;
}
if (set)
{
currentModule = ((struct defmodule *) EnvGetCurrentModule(theEnv));
for (i = 0 ; i <= (int) bmp->maxid ; i++)
{
cls = DefclassData(theEnv)->ClassIDMap[i];
if ((cls != NULL) ? DefclassInScope(theEnv,cls,currentModule) : FALSE)
{
if (cls->reactive && (cls->abstract == 0))
SetBitMap(bmp->map,i);
}
}
}
}
/********************************************
NAME : DeleteIntermediateClassBitMap
DESCRIPTION : Deallocates a bitmap
INPUTS : The class set
RETURNS : Nothing useful
SIDE EFFECTS : Class set deallocated
NOTES : None
********************************************/
static void DeleteIntermediateClassBitMap(
void *theEnv,
CLASS_BITMAP *bmp)
{
rm(theEnv,(void *) bmp,ClassBitMapSize(bmp));
}
/******************************************************
NAME : CopyClassBitMap
DESCRIPTION : Increments the in use count of a
bitmap and returns the same pointer
INPUTS : The bitmap
RETURNS : The bitmap
SIDE EFFECTS : Increments the in use count
NOTES : Class sets are shared by multiple
copies of an object pattern within an
OR CE. The use count prevents having
to make duplicate copies of the bitmap
******************************************************/
static void *CopyClassBitMap(
void *theEnv,
void *gset)
{
if (gset != NULL)
IncrementBitMapCount(gset);
return(gset);
}
/**********************************************************
NAME : DeleteClassBitMap
DESCRIPTION : Deallocates a bitmap,
and decrements the busy flags of the
classes marked in the bitmap
INPUTS : The bitmap
RETURNS : Nothing useful
SIDE EFFECTS : Class set deallocated and classes unmarked
NOTES : None
**********************************************************/
static void DeleteClassBitMap(
void *theEnv,
void *gset)
{
if (gset == NULL)
return;
DecrementBitMapCount(theEnv,(BITMAP_HN *) gset);
}
/***************************************************
NAME : MarkBitMapClassesBusy
DESCRIPTION : Increments/Decrements busy counts
of all classes marked in a bitmap
INPUTS : 1) The bitmap hash node
2) 1 or -1 (to increment or
decrement class busy counts)
RETURNS : Nothing useful
SIDE EFFECTS : Bitmap class busy counts updated
NOTES : None
***************************************************/
static void MarkBitMapClassesBusy(
void *theEnv,
BITMAP_HN *bmphn,
int offset)
{
register CLASS_BITMAP *bmp;
register unsigned short i;
register DEFCLASS *cls;
/* ====================================
If a clear is in progress, we do not
have to worry about busy counts
==================================== */
if (ConstructData(theEnv)->ClearInProgress)
return;
bmp = (CLASS_BITMAP *) ValueToBitMap(bmphn);
for (i = 0 ; i <= bmp->maxid ; i++)
if (TestBitMap(bmp->map,i))
{
cls = DefclassData(theEnv)->ClassIDMap[i];
cls->busy += (unsigned int) offset;
}
}
/****************************************************
NAME : EmptyClassBitMap
DESCRIPTION : Determines if one or more bits
are marked in a bitmap
INPUTS : The bitmap
RETURNS : TRUE if the set has no bits
marked, FALSE otherwise
SIDE EFFECTS : None
NOTES : None
****************************************************/
static intBool EmptyClassBitMap(
CLASS_BITMAP *bmp)
{
register unsigned short bytes;
bytes = (unsigned short) (bmp->maxid / BITS_PER_BYTE + 1);
while (bytes > 0)
{
if (bmp->map[bytes - 1] != (char) 0)
return(FALSE);
bytes--;
}
return(TRUE);
}
/***************************************************
NAME : IdenticalClassBitMap
DESCRIPTION : Determines if two bitmaps
are identical
INPUTS : 1) First bitmap
2) Second bitmap
RETURNS : TRUE if bitmaps are the same,
FALSE otherwise
SIDE EFFECTS : None
NOTES : None
***************************************************/
static intBool IdenticalClassBitMap(
CLASS_BITMAP *cs1,
CLASS_BITMAP *cs2)
{
register int i;
if (cs1->maxid != cs2->maxid)
return(FALSE);
for (i = 0 ; i < (int) (cs1->maxid / BITS_PER_BYTE + 1) ; i++)
if (cs1->map[i] != cs2->map[i])
return(FALSE);
return(TRUE);
}
/*****************************************************************
NAME : ProcessClassRestriction
DESCRIPTION : Examines a class restriction and forms a bitmap
corresponding to the maximal set of classes which
can satisfy a static analysis of the restriction
INPUTS : 1) The bitmap to mark classes in
2) The lhsParseNodes of the restriction
3) A flag indicating if this is the first
non-recursive call or not
RETURNS : TRUE if all OK, FALSE otherwise
SIDE EFFECTS : Class bitmap set and lhsParseNodes corressponding
to constant restrictions are removed
NOTES : None
*****************************************************************/
static intBool ProcessClassRestriction(
void *theEnv,
CLASS_BITMAP *clsset,
struct lhsParseNode **classRestrictions,
int recursiveCall)
{
register struct lhsParseNode *chk,**oraddr;
CLASS_BITMAP *tmpset1,*tmpset2;
int constant_restriction = TRUE;
if (*classRestrictions == NULL)
{
if (recursiveCall)
InitializeClassBitMap(theEnv,clsset,1);
return(TRUE);
}
/* ===============================================
Determine the corresponding class set and union
it with the current total class set. If an AND
restriction is comprised entirely of symbols,
it can be removed
=============================================== */
tmpset1 = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,1);
tmpset2 = NewClassBitMap(theEnv,((int) DefclassData(theEnv)->MaxClassID) - 1,0);
for (chk = *classRestrictions ; chk != NULL ; chk = chk->right)
{
if (chk->type == SYMBOL)
{
chk->value = (void *) LookupDefclassInScope(theEnv,ValueToString(chk->value));
if (chk->value == NULL)
{
PrintErrorID(theEnv,"OBJRTBLD",5,FALSE);
EnvPrintRouter(theEnv,WERROR,"Undefined class in object pattern.\n");
DeleteIntermediateClassBitMap(theEnv,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset2);
return(FALSE);
}
if (chk->negated)
{
InitializeClassBitMap(theEnv,tmpset2,1);
MarkBitMapSubclasses(tmpset2->map,(DEFCLASS *) chk->value,0);
}
else
{
InitializeClassBitMap(theEnv,tmpset2,0);
MarkBitMapSubclasses(tmpset2->map,(DEFCLASS *) chk->value,1);
}
IntersectClassBitMaps(tmpset1,tmpset2);
}
else
constant_restriction = FALSE;
}
if (EmptyClassBitMap(tmpset1))
{
PrintErrorID(theEnv,"OBJRTBLD",2,FALSE);
EnvPrintRouter(theEnv,WERROR,"No objects of existing classes can satisfy ");
EnvPrintRouter(theEnv,WERROR,"is-a restriction in object pattern.\n");
DeleteIntermediateClassBitMap(theEnv,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset2);
return(FALSE);
}
if (constant_restriction)
{
chk = *classRestrictions;
*classRestrictions = chk->bottom;
chk->bottom = NULL;
ReturnLHSParseNodes(theEnv,chk);
oraddr = classRestrictions;
}
else
oraddr = &(*classRestrictions)->bottom;
UnionClassBitMaps(clsset,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset1);
DeleteIntermediateClassBitMap(theEnv,tmpset2);
/* =====================================
Process the next OR class restriction
===================================== */
return(ProcessClassRestriction(theEnv,clsset,oraddr,FALSE));
}
/****************************************************************
NAME : ProcessSlotRestriction
DESCRIPTION : Determines which slots could match the slot
pattern and determines the union of all
constraints for the pattern
INPUTS : 1) The class set
2) The slot name
3) A buffer to hold a flag indicating if
any multifield slots are found w/ this name
RETURNS : A union of the constraints on all the slots
which could match the slots (NULL if no
slots found)
SIDE EFFECTS : The class bitmap set is marked/cleared
NOTES : None
****************************************************************/
static CONSTRAINT_RECORD *ProcessSlotRestriction(
void *theEnv,
CLASS_BITMAP *clsset,
SYMBOL_HN *slotName,
int *multip)
{
register DEFCLASS *cls;
register int si;
CONSTRAINT_RECORD *totalConstraints = NULL,*tmpConstraints;
register unsigned i;
*multip = FALSE;
for (i = 0 ; i < CLASS_TABLE_HASH_SIZE ; i++)
for (cls = DefclassData(theEnv)->ClassTable[i] ; cls != NULL ; cls = cls->nxtHash)
{
if (TestBitMap(clsset->map,cls->id))
{
si = FindInstanceTemplateSlot(theEnv,cls,slotName);
if ((si != -1) ? cls->instanceTemplate[si]->reactive : FALSE)
{
if (cls->instanceTemplate[si]->multiple)
*multip = TRUE;
tmpConstraints =
UnionConstraints(theEnv,cls->instanceTemplate[si]->constraint,totalConstraints);
RemoveConstraint(theEnv,totalConstraints);
totalConstraints = tmpConstraints;
}
else
ClearBitMap(clsset->map,cls->id);
}
}
return(totalConstraints);
}
/****************************************************
NAME : IntersectClassBitMaps
DESCRIPTION : Bitwise-ands two bitmaps and stores
the result in the first
INPUTS : The two bitmaps
RETURNS : Nothing useful
SIDE EFFECTS : ClassBitMaps anded
NOTES : Assumes the first bitmap is at least
as large as the second
****************************************************/
static void IntersectClassBitMaps(
CLASS_BITMAP *cs1,
CLASS_BITMAP *cs2)
{
register unsigned short bytes;
bytes = (unsigned short) (cs2->maxid / BITS_PER_BYTE + 1);
while (bytes > 0)
{
cs1->map[bytes - 1] &= cs2->map[bytes - 1];
bytes--;
}
}
/****************************************************
NAME : UnionClassBitMaps
DESCRIPTION : Bitwise-ors two bitmaps and stores
the result in the first
INPUTS : The two bitmaps
RETURNS : Nothing useful
SIDE EFFECTS : ClassBitMaps ored
NOTES : Assumes the first bitmap is at least
as large as the second
****************************************************/
static void UnionClassBitMaps(
CLASS_BITMAP *cs1,
CLASS_BITMAP *cs2)
{
register unsigned short bytes;
bytes = (unsigned short) (cs2->maxid / BITS_PER_BYTE + 1);
while (bytes > 0)
{
cs1->map[bytes - 1] |= cs2->map[bytes - 1];
bytes--;
}
}
/*****************************************************
NAME : PackClassBitMap
DESCRIPTION : This routine packs a bitmap
bitmap such that at least one of
the bits in the rightmost byte is
set (i.e. the bitmap takes up
the smallest space possible).
INPUTS : The bitmap
RETURNS : The new (packed) bitmap
SIDE EFFECTS : The oldset is deallocated
NOTES : None
*****************************************************/
static CLASS_BITMAP *PackClassBitMap(
void *theEnv,
CLASS_BITMAP *oldset)
{
register unsigned short newmaxid;
CLASS_BITMAP *newset;
for (newmaxid = oldset->maxid ; newmaxid > 0 ; newmaxid--)
if (TestBitMap(oldset->map,newmaxid))
break;
if (newmaxid != oldset->maxid)
{
newset = NewClassBitMap(theEnv,(int) newmaxid,0);
GenCopyMemory(char,newmaxid / BITS_PER_BYTE + 1,newset->map,oldset->map);
DeleteIntermediateClassBitMap(theEnv,oldset);
}
else
newset = oldset;
return(newset);
}
/*****************************************************************
NAME : FilterObjectPattern
DESCRIPTION : Appends an extra node to hold the bitmap,
and finds is-a and name nodes
INPUTS : 1) The object pattern parser address
to give to a default is-a slot
2) The unfiltered slot list
3) A buffer to hold the address of
the class bitmap restriction node
4) A buffer to hold the address of
the is-a restriction node
4) A buffer to hold the address of
the name restriction node
RETURNS : The filtered slot list
SIDE EFFECTS : clsset is attached to extra slot pattern
Pointers to the is-a and name slots are also
stored (if they exist) for easy reference
NOTES : None
*****************************************************************/
static struct lhsParseNode *FilterObjectPattern(
void *theEnv,
struct patternParser *selfPatternType,
struct lhsParseNode *unfilteredSlots,
struct lhsParseNode **bitmap_slot,
struct lhsParseNode **isa_slot,
struct lhsParseNode **name_slot)
{
struct lhsParseNode *prv,*cur;
*isa_slot = NULL;
*name_slot = NULL;
/* ============================================
Create a dummy node to attach to the end
of the pattern which holds the class bitmap.
============================================ */
*bitmap_slot = GetLHSParseNode(theEnv);
(*bitmap_slot)->type = SF_WILDCARD;
(*bitmap_slot)->slot = DefclassData(theEnv)->ISA_SYMBOL;
(*bitmap_slot)->slotNumber = ISA_ID;
(*bitmap_slot)->index = 1;
(*bitmap_slot)->patternType = selfPatternType;
(*bitmap_slot)->userData = unfilteredSlots->userData;
unfilteredSlots->userData = NULL;
/* ========================
Find is-a and name nodes
======================== */
prv = NULL;
cur = unfilteredSlots;
while (cur != NULL)
{
if (cur->slot == DefclassData(theEnv)->ISA_SYMBOL)
*isa_slot = cur;
else if (cur->slot == DefclassData(theEnv)->NAME_SYMBOL)
*name_slot = cur;
prv = cur;
cur = cur->right;
}
/* ================================
Add the class bitmap conditional
element to end of pattern
================================ */
if (prv == NULL)
unfilteredSlots = *bitmap_slot;
else
prv->right = *bitmap_slot;
return(unfilteredSlots);
}
/***************************************************
NAME : FormSlotBitMap
DESCRIPTION : Examines an object pattern and
forms a minimal bitmap marking
the ids of the slots used in
the pattern
INPUTS : The intermediate parsed pattern
RETURNS : The new slot bitmap (can be NULL)
SIDE EFFECTS : Bitmap created and added to hash
table - corresponding bits set
for ids of slots used in pattern
NOTES : None
***************************************************/
static BITMAP_HN *FormSlotBitMap(
void *theEnv,
struct lhsParseNode *thePattern)
{
struct lhsParseNode *node;
int maxSlotID = -1;
unsigned size;
SLOT_BITMAP *bmp;
BITMAP_HN *hshBmp;
/* =======================================
Find the largest slot id in the pattern
======================================= */
for (node = thePattern ; node != NULL ; node = node->right)
if (node->slotNumber > maxSlotID)
maxSlotID = node->slotNumber;
/* ===================================================
If the pattern contains no slot tests or only tests
on the class or name (which do not change) do not
store a slot bitmap
=================================================== */
if ((maxSlotID == ISA_ID) || (maxSlotID == NAME_ID))
return(NULL);
/* ===================================
Initialize the bitmap to all zeroes
=================================== */
size = (sizeof(SLOT_BITMAP) +
(sizeof(char) * (maxSlotID / BITS_PER_BYTE)));
bmp = (SLOT_BITMAP *) gm2(theEnv,size);
ClearBitString((void *) bmp,size);
bmp->maxid = (unsigned short) maxSlotID;
/* ============================================
Add (retrieve) a bitmap to (from) the bitmap
hash table which has a corresponding bit set
for the id of every slot used in the pattern
============================================ */
for (node = thePattern ; node != NULL ; node = node->right)
SetBitMap(bmp->map,node->slotNumber);
hshBmp = (BITMAP_HN *) EnvAddBitMap(theEnv,(void *) bmp,SlotBitMapSize(bmp));
rm(theEnv,(void *) bmp,size);
return(hshBmp);
}
/****************************************************
NAME : RemoveSlotExistenceTests
DESCRIPTION : Removes slot existence test since
these are accounted for by class
bitmap or name slot.
INPUTS : 1) The intermediate pattern nodes
2) A buffer to hold the class bitmap
RETURNS : The filtered list
SIDE EFFECTS : Slot existence tests removed
NOTES : None
****************************************************/
static struct lhsParseNode *RemoveSlotExistenceTests(
void *theEnv,
struct lhsParseNode *thePattern,
BITMAP_HN **bmp)
{
struct lhsParseNode *tempPattern = thePattern;
struct lhsParseNode *lastPattern = NULL, *head = thePattern;
while (tempPattern != NULL)
{
/* ==========================================
Remember the class bitmap for this pattern
========================================== */
if (tempPattern->userData != NULL)
{
*bmp = (BITMAP_HN *) tempPattern->userData;
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
/* ===========================================================
A single field slot that has no pattern network expression
associated with it can be removed (i.e. any value contained
in this slot will satisfy the pattern being matched).
=========================================================== */
else if (((tempPattern->type == SF_WILDCARD) ||
(tempPattern->type == SF_VARIABLE)) &&
(tempPattern->networkTest == NULL))
{
if (lastPattern != NULL) lastPattern->right = tempPattern->right;
else head = tempPattern->right;
tempPattern->right = NULL;
ReturnLHSParseNodes(theEnv,tempPattern);
if (lastPattern != NULL) tempPattern = lastPattern->right;
else tempPattern = head;
}
/* =====================================================
A multifield variable or wildcard within a multifield
slot can be removed if there are no other multifield
variables or wildcards contained in the same slot
(and the multifield has no expressions which must be
evaluated in the fact pattern network).
===================================================== */
else if (((tempPattern->type == MF_WILDCARD) || (tempPattern->type == MF_VARIABLE)) &&
(tempPattern->multifieldSlot == FALSE) &&
(tempPattern->networkTest == NULL) &&
(tempPattern->multiFieldsBefore == 0) &&
(tempPattern->multiFieldsAfter == 0))
{
if (lastPattern != NULL) lastPattern->right = tempPattern->right;
else head = tempPattern->right;
tempPattern->right = NULL;
ReturnLHSParseNodes(theEnv,tempPattern);
if (lastPattern != NULL) tempPattern = lastPattern->right;
else tempPattern = head;
}
/* ================================================================
A multifield wildcard or variable contained in a multifield slot
that contains no other multifield wildcards or variables, but
does have an expression that must be evaluated, can be changed
to a single field pattern node with the same expression.
================================================================ */
else if (((tempPattern->type == MF_WILDCARD) || (tempPattern->type == MF_VARIABLE)) &&
(tempPattern->multifieldSlot == FALSE) &&
(tempPattern->networkTest != NULL) &&
(tempPattern->multiFieldsBefore == 0) &&
(tempPattern->multiFieldsAfter == 0))
{
tempPattern->type = SF_WILDCARD;
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
/* =======================================================
If we're dealing with a multifield slot with no slot
restrictions, then treat the multfield slot as a single
field slot, but attach a test which verifies that the
slot contains a zero length multifield value.
======================================================= */
else if ((tempPattern->type == MF_WILDCARD) &&
(tempPattern->multifieldSlot == TRUE) &&
(tempPattern->bottom == NULL))
{
tempPattern->type = SF_WILDCARD;
GenObjectZeroLengthTest(theEnv,tempPattern);
tempPattern->multifieldSlot = FALSE;
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
/* ======================================================
Recursively call RemoveSlotExistenceTests for the slot
restrictions contained within a multifield slot.
====================================================== */
else if ((tempPattern->type == MF_WILDCARD) &&
(tempPattern->multifieldSlot == TRUE))
{
/* =====================================================
Add an expression to the first pattern restriction in
the multifield slot that determines whether or not
the fact's slot value contains the minimum number of
required fields to satisfy the pattern restrictions
for this slot. The length check is place before any
other tests, so that preceeding checks do not have to
determine if there are enough fields in the slot to
safely retrieve a value.
===================================================== */
GenObjectLengthTest(theEnv,tempPattern->bottom);
/* =======================================================
Remove any unneeded pattern restrictions from the slot.
======================================================= */
tempPattern->bottom = RemoveSlotExistenceTests(theEnv,tempPattern->bottom,bmp);
/* =========================================================
If the slot no longer contains any restrictions, then the
multifield slot can be completely removed. In any case,
move on to the next slot to be examined for removal.
========================================================= */
if (tempPattern->bottom == NULL)
{
if (lastPattern != NULL) lastPattern->right = tempPattern->right;
else head = tempPattern->right;
tempPattern->right = NULL;
ReturnLHSParseNodes(theEnv,tempPattern);
if (lastPattern != NULL) tempPattern = lastPattern->right;
else tempPattern = head;
}
else
{
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
}
/* =====================================================
If none of the other tests for removing slots or slot
restrictions apply, then move on to the next slot or
slot restriction to be tested.
===================================================== */
else
{
lastPattern = tempPattern;
tempPattern = tempPattern->right;
}
}
/* ====================================
Return the pattern with unused slots
and slot restrictions removed.
==================================== */
return(head);
}
/***************************************************
NAME : CreateInitialObjectPattern
DESCRIPTION : Creates a default object pattern
for use in defrules
INPUTS : None
RETURNS : The default initial pattern
SIDE EFFECTS : Pattern created
NOTES : The pattern created is:
(object (is-a INITIAL-OBJECT)
(name [initial-object]))
***************************************************/
static struct lhsParseNode *CreateInitialObjectPattern(
void *theEnv)
{
struct lhsParseNode *topNode;
CLASS_BITMAP *clsset;
int initialObjectClassID;
initialObjectClassID = LookupDefclassInScope(theEnv,INITIAL_OBJECT_CLASS_NAME)->id;
clsset = NewClassBitMap(theEnv,initialObjectClassID,0);
SetBitMap(clsset->map,initialObjectClassID);
clsset = PackClassBitMap(theEnv,clsset);
topNode = GetLHSParseNode(theEnv);
topNode->userData = EnvAddBitMap(theEnv,(void *) clsset,ClassBitMapSize(clsset));
IncrementBitMapCount(topNode->userData);
DeleteIntermediateClassBitMap(theEnv,clsset);
topNode->type = SF_WILDCARD;
topNode->index = 1;
topNode->slot = DefclassData(theEnv)->NAME_SYMBOL;
topNode->slotNumber = NAME_ID;
topNode->bottom = GetLHSParseNode(theEnv);
topNode->bottom->type = INSTANCE_NAME;
topNode->bottom->value = (void *) DefclassData(theEnv)->INITIAL_OBJECT_SYMBOL;
return(topNode);
}
/**************************************************************
NAME : ObjectMatchDelayParse
DESCRIPTION : Parses the object-pattern-match-delay function
INPUTS : 1) The function call expression
2) The logical name of the input source
RETURNS : The top expression with the other
action expressions attached
SIDE EFFECTS : Parses the function call and attaches
the appropriate arguments to the
top node
NOTES : None
**************************************************************/
static EXPRESSION *ObjectMatchDelayParse(
void *theEnv,
struct expr *top,
const char *infile)
{
struct token tkn;
IncrementIndentDepth(theEnv,3);
PPCRAndIndent(theEnv);
top->argList = GroupActions(theEnv,infile,&tkn,TRUE,NULL,FALSE);
PPBackup(theEnv);
PPBackup(theEnv);
SavePPBuffer(theEnv,tkn.printForm);
DecrementIndentDepth(theEnv,3);
if (top->argList == NULL)
{
ReturnExpression(theEnv,top);
return(NULL);
}
return(top);
}
/***************************************************
NAME : MarkObjectPtnIncrementalReset
DESCRIPTION : Marks/unmarks an object pattern for
incremental reset
INPUTS : 1) The object pattern alpha node
2) The value to which to set the
incremental reset flag
RETURNS : Nothing useful
SIDE EFFECTS : The pattern node is set/unset
NOTES : The pattern node can only be
set if it is a new node and
thus marked for initialization
by PlaceObjectPattern
***************************************************/
static void MarkObjectPtnIncrementalReset(
void *theEnv,
struct patternNodeHeader *thePattern,
int value)
{
if (thePattern->initialize == FALSE)
return;
thePattern->initialize = value;
}
/***********************************************************
NAME : ObjectIncrementalReset
DESCRIPTION : Performs an assert for all instances in the
system. All new patterns in the pattern
network from the new rule have been marked
as needing processing. Old patterns will
be ignored.
INPUTS : None
RETURNS : Nothing useful
SIDE EFFECTS : All objects driven through new patterns
NOTES : None
***********************************************************/
static void ObjectIncrementalReset(
void *theEnv)
{
INSTANCE_TYPE *ins;
for (ins = InstanceData(theEnv)->InstanceList ; ins != NULL ; ins = ins->nxtList)
ObjectNetworkAction(theEnv,OBJECT_ASSERT,(INSTANCE_TYPE *) ins,-1);
}
#endif
#endif
|
CREATE TABLE books (
id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
author_id INT(11) UNSIGNED NOT NULL,
publisher_id INT(11) UNSIGNED NOT NULL
);
CREATE TABLE authors (
id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
);
CREATE TABLE publishers (
id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
);
ALTER TABLE books
ADD CONSTRAINT FK_books_author
FOREIGN KEY (author_id) REFERENCES authors(id);
ALTER TABLE books
ADD CONSTRAINT FK_books_publisher
FOREIGN KEY (publisher_id) REFERENCES publishers(id); |
package com.team242.robozzle.telemetry;
import flexjson.ObjectBinder;
import flexjson.ObjectFactory;
import flexjson.transformer.AbstractTransformer;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Created by lost on 10/25/2015.
*/
public class Iso8601DateTransformer extends AbstractTransformer
implements ObjectFactory {
static final SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
static {
TimeZone utc = TimeZone.getTimeZone("UTC");
iso8601.setTimeZone(utc);
}
@Override
public void transform(Object object) {
Date date = (Date)object;
if (date == null) {
this.getContext().write("null");
return;
}
String formattedValue = iso8601.format(date);
this.getContext().writeQuoted(formattedValue);
}
@Override
public Object instantiate(ObjectBinder context, Object value, Type targetType, Class targetClass) {
if (value == null)
return null;
try {
return iso8601.parse(value.toString());
} catch (ParseException e){
throw new RuntimeException(e);
}
}
}
|
#!/bin/bash
################################################################################################################################################################
# @project Library/Mathematics
# @file tools/ci/documentation.sh
# @author Lucas Brémond <lucas@loftorbital.com>
# @license Apache License 2.0
################################################################################################################################################################
# https://gist.github.com/vidavidorra/548ffbcdae99d752da02
script_directory="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
project_directory="${script_directory}/../.."
source "${project_directory}/tools/.env"
# Generate documentation
docker run \
--rm \
--volume="${project_directory}:/app:rw" \
--volume="/app/build" \
--workdir="/app/build" \
${image_name}:${image_version} \
/bin/bash -c "cmake -DBUILD_DOCUMENTATION=ON .. && make docs"
# Deploy documentation
mkdir -p "./gh-pages"
pushd "./gh-pages"
git clone -b gh-pages https://git@${ci_doc_repo_ref}
pushd ${ci_doc_repo_name}
# Set the push default to simple i.e. push only the current branch.
git config --global push.default simple
# Pretend to be an user called Travis CI.
git config user.name ${ci_doc_repo_user_name}
git config user.email ${ci_doc_repo_user_email}
rm -rf ./*
mv .git git
rm -rf ./.*
mv git .git
cp "${project_directory}"/README.md .
cp -r "${project_directory}"/docs/* .
# Need to create a .nojekyll file to allow filenames starting with an underscore
# to be seen on the gh-pages site. Therefore creating an empty .nojekyll file.
# Presumably this is only needed when the SHORT_NAMES option in Doxygen is set
# to NO, which it is by default. So creating the file just in case.
echo "" > .nojekyll
# Only upload if Doxygen successfully created the documentation.
# Check this by verifying that the html directory and the file html/index.html
# both exist. This is a good indication that Doxygen did its work.
if [ -d "html" ] && [ -f "html/index.html" ]; then
# Add everything in this directory (the Doxygen code documentation) to the gh-pages branch.
# GitHub is smart enough to know which files have changed and which files have
# stayed the same and will only update the changed files.
echo 'Adding documentation to the gh-pages branch...'
git add --all
# Commit the added files with a title and description containing the Travis CI
# build number and the GitHub commit reference that issued this build.
git commit -m "[feature] Deploy documentation to GitHub Pages" -m "Travis build: ${TRAVIS_BUILD_NUMBER}" -m "Commit: ${TRAVIS_COMMIT}"
# Force push to the remote gh-pages branch.
# The ouput is redirected to /dev/null to hide any sensitive credential data that might otherwise be exposed.
echo 'Pushing documentation to remote...'
git push --force "https://${ci_doc_repo_token}@${ci_doc_repo_ref}" > /dev/null 2>&1
else
echo '' >&2
echo '[Error] No documentation (html) files have been found!' >&2
exit 1
fi
popd
################################################################################################################################################################ |
def commonElements(l1, l2):
return set(l1).intersection(l2) |
#!/bin/bash
set -e
# Path
LOCAL_DIR=../data/wikitext-103
GSDATA=gs://kl-colab/transformer-xl
GSEXP=gs://kl-colab/transformer-xl/wt103-3
# TPU setting
NUM_HOST=1
NUM_CORE=8 # TPUv2 -> 8 | TPUv3 -> 16
TEST_NUM_HOST=1
TEST_NUM_CORE=8 # TPUv2 -> 8 | TPUv3 -> 16
TRAIN_BSZ=128
VALID_BSZ=128
# Model
DIV_VAL=4
N_LAYER=12
D_MODEL=512
D_EMBED=512
N_HEAD=8
D_HEAD=64
D_INNER=4096
# Training
TGT_LEN=256
MEM_LEN=256
# Testing
TEST_TGT_LEN=128
TEST_MEM_LEN=1600
TEST_CLAMP_LEN=1000
TEST_BSZ=8
if [[ $1 == 'train_data' ]]; then
python data_utils.py \
--data_dir=${LOCAL_DIR}/ \
--dataset=wt103 \
--tgt_len=${TGT_LEN} \
--per_host_train_bsz=${TRAIN_BSZ} \
--per_host_valid_bsz=${VALID_BSZ} \
--num_core_per_host=${NUM_CORE} \
--num_passes=2 \
--use_tpu=True \
${@:2}
SRC_PATTERN=train.bsz-${TRAIN_BSZ}.tlen-${TGT_LEN}.core-${NUM_CORE}*
gsutil cp ${LOCAL_DIR}/tfrecords/${SRC_PATTERN} ${GSDATA}/wt103-tfrecords/
SRC_PATTERN=valid.bsz-${VALID_BSZ}.tlen-${TGT_LEN}.core-${NUM_CORE}*
gsutil cp ${LOCAL_DIR}/tfrecords/${SRC_PATTERN} ${GSDATA}/wt103-tfrecords/
elif [[ $1 == 'test_data' ]]; then
python data_utils.py \
--data_dir=${LOCAL_DIR}/ \
--dataset=wt103 \
--tgt_len=${TEST_TGT_LEN} \
--per_host_test_bsz=${TEST_BSZ} \
--num_core_per_host=${TEST_NUM_CORE} \
--num_passes=1 \
--use_tpu=True \
${@:2}
SRC_PATTERN=test.bsz-${TEST_BSZ}.tlen-${TEST_TGT_LEN}.core-${TEST_NUM_CORE}*
gsutil cp ${LOCAL_DIR}/tfrecords/${SRC_PATTERN} ${GSDATA}/wt103-tfrecords/
elif [[ $1 == 'train' ]]; then
echo 'Run training...'
python train.py \
--data_dir=${GSDATA}/wt103-tfrecords \
--record_info_dir=${LOCAL_DIR}/tfrecords/ \
--corpus_info_path=${LOCAL_DIR}/corpus-info.json \
--model_dir=${GSEXP} \
--div_val=${DIV_VAL} \
--untie_r=True \
--proj_share_all_but_first=True \
--proj_same_dim=True \
--n_layer=${N_LAYER} \
--d_model=${D_MODEL} \
--d_embed=${D_EMBED} \
--n_head=${N_HEAD} \
--d_head=${D_HEAD} \
--d_inner=${D_INNER} \
--dropout=0.2 \
--dropatt=0.2 \
--init_std=0.005 \
--learning_rate=0.00025 \
--warmup_steps=8000 \
--train_steps=4000000 \
--tgt_len=${TGT_LEN} \
--mem_len=${MEM_LEN} \
--train_batch_size=${TRAIN_BSZ} \
--num_hosts=${NUM_HOST} \
--num_core_per_host=${NUM_CORE} \
--iterations=1000 \
--save_steps=1000 \
--use_tpu=True \
--do_eval=False \
${@:2}
elif [[ $1 == 'eval' ]]; then
echo 'Run evaluation...'
python train.py \
--data_dir=${GSDATA}/wt103-tfrecords \
--record_info_dir=${LOCAL_DIR}/tfrecords/ \
--corpus_info_path=${LOCAL_DIR}/corpus-info.json \
--model_dir=${GSEXP} \
--div_val=${DIV_VAL} \
--untie_r=True \
--proj_share_all_but_first=True \
--proj_same_dim=True \
--n_layer=${N_LAYER} \
--d_model=${D_MODEL} \
--d_embed=${D_EMBED} \
--n_head=${N_HEAD} \
--d_head=${D_HEAD} \
--d_inner=${D_INNER} \
--tgt_len=${TEST_TGT_LEN} \
--mem_len=${TEST_MEM_LEN} \
--clamp_len=${TEST_CLAMP_LEN} \
--same_length=True \
--eval_batch_size=${TEST_BSZ} \
--num_host=${TEST_NUM_HOST} \
--num_core_per_host=${TEST_NUM_CORE} \
--use_tpu=True \
--do_train=False \
--do_eval_only=True \
--eval_split=test \
${@:2}
else
echo 'unknown argment 1'
fi
|
/*
Copyright 2020, Verizon Media
Licensed under the terms of the MIT license. See the LICENSE file in the project root for license terms.
*/
export class SelectThemeProperties {
public selectThemeCols = [
{
_class: 'monospaced',
colHeadName: 'name',
colHeadValue: 'Name',
},
{
_class: 'monospaced',
colHeadName: 'property',
colHeadValue: 'CSS Property',
},
{
_class: 'monospaced',
colClass: 't350',
colHeadName: 'default',
colHeadValue: 'Bindable Theme',
},
];
public selectThemeProperties = [
{
default: 'var(--s3)',
name: '--select-padding-right',
property: 'padding-right',
},
{
default: 'var(--c_subOneMain)',
name: '--select-multiple-checked',
property: 'background',
},
{
default: 'var(--c_asphalt)',
name: '--select-multiple-load-more-background',
property: 'background',
},
{
default: 'url(\'data:image/svg+xml;utf8,<svg width="12" height="7" viewBox="0 0 12 7" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h12L5.94 7 0 0z" fill="\%239B9B97"/></svg>\')',
name: '--select-arrow-svg',
property: 'background-image',
},
{
default: 'right 10px center',
name: '--select-arrow-position',
property: 'background-position',
},
];
}
|
/*
* This file is based on the server example of aiortc.
*/
'use strict';
// Put variables in global scope to make them available to the browser console.
const audio = document.querySelector('audio');
const constraints = window.constraints = {
audio: true,
video: false
};
var dataChannelLog = document.getElementById('data-channel'),
iceConnectionLog = document.getElementById('ice-connection-state'),
iceGatheringLog = document.getElementById('ice-gathering-state'),
signalingLog = document.getElementById('signaling-state');
var pc = null;
var apc = null;
var dc = null;
var canSend = false;
function createPeerConnection() {
var config = {
sdpSemantics: 'unified-plan'
};
var pc = new RTCPeerConnection(config);
//pc.onnegotiationneeded = negotiate;
// register some listeners to help debugging
pc.addEventListener('icegatheringstatechange', function() {
iceGatheringLog.textContent += ' -> ' + pc.iceGatheringState;
}, false);
iceGatheringLog.textContent = pc.iceGatheringState;
pc.addEventListener('iceconnectionstatechange', function() {
iceConnectionLog.textContent += ' -> ' + pc.iceConnectionState;
}, false);
iceConnectionLog.textContent = pc.iceConnectionState;
pc.addEventListener('signalingstatechange', function() {
signalingLog.textContent += ' -> ' + pc.signalingState;
}, false);
signalingLog.textContent = pc.signalingState;
//pc.addEventListener('icegatheringstatechange')
//pc.addEventListener('iceconnectionstatechange')
//pc.addEventListener('signalingstatechange')
//pc.addEventListener('track', function(e) {
//audio.srcObject = e.streams[0];
//});
return pc;
}
function negotiate() {
return pc.createOffer().then(function(offer) {
return pc.setLocalDescription(offer);
}).then(function() {
return new Promise(function(resolve) {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange',
checkState);
resolve();
}
}
pc.addEventListener('icegatheringstatechange', checkState);
}
});
}).then(function(){
var offer = pc.localDescription;
document.getElementById('offer-sdp').textContent = offer.sdp;
return fetch('/offer', {
body: JSON.stringify({
sdp: offer.sdp,
type: offer.type
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
}).then(function(response) {
return response.json();
}).then(function(answer) {
document.getElementById('answer-sdp').textContent = answer.sdp;
return pc.setRemoteDescription(answer);
}).catch(function(e){
alert(e);
});
}
/** Duties and expectations
* Expectations:
* 1. Will receive update of place in queue
* 2. Users may be stopped during speaking
*
* Duties:
* 1. Join queue
* 2. Leave queue
* 3. Speak when activated
* 4. Check status
*/
function status() {
sendMessage('status-check');
}
function sendMessage(message) {
if (canSend) {
dataChannelLog.textContent += '> ' + message + '\n';
dc.send(message);
}
}
function queue() {
pc = createPeerConnection();
dc = pc.createDataChannel('chat', { "ordered": true });
dc.onclose = function() {
canSend = false;
};
dc.onopen = function() {
canSend = true;
sendMessage('enterqueue');
};
dc.onmessage = function(e) {
dataChannelLog.textContent += '< ' + e.data + '\n';
if (e.data === 'ready') {
// FIXME remove queue position
audioStart();
document.getElementById('queue-status').textContent = "Live";
} else if (e.data.substring(0, 8) === 'position') {
document.getElementById('queue-status').textContent =
e.data.substring(9);
} else if (e.data === 'bumped') {
unqueue(true);
}
};
// We create this now, rather than when the client is "called on"
// This is because we have to have the audio stream in our
// initial connection or it will fail on renegotiating in Firefox
// (Because Firefox insanely sends an RTP Goodbye packet upon opening
// the audio stream when done from renegotiation (BZ: 1232234))
// This could alternatively be done by creating a separate PC at
// the time the client is called on.
//navigator.mediaDevices.getUserMedia(constraints).then(
//function(stream) {
//stream.getTracks().forEach(function(track) {
//pc.addTrack(track, stream);
//});
//},
//function(err) {
//alert('Could not acquire media: ' + err);
//});
negotiate();
}
function unqueue(byRemote) {
audioStop();
if (dc) {
if (!byRemote) {
sendMessage('leaving');
// to prevent it from trying to reconnect
}
dc.close();
}
setTimeout(function() {
pc.close();
}, 5000);
}
function audioNegotiate() {
return apc.createOffer().then(function(offer) {
return apc.setLocalDescription(offer);
}).then(function() {
return new Promise(function(resolve) {
if (apc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
if (apc.iceGatheringState === 'complete') {
apc.removeEventListener('icegatheringstatechange',
checkState);
resolve();
}
}
apc.addEventListener('icegatheringstatechange', checkState);
}
});
}).then(function(){
var offer = apc.localDescription;
return fetch('/audio_offer', {
body: JSON.stringify({
sdp: offer.sdp,
type: offer.type
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
}).then(function(response) {
return response.json();
}).then(function(answer) {
return apc.setRemoteDescription(answer);
}).catch(function(e){
alert(e);
});
}
function createAudioPeerConnection() {
var config = {
sdpSemantics: 'unified-plan'
};
var apc = new RTCPeerConnection(config);
return apc;
}
function audioStart() {
apc = createAudioPeerConnection();
navigator.mediaDevices.getUserMedia(constraints).then(
function(stream) {
stream.getTracks().forEach(function(track) {
apc.addTrack(track, stream);
});
},
function(err) {
alert('Could not acquire media: ' + err);
}).then(audioNegotiate);
}
function audioStop() {
if (!apc) {
// nothing to do
return;
}
if (apc.getTransceivers) {
apc.getTransceivers().forEach(function(transceiver) {
if (transceiver.stop) {
transceiver.stop();
}
});
}
apc.getSenders().forEach(function(sender) {
sender.track.stop();
});
setTimeout(function() {
apc.close();
}, 500);
}
|
import java.util.function.Function;
public class TypeSetter {
private com.commercetools.api.models.type.TypeResourceIdentifier type;
public TypeSetter setTypeResourceIdentifier(Function<com.commercetools.api.models.type.TypeResourceIdentifierBuilder, com.commercetools.api.models.type.TypeResourceIdentifierBuilder> builder) {
this.type = builder.apply(com.commercetools.api.models.type.TypeResourceIdentifierBuilder.of()).build();
return this;
}
} |
<reponame>noah-/AutoTathamet
const { createBot } = require('../index')
if (process.argv.length !== 9) {
console.log('Usage : node bot.js <username> <password> <character> <gamename> <gamepasswd> <gameserver> <host>')
process.exit(1)
}
const possible = 'abcdefghijklmnopqrstuvwxyz'
let randomGame = ''
for (let i = 0; i < 5; i++) { randomGame += possible.charAt(Math.floor(Math.random() * possible.length)) }
if (process.argv[5] === 'rand') { console.log('connecting to randomGame ' + randomGame) }
const character = process.argv[4]
const gameName = process.argv[5] === 'rand' ? randomGame : process.argv[5]
const gamePassword = process.argv[6] === 'none' ? '' : process.argv[6]
const gameServer = process.argv[7]
const host = process.argv[8]
async function start () {
const bot = await createBot({
host: host,
username: process.argv[2],
password: process.argv[3]
})
await bot.selectCharacter(character)
await bot.createGame(gameName, gamePassword, gameServer, 0)
}
start()
|
#!/usr/bin/env bash
#Description: Kyma CLI Integration plan on Gardener. This scripts implements a pipeline that consists of many steps. The purpose is to install and test Kyma using the CLI on a real Gardener cluster.
#
#
#Expected vars:
#
# - KYMA_PROJECT_DIR - directory path with Kyma sources to use for installation
# - GARDENER_REGION - Gardener compute region
# - GARDENER_ZONES - Gardener compute zones inside the region
# - GARDENER_KYMA_PROW_KUBECONFIG - Kubeconfig of the Gardener service account
# - GARDENER_KYMA_PROW_PROJECT_NAME Name of the gardener project where the cluster will be integrated.
# - GARDENER_KYMA_PROW_PROVIDER_SECRET_NAME Name of the GCP secret configured in the gardener project to access the cloud provider
# - MACHINE_TYPE (optional): GCP machine type
#
#Permissions: In order to run this script you need to use a service account with permissions equivalent to the following GCP roles:
# - Compute Admin
# - Service Account User
# - Service Account Admin
# - Service Account Token Creator
# - Make sure the service account is enabled for the Google Identity and Access Management API.
set -e
discoverUnsetVar=false
VARIABLES=(
KYMA_PROJECT_DIR
GARDENER_REGION
GARDENER_ZONES
GARDENER_KYMA_PROW_KUBECONFIG
GARDENER_KYMA_PROW_PROJECT_NAME
GARDENER_KYMA_PROW_PROVIDER_SECRET_NAME
)
for var in "${VARIABLES[@]}"; do
if [ -z "${!var}" ] ; then
echo "ERROR: $var is not set"
discoverUnsetVar=true
fi
done
if [ "${discoverUnsetVar}" = true ] ; then
exit 1
fi
readonly GARDENER_CLUSTER_VERSION="1.16"
#Exported variables
export TEST_INFRA_SOURCES_DIR="${KYMA_PROJECT_DIR}/test-infra"
export TEST_INFRA_CLUSTER_INTEGRATION_SCRIPTS="${TEST_INFRA_SOURCES_DIR}/prow/scripts/cluster-integration/helpers"
# shellcheck disable=SC1090
source "${TEST_INFRA_SOURCES_DIR}/prow/scripts/library.sh"
# shellcheck disable=SC1090
source "${TEST_INFRA_SOURCES_DIR}/prow/scripts/lib/testing-helpers.sh"
# shellcheck disable=SC1090
source "${TEST_INFRA_SOURCES_DIR}/prow/scripts/cluster-integration/helpers/kyma-cli.sh"
#!Put cleanup code in this function! Function is executed at exit from the script and on interuption.
cleanup() {
#!!! Must be at the beginning of this function !!!
EXIT_STATUS=$?
#Turn off exit-on-error so that next step is executed even if previous one fails.
set +e
if [[ -n "${SUITE_NAME}" ]]; then
testSummary
fi
if [ "${ERROR_LOGGING_GUARD}" = "true" ]; then
shout "AN ERROR OCCURED! Take a look at preceding log entries."
echo
fi
if [ -n "${CLEANUP_CLUSTER}" ]; then
shout "Deprovision cluster: \"${CLUSTER_NAME}\""
date
# Export envvars for the script
export GARDENER_CLUSTER_NAME=${CLUSTER_NAME}
export GARDENER_PROJECT_NAME=${GARDENER_KYMA_PROW_PROJECT_NAME}
export GARDENER_CREDENTIALS=${GARDENER_KYMA_PROW_KUBECONFIG}
"${TEST_INFRA_CLUSTER_INTEGRATION_SCRIPTS}"/deprovision-gardener-cluster.sh
fi
rm -rf "${TMP_DIR}"
MSG=""
if [[ ${EXIT_STATUS} -ne 0 ]]; then MSG="(exit status: ${EXIT_STATUS})"; fi
shout "Job is finished ${MSG}"
date
set -e
exit "${EXIT_STATUS}"
}
testSummary() {
echo "Test Summary"
kyma test status "${SUITE_NAME}" -owide
statusSucceeded=$(kubectl get cts "${SUITE_NAME}" -ojsonpath="{.status.conditions[?(@.type=='Succeeded')]}")
if [[ "${statusSucceeded}" != *"True"* ]]; then
echo "- Fetching logs due to test suite failure"
echo "- Fetching logs from testing pods in Failed status..."
kyma test logs "${SUITE_NAME}" --test-status Failed
echo "- Fetching logs from testing pods in Unknown status..."
kyma test logs "${SUITE_NAME}" --test-status Unknown
echo "- Fetching logs from testing pods in Running status due to running afer test suite timeout..."
kyma test logs "${SUITE_NAME}" --test-status Running
echo "ClusterTestSuite details"
kubectl get cts "${SUITE_NAME}" -oyaml
exit 1
fi
echo "ClusterTestSuite details"
kubectl get cts "${SUITE_NAME}" -oyaml
}
trap cleanup EXIT INT
RANDOM_NAME_SUFFIX=$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom | head -c4)
readonly COMMON_NAME_PREFIX="grdnr"
COMMON_NAME=$(echo "${COMMON_NAME_PREFIX}${RANDOM_NAME_SUFFIX}" | tr "[:upper:]" "[:lower:]")
### Cluster name must be less than 10 characters!
export CLUSTER_NAME="${COMMON_NAME}"
# Local variables
#Used to detect errors for logging purposes
ERROR_LOGGING_GUARD="true"
export INSTALL_DIR=${TMP_DIR}
install::kyma_cli
shout "Provision cluster: \"${CLUSTER_NAME}\""
if [ -z "$MACHINE_TYPE" ]; then
export MACHINE_TYPE="n1-standard-4"
fi
CLEANUP_CLUSTER="true"
(
set -x
kyma provision gardener \
--target-provider gcp --secret "${GARDENER_KYMA_PROW_PROVIDER_SECRET_NAME}" \
--name "${CLUSTER_NAME}" --project "${GARDENER_KYMA_PROW_PROJECT_NAME}" --credentials "${GARDENER_KYMA_PROW_KUBECONFIG}" \
--region "${GARDENER_REGION}" -z "${GARDENER_ZONES}" -t "${MACHINE_TYPE}" --nodes 4 --scaler-min 3 --kube-version=${GARDENER_CLUSTER_VERSION} \
)
shout "Installing Kyma"
date
echo "Downlading production profile"
curl -L --silent --fail --show-error "https://raw.githubusercontent.com/kyma-project/kyma/master/installation/resources/installer-config-production.yaml.tpl" \
--output installer-config-production.yaml.tpl
(
set -x
kyma install \
--ci \
--source latest \
-o installer-config-production.yaml.tpl \
--timeout 90m
)
shout "Checking the versions"
date
kyma version
shout "Running Kyma tests"
date
readonly SUITE_NAME="testsuite-all-$(date '+%Y-%m-%d-%H-%M')"
readonly CONCURRENCY=5
(
set -x
kyma test run \
--name "${SUITE_NAME}" \
--concurrency "${CONCURRENCY}" \
--max-retries 1 \
--timeout 90m \
--watch \
--non-interactive
)
shout "Success"
#!!! Must be at the end of the script !!!
ERROR_LOGGING_GUARD="false"
|
__has screen && alias c=__connect_screen
__connect_screen()
{
if [ -n "$STY" ]; then
echo '*** Nested screen is forbidden here ***'
return
fi
case "_$1" in
_)
screen -q -x main || screen -S main
;;
_:)
screen -ls
;;
_::)
screen -q -ls
errno=$?
if [ $errno -le 10 ]; then
echo '*** No available screens to attach. ***'
return
fi
scrno=`screen -ls | sed -e '2q;d' | sed 's/^\s*\([0-9]\+\).*$/\1/g'`
screen -x $scrno
;;
*)
screen -q -x "$1" || screen -S "$1"
;;
esac
}
__has tmux && alias t=__connect_tmux
__connect_tmux()
{
case "_$1" in
_)
[ "$TMUX_ATTACHED" != yes ] && tmux new -As main
;;
_:)
tmux ls
;;
*)
[ "$TMUX_ATTACHED" != yes ] && tmux new -As "$1"
;;
esac
}
__has ssh && alias connect=__connect_ssh
__connect_ssh()
{
command ssh -t $@ exec env TMUX_ATTACHED="'$TMUX_ATTACHED'" SSH_CONNECTION_CHAIN="'$SSH_CONNECTION_CHAIN'" bash --login
}
__has ssh && alias connect-no-tmux=__connect_ssh_no_tmux
__connect_ssh_no_tmux()
{
command ssh -t $@ exec env FORCE_TMUX=no TMUX_ATTACHED="'$TMUX_ATTACHED'" SSH_CONNECTION_CHAIN="'$SSH_CONNECTION_CHAIN'" bash --login
}
__has ssh && alias connect-tmux=__connect_ssh_tmux
__connect_ssh_tmux()
{
command ssh -t $@ exec env FORCE_TMUX=yes TMUX_ATTACHED="'$TMUX_ATTACHED'" SSH_CONNECTION_CHAIN="'$SSH_CONNECTION_CHAIN'" bash --login
}
__update_ssh_connection_chain()
{
if [ "$__ssh_connection_chain_updated" = yes ]; then
return
fi
local IFS=$' \t\n'
local ps1_hostname=$(__short_hostname)
if [ -n "$TMUX" ] || [ -z "$SSH_CONNECTION_CHAIN" ]; then
SSH_CONNECTION_CHAIN=$ps1_hostname
else
local ssh_conn_tokens=($SSH_CONNECTION)
local ssh_conn_chain_tokens=($SSH_CONNECTION_CHAIN)
local ntok=${#ssh_conn_chain_tokens[@]}
if [ "$ntok" -gt 3 ] && [ "${ssh_conn_chain_tokens[ntok-1]}" = "$ps1_hostname" ] \
&& [ "${ssh_conn_chain_tokens[ntok-2]}" = "${ssh_conn_tokens[3]}" ] \
&& [ "${ssh_conn_chain_tokens[ntok-3]}" = "${ssh_conn_tokens[1]}" ]; then
return
fi
SSH_CONNECTION_CHAIN="$SSH_CONNECTION_CHAIN ${ssh_conn_tokens[1]} ${ssh_conn_tokens[3]} $ps1_hostname"
fi
__ssh_connection_chain_updated=yes
}
__update_tmux_status()
{
if [ "$TMUX_ATTACHED" = yes ] || [ -n "$TMUX" ]; then
TMUX_ATTACHED=yes
fi
}
__update_ssh_connection_chain
__update_tmux_status
|
<filename>node_modules/ts-toolbelt/out/Object/Nullable.d.ts
import { Nullable as UNullable } from '../Union/Nullable';
import { Depth } from './_Internal';
import { _Pick } from './Pick';
import { Key } from '../Any/Key';
import { PatchFlat } from './Patch';
/**
* @hidden
*/
export declare type NullableFlat<O> = {
[K in keyof O]: UNullable<O[K]>;
} & {};
/**
* @hidden
*/
export declare type NullableDeep<O> = {
[K in keyof O]: NullableDeep<UNullable<O[K]>>;
};
/**
* @hidden
*/
declare type NullablePart<O extends object, depth extends Depth> = {
'flat': NullableFlat<O>;
'deep': NullableDeep<O>;
}[depth];
/**
* @hidden
*/
export declare type _Nullable<O extends object, K extends Key, depth extends Depth> = PatchFlat<NullablePart<_Pick<O, K>, depth>, O>;
/**
* Make some fields of `O` nullable (deeply or not)
* @param O to make nullable
* @param K (?=`Key`) to choose fields
* @param depth (?=`'flat'`) 'deep' to do it deeply
* @returns [[Object]]
* @example
* ```ts
* ```
*/
export declare type Nullable<O extends object, K extends Key = Key, depth extends Depth = 'flat'> = O extends unknown ? _Nullable<O, K, depth> : never;
export {};
|
<filename>libs/shared/hooks/src/lib/query/useDetailQuery/index.ts
import { QueryFunction, QueryKey, useQuery, UseQueryOptions } from 'react-query'
export { useQuery } from 'react-query'
export const useDetailQuery = <
TQueryFnData = unknown,
TError = unknown,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey
>(
queryKey: TQueryKey,
queryFn: QueryFunction<TQueryFnData, TQueryKey>,
options?: Omit<
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn'
>
) => {
const res = useQuery(queryKey, queryFn, options)
return { ...res, detail: res.data }
}
|
package servidor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class HiloServidor extends Thread {
private ObjectOutputStream output;
private ObjectInputStream input;
private Servidor servidor;
boolean activo = true;
private String mensajeRecibido;
public HiloServidor(String nombre, ObjectInputStream input, ObjectOutputStream output, Servidor servidor) {
super(nombre);
this.input=input;
this.output=output;
this.servidor=servidor;
}
@Override
public void run() {
while (this.activo) {
try {
this.mensajeRecibido = (String)this.input.readObject();
System.out.println(this.getName()+" dice: "+this.mensajeRecibido);
this.servidor.enviarMensaje(this.mensajeRecibido);
} catch (IOException e) {
this.activo=false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public void enviar(String mensaje) {
try {
this.output.writeObject(mensaje);
this.output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package healthcheck
import (
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/slotix/dataflowkit/splash"
"github.com/spf13/viper"
)
type healthChecker interface {
isAlive() error
serviceName() string
}
type redisConn struct {
conn redis.Conn
network string
host string
}
type splashConn struct {
Host string
User string
Password string
Timeout int
ResourceTimeout int
LUAScript string
}
func (r redisConn) serviceName() string {
return "Redis"
}
func (s splashConn) serviceName() string {
return "Splash"
}
func (r redisConn) isAlive() error {
var err error
r.conn, err = redis.Dial(r.network, r.host)
if err != nil {
return err
}
defer r.conn.Close()
res, err := r.conn.Do("PING")
if err != nil {
return err
}
if res == "PONG" {
return nil
}
return err
}
func (s splashConn) isAlive() error {
resp, err := splash.Ping(s.Host)
if err != nil {
return err
}
if resp.Status == "ok" {
return nil
}
return err
}
func CheckServices() (status map[string]string) {
status = make(map[string]string)
services := []healthChecker{
redisConn{
network: viper.GetString("REDIS_NETWORK"),
host: viper.GetString("REDIS")},
splashConn{
Host: viper.GetString("SPLASH"),
},
}
for _, srv := range services {
err := srv.isAlive()
if err != nil {
status[srv.serviceName()] =
fmt.Sprintf("%s: %s", srv.serviceName(), err.Error())
} else {
status[srv.serviceName()] = "Ok"
}
}
return status
}
|
<reponame>masschildcaredata/masschildcaredata.github.io
function summarizeGeocodedProvider(provider) {
if (!provider.lat || !provider.lng) {
return null;
}
return {
providerid: provider.providerid,
lat: provider.lat,
lng: provider.lng
};
}
module.exports = summarizeGeocodedProvider;
|
import IVarSection from "../components/models/var-section.model";
import ITokenReader from "../../tokenizers/models/token-reader.model";
import IVariable from "../models/variable.model";
import AttributeReader from "./attribute-reader";
import VariableReader from "./variable-reader";
export default class VarSectionReader {
static read(tokenReader: ITokenReader): IVarSection | undefined {
const protected2 = this.isProtected(tokenReader);
if (!this.hasVariables(tokenReader)) {
return;
}
return {
protected: protected2,
variables: this.readVariables(tokenReader),
};
}
private static isProtected(tokenReader: ITokenReader) {
let value = tokenReader.peekTokenValue();
return value.toLowerCase() === "protected";
}
private static hasVariables(tokenReader: ITokenReader) {
let pos = tokenReader.pos;
let value = tokenReader.peekTokenValue();
if (value.toLowerCase() === "protected") {
tokenReader.next();
tokenReader.readWhiteSpaces();
value = tokenReader.peekTokenValue();
}
if (value.toLowerCase() !== "var") {
tokenReader.pos = pos;
return false;
}
tokenReader.next();
tokenReader.readWhiteSpaces();
return true;
}
private static readVariables(tokenReader: ITokenReader): IVariable[] {
const variables: IVariable[] = [];
let preBuffer: string[] = [];
let resetIndex = tokenReader.pos;
while (tokenReader.pos + 3 < tokenReader.tokens.length) {
// Comments
if (tokenReader.tokenType() === "comment") {
preBuffer.push(...tokenReader.readComments());
continue;
}
// Attributes
const attribute = AttributeReader.read(tokenReader);
if (attribute.length > 0) {
preBuffer.push(attribute);
continue;
}
const variable = VariableReader.read(tokenReader, false, resetIndex);
if (!variable) {
tokenReader.pos = resetIndex;
return variables;
}
variable.preVariable = preBuffer;
variables.push(variable);
preBuffer = [];
resetIndex = tokenReader.pos;
}
tokenReader.readWhiteSpaces();
return variables;
}
}
|
import { AnyComponent } from "../any-component";
import { Component } from "../component";
import { ComponentLink } from "../component-link";
import { CollectionDisplay } from "./collection-display";
import { ConditionalContainer } from "./conditional-container";
import { HorizontalStackDisplay } from "./horizontal-stack-display";
/**
* Base for container-like components
* @extends {Component}
*/
export interface ContainerComponent extends Component {
additions?: ComponentLink[];
conditional?: ConditionalContainer | ConditionalContainer[];
contentDisplay?: CollectionDisplay | HorizontalStackDisplay;
components?: AnyComponent[];
}
|
#!/bin/bash
docker build -t vsts-arm64v8-agent-proxy -f Dockerfile .
|
<filename>django-view-auth/Blog/core/models.py
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
|
#!/bin/bash
# Usage:
# Go into cmd loop: sudo ./clVAC.sh
# Run single cmd: sudo ./clVAC.sh <clVAC paramers>
PREFIX="docker-compose exec nodVACd clVAC"
if [ -z $1 ] ; then
while :
do
read -e -p "clVAC " cmd
history -s "$cmd"
$PREFIX $cmd
done
else
$PREFIX "$@"
fi
|
using System;
class Fibonacci
{
// Method to print the Nth number in
// the fibonacci series
static int Fibonacci(int n)
{
int a = 0, b = 1, c;
if (n == 0)
return a;
for (int i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}
public static void Main()
{
int n = 9;
Console.WriteLine(Fibonacci(n));
}
} |
/**
params:
- name: column
label: Column
value:
- control: 'textbox'
value: newColumn
- name: array
label: Array
value:
- control: 'textbox'
value: data.indices()
deps:
- https://cdn.jsdelivr.net/npm/arquero@latest
- https://cdn.jsdelivr.net/npm/hal9-utils@latest/dist/hal9-utils.min.js
**/
data = await hal9.utils.toArquero(data);
if (array && column) {
arr = new Function('data', 'return ' + array)
data = data.assign({ column: arr(data) });
data = data.rename({ column : column });
} |
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"github.com/grailbio/go-dicom"
"github.com/grailbio/go-dicom/dicomtag"
)
var (
printMetadata = flag.Bool("print-metadata", true, "Print image metadata")
extractImages = flag.Bool("extract-images", false, "Extract images into separate files")
)
func main() {
flag.Parse()
if len(flag.Args()) == 0 {
log.Panic("dicomutil <dicomfile>")
}
path := flag.Arg(0)
data, err := dicom.ReadDataSetFromFile(path, dicom.ReadOptions{DropPixelData: !*extractImages})
if data == nil {
log.Panicf("Error reading %s: %v", path, err)
}
log.Printf("Error reading %s: %v", path, err)
if *printMetadata {
for _, elem := range data.Elements {
fmt.Printf("%v\n", elem.String())
}
}
if *extractImages {
n := 0
for _, elem := range data.Elements {
if elem.Tag == dicomtag.PixelData {
data := elem.Value[0].(dicom.PixelDataInfo)
for _, frame := range data.Frames {
path := fmt.Sprintf("image.%d.jpg", n) // TODO: figure out the image format
n++
ioutil.WriteFile(path, frame, 0644)
fmt.Printf("%s: %d bytes\n", path, len(frame))
}
}
}
}
}
|
// Generated by script, don't edit it please.
import createSvgIcon from '../../createSvgIcon';
import GooglePlusCircleSvg from '@rsuite/icon-font/lib/legacy/GooglePlusCircle';
const GooglePlusCircle = createSvgIcon({
as: GooglePlusCircleSvg,
ariaLabel: 'google plus circle',
category: 'legacy',
displayName: 'GooglePlusCircle'
});
export default GooglePlusCircle;
|
class User {
name: string;
age: number;
email: string;
address: string;
constructor(name: string, age: number, email: string, address: string) {
this.name = name;
this.age = age;
this.email = email;
this.address = address;
}
}
let user = new User('John', 25, 'john@example.com', '123 Main Street');
console.log(user); |
#!/bin/bash
# -----------------------------------------------------------------
# usage
if [ "$#" -lt 1 ]; then
echo "./get-all-packages.sh <namespace>"
echo "./get-all-packages.sh lb-ns"
exit 0;
fi
source ./conf.env
# ------------------------------------------------------------------------------
# const
# -----------------------------------------------------------------
# parameter
# 1. namespace
if [ "$#" -gt 0 ]; then v_NAMESPACE="$1"; else v_NAMESPACE="${NAMESPACE}"; fi
if [ "${v_NAMESPACE}" == "" ]; then
read -e -p "Namespace ? : " v_NAMESPACE
fi
if [ "${v_NAMESPACE}" == "" ]; then echo "[ERROR] missing <namespace>"; exit -1; fi
c_URL_LADYBUG_NS="${c_URL_LADYBUG}/ns/${v_NAMESPACE}"
# ------------------------------------------------------------------------------
# print info.
echo ""
echo "[INFO]"
echo "- Namespace is '${v_NAMESPACE}'"
# ------------------------------------------------------------------------------
# get all packages
get_all_packages() {
if [ "$LADYBUG_CALL_METHOD" == "REST" ]; then
curl -sX GET ${c_URL_LADYBUG_NS}/packages -H "${c_CT}" -H "${c_AUTH}" | jq;
elif [ "$LADYBUG_CALL_METHOD" == "GRPC" ]; then
#$APP_ROOT/src/grpc-api/cbadm/cbadm package get --config $APP_ROOT/src/grpc-api/cbadm/grpc_conf.yaml -o json --ns ${v_NAMESPACE} --package ${v_PACKAGE_NAME}
echo "[ERROR] not yet implementd"; exit -1;
else
echo "[ERROR] missing LADYBUG_CALL_METHOD"; exit -1;
fi
}
# ------------------------------------------------------------------------------
if [ "$1" != "-h" ]; then
echo ""
echo "------------------------------------------------------------------------------"
get_all_packages;
fi
|
require 'test/unit'
require 'rubygems'
require 'action_controller'
require File.dirname(__FILE__) + "/../init"
class ChildrenController < Class.new(ActionController::Base)
def show
end
end
class ParentsController < Class.new(ActionController::Base)
def index
end
def show
end
end
class MockRequest < Struct.new(:path, :subdomains, :method, :remote_ip, :protocol, :path_parameters, :domain, :port, :content_type, :accepts, :request_uri)
end
class RequestRoutingTest < Test::Unit::TestCase
attr_reader :rs
def setup
@rs = ::ActionController::Routing::RouteSet.new
ActionController::Routing.use_controllers! %w(test) if ActionController::Routing.respond_to? :use_controllers!
@rs.draw do |map|
map.resources :parents do |parents|
parents.resources :children, :default => true
end
end
@request = MockRequest.new(
'',
['www'],
:get,
'1.2.3.4',
'http://',
'',
'thing.com',
3432,
'text/html',
['*/*'],
'/'
)
end
def test_normal_routes
@request.path = '/parents/parent-id'
assert(@rs.recognize(@request))
end
# this would pass if I could get the environment set up correctly.
def test_child_id
@request.path = '/parents/parent-id/child-id'
assert(@rs.recognize(@request))
end
# this would pass if I could get the environment set up correctly.
def test_generation
assert_equal '/parents/parent-id/child-id', @rs.generate(:controller => 'children', :action => 'show', :parent_id => 'parent-id', :id => 'child-id')
end
end
|
Advanced Bash-Scripting Guide:
Prev Chapter 36. Miscellany Next
36.6. Optimizations
Most shell scripts are quick 'n dirty solutions to non-complex problems. As such, optimizing them for speed is not much of an issue. Consider the case, though, where a script carries out an important task, does it well, but runs too slowly. Rewriting it in a compiled language may not be a palatable option. The simplest fix would be to rewrite the parts of the script that slow it down. Is it possible to apply principles of code optimization even to a lowly shell script?
Check the loops in the script. Time consumed by repetitive operations adds up quickly. If at all possible, remove time-consuming operations from within loops.
Use builtin commands in preference to system commands. Builtins execute faster and usually do not launch a subshell when invoked.
Avoid unnecessary commands, particularly in a pipe.
cat "$file" | grep "$word"
grep "$word" "$file"
# The above command-lines have an identical effect,
#+ but the second runs faster since it launches one fewer subprocess.
The cat command seems especially prone to overuse in scripts.
Disabling certain Bash options can speed up scripts.
As Erik Brandsberg points out:
If you don't need Unicode support, you can get potentially a 2x or more improvement in speed by simply setting the LC_ALL variable.
export LC_ALL=C
[specifies the locale as ANSI C,
thereby disabling Unicode support]
[In an example script ...]
Without [Unicode support]:
erik@erik-desktop:~/capture$ time ./cap-ngrep.sh
live2.pcap > out.txt
real 0m20.483s
user 1m34.470s
sys 0m12.869s
With [Unicode support]:
erik@erik-desktop:~/capture$ time ./cap-ngrep.sh
live2.pcap > out.txt
real 0m50.232s
user 3m51.118s
sys 0m11.221s
A large part of the overhead that is optimized is, I believe,
regex match using [[ string =~ REGEX ]],
but it may help with other portions of the code as well.
I hadn't [seen it] mentioned that this optimization helped
with Bash, but I had seen it helped with "grep,"
so why not try?
Note
Certain operators, notably expr, are very inefficient and might be replaced by double parentheses arithmetic expansion. See Example A-59.
Math tests
math via $(( ))
real 0m0.294s
user 0m0.288s
sys 0m0.008s
math via expr:
real 1m17.879s # Much slower!
user 0m3.600s
sys 0m8.765s
math via let:
real 0m0.364s
user 0m0.372s
sys 0m0.000s
Condition testing constructs in scripts deserve close scrutiny. Substitute case for if-then constructs and combine tests when possible, to minimize script execution time. Again, refer to Example A-59.
Test using "case" construct:
real 0m0.329s
user 0m0.320s
sys 0m0.000s
Test with if [], no quotes:
real 0m0.438s
user 0m0.432s
sys 0m0.008s
Test with if [], quotes:
real 0m0.476s
user 0m0.452s
sys 0m0.024s
Test with if [], using -eq:
real 0m0.457s
user 0m0.456s
sys 0m0.000s
Note
Erik Brandsberg recommends using associative arrays in preference to conventional numeric-indexed arrays in most cases. When overwriting values in a numeric array, there is a significant performance penalty vs. associative arrays. Running a test script confirms this. See Example A-60.
Assignment tests
Assigning a simple variable
real 0m0.418s
user 0m0.416s
sys 0m0.004s
Assigning a numeric index array entry
real 0m0.582s
user 0m0.564s
sys 0m0.016s
Overwriting a numeric index array entry
real 0m21.931s
user 0m21.913s
sys 0m0.016s
Linear reading of numeric index array
real 0m0.422s
user 0m0.416s
sys 0m0.004s
Assigning an associative array entry
real 0m1.800s
user 0m1.796s
sys 0m0.004s
Overwriting an associative array entry
real 0m1.798s
user 0m1.784s
sys 0m0.012s
Linear reading an associative array entry
real 0m0.420s
user 0m0.420s
sys 0m0.000s
Assigning a random number to a simple variable
real 0m0.402s
user 0m0.388s
sys 0m0.016s
Assigning a sparse numeric index array entry randomly into 64k cells
real 0m12.678s
user 0m12.649s
sys 0m0.028s
Reading sparse numeric index array entry
real 0m0.087s
user 0m0.084s
sys 0m0.000s
Assigning a sparse associative array entry randomly into 64k cells
real 0m0.698s
user 0m0.696s
sys 0m0.004s
Reading sparse associative index array entry
real 0m0.083s
user 0m0.084s
sys 0m0.000s
Use the time and times tools to profile computation-intensive commands. Consider rewriting time-critical code sections in C, or even in assembler.
Try to minimize file I/O. Bash is not particularly efficient at handling files, so consider using more appropriate tools for this within the script, such as awk or Perl.
Write your scripts in a modular and coherent form, [1] so they can be reorganized and tightened up as necessary. Some of the optimization techniques applicable to high-level languages may work for scripts, but others, such as loop unrolling, are mostly irrelevant. Above all, use common sense.
For an excellent demonstration of how optimization can dramatically reduce the execution time of a script, see Example 16-47.
Notes
[1]
This usually means liberal use of functions.
Prev Home Next
"Colorizing" Scripts Up Assorted Tips |
package com.example.googleplay.ui.fragment;
import java.util.ArrayList;
import android.view.View;
import com.example.googleplay.domain.AppInfo;
import com.example.googleplay.http.protocol.AppProtocol;
import com.example.googleplay.ui.adapter.MyBaseAdapter;
import com.example.googleplay.ui.holder.AppHolder;
import com.example.googleplay.ui.holder.BaseHolder;
import com.example.googleplay.ui.view.LoadingPage.ResultState;
import com.example.googleplay.ui.view.MyListView;
import com.example.googleplay.utils.UIUtils;
/**
* 应用
*
* @author Administrator
*
*/
public class AppFragment extends BaseFragment {
private ArrayList<AppInfo> data;
@Override
public View onCreateSuccessView() {
MyListView view = new MyListView(UIUtils.getContext());
view.setAdapter(new AppAdapter(data));
return view;
}
@Override
public ResultState onLoad() {
AppProtocol appProtocol = new AppProtocol();
data = appProtocol.getData(0);
return check(data);
}
class AppAdapter extends MyBaseAdapter<AppInfo> {
public AppAdapter(ArrayList<AppInfo> data) {
super(data);
}
@Override
public BaseHolder<AppInfo> getHolder(int position) {
return new AppHolder();
}
@Override
public ArrayList<AppInfo> onLoadMore() {
AppProtocol appProtocol = new AppProtocol();
ArrayList<AppInfo> moreData = appProtocol.getData(getListSize());
return moreData;
}
}
}
|
<filename>config/defaultMessages.js<gh_stars>1-10
module.exports = {
busyMessage: "Dude, I'm busy!",
goToVoiceChannelMessage: "Go to a voice channel!",
permissionDeniedMessage: "You have no power here!",
permissionAddMessage: "Blessed by the King:",
permissionRemoveMessage: "Kryptonite for:",
listPermissionsMessage: "Powerful people:",
nonePermissionMessage: "Nobody has power!",
listenningMessage: "Type !helpme"
};
|
var scrollNav = document.getElementById("scrollNav");
var scrollNavContents = document.getElementById("scrollNavContents");
var scrollBtnLeft = document.getElementById("scrollBtnLeft");
var scrollBtnRight = document.getElementById("scrollBtnRight");
var SETTINGS = {
navBarTravelling: false,
navBarDirection: "",
navBarTravelDistance: 150
}
function determineOverflow(content, container) {
var containerMetrics = container.getBoundingClientRect();
var containerMetricsRight = Math.floor(containerMetrics.right);
var containerMetricsLeft = Math.floor(containerMetrics.left);
var contentMetrics = content.getBoundingClientRect();
var contentMetricsRight = Math.floor(contentMetrics.right);
var contentMetricsLeft = Math.floor(contentMetrics.left);
if (containerMetricsLeft > contentMetricsLeft && containerMetricsRight < contentMetricsRight) {
return "both";
} else if (contentMetricsLeft < containerMetricsLeft) {
return "left";
} else if (contentMetricsRight > containerMetricsRight) {
return "right";
} else {
return "none";
}
}
scrollNav.setAttribute("data-overflowing", determineOverflow(scrollNavContents, scrollNav));
// Handle the scroll of the horizontal container
var last_known_scroll_position = 0;
var ticking = false;
function doSomething(scroll_pos) {
scrollNav.setAttribute("data-overflowing", determineOverflow(scrollNavContents, scrollNav));
}
scrollNav.addEventListener("scroll", function () {
last_known_scroll_position = window.scrollX;
if (!ticking) {
window.requestAnimationFrame(function () {
doSomething(last_known_scroll_position);
ticking = false;
});
}
ticking = true;
});
// Click arrow button
scrollBtnLeft.addEventListener("click", function () {
// if in the middle
if (SETTINGS.navBarTravelling === true) {
return;
}
// if we have content overflow both side or on the left
if (determineOverflow(scrollNavContents, scrollNav) === "left"
|| determineOverflow(scrollNavContents, scrollNav) === "both") {
// Find how far this panel has been scrolled
var availableScrollLeft = scrollNav.scrollLeft;
// if the space available is less than two lots of our desired distance distance
// otherwise, move by the amount in the settings
if (availableScrollLeft < SETTINGS.navBarTravelDistance * 2) {
scrollNavContents.style.transform = "translateX(" + availableScrollLeft + "px)";
} else {
scrollNavContents.style.transform = "translateX(" + SETTINGS.navBarTravelDistance + "px)";
}
scrollNavContents.classList.remove("transition-none");
// Update our settings
SETTINGS.navBarTravelDirection = "left";
SETTINGS.navBarTravelling = true;
}
// Update attribute in the DOM
scrollNav.setAttribute("data-overflowing", determineOverflow(scrollNavContents, scrollNav));
});
scrollBtnRight.addEventListener("click", function () {
// if in the middle
if (SETTINGS.navBarTravelling === true) {
return;
}
// in the both side or on the right
if (determineOverflow(scrollNavContents, scrollNav) === "right"
|| determineOverflow(scrollNavContents, scrollNav) === "both") {
var navBarRightEdge = scrollNavContents.getBoundingClientRect().right;
var navBarScrollerRightEdge = scrollNav.getBoundingClientRect().right;
// we know how much space we have available to scroll
var availableScrollRight = Math.floor(navBarRightEdge - navBarScrollerRightEdge);
if (availableScrollRight < SETTINGS.navBarTravelDistance * 2) {
scrollNavContents.style.transform = "translateX(-" + availableScrollRight + "px)";
} else {
scrollNavContents.style.transform = "translateX(-" + SETTINGS.navBarTravelDistance + "px)";
}
scrollNavContents.classList.remove("transition-none");
// Update our settings
SETTINGS.navBarTravelDirection = "right";
SETTINGS.navBarTravelling = true;
}
// Update attribute in the DOM
scrollNav.setAttribute("data-overflowing", determineOverflow(scrollNavContents, scrollNav));
});
scrollNavContents.addEventListener(
"transitionend",
function () {
// get the value of the transform, apply that to the current scroll position (so get the scroll pos first) and then remove the transform
var styleOfTransform = window.getComputedStyle(scrollNavContents, null);
var tr = styleOfTransform.getPropertyValue("-webkit-transform") || styleOfTransform.getPropertyValue("transform");
// If there is no transition we want to default to 0 and not null
var amount = Math.abs(parseInt(tr.split(",")[4]) || 0);
scrollNavContents.style.transform = "none";
scrollNavContents.classList.add("transition-none");
// Now lets set the scroll position
if (SETTINGS.navBarTravelDirection === "left") {
scrollNav.scrollLeft = scrollNav.scrollLeft - amount;
} else {
scrollNav.scrollLeft = scrollNav.scrollLeft + amount;
}
SETTINGS.navBarTravelling = false;
},
false
);
scrollNavContents.addEventListener("click", function (e) {
// Make an array from each of the links in the nav
var links = [].slice.call(document.querySelectorAll(".nav-scroll .nav-link"));
// Turn all of them off
links.forEach(function (item) {
item.setAttribute("aria-selected", "false");
})
// Set the clicked one on
e.target.setAttribute("aria-selected", "true");
})
// Sticky Header
var currentHeight = 0;
var stickyHeader = document.getElementById("stickyHeader");
window.addEventListener("scroll", function (e) {
var scrollHeight = window.scrollY;
if (scrollHeight < currentHeight) {
// show header
stickyHeader.classList.add("sticky-top");
stickyHeader.classList.add("shadow-sm");
stickyHeader.classList.remove("header-unpinned");
stickyHeader.classList.add("header-pinned");
} else {
stickyHeader.classList.remove("header-pinned");
stickyHeader.classList.add("header-unpinned");
}
if (scrollHeight === 0) {
stickyHeader.classList.remove("sticky-top");
stickyHeader.classList.remove("shadow-sm");
}
// set current height to $currentHeight
currentHeight = scrollHeight;
}); |
const contentList = require('./graphql/fragments/content-list');
const contentLatest = require('./graphql/fragments/content-latest');
const magazineIssueArchive = require('./graphql/fragments/magazine-issue-archive');
module.exports = {
contentList,
contentLatest,
magazineIssueArchive,
};
|
<filename>SOLVER/src/models3D/volumetric/StructuredGridV3D.hpp<gh_stars>1-10
//
// StructuredGridV3D.hpp
// AxiSEM3D
//
// Created by <NAME> on 4/15/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
// 3D volumetric models based on structured grid
#ifndef StructuredGridV3D_hpp
#define StructuredGridV3D_hpp
#include "Volumetric3D.hpp"
#include "sg_tools.hpp"
class StructuredGridV3D: public Volumetric3D {
public:
// constructor
StructuredGridV3D(const std::string &modelName, const std::string &fname,
const std::array<std::string, 3> &crdVarNames,
const std::array<int, 3> &shuffleData,
bool sourceCentered, bool xy, bool ellipticity,
bool useDepth, bool depthSolid, bool undulated,
double lengthUnit, double angleUnit, bool center,
const std::vector<std::tuple<std::string, std::string,
double, ReferenceKind>> &propertyInfo, bool superOnly);
private:
// using reference or undulated geometry
bool usingUndulatedGeometry() const {
return mUndulatedGeometry;
}
// get property info
void getPropertyInfo(std::vector<std::string> &propKeys,
std::vector<ReferenceKind> &refKinds) const;
// get properties
bool getProperties(const eigen::DMatX3 &spz,
const eigen::DMat24 &nodalSZ,
eigen::IMatXX &inScopes,
eigen::DMatXX &propValues) const;
// verbose
std::string verbose() const;
// super-only: data stored only on super ranks
bool isSuperOnly() const {
return mSuperOnly;
}
private:
// file
const std::string mFileName;
const std::array<std::string, 3> mCrdVarNames;
// horizontal options
const bool mSourceCentered;
const bool mXY;
const bool mEllipticity;
bool mLon360 = false;
// vertical options
const bool mUseDepth;
const bool mDepthSolid;
const bool mUndulatedGeometry;
// use element center for scope check
const bool mElementCenter;
// data info
// not using std::map because one property may be set twice in a model
std::vector<std::string> mPropertyKeys;
std::vector<std::string> mPropertyVarNames;
std::vector<double> mPropertyFactors;
std::vector<ReferenceKind> mPropertyReferenceKinds;
std::unique_ptr<eigen::IMat66> mIndexCIJ;
// grid
std::unique_ptr<StructuredGrid<3, double>> mGrid = nullptr;
// super only
const bool mSuperOnly;
};
#endif /* StructuredGridV3D_hpp */
|
<filename>process/process_test.go
package process
import (
"os"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/okmeter/gopsutil/internal/common"
)
var mu sync.Mutex
func testGetProcess() Process {
checkPid := os.Getpid() // process.test
ret, _ := NewProcess(int32(checkPid))
return *ret
}
func Test_Pids(t *testing.T) {
ret, err := Pids()
if err != nil {
t.Errorf("error %v", err)
}
if len(ret) == 0 {
t.Errorf("could not get pids %v", ret)
}
}
func Test_Pids_Fail(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("darwin only")
}
mu.Lock()
defer mu.Unlock()
invoke = common.FakeInvoke{Suffix: "fail"}
ret, err := Pids()
invoke = common.Invoke{}
if err != nil {
t.Errorf("error %v", err)
}
if len(ret) != 9 {
t.Errorf("wrong getted pid nums: %v/%d", ret, len(ret))
}
}
func Test_Pid_exists(t *testing.T) {
checkPid := os.Getpid()
ret, err := PidExists(int32(checkPid))
if err != nil {
t.Errorf("error %v", err)
}
if ret == false {
t.Errorf("could not get process exists: %v", ret)
}
}
func Test_NewProcess(t *testing.T) {
checkPid := os.Getpid()
ret, err := NewProcess(int32(checkPid))
if err != nil {
t.Errorf("error %v", err)
}
empty := &Process{}
if runtime.GOOS != "windows" { // Windows pid is 0
if empty == ret {
t.Errorf("error %v", ret)
}
}
}
func Test_Process_memory_maps(t *testing.T) {
checkPid := os.Getpid()
ret, err := NewProcess(int32(checkPid))
mmaps, err := ret.MemoryMaps(false)
if err != nil {
t.Errorf("memory map get error %v", err)
}
empty := MemoryMapsStat{}
for _, m := range *mmaps {
if m == empty {
t.Errorf("memory map get error %v", m)
}
}
}
func Test_Process_MemoryInfo(t *testing.T) {
p := testGetProcess()
v, err := p.MemoryInfo()
if err != nil {
t.Errorf("geting memory info error %v", err)
}
empty := MemoryInfoStat{}
if v == nil || *v == empty {
t.Errorf("could not get memory info %v", v)
}
}
func Test_Process_CmdLine(t *testing.T) {
p := testGetProcess()
v, err := p.Cmdline()
if err != nil {
t.Errorf("geting cmdline error %v", err)
}
if !strings.Contains(v, "process.test") {
t.Errorf("invalid cmd line %v", v)
}
}
func Test_Process_Ppid(t *testing.T) {
p := testGetProcess()
v, err := p.Ppid()
if err != nil {
t.Errorf("geting ppid error %v", err)
}
if v == 0 {
t.Errorf("return value is 0 %v", v)
}
}
func Test_Process_Status(t *testing.T) {
p := testGetProcess()
v, err := p.Status()
if err != nil {
t.Errorf("geting status error %v", err)
}
if !strings.HasPrefix(v, "S") && v != "running" && v != "sleeping" {
t.Errorf("could not get state %v", v)
}
}
func Test_Process_Terminal(t *testing.T) {
p := testGetProcess()
_, err := p.Terminal()
if err != nil {
t.Errorf("geting terminal error %v", err)
}
/*
if v == "" {
t.Errorf("could not get terminal %v", v)
}
*/
}
func Test_Process_IOCounters(t *testing.T) {
p := testGetProcess()
v, err := p.IOCounters()
if err != nil {
t.Errorf("geting iocounter error %v", err)
return
}
empty := &IOCountersStat{}
if v == empty {
t.Errorf("error %v", v)
}
}
func Test_Process_NumCtx(t *testing.T) {
p := testGetProcess()
_, err := p.NumCtxSwitches()
if err != nil {
t.Errorf("geting numctx error %v", err)
return
}
}
func Test_Process_Nice(t *testing.T) {
p := testGetProcess()
n, err := p.Nice()
if err != nil {
t.Errorf("geting nice error %v", err)
}
if n != 0 && n != 20 && n != 8 {
t.Errorf("invalid nice: %d", n)
}
}
func Test_Process_NumThread(t *testing.T) {
p := testGetProcess()
n, err := p.NumThreads()
if err != nil {
t.Errorf("geting NumThread error %v", err)
}
if n < 0 {
t.Errorf("invalid NumThread: %d", n)
}
}
func Test_Process_Name(t *testing.T) {
p := testGetProcess()
n, err := p.Name()
if err != nil {
t.Errorf("geting name error %v", err)
}
if !strings.Contains(n, "process.test") {
t.Errorf("invalid Exe %s", n)
}
}
func Test_Process_Exe(t *testing.T) {
p := testGetProcess()
n, err := p.Exe()
if err != nil {
t.Errorf("geting Exe error %v", err)
}
if !strings.Contains(n, "process.test") {
t.Errorf("invalid Exe %s", n)
}
}
func Test_Process_CpuPercent(t *testing.T) {
p := testGetProcess()
percent, err := p.CPUPercent(0)
if err != nil {
t.Errorf("error %v", err)
}
duration := time.Duration(1000) * time.Microsecond
time.Sleep(duration)
percent, err = p.CPUPercent(0)
if err != nil {
t.Errorf("error %v", err)
}
numcpu := runtime.NumCPU()
// if percent < 0.0 || percent > 100.0*float64(numcpu) { // TODO
if percent < 0.0 {
t.Fatalf("CPUPercent value is invalid: %f, %d", percent, numcpu)
}
}
func Test_Process_CpuPercentLoop(t *testing.T) {
p := testGetProcess()
numcpu := runtime.NumCPU()
for i := 0; i < 2; i++ {
duration := time.Duration(100) * time.Microsecond
percent, err := p.CPUPercent(duration)
if err != nil {
t.Errorf("error %v", err)
}
// if percent < 0.0 || percent > 100.0*float64(numcpu) { // TODO
if percent < 0.0 {
t.Fatalf("CPUPercent value is invalid: %f, %d", percent, numcpu)
}
}
}
func Test_Process_CreateTime(t *testing.T) {
p := testGetProcess()
c, err := p.CreateTime()
if err != nil {
t.Errorf("error %v", err)
}
if c < 1420000000 {
t.Errorf("process created time is wrong.")
}
gotElapsed := time.Since(time.Unix(int64(c/1000), 0))
maxElapsed := time.Duration(5 * time.Second)
if gotElapsed >= maxElapsed {
t.Errorf("this process has not been running for %v", gotElapsed)
}
}
func Test_Parent(t *testing.T) {
p := testGetProcess()
c, err := p.Parent()
if err != nil {
t.Fatalf("error %v", err)
}
if c == nil {
t.Fatalf("could not get parent")
}
if c.Pid == 0 {
t.Fatalf("wrong parent pid")
}
}
func Test_Connections(t *testing.T) {
p := testGetProcess()
c, err := p.Connections()
if err != nil {
t.Fatalf("error %v", err)
}
// TODO:
// Since go test open no conneciton, ret is empty.
// should invoke child process or other solutions.
if len(c) != 0 {
t.Fatalf("wrong connections")
}
}
func Test_Children(t *testing.T) {
p, err := NewProcess(1)
if err != nil {
t.Fatalf("new process error %v", err)
}
c, err := p.Children()
if err != nil {
t.Fatalf("error %v", err)
}
if len(c) == 0 {
t.Fatalf("children is empty")
}
}
|
def calculate(s):
values = s.split(" ")
value1 = int(values[0])
value2 = int(values[2])
if values[1] == "+":
result = value1 + value2
elif values[1] == "-":
result = value1 - value2
elif values[1] == "*":
result = value1 * value2
elif values[1] == "/":
result = value1 / value2
else:
print("Invalid operator.")
return
print("Result: ", result)
calculate("5 + 7") |
<reponame>RobertPHeller/RPi-RRCircuits<gh_stars>1-10
// -!- c++ -!- //////////////////////////////////////////////////////////////
//
// System :
// Module :
// Object Name : $RCSfile$
// Revision : $Revision$
// Date : $Date$
// Author : $Author$
// Created By : <NAME>
// Created : Sun Oct 14 15:16:50 2018
// Last Modified : <181014.1643>
//
// Description
//
// Notes
//
// History
//
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018 <NAME> D/B/A Deepwoods Software
// 51 Lock<NAME>ill Road
// Wendell, MA 01379-9728
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//
//
//////////////////////////////////////////////////////////////////////////////
#ifndef __POINTS_HXX
#define __POINTS_HXX
#include "openlcb/PolledProducer.hxx"
#include "openlcb/EventHandlerTemplates.hxx"
#include "openlcb/ConfigRepresentation.hxx"
#include "utils/ConfigUpdateListener.hxx"
#include "utils/ConfigUpdateService.hxx"
/// CDI Configuration for a @ref ConfiguredProducer.
CDI_GROUP(PointsConfig);
/// Allows the user to assign a name for this input.
CDI_GROUP_ENTRY(description, openlcb::StringConfigEntry<15>, //
Name("Description"), Description("User name of this input."));
/// This event will be produced when the input goes to HIGH.
CDI_GROUP_ENTRY(
normal, openlcb::EventConfigEntry, //
Name("Normal"),
Description("This event will be produced when the points are aligned for normal."));
/// This event will be produced when the input goes to LOW.
CDI_GROUP_ENTRY(
reversed, openlcb::EventConfigEntry, //
Name("Reversed"),
Description("This event will be produced when the are aligned for reversed."));
CDI_GROUP_END();
template <class BaseBit> class PolledProducerNoDebouncer : public BaseBit, public openlcb::Polling
{
public:
template <typename... Fields>
PolledProducerNoDebouncer(Fields... bit_args)
: BaseBit(bit_args...)
, producer_(this)
{
old_state = BaseBit::get_current_state();
}
openlcb::EventState get_current_state() OVERRIDE
{
return BaseBit::get_current_state();
}
void poll_33hz(openlcb::WriteHelper *helper, Notifiable *done) OVERRIDE
{
if (old_state != BaseBit::get_current_state()) {
old_state = BaseBit::get_current_state();
producer_.SendEventReport(helper, done);
}
else
{
done->notify();
}
}
private:
openlcb::BitEventPC producer_;
openlcb::EventState old_state;
};
class Points : public ConfigUpdateListener
{
public:
using Impl = openlcb::GPIOBit;
using ProducerClass = PolledProducerNoDebouncer<Impl>;
Points(openlcb::Node *node, const PointsConfig &cfg, const Gpio *gpio)
: producer_(node, 0, 0, gpio)
, cfg_(cfg)
{
ConfigUpdateService::instance()->register_update_listener(this);
}
template <class HW>
Points(openlcb::Node *node, const PointsConfig &cfg, const HW &,
const Gpio *g = HW::instance())
: producer_(node, 0, 0, g)
, cfg_(cfg)
{
ConfigUpdateService::instance()->register_update_listener(this);
}
UpdateAction apply_configuration(int fd, bool initial_load,
BarrierNotifiable *done) override
{
AutoNotify n(done);
openlcb::EventId cfg_event_on = cfg_.normal().read(fd);
openlcb::EventId cfg_event_off = cfg_.reversed().read(fd);
if (cfg_event_off != producer_.event_off() ||
cfg_event_on != producer_.event_on())
{
auto saved_gpio = producer_.gpio_;
auto saved_node = producer_.node();
// Need to reinitialize the producer. We do this with in-place
// destruction and construction.
producer_.ProducerClass::~ProducerClass();
new (&producer_) ProducerClass(
saved_node,
cfg_event_on, cfg_event_off, saved_gpio);
return REINIT_NEEDED; // Causes events identify.
}
return UPDATED;
}
void factory_reset(int fd) OVERRIDE
{
cfg_.description().write(fd, "");
}
openlcb::Polling *polling()
{
return &producer_;
}
openlcb::EventState get_current_state()
{
return producer_.get_current_state();
}
private:
ProducerClass producer_;
const PointsConfig cfg_;
};
#endif // __POINTS_HXX
|
<gh_stars>0
// Copyright (c) 2017-2022 Uber Technologies Inc.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import moment from 'moment';
import {
DATE_FORMAT_YYYY_MM_DD,
DATE_FORMAT_MMM_D_YYYY,
DATE_FORMAT_D_MMM_YYYY,
TIME_FORMAT_12,
TIME_FORMAT_24,
TIMEZONE_LOCAL,
TIMEZONE_UTC,
} from '../constants';
export const getDateFormat = dateFormat => {
switch (dateFormat) {
case DATE_FORMAT_YYYY_MM_DD:
return 'YYYY-MM-DD';
case DATE_FORMAT_D_MMM_YYYY:
return 'D MMM, YYYY';
case DATE_FORMAT_MMM_D_YYYY:
default:
return 'MMM D, YYYY';
}
};
export const getTimeFormat = timeFormat => {
switch (timeFormat) {
case TIME_FORMAT_24:
return 'HH:mm:ss';
case TIME_FORMAT_12:
default:
return 'h:mm:ss A';
}
};
export const getDateTimeFormat = (dateFormat, timeFormat) =>
`${getDateFormat(dateFormat)} ${getTimeFormat(timeFormat)}`;
export const getMomentFn = timezone => {
switch (timezone) {
case TIMEZONE_UTC:
return moment.utc;
case TIMEZONE_LOCAL:
default:
return moment;
}
};
export default ({ date, dateFormat, timeFormat, timezone }) => {
const dateTimeFormat = getDateTimeFormat(dateFormat, timeFormat);
const momentFn = getMomentFn(timezone);
return momentFn(date).format(dateTimeFormat);
};
|
<filename>tests/test_exceptions.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pytest
from tableschema.exceptions import CastError
# Tests
def test_no_errors_reuse():
ce1 = CastError('message1')
ce1.errors.append('error')
ce2 = CastError('message2')
assert len(ce2.errors) == 0
|
import React from 'react';
import { MapDataProvider } from '../contexts/MapDataProvider';
import ReMap from './ReMap';
import world from '../docs/world.json';
import PropTypes from 'prop-types';
export const ReGeoMapChart = React.memo((props) => {
return (
<MapDataProvider data={props.data}>
<ReMap {...world} {...props} />
</MapDataProvider>
);
});
ReGeoMapChart.defaultProps = {
datalessRegionColor: '#D3D3D3',
datafulRegionColor: '#047FFE',
backgroundColor: '',
hideMapLegend: false,
width: '',
strokeColor: '#fff',
tooltipBackgroundColor: '#E0E0E0',
style: {},
};
ReGeoMapChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.array).isRequired,
layerProps: PropTypes.any,
datalessRegionColor: PropTypes.string,
datafulRegionColor: PropTypes.string,
backgroundColor: PropTypes.string,
regionNamesText: PropTypes.shape({
region: [
{
id: PropTypes.string,
name: PropTypes.string,
},
],
}),
hideMapLegend: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
strokeColor: PropTypes.string,
tooltipBackgroundColor: PropTypes.string,
style: PropTypes.object,
};
|
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="let item of items" (click)="showDetails(item)">
{{item.title}}
</li>
</ul>
`
})
export class AppComponent {
items = [
{
title: 'Item 1',
description: 'Description for Item 1',
},
{
title: 'Item 2',
description: 'Description for Item 2',
},
{
title: 'Item 3',
description: 'Description for Item 3',
}
];
showDetails(item) {
console.log(item);
}
} |
# API sentiment
from deeptrade.sentiment import *
# API stocks
from deeptrade.stocks import *
def average_sentiment_score(stock_symbol, start_date, end_date):
# Retrieve news articles related to the stock_symbol within the specified date range
news_articles = deeptrade.stocks.get_news(stock_symbol, start_date, end_date)
total_sentiment_score = 0
num_articles = 0
# Calculate sentiment score for each news article and accumulate the total sentiment score
for article in news_articles:
sentiment_score = deeptrade.sentiment.analyze_sentiment(article)
total_sentiment_score += sentiment_score
num_articles += 1
# Compute the average sentiment score
if num_articles > 0:
average_score = total_sentiment_score / num_articles
else:
average_score = 0 # Default to 0 if no articles found
return average_score |
package com.sb.android.homeradio.Adapter;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DrawableUtils;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.sb.android.homeradio.MainActivity;
import com.sb.android.homeradio.Model.SongModel;
import com.sb.android.homeradio.PlayerActivity;
import com.sb.android.homeradio.R;
import java.util.ArrayList;
/**
* Created by singhsh on 9/28/2019.
*/
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.ViewHolder>{
private ArrayList<SongModel> songModel;
private Context mContext;
public SongAdapter( ArrayList<SongModel> songmodel, Context context){
songModel = songmodel;
mContext = context;
}
@Override
public SongAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
SongAdapter.ViewHolder viewHolder = new SongAdapter.ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(SongAdapter.ViewHolder holder, int position) {
holder.bindRestaurant(songModel.get(position));
}
@Override
public int getItemCount() {
return songModel.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView img;
TextView titletv;
TextView singertv;
private Context mContext;
public ViewHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
AssetManager Amr = mContext.getAssets();
Typeface facebold = Typeface.createFromAsset(Amr,"fonts/AEB.ttf");
titletv = (TextView) itemView.findViewById(R.id.titletv);
singertv = (TextView) itemView.findViewById(R.id.singertv);
titletv.setTypeface(facebold);
titletv.setTypeface(facebold);
img = (ImageView) itemView.findViewById(R.id.coveriv);
}
public void bindRestaurant(final SongModel songmodel) {
titletv.setText(songmodel.getTitle());
singertv.setText(songmodel.getSinger());
img.setImageResource(songmodel.getImgico());
Log.d("SongAdapter","added : " + songmodel.getTitle());
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
/* ImageView view = (ImageView ) v;
view.getBackground().setColorFilter(0x77ffffff, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
*/
break;
}
case MotionEvent.ACTION_UP:
Log.d("songAdapter","ACTION_UP");
Intent intent = new Intent(mContext , PlayerActivity.class);
intent.putExtra("murl",songmodel.getSongurl());
intent.putExtra("imgico",songmodel.getImgico());
intent.putExtra("title",songmodel.getTitle());
intent.putExtra("desc",songmodel.getImg());
mContext.startActivity(intent);
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
/* ImageView view = (ImageView) v;
view.getBackground().clearColorFilter();
view.invalidate();
*/
break;
}
}
return true;
}
});
}
}
}
|
<filename>lang/py/pylib/code/pdb/pdb_script.py
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2010 <NAME>. All rights reserved.
#
class MyObj(object):
def __init__(self, num_loops):
self.count = num_loops
def go(self):
for i in range(self.count):
print i
return
if __name__ == '__main__':
MyObj(5).go()
|
'use strict';
/**
* Module provides calendar (daily, weekly, monthly etc.)
*/
angular.module('chronos.calendar', [
'chronos.calendar.directives',
'chronos.events',
'chronos.commons',
'users.commons.filters',
'ui.dnd',
'ui.elements',
'ui.notifications',
'ngTouch'
]);
|
joms.extend({
settings: '',
stream: {
init: function(options) {
settings = options;
var Stream = this;
var elStream = options.elStream;
var elActivity = options.elActivity;
var elPrivacy = options.elPrivacy;
joms.jQuery( document ).on( 'click', [ elStream, elActivity, elPrivacy, '.dropdown-menu li a' ].join(' '), function() {
var el = joms.jQuery( this ),
intStreamId = el.closest( elActivity ).data('streamid'),
intPrivacyValue = el.data('option-value');
Stream.updatePrivacy(intStreamId, intPrivacyValue);
});
joms.stream.like();
joms.stream.dislike();
joms.stream.comment();
joms.stream.editStatus();
joms.stream.hideStatus();
joms.stream.ajaxAddMood();
joms.stream.ajaxRemoveMood();
joms.stream.ignoreUser();
joms.stream.showlike();
},
like: function() {
joms.jQuery(settings.elStream).on('click', '[data-action="like"]', function(e) {
e.preventDefault();
var streamId = joms.jQuery(this).data('stream-id');
var streamType = joms.jQuery(this).data('stream-type');
jax.call('community', 'system,ajaxStreamAddLike', streamId, streamType);
});
},
dislike: function() {
joms.jQuery(settings.elStream).on('click', '[data-action="unlike"]', function(e) {
e.preventDefault();
var streamId = joms.jQuery(this).data('stream-id');
var streamType = joms.jQuery(this).data('stream-type');
jax.call('community', 'system,ajaxStreamUnlike', streamId, streamType);
});
},
share: function() {
},
comment: function() {},
updatePrivacy: function(intStreamId, intPrivacyValue) {
jax.call('community', 'activities,ajaxUpdatePrivacyActivity', intStreamId, intPrivacyValue);
},
editStatus: function() {},
showTextarea: function() {},
hideStatus: function() {
joms.jQuery(settings.elStream).on('click', '[data-action="hide"]', function(e) {
e.preventDefault();
var t = joms.jQuery(this);
var p = t.parents('li');
var streamId = t.data('stream-id');
var userId = t.data('user-id');
var groupId = t.data('group-id') ? t.data('group-id') : null;
jax.call('community', 'activities,ajaxHideStatus', streamId, userId, groupId);
});
},
updateHideStatus: function(data) {
var data = joms.jQuery.parseJSON(data);
var streamId = data.streamId;
var userId = data.userId;
var groupId = data.groupId;
var html = unescape(data.html);
var target = joms.jQuery(settings.elStream).find('li[data-streamid="' + streamId + '"]');
target.children().hide();
target.html(html);
target.find('a[data-action="close-hide"]').click(function(e) {
e.preventDefault();
target.remove();
});
},
ajaxSaveStatus: function(id, data) {
jax.call('community', 'activities,ajaxSaveStatus', id, data);
},
ajaxAddMood: function() {
joms.jQuery(settings.elStream).on('click', '[data-action="add-mood"]', function(e) {
e.preventDefault();
var t = joms.jQuery(this);
var streamId = t.data('stream-id');
var ajaxCall = "jax.call('community', 'activities,ajaxAddMood', '" + streamId + "' )";
cWindowShow(ajaxCall, '', 200, 200);
});
},
ajaxRemoveMood: function() {
joms.jQuery(settings.elStream).on('click', '[data-action="remove-mood"]', function(e) {
e.preventDefault();
var t = joms.jQuery(this);
var streamId = t.data('stream-id');
var ajaxCall = "jax.call('community', 'activities,ajaxConfirmRemoveMood', '" + streamId + "' )";
cWindowShow(ajaxCall, '', 450, 100);
});
},
showOthers: function(id) {
var ajaxCall = "jax.call('community', 'activities,ajaxShowOthers', '" + id + "' )";
cWindowShow(ajaxCall, '', 450, 100);
},
/**
* Bind to ignore menu item
*/
ignoreUser: function() {
joms.jQuery(settings.elStream).on('click', '[data-action="ignore"]', function(e) {
e.preventDefault();
var t = joms.jQuery(this);
var userId = t.data('user-id');
var ajaxCall = "jax.call('community', 'activities,ajaxConfirmIgnoreUser', '" + userId + "' )";
cWindowShow(ajaxCall, '', 450, 100);
});
},
showlike: function() {
joms.jQuery(settings.elStream).on('click','[data-action="showlike"]',function(e){
e.preventDefault();
var t = joms.jQuery(this);
var id = t.data('stream-id');
var ajaxCall = "jax.call('community', 'activities,ajaxshowLikedUser', '" + id + "' )";
cWindowShow(ajaxCall,'',450,100);
});
}
}
});
joms.jQuery(document).ready(function() {
joms.stream.init({
elStream: '#activity-stream-container',
elActivity: '.joms-stream',
elPrivacy: '.joms-stream-privacy'
});
})
|
awk '$0=(a=$1/2)==int(a)?a*a:a*++a' |
#!/bin/bash
set -e
export PATH=${HOSTDIR}/nasm_bin/bin:$PATH
case $HOST in
*mipsel-*)
export MIPS_HACK="--with-simd=no"
;;
esac
${SRCDIR}/configure --build=x86_64-unknown-linux-gnu --host=${PREFIX} --prefix=${OUTPUT} \
--enable-static --with-jpeg8 ${MIPS_HACK}
make -j8
make install
|
<filename>buildscripts/scons.py
#!/usr/bin/env python2
from __future__ import print_function
import os
import sys
SCONS_VERSION = os.environ.get('SCONS_VERSION', "2.5.0")
mongodb_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
scons_dir = os.path.join(mongodb_root, 'src', 'third_party','scons-' + SCONS_VERSION,
'scons-local-' + SCONS_VERSION)
if not os.path.exists(scons_dir):
print("Could not find SCons in '%s'" % (scons_dir))
sys.exit(1)
sys.path = [scons_dir] + sys.path
try:
import SCons.Script
except ImportError:
print("Could not find SCons in '%s'" % (scons_dir))
sys.exit(1)
SCons.Script.main()
|
import numpy as np
from itertools import product
def generate_basis_blocks(Nfs, kblocks, pblocks):
L = len(Nfs) # Assuming L is the length of Nfs
t = np.array([(i+1)%L for i in range(L)])
p = np.array([L-i-1 for i in range(L)])
gen_blocks = {}
basis_blocks = {}
for Nf, kblock, pblock in product(Nfs, kblocks, pblocks):
# Generate basis blocks for each combination of Nf, kblock, and pblock
# Your basis block generation logic here
# Store the generated basis blocks in gen_blocks
gen_blocks[(Nf, kblock, pblock)] = generated_basis_blocks
# Organize basis blocks in gen_blocks based on calculations using arrays t and p
# Your organization logic here
# Further organize basis blocks from gen_blocks and store them in basis_blocks
# Your further organization logic here
return basis_blocks |
#!/usr/bin/env bash
if [[ -z $1 ]]; then
echo "Usage $0 <new version>"
exit 1
fi
newVersion=$1
find . -name "Makefile" -exec sed -i '' "s/VERSION = \(.*\)/VERSION = $newVersion/g" {} \;
|
#!/bin/bash
source ../../bin/settings.sh
rm -f output
for v in *.y
do
echo testing $v
echo $v :>>output
"$java" -jar "${COOKCC}" $v > /dev/null 2>> output
done
diff output test.output > /dev/null || error test failed
rm -f Lexer.java
rm -f output
|
Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes"
root "welcome#index"
get "login" => "sessions#new", as: "login"
post "login" => "sessions#create", as: "new_login"
delete "logout" => "sessions#destroy", as: "logout"
def reports
get "inaccuracy" => "report#new_inaccuracy", as: "report_inaccuracy"
get "inquiry" => "report#new_inquiry", as: "report_inquiry"
end
resources :report, only: [:create]
resources :users, except: [:index, :new] do
reports
get :events
get :edit_password
put :update_password
put :update_favorite
end
get 'profile/:user_name', to: 'users#show', as: :user_profile
resources :about, only: [:index]
resources :contact, only: [:index]
resources :venues, except: [:destroy, :edit] do
get :search, :on => :collection
get :add_games, :on => :collection
get :add_neighborhood, :on => :collection
post :results, :on => :collection
get :dropdown, :on => :collection
resources :reviews, only: [:new, :create, :update, :show]
resources :events, only: [:index]
end
post "/games/add_game" => "games#add_game", as: "add_game"
resources :events, except: [:destroy] do
get :search, :on => :collection
get :add_venue, :on => :collection
get :update_games, :on => :collection
post :results, :on => :collection
get :dropdown, :on => :collection
put :guests
post :cancel
resources :comments, only: [:create]
end
end
|
<filename>adapters/yieldlab/yieldlab_test.go
package yieldlab
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/eugene-fedorenko/prebid-server/adapters/adapterstest"
"github.com/eugene-fedorenko/prebid-server/config"
"github.com/eugene-fedorenko/prebid-server/openrtb_ext"
)
const testURL = "https://ad.yieldlab.net/testing/"
var testCacheBuster cacheBuster = func() string {
return "testing"
}
var testWeekGenerator weekGenerator = func() string {
return "33"
}
func newTestYieldlabBidder(endpoint string) *YieldlabAdapter {
return &YieldlabAdapter{
endpoint: endpoint,
cacheBuster: testCacheBuster,
getWeek: testWeekGenerator,
}
}
func TestNewYieldlabBidder(t *testing.T) {
bidder, buildErr := Builder(openrtb_ext.BidderYieldlab, config.Adapter{
Endpoint: testURL})
assert.NoError(t, buildErr)
assert.NotNil(t, bidder)
bidderYieldlab := bidder.(*YieldlabAdapter)
assert.Equal(t, testURL, bidderYieldlab.endpoint)
assert.NotNil(t, bidderYieldlab.cacheBuster)
assert.NotNil(t, bidderYieldlab.getWeek)
}
func TestJsonSamples(t *testing.T) {
adapterstest.RunJSONBidderTest(t, "yieldlabtest", newTestYieldlabBidder(testURL))
}
func Test_splitSize(t *testing.T) {
type args struct {
size string
}
tests := []struct {
name string
args args
want uint64
want1 uint64
wantErr bool
}{
{
name: "valid",
args: args{
size: "300x800",
},
want: 300,
want1: 800,
wantErr: false,
},
{
name: "empty",
args: args{
size: "",
},
want: 0,
want1: 0,
wantErr: false,
},
{
name: "invalid",
args: args{
size: "test",
},
want: 0,
want1: 0,
wantErr: false,
},
{
name: "invalid_height",
args: args{
size: "200xtest",
},
want: 0,
want1: 0,
wantErr: true,
},
{
name: "invalid_width",
args: args{
size: "testx200",
},
want: 0,
want1: 0,
wantErr: true,
},
{
name: "invalid_separator",
args: args{
size: "200y200",
},
want: 0,
want1: 0,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1, err := splitSize(tt.args.size)
if (err != nil) != tt.wantErr {
t.Errorf("splitSize() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("splitSize() got = %v, want %v", got, tt.want)
}
if got1 != tt.want1 {
t.Errorf("splitSize() got1 = %v, want %v", got1, tt.want1)
}
})
}
}
func TestYieldlabAdapter_makeEndpointURL_invalidEndpoint(t *testing.T) {
bidder, buildErr := Builder(openrtb_ext.BidderYieldlab, config.Adapter{
Endpoint: "test$:/something§"})
if buildErr != nil {
t.Fatalf("Builder returned unexpected error %v", buildErr)
}
bidderYieldlab := bidder.(*YieldlabAdapter)
_, err := bidderYieldlab.makeEndpointURL(nil, nil)
assert.Error(t, err)
}
|
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// For more information, please refer to <http://unlicense.org/>
#ifndef SHEREDOM_UTF8_H_INCLUDED
#define SHEREDOM_UTF8_H_INCLUDED
#if defined(_MSC_VER)
#pragma warning(push)
// disable 'bytes padding added after construct' warning
#pragma warning(disable : 4820)
#endif
#include <stddef.h>
#include <stdlib.h>
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#if defined(_MSC_VER)
#define int32_t __int32
#define uint32_t __uint32
#else
#include <stdint.h>
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wcast-qual"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__clang__) || defined(__GNUC__)
#define utf8_nonnull __attribute__((nonnull))
#define utf8_pure __attribute__((pure))
#define utf8_restrict __restrict__
#define utf8_weak __attribute__((weak))
#elif defined(_MSC_VER)
#define utf8_nonnull
#define utf8_pure
#define utf8_restrict __restrict
#define utf8_weak __inline
#else
#error Non clang, non gcc, non MSVC compiler found!
#endif
// While ignoring the case of ASCII characters, return less
// than 0, 0, greater than 0 if src1 < src2, src1 == src2,
// src1 > src2 respectively.
utf8_nonnull utf8_pure utf8_weak int utf8casecmp(const void *src1,
const void *src2);
// Append the utf8 string src onto the utf8 string dst.
utf8_nonnull utf8_weak void *utf8cat(void *utf8_restrict dst,
const void *utf8_restrict src);
// Find the first match of the utf8 codepoint chr in the utf8 string src.
utf8_nonnull utf8_pure utf8_weak void *utf8chr(const void *src, int32_t chr);
// Return less than 0, 0, greater than 0 if src1 < src2,
// src1 == src2, src1 > src2 respectively.
utf8_nonnull utf8_pure utf8_weak int utf8cmp(const void *src1,
const void *src2);
// Copy the utf8 string src onto the memory allocated in dst.
utf8_nonnull utf8_weak void *utf8cpy(void *utf8_restrict dst,
const void *utf8_restrict src);
// Number of utf8 codepoints in the utf8 string src that consists entirely
// of utf8 codepoints not from the utf8 string reject.
utf8_nonnull utf8_pure utf8_weak size_t utf8cspn(const void *src,
const void *reject);
// Duplicate the utf8 string src by getting its size, malloc'ing a new buffer
// copying over the data, and returning that. Or 0 if malloc failed.
utf8_nonnull utf8_weak void *utf8dup(const void *src);
// Number of utf8 codepoints in the utf8 string str,
// excluding the null terminating byte.
utf8_nonnull utf8_pure utf8_weak size_t utf8len(const void *str);
// While ignoring the case of ASCII characters, return less
// than 0, 0, greater than 0 if src1 < src2, src1 == src2,
// src1 > src2 respectively. Checking at most n
// bytes of each utf8 string.
utf8_nonnull utf8_pure utf8_weak int utf8ncasecmp(const void *src1,
const void *src2, size_t n);
// Append the utf8 string src onto the utf8 string dst,
// writing at most n+1 bytes. Can produce an invalid utf8
// string if n falls partway through a utf8 codepoint.
utf8_nonnull utf8_weak void *utf8ncat(void *utf8_restrict dst,
const void *utf8_restrict src, size_t n);
// Return less than 0, 0, greater than 0 if src1 < src2,
// src1 == src2, src1 > src2 respectively. Checking at most n
// bytes of each utf8 string.
utf8_nonnull utf8_pure utf8_weak int utf8ncmp(const void *src1,
const void *src2, size_t n);
// Copy the utf8 string src onto the memory allocated in dst.
// Copies at most n bytes. If there is no terminating null byte in
// the first n bytes of src, the string placed into dst will not be
// null-terminated. If the size (in bytes) of src is less than n,
// extra null terminating bytes are appended to dst such that at
// total of n bytes are written. Can produce an invalid utf8
// string if n falls partway through a utf8 codepoint.
utf8_nonnull utf8_weak void *utf8ncpy(void *utf8_restrict dst,
const void *utf8_restrict src, size_t n);
// Locates the first occurence in the utf8 string str of any byte in the
// utf8 string accept, or 0 if no match was found.
utf8_nonnull utf8_pure utf8_weak void *utf8pbrk(const void *str,
const void *accept);
// Find the last match of the utf8 codepoint chr in the utf8 string src.
utf8_nonnull utf8_pure utf8_weak void *utf8rchr(const void *src, int chr);
// Number of bytes in the utf8 string str,
// including the null terminating byte.
utf8_nonnull utf8_pure utf8_weak size_t utf8size(const void *str);
// Number of utf8 codepoints in the utf8 string src that consists entirely
// of utf8 codepoints from the utf8 string accept.
utf8_nonnull utf8_pure utf8_weak size_t utf8spn(const void *src,
const void *accept);
// The position of the utf8 string needle in the utf8 string haystack.
utf8_nonnull utf8_pure utf8_weak void *utf8str(const void *haystack,
const void *needle);
// The position of the utf8 string needle in the utf8 string haystack, case
// instensitive.
utf8_nonnull utf8_pure utf8_weak void *utf8casestr(const void *haystack,
const void *needle);
// Return 0 on success, or the position of the invalid
// utf8 codepoint on failure.
utf8_nonnull utf8_pure utf8_weak void *utf8valid(const void *str);
// Sets out_codepoint to the next utf8 codepoint in str, and returns the address
// of the utf8 codepoint after the current one in str.
utf8_nonnull utf8_weak void *utf8codepoint(const void *utf8_restrict str,
int32_t *utf8_restrict out_codepoint);
// Returns the size of the given codepoint in bytes.
utf8_weak size_t utf8codepointsize(int32_t chr);
// Write a codepoint to the given string, and return the address to the next place
// after the written codepoint. Pass how many bytes left in the buffer to n. If there
// is not enough space for the codepoint, this function returns null.
utf8_nonnull utf8_weak void *utf8catcodepoint(void *utf8_restrict str, int32_t chr, size_t n);
// Returns 1 if the given character is lowercase, or 0 if it is not.
utf8_weak int utf8islower(int32_t chr);
// Returns 1 if the given character is uppercase, or 0 if it is not.
utf8_weak int utf8isupper(int32_t chr);
// Transform the given string into all lowercase codepoints.
utf8_nonnull utf8_weak void utf8lwr(void *utf8_restrict str);
// Transform the given string into all uppercase codepoints.
utf8_nonnull utf8_weak void utf8upr(void *utf8_restrict str);
#undef utf8_weak
#undef utf8_pure
#undef utf8_nonnull
int utf8casecmp(const void *src1, const void *src2) {
const unsigned char *s1 = (const unsigned char *)src1;
const unsigned char *s2 = (const unsigned char *)src2;
while (('\0' != *s1) || ('\0' != *s2)) {
unsigned char a = *s1;
unsigned char b = *s2;
if (('A' <= a) && ('Z' >= a)) {
a |= 0x20; // make a lowercase
}
if (('A' <= b) && ('Z' >= b)) {
b |= 0x20; // make b lowercase
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
s1++;
s2++;
}
// both utf8 strings matched
return 0;
}
void *utf8cat(void *utf8_restrict dst, const void *utf8_restrict src) {
char *d = (char *)dst;
const char *s = (const char *)src;
// find the null terminating byte in dst
while ('\0' != *d) {
d++;
}
// overwriting the null terminating byte in dst, append src byte-by-byte
while ('\0' != *s) {
*d++ = *s++;
}
// write out a new null terminating byte into dst
*d = '\0';
return dst;
}
void *utf8chr(const void *src, int32_t chr) {
char c[5] = {'\0', '\0', '\0', '\0', '\0'};
if (0 == chr) {
// being asked to return position of null terminating byte, so
// just run s to the end, and return!
const char *s = (const char *)src;
while ('\0' != *s) {
s++;
}
return (void *)s;
} else if (0 == ((int32_t)0xffffff80 & chr)) {
// 1-byte/7-bit ascii
// (0b0xxxxxxx)
c[0] = (char)chr;
} else if (0 == ((int32_t)0xfffff800 & chr)) {
// 2-byte/11-bit utf8 code point
// (0b110xxxxx 0b10xxxxxx)
c[0] = 0xc0 | (char)(chr >> 6);
c[1] = 0x80 | (char)(chr & 0x3f);
} else if (0 == ((int32_t)0xffff0000 & chr)) {
// 3-byte/16-bit utf8 code point
// (0b1110xxxx 0b10xxxxxx 0b10xxxxxx)
c[0] = 0xe0 | (char)(chr >> 12);
c[1] = 0x80 | (char)((chr >> 6) & 0x3f);
c[2] = 0x80 | (char)(chr & 0x3f);
} else { // if (0 == ((int)0xffe00000 & chr)) {
// 4-byte/21-bit utf8 code point
// (0b11110xxx 0b10xxxxxx 0b10xxxxxx 0b10xxxxxx)
c[0] = 0xf0 | (char)(chr >> 18);
c[1] = 0x80 | (char)((chr >> 12) & 0x3f);
c[2] = 0x80 | (char)((chr >> 6) & 0x3f);
c[3] = 0x80 | (char)(chr & 0x3f);
}
// we've made c into a 2 utf8 codepoint string, one for the chr we are
// seeking, another for the null terminating byte. Now use utf8str to
// search
return utf8str(src, c);
}
int utf8cmp(const void *src1, const void *src2) {
const unsigned char *s1 = (const unsigned char *)src1;
const unsigned char *s2 = (const unsigned char *)src2;
while (('\0' != *s1) || ('\0' != *s2)) {
if (*s1 < *s2) {
return -1;
} else if (*s1 > *s2) {
return 1;
}
s1++;
s2++;
}
// both utf8 strings matched
return 0;
}
int utf8coll(const void *src1, const void *src2);
void *utf8cpy(void *utf8_restrict dst, const void *utf8_restrict src) {
char *d = (char *)dst;
const char *s = (const char *)src;
// overwriting anything previously in dst, write byte-by-byte
// from src
while ('\0' != *s) {
*d++ = *s++;
}
// append null terminating byte
*d = '\0';
return dst;
}
size_t utf8cspn(const void *src, const void *reject) {
const char *s = (const char *)src;
size_t chars = 0;
while ('\0' != *s) {
const char *r = (const char *)reject;
size_t offset = 0;
while ('\0' != *r) {
// checking that if *r is the start of a utf8 codepoint
// (it is not 0b10xxxxxx) and we have successfully matched
// a previous character (0 < offset) - we found a match
if ((0x80 != (0xc0 & *r)) && (0 < offset)) {
return chars;
} else {
if (*r == s[offset]) {
// part of a utf8 codepoint matched, so move our checking
// onwards to the next byte
offset++;
r++;
} else {
// r could be in the middle of an unmatching utf8 code point,
// so we need to march it on to the next character beginning,
do {
r++;
} while (0x80 == (0xc0 & *r));
// reset offset too as we found a mismatch
offset = 0;
}
}
}
// the current utf8 codepoint in src did not match reject, but src
// could have been partway through a utf8 codepoint, so we need to
// march it onto the next utf8 codepoint starting byte
do {
s++;
} while ((0x80 == (0xc0 & *s)));
chars++;
}
return chars;
}
size_t utf8size(const void *str);
void *utf8dup(const void *src) {
const char *s = (const char *)src;
char *n = 0;
// figure out how many bytes (including the terminator) we need to copy first
size_t bytes = utf8size(src);
n = (char *)malloc(bytes);
if (0 == n) {
// out of memory so we bail
return 0;
} else {
bytes = 0;
// copy src byte-by-byte into our new utf8 string
while ('\0' != s[bytes]) {
n[bytes] = s[bytes];
bytes++;
}
// append null terminating byte
n[bytes] = '\0';
return n;
}
}
void *utf8fry(const void *str);
size_t utf8len(const void *str) {
const unsigned char *s = (const unsigned char *)str;
size_t length = 0;
while ('\0' != *s) {
if (0xf0 == (0xf8 & *s)) {
// 4-byte utf8 code point (began with 0b11110xxx)
s += 4;
} else if (0xe0 == (0xf0 & *s)) {
// 3-byte utf8 code point (began with 0b1110xxxx)
s += 3;
} else if (0xc0 == (0xe0 & *s)) {
// 2-byte utf8 code point (began with 0b110xxxxx)
s += 2;
} else { // if (0x00 == (0x80 & *s)) {
// 1-byte ascii (began with 0b0xxxxxxx)
s += 1;
}
// no matter the bytes we marched s forward by, it was
// only 1 utf8 codepoint
length++;
}
return length;
}
int utf8ncasecmp(const void *src1, const void *src2, size_t n) {
const unsigned char *s1 = (const unsigned char *)src1;
const unsigned char *s2 = (const unsigned char *)src2;
while ((('\0' != *s1) || ('\0' != *s2)) && (0 != n--)) {
unsigned char a = *s1;
unsigned char b = *s2;
if (('A' <= a) && ('Z' >= a)) {
a |= 0x20; // make a lowercase
}
if (('A' <= b) && ('Z' >= b)) {
b |= 0x20; // make b lowercase
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
s1++;
s2++;
}
// both utf8 strings matched
return 0;
}
void *utf8ncat(void *utf8_restrict dst, const void *utf8_restrict src,
size_t n) {
char *d = (char *)dst;
const char *s = (const char *)src;
// find the null terminating byte in dst
while ('\0' != *d) {
d++;
}
// overwriting the null terminating byte in dst, append src byte-by-byte
// stopping if we run out of space
do {
*d++ = *s++;
} while (('\0' != *s) && (0 != --n));
// write out a new null terminating byte into dst
*d = '\0';
return dst;
}
int utf8ncmp(const void *src1, const void *src2, size_t n) {
const unsigned char *s1 = (const unsigned char *)src1;
const unsigned char *s2 = (const unsigned char *)src2;
while ((('\0' != *s1) || ('\0' != *s2)) && (0 != n--)) {
if (*s1 < *s2) {
return -1;
} else if (*s1 > *s2) {
return 1;
}
s1++;
s2++;
}
// both utf8 strings matched
return 0;
}
void *utf8ncpy(void *utf8_restrict dst, const void *utf8_restrict src,
size_t n) {
char *d = (char *)dst;
const char *s = (const char *)src;
// overwriting anything previously in dst, write byte-by-byte
// from src
do {
*d++ = *s++;
} while (('\0' != *s) && (0 != --n));
// append null terminating byte
while (0 != n) {
*d++ = '\0';
n--;
}
return dst;
}
void *utf8rchr(const void *src, int chr) {
const char *s = (const char *)src;
const char *match = 0;
char c[5] = {'\0', '\0', '\0', '\0', '\0'};
if (0 == chr) {
// being asked to return position of null terminating byte, so
// just run s to the end, and return!
while ('\0' != *s) {
s++;
}
return (void *)s;
} else if (0 == ((int)0xffffff80 & chr)) {
// 1-byte/7-bit ascii
// (0b0xxxxxxx)
c[0] = (char)chr;
} else if (0 == ((int)0xfffff800 & chr)) {
// 2-byte/11-bit utf8 code point
// (0b110xxxxx 0b10xxxxxx)
c[0] = 0xc0 | (char)(chr >> 6);
c[1] = 0x80 | (char)(chr & 0x3f);
} else if (0 == ((int)0xffff0000 & chr)) {
// 3-byte/16-bit utf8 code point
// (0b1110xxxx 0b10xxxxxx 0b10xxxxxx)
c[0] = 0xe0 | (char)(chr >> 12);
c[1] = 0x80 | (char)((chr >> 6) & 0x3f);
c[2] = 0x80 | (char)(chr & 0x3f);
} else { // if (0 == ((int)0xffe00000 & chr)) {
// 4-byte/21-bit utf8 code point
// (0b11110xxx 0b10xxxxxx 0b10xxxxxx 0b10xxxxxx)
c[0] = 0xf0 | (char)(chr >> 18);
c[1] = 0x80 | (char)((chr >> 12) & 0x3f);
c[2] = 0x80 | (char)((chr >> 6) & 0x3f);
c[3] = 0x80 | (char)(chr & 0x3f);
}
// we've created a 2 utf8 codepoint string in c that is
// the utf8 character asked for by chr, and a null
// terminating byte
while ('\0' != *s) {
size_t offset = 0;
while (s[offset] == c[offset]) {
offset++;
}
if ('\0' == c[offset]) {
// we found a matching utf8 code point
match = s;
s += offset;
} else {
s += offset;
// need to march s along to next utf8 codepoint start
// (the next byte that doesn't match 0b10xxxxxx)
if ('\0' != *s) {
do {
s++;
} while (0x80 == (0xc0 & *s));
}
}
}
// return the last match we found (or 0 if no match was found)
return (void *)match;
}
void *utf8pbrk(const void *str, const void *accept) {
const char *s = (const char *)str;
while ('\0' != *s) {
const char *a = (const char *)accept;
size_t offset = 0;
while ('\0' != *a) {
// checking that if *a is the start of a utf8 codepoint
// (it is not 0b10xxxxxx) and we have successfully matched
// a previous character (0 < offset) - we found a match
if ((0x80 != (0xc0 & *a)) && (0 < offset)) {
return (void *)s;
} else {
if (*a == s[offset]) {
// part of a utf8 codepoint matched, so move our checking
// onwards to the next byte
offset++;
a++;
} else {
// r could be in the middle of an unmatching utf8 code point,
// so we need to march it on to the next character beginning,
do {
a++;
} while (0x80 == (0xc0 & *a));
// reset offset too as we found a mismatch
offset = 0;
}
}
}
// we found a match on the last utf8 codepoint
if (0 < offset) {
return (void *)s;
}
// the current utf8 codepoint in src did not match accept, but src
// could have been partway through a utf8 codepoint, so we need to
// march it onto the next utf8 codepoint starting byte
do {
s++;
} while ((0x80 == (0xc0 & *s)));
}
return 0;
}
size_t utf8size(const void *str) {
const char *s = (const char *)str;
size_t size = 0;
while ('\0' != s[size]) {
size++;
}
// we are including the null terminating byte in the size calculation
size++;
return size;
}
size_t utf8spn(const void *src, const void *accept) {
const char *s = (const char *)src;
size_t chars = 0;
while ('\0' != *s) {
const char *a = (const char *)accept;
size_t offset = 0;
while ('\0' != *a) {
// checking that if *r is the start of a utf8 codepoint
// (it is not 0b10xxxxxx) and we have successfully matched
// a previous character (0 < offset) - we found a match
if ((0x80 != (0xc0 & *a)) && (0 < offset)) {
// found a match, so increment the number of utf8 codepoints
// that have matched and stop checking whether any other utf8
// codepoints in a match
chars++;
s += offset;
break;
} else {
if (*a == s[offset]) {
offset++;
a++;
} else {
// a could be in the middle of an unmatching utf8 codepoint,
// so we need to march it on to the next character beginning,
do {
a++;
} while (0x80 == (0xc0 & *a));
// reset offset too as we found a mismatch
offset = 0;
}
}
}
// if a got to its terminating null byte, then we didn't find a match.
// Return the current number of matched utf8 codepoints
if ('\0' == *a) {
return chars;
}
}
return chars;
}
void *utf8str(const void *haystack, const void *needle) {
const char *h = (const char *)haystack;
// if needle has no utf8 codepoints before the null terminating
// byte then return haystack
if ('\0' == *((const char *)needle)) {
return (void *)haystack;
}
while ('\0' != *h) {
const char *maybeMatch = h;
const char *n = (const char *)needle;
while (*h == *n && (*h != '\0' && *n != '\0')) {
n++;
h++;
}
if ('\0' == *n) {
// we found the whole utf8 string for needle in haystack at
// maybeMatch, so return it
return (void *)maybeMatch;
} else {
// h could be in the middle of an unmatching utf8 codepoint,
// so we need to march it on to the next character beginning,
if ('\0' != *h) {
do {
h++;
} while (0x80 == (0xc0 & *h));
}
}
}
// no match
return 0;
}
void *utf8casestr(const void *haystack, const void *needle) {
const char *h = (const char *)haystack;
// if needle has no utf8 codepoints before the null terminating
// byte then return haystack
if ('\0' == *((const char *)needle)) {
return (void *)haystack;
}
while ('\0' != *h) {
const char *maybeMatch = h;
const char *n = (const char *)needle;
for (;;) {
char a = *h;
char b = *n;
// not entirely correct, but good enough
if (('A' <= a) && ('Z' >= a)) {
a |= 0x20; // make a lowercase
}
if (('A' <= b) && ('Z' >= b)) {
b |= 0x20; // make b lowercase
}
// if we find a mismatch, bail out!
if (a != b) {
break;
}
n++;
h++;
}
if ('\0' == *n) {
// we found the whole utf8 string for needle in haystack at
// maybeMatch, so return it
return (void *)maybeMatch;
} else {
// h could be in the middle of an unmatching utf8 codepoint,
// so we need to march it on to the next character beginning,
if ('\0' != *h) {
do {
h++;
} while (0x80 == (0xc0 & *h));
}
}
}
// no match
return 0;
}
void *utf8valid(const void *str) {
const char *s = (const char *)str;
while ('\0' != *s) {
if (0xf0 == (0xf8 & *s)) {
// ensure each of the 3 following bytes in this 4-byte
// utf8 codepoint began with 0b10xxxxxx
if ((0x80 != (0xc0 & s[1])) || (0x80 != (0xc0 & s[2])) ||
(0x80 != (0xc0 & s[3]))) {
return (void *)s;
}
// ensure that our utf8 codepoint ended after 4 bytes
if (0x80 == (0xc0 & s[4])) {
return (void *)s;
}
// ensure that the top 5 bits of this 4-byte utf8
// codepoint were not 0, as then we could have used
// one of the smaller encodings
if ((0 == (0x07 & s[0])) && (0 == (0x30 & s[1]))) {
return (void *)s;
}
// 4-byte utf8 code point (began with 0b11110xxx)
s += 4;
} else if (0xe0 == (0xf0 & *s)) {
// ensure each of the 2 following bytes in this 3-byte
// utf8 codepoint began with 0b10xxxxxx
if ((0x80 != (0xc0 & s[1])) || (0x80 != (0xc0 & s[2]))) {
return (void *)s;
}
// ensure that our utf8 codepoint ended after 3 bytes
if (0x80 == (0xc0 & s[3])) {
return (void *)s;
}
// ensure that the top 5 bits of this 3-byte utf8
// codepoint were not 0, as then we could have used
// one of the smaller encodings
if ((0 == (0x0f & s[0])) && (0 == (0x20 & s[1]))) {
return (void *)s;
}
// 3-byte utf8 code point (began with 0b1110xxxx)
s += 3;
} else if (0xc0 == (0xe0 & *s)) {
// ensure the 1 following byte in this 2-byte
// utf8 codepoint began with 0b10xxxxxx
if (0x80 != (0xc0 & s[1])) {
return (void *)s;
}
// ensure that our utf8 codepoint ended after 2 bytes
if (0x80 == (0xc0 & s[2])) {
return (void *)s;
}
// ensure that the top 4 bits of this 2-byte utf8
// codepoint were not 0, as then we could have used
// one of the smaller encodings
if (0 == (0x1e & s[0])) {
return (void *)s;
}
// 2-byte utf8 code point (began with 0b110xxxxx)
s += 2;
} else if (0x00 == (0x80 & *s)) {
// 1-byte ascii (began with 0b0xxxxxxx)
s += 1;
} else {
// we have an invalid 0b1xxxxxxx utf8 code point entry
return (void *)s;
}
}
return 0;
}
void *utf8codepoint(const void *utf8_restrict str,
int32_t *utf8_restrict out_codepoint) {
const char *s = (const char *)str;
if (0xf0 == (0xf8 & s[0])) {
// 4 byte utf8 codepoint
*out_codepoint = ((0x07 & s[0]) << 18) | ((0x3f & s[1]) << 12) |
((0x3f & s[2]) << 6) | (0x3f & s[3]);
s += 4;
} else if (0xe0 == (0xf0 & s[0])) {
// 3 byte utf8 codepoint
*out_codepoint =
((0x0f & s[0]) << 12) | ((0x3f & s[1]) << 6) | (0x3f & s[2]);
s += 3;
} else if (0xc0 == (0xe0 & s[0])) {
// 2 byte utf8 codepoint
*out_codepoint = ((0x1f & s[0]) << 6) | (0x3f & s[1]);
s += 2;
} else {
// 1 byte utf8 codepoint otherwise
*out_codepoint = s[0];
s += 1;
}
return (void *)s;
}
size_t utf8codepointsize(int32_t chr) {
if (0 == ((int32_t)0xffffff80 & chr)) {
return 1;
} else if (0 == ((int32_t)0xfffff800 & chr)) {
return 2;
} else if (0 == ((int32_t)0xffff0000 & chr)) {
return 3;
} else { // if (0 == ((int)0xffe00000 & chr)) {
return 4;
}
}
void *utf8catcodepoint(void *utf8_restrict str, int32_t chr, size_t n) {
char *s = (char *)str;
if (0 == ((int32_t)0xffffff80 & chr)) {
// 1-byte/7-bit ascii
// (0b0xxxxxxx)
if (n < 1) {
return 0;
}
s[0] = (char)chr;
s += 1;
} else if (0 == ((int32_t)0xfffff800 & chr)) {
// 2-byte/11-bit utf8 code point
// (0b110xxxxx 0b10xxxxxx)
if (n < 2) {
return 0;
}
s[0] = 0xc0 | (char)(chr >> 6);
s[1] = 0x80 | (char)(chr & 0x3f);
s += 2;
} else if (0 == ((int32_t)0xffff0000 & chr)) {
// 3-byte/16-bit utf8 code point
// (0b1110xxxx 0b10xxxxxx 0b10xxxxxx)
if (n < 3) {
return 0;
}
s[0] = 0xe0 | (char)(chr >> 12);
s[1] = 0x80 | (char)((chr >> 6) & 0x3f);
s[2] = 0x80 | (char)(chr & 0x3f);
s += 3;
} else { // if (0 == ((int)0xffe00000 & chr)) {
// 4-byte/21-bit utf8 code point
// (0b11110xxx 0b10xxxxxx 0b10xxxxxx 0b10xxxxxx)
if (n < 4) {
return 0;
}
s[0] = 0xf0 | (char)(chr >> 18);
s[1] = 0x80 | (char)((chr >> 12) & 0x3f);
s[2] = 0x80 | (char)((chr >> 6) & 0x3f);
s[3] = 0x80 | (char)(chr & 0x3f);
s += 4;
}
return s;
}
int utf8islower(int32_t chr)
{
if (('A' <= chr) && ('Z' >= chr)) {
return 0;
}
// Because we're not all-inclusive, assume everything else is lowercase
return 1;
}
int utf8isupper(int32_t chr)
{
if (('A' <= chr) && ('Z' >= chr)) {
return 1;
}
return 0;
}
void utf8lwr(void *utf8_restrict str)
{
void *p, *pn;
int cp;
p = (char *)str;
pn = utf8codepoint(p, &cp);
while (cp != 0) {
if (('A' <= cp) && ('Z' >= cp)) {
cp |= 0x20;
utf8catcodepoint(p, cp, 1);
}
p = pn;
pn = utf8codepoint(p, &cp);
}
}
void utf8upr(void *utf8_restrict str)
{
void *p, *pn;
int cp;
p = (char *)str;
pn = utf8codepoint(p, &cp);
while (cp != 0) {
if (('a' <= cp) && ('z' >= cp)) {
cp &= ~0x20;
utf8catcodepoint(p, cp, 1);
}
p = pn;
pn = utf8codepoint(p, &cp);
}
}
#undef utf8_restrict
#ifdef __cplusplus
} // extern "C"
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // SHEREDOM_UTF8_H_INCLUDED
|
<reponame>Es10liv/mcc.cplusplus<gh_stars>0
// Chapter 9 Programming Challenge 11
#include <iostream>
using namespace std;
// function prototype
int * arrayExpander(int[], int size);
int main()
{
// create the first array
int arr[] = { 1, 2, 3, 4, 5 };
// variable for size of array
int intSize = 5;
// create pointer and call arrayExpander function
int *arrayPointer = arrayExpander(arr, intSize);
// create a for loop to loop through the second array and display each number
for (int i = 0; i < intSize * 2; i++)
{
cout << arrayPointer[i] << endl;
}
return 0;
}
// create an array that
int * arrayExpander(int arr[], int size)
{
// create a pointer that will be the returned values
int *expanderArr = new int[size * 2]; // multiply size by two to get double
// move elements from original array into the expander array
// initialize the rest of the elements in the array to 0
for (int i = 0; i < size * 2; i++)
{
// if statement adds the orignal array's items to the new array and adds the zeroes
if (i < size)
{
// adds in the items from the first array
expanderArr[i] = arr[i];
}
else
{
// adds zeroes to the rest of the array items
expanderArr[i] = 0;
}
}
return expanderArr;
} |
public static int sumTwoDimensionArray(int[][] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
return sum;
}
int result = sumTwoDimensionArray([[1, 2], [3, 4]]);
System.out.println(result); |
#include "table.h"
Table::Table(){
numCombinationsOnTable = 0;
combinationsOnTable = new Combination*[numCombinationsOnTable];
}
Table::~Table(){
for (int i = 0; i < numCombinationsOnTable; i++)
delete combinationsOnTable[i];
delete[] combinationsOnTable;
numCombinationsOnTable = 0;
}
void Table::clear(){
for (int i = 0; i < numCombinationsOnTable; i++)
delete combinationsOnTable[i];
delete[] combinationsOnTable;
numCombinationsOnTable = 0;
combinationsOnTable = new Combination*[numCombinationsOnTable];
}
int Table::getNumberOfCombinations(){
return numCombinationsOnTable;
}
void Table::addCombinationOnTable(Combination *combination){
numCombinationsOnTable++;
Combination** temp = new Combination*[numCombinationsOnTable];
for (int i = 0; i < numCombinationsOnTable - 1; i++){
temp[i] = combinationsOnTable[i];
}
temp[numCombinationsOnTable - 1] = combination;
delete[] combinationsOnTable;
combinationsOnTable = temp;
}
Combination *Table::getTopCombination(){
if (numCombinationsOnTable > 0)
return combinationsOnTable[numCombinationsOnTable - 1];
else
return NULL;
}
Combination* Table::getCombination(int index){
return combinationsOnTable[index];
}
|
def linha():
print()
print('=' * 80)
print()
linha()
sexo = str(input('Sexo [M/F]: ')).upper()
if sexo != 'M' and sexo != 'F':
cont = 0
while True:
if cont == 0:
print('Por favor, digite corretamente com M para sexo masculino e F para sexo feminino.')
sexo = str(input('Sexo [M/F]: ')).upper()
if sexo == 'M' or sexo == 'F':
print()
break
else:
cont += 1
elif cont == 1:
print('Irmão, digite certo igual te ensinei da última vez.')
sexo = str(input('Sexo [M/F]: ')).upper()
if sexo == 'M' or sexo == 'F':
print()
break
else:
cont += 1
elif cont == 2:
print('Cara? Qual a dificuldade de digitar M ou F??? Bora acabar com isso logo...')
sexo = str(input('Sexo [M/F]: ')).upper()
if sexo == 'M' or sexo == 'F':
print()
break
else:
cont += 1
elif cont == 3:
print('É sério isso? Porra maluco, dá o fora daqui então. Desisto de você!!')
break
if sexo == 'M':
print(f'Seu sexo é MASCULINO')
elif sexo == 'F':
print(f'Seu sexo é FEMININO')
linha()
|
import java.util.Objects;
class CustomNullPointerException extends RuntimeException {
public CustomNullPointerException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
checkNotNull(System.currentTimeMillis() > 0 ? MyEnum.A : null, "x");
checkNotNull(System.currentTimeMillis() > 0 ? new Object() : null, "y");
}
@NeverInline
static void checkNotNull(Object o, String name) {
if (o == null) {
throw new CustomNullPointerException("Variable '" + name + "' is null");
}
}
}
enum MyEnum {
A, B, C
} |
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
1,2,3,4,5
3
3,4,5,1,2
"""
move = k % len(nums)
nums[:] = nums[-move:] + nums[:-move]
|
<html>
<head>
</head>
<body>
<div class="welcome-message">Hello World!</div>
</body>
</html> |
SyntaxError();
|
<gh_stars>1-10
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { Experience } from './experience.model';
import { ExperiencePopupService } from './experience-popup.service';
import { ExperienceService } from './experience.service';
@Component({
selector: 'jhi-experience-delete-dialog',
templateUrl: './experience-delete-dialog.component.html'
})
export class ExperienceDeleteDialogComponent {
experience: Experience;
constructor(
private experienceService: ExperienceService,
public activeModal: NgbActiveModal,
private eventManager: JhiEventManager
) {
}
clear() {
this.activeModal.dismiss('cancel');
}
confirmDelete(id: number) {
this.experienceService.delete(id).subscribe((response) => {
this.eventManager.broadcast({
name: 'experienceListModification',
content: 'Deleted an experience'
});
this.activeModal.dismiss(true);
});
}
}
@Component({
selector: 'jhi-experience-delete-popup',
template: ''
})
export class ExperienceDeletePopupComponent implements OnInit, OnDestroy {
routeSub: any;
constructor(
private route: ActivatedRoute,
private experiencePopupService: ExperiencePopupService
) {}
ngOnInit() {
this.routeSub = this.route.params.subscribe((params) => {
this.experiencePopupService
.open(ExperienceDeleteDialogComponent as Component, params['id']);
});
}
ngOnDestroy() {
this.routeSub.unsubscribe();
}
}
|
// http://www.libpng.org/pub/png/spec/1.1/PNG-CRCAppendix.html
function CRC() {
var table = [ ];
var c;
var n, k;
for (n = 0; n < 256; ++n) {
c = n;
for (k = 0; k < 8; k++) {
if (c & 1) {
c = 0xedb88320 ^ (c >>> 1);
} else {
c = c >>> 1;
}
}
table[n] = c;
}
function update_crc(buf) {
var c = -1 >> 0;
var n;
for (n = 0; n < buf.length; ++n) {
var b = buf[n];
var d = c ^ b;
var e = d & 0xff;
var f = c >>> 8;
c = table[(c ^ buf[n]) & 0xff] ^ (c >>> 8);
}
return c;
}
this.compute = function(buf) {
return ((update_crc(buf) >>> 0) ^ (-1 >>> 0)) >>> 0;
}
}
|
if hash jpegtran 2>/dev/null; then
jpg.optimize() {
_find_files_helper "*.jpg" "$@" | xargs -0 -P$(nproc) -I{} \
sh -c 'OS=$(wc -c < "{}")
T="$(mktemp)"
jpegtran -copy none -progressive -optimize "{}" > "$T"
if [[ $? -eq 0 ]]; then
NS=$(wc -c < "$T")
if [[ $NS -gt $OS ]]; then
rm "$T"
NS=$OS
else
mv "$T" "{}"
fi
printf "%-30s %10s -> %-10s\n" "{}" "$OS" "$NS"
else
rm "$T"
fi'
}
fi # end of jpegtran
|
#!/usr/bin/env -S bash -euET -o pipefail -O inherit_errexit
SCRIPT=$(readlink -f "$0") && cd $(dirname "$SCRIPT")
# --- Script Init ---
mkdir -p log
rm -R -f log/*
touch log/stderror.err
ktools_monitor.sh $$ & pid0=$!
exit_handler(){
exit_code=$?
kill -9 $pid0 2> /dev/null
if [ "$exit_code" -gt 0 ]; then
echo 'Ktools Run Error - exitcode='$exit_code
else
echo 'Run Completed'
fi
set +x
group_pid=$(ps -p $$ -o pgid --no-headers)
sess_pid=$(ps -p $$ -o sess --no-headers)
script_pid=$$
printf "Script PID:%d, GPID:%s, SPID:%d
" $script_pid $group_pid $sess_pid >> log/killout.txt
ps -jf f -g $sess_pid > log/subprocess_list
PIDS_KILL=$(pgrep -a --pgroup $group_pid | awk 'BEGIN { FS = "[ \t\n]+" }{ if ($1 >= '$script_pid') print}' | grep -v celery | egrep -v *\\.log$ | egrep -v *\\.sh$ | sort -n -r)
echo "$PIDS_KILL" >> log/killout.txt
kill -9 $(echo "$PIDS_KILL" | awk 'BEGIN { FS = "[ \t\n]+" }{ print $1 }') 2>/dev/null
exit $exit_code
}
trap exit_handler QUIT HUP INT KILL TERM ERR EXIT
check_complete(){
set +e
proc_list="eve getmodel gulcalc fmcalc summarycalc eltcalc aalcalc leccalc pltcalc ordleccalc"
has_error=0
for p in $proc_list; do
started=$(find log -name "$p*.log" | wc -l)
finished=$(find log -name "$p*.log" -exec grep -l "finish" {} + | wc -l)
if [ "$finished" -lt "$started" ]; then
echo "[ERROR] $p - $((started-finished)) processes lost"
has_error=1
elif [ "$started" -gt 0 ]; then
echo "[OK] $p"
fi
done
if [ "$has_error" -ne 0 ]; then
false # raise non-zero exit code
fi
}
# --- Setup run dirs ---
find output -type f -not -name '*summary-info*' -not -name '*.json' -exec rm -R -f {} +
rm -R -f fifo/*
rm -R -f work/*
mkdir work/kat/
mkdir work/gul_S1_summaryleccalc
mkdir work/gul_S1_summaryaalcalc
mkdir work/il_S1_summaryleccalc
mkdir work/il_S1_summaryaalcalc
mkfifo fifo/gul_P10
mkfifo fifo/gul_S1_summary_P10
mkfifo fifo/gul_S1_summary_P10.idx
mkfifo fifo/gul_S1_eltcalc_P10
mkfifo fifo/gul_S1_summarycalc_P10
mkfifo fifo/gul_S1_pltcalc_P10
mkfifo fifo/il_P10
mkfifo fifo/il_S1_summary_P10
mkfifo fifo/il_S1_summary_P10.idx
mkfifo fifo/il_S1_eltcalc_P10
mkfifo fifo/il_S1_summarycalc_P10
mkfifo fifo/il_S1_pltcalc_P10
# --- Do insured loss computes ---
( eltcalc -s < fifo/il_S1_eltcalc_P10 > work/kat/il_S1_eltcalc_P10 ) 2>> log/stderror.err & pid1=$!
( summarycalctocsv -s < fifo/il_S1_summarycalc_P10 > work/kat/il_S1_summarycalc_P10 ) 2>> log/stderror.err & pid2=$!
( pltcalc -s < fifo/il_S1_pltcalc_P10 > work/kat/il_S1_pltcalc_P10 ) 2>> log/stderror.err & pid3=$!
tee < fifo/il_S1_summary_P10 fifo/il_S1_eltcalc_P10 fifo/il_S1_summarycalc_P10 fifo/il_S1_pltcalc_P10 work/il_S1_summaryaalcalc/P10.bin work/il_S1_summaryleccalc/P10.bin > /dev/null & pid4=$!
tee < fifo/il_S1_summary_P10.idx work/il_S1_summaryleccalc/P10.idx > /dev/null & pid5=$!
( summarycalc -m -f -1 fifo/il_S1_summary_P10 < fifo/il_P10 ) 2>> log/stderror.err &
# --- Do ground up loss computes ---
( eltcalc -s < fifo/gul_S1_eltcalc_P10 > work/kat/gul_S1_eltcalc_P10 ) 2>> log/stderror.err & pid6=$!
( summarycalctocsv -s < fifo/gul_S1_summarycalc_P10 > work/kat/gul_S1_summarycalc_P10 ) 2>> log/stderror.err & pid7=$!
( pltcalc -s < fifo/gul_S1_pltcalc_P10 > work/kat/gul_S1_pltcalc_P10 ) 2>> log/stderror.err & pid8=$!
tee < fifo/gul_S1_summary_P10 fifo/gul_S1_eltcalc_P10 fifo/gul_S1_summarycalc_P10 fifo/gul_S1_pltcalc_P10 work/gul_S1_summaryaalcalc/P10.bin work/gul_S1_summaryleccalc/P10.bin > /dev/null & pid9=$!
tee < fifo/gul_S1_summary_P10.idx work/gul_S1_summaryleccalc/P10.idx > /dev/null & pid10=$!
( summarycalc -m -i -1 fifo/gul_S1_summary_P10 < fifo/gul_P10 ) 2>> log/stderror.err &
( eve 10 40 | getmodel | gulcalc -S100 -L100 -r -a1 -i - | tee fifo/gul_P10 | fmcalc -a2 > fifo/il_P10 ) 2>> log/stderror.err &
wait $pid1 $pid2 $pid3 $pid4 $pid5 $pid6 $pid7 $pid8 $pid9 $pid10
# --- Do insured loss kats ---
kat -s work/kat/il_S1_eltcalc_P10 > output/il_S1_eltcalc.csv & kpid1=$!
kat work/kat/il_S1_pltcalc_P10 > output/il_S1_pltcalc.csv & kpid2=$!
kat work/kat/il_S1_summarycalc_P10 > output/il_S1_summarycalc.csv & kpid3=$!
# --- Do ground up loss kats ---
kat -s work/kat/gul_S1_eltcalc_P10 > output/gul_S1_eltcalc.csv & kpid4=$!
kat work/kat/gul_S1_pltcalc_P10 > output/gul_S1_pltcalc.csv & kpid5=$!
kat work/kat/gul_S1_summarycalc_P10 > output/gul_S1_summarycalc.csv & kpid6=$!
wait $kpid1 $kpid2 $kpid3 $kpid4 $kpid5 $kpid6
check_complete
exit_handler
|
#!/usr/bin/env bash
set -e
if [[ -z "${CI}" ]]; then
FEAT="use-compiled-tools"
else
FEAT="use-installed-tools"
fi
function doc() {
echo ::group::"$1"
cargo doc \
--manifest-path "$1/Cargo.toml" \
--no-default-features \
--features "$FEAT"
echo ::endgroup::
}
# Core crates only!
doc spirv-tools-sys
doc spirv-tools
doc rustc_codegen_spirv
doc spirv-builder
|
package main
import "errors"
var (
// ErrNoBurpAPIToken is returned by the check when the Burp api token is
// not defined.
ErrNoBurpAPIToken = errors.New("BURP_API_TOKEN env var must be set")
// ErrNoBurpAPIEndPoint is returned by the check when the Burp API endpoint
// is not defined.
ErrNoBurpBaseURL = errors.New("BURP_BASE_URL env var must be set")
)
|
<reponame>VGLoic/permissioning-smart-contracts<filename>app/src/App.js
// Libs
import React from "react";
import { ThemeProvider } from "styled-components";
// Components
import Layout from "./components/Layout/Layout";
import Initializer from "./containers/Layout/Initializer";
import Dashboard from "./containers/Dashboard/Dashboard";
import NoProviderFlash from "./components/Flashes/NoProvider";
import WrongNetworkFlash from "./components/Flashes/WrongNetwork";
// Theme
import theme from "./constants/theme";
// Context
import { NetworkProvider } from "./context/network";
import { DataProvider } from "./context/data";
const App = () => (
<ThemeProvider theme={theme}>
<NetworkProvider>
<Layout>
<Initializer
NoProvider={NoProviderFlash}
WrongNetwork={WrongNetworkFlash}
>
<DataProvider>
<Dashboard />
</DataProvider>
</Initializer>
</Layout>
</NetworkProvider>
</ThemeProvider>
);
export default App;
|
<reponame>heylenz/python27
#!/usr/bin/env python
############################################################################
##
## Copyright (C) 2006-2006 Trolltech ASA. All rights reserved.
##
## This file is part of the example classes of the Qt Toolkit.
##
## Licensees holding a valid Qt License Agreement may use this file in
## accordance with the rights, responsibilities and obligations
## contained therein. Please consult your licensing agreement or
## contact <EMAIL> if any conditions of this licensing
## agreement are not clear to you.
##
## Further information about Qt licensing is available at:
## http://www.trolltech.com/products/qt/licensing.html or by
## contacting <EMAIL>.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
############################################################################
import math
from PySide import QtCore, QtGui
import mice_rc
class Mouse(QtGui.QGraphicsItem):
Pi = math.pi
TwoPi = 2.0 * Pi
# Create the bounding rectangle once.
adjust = 0.5
BoundingRect = QtCore.QRectF(-20 - adjust, -22 - adjust, 40 + adjust,
83 + adjust)
def __init__(self):
super(Mouse, self).__init__()
self.angle = 0.0
self.speed = 0.0
self.mouseEyeDirection = 0.0
self.color = QtGui.QColor(QtCore.qrand() % 256, QtCore.qrand() % 256,
QtCore.qrand() % 256)
self.rotate(QtCore.qrand() % (360 * 16))
# In the C++ version of this example, this class is also derived from
# QObject in order to receive timer events. PyQt does not support
# deriving from more than one wrapped class so we just create an
# explicit timer instead.
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.timerEvent)
self.timer.start(1000 / 33)
@staticmethod
def normalizeAngle(angle):
while angle < 0:
angle += Mouse.TwoPi
while angle > Mouse.TwoPi:
angle -= Mouse.TwoPi
return angle
def boundingRect(self):
return Mouse.BoundingRect
def shape(self):
path = QtGui.QPainterPath()
path.addRect(-10, -20, 20, 40)
return path;
def paint(self, painter, option, widget):
# Body.
painter.setBrush(self.color)
painter.drawEllipse(-10, -20, 20, 40)
# Eyes.
painter.setBrush(QtCore.Qt.white)
painter.drawEllipse(-10, -17, 8, 8)
painter.drawEllipse(2, -17, 8, 8)
# Nose.
painter.setBrush(QtCore.Qt.black)
painter.drawEllipse(QtCore.QRectF(-2, -22, 4, 4))
# Pupils.
painter.drawEllipse(QtCore.QRectF(-8.0 + self.mouseEyeDirection, -17, 4, 4))
painter.drawEllipse(QtCore.QRectF(4.0 + self.mouseEyeDirection, -17, 4, 4))
# Ears.
if self.scene().collidingItems(self):
painter.setBrush(QtCore.Qt.red)
else:
painter.setBrush(QtCore.Qt.darkYellow)
painter.drawEllipse(-17, -12, 16, 16)
painter.drawEllipse(1, -12, 16, 16)
# Tail.
path = QtGui.QPainterPath(QtCore.QPointF(0, 20))
path.cubicTo(-5, 22, -5, 22, 0, 25)
path.cubicTo(5, 27, 5, 32, 0, 30)
path.cubicTo(-5, 32, -5, 42, 0, 35)
painter.setBrush(QtCore.Qt.NoBrush)
painter.drawPath(path)
def timerEvent(self):
# Don't move too far away.
lineToCenter = QtCore.QLineF(QtCore.QPointF(0, 0), self.mapFromScene(0, 0))
if lineToCenter.length() > 150:
angleToCenter = math.acos(lineToCenter.dx() / lineToCenter.length())
if lineToCenter.dy() < 0:
angleToCenter = Mouse.TwoPi - angleToCenter;
angleToCenter = Mouse.normalizeAngle((Mouse.Pi - angleToCenter) + Mouse.Pi / 2)
if angleToCenter < Mouse.Pi and angleToCenter > Mouse.Pi / 4:
# Rotate left.
self.angle += [-0.25, 0.25][self.angle < -Mouse.Pi / 2]
elif angleToCenter >= Mouse.Pi and angleToCenter < (Mouse.Pi + Mouse.Pi / 2 + Mouse.Pi / 4):
# Rotate right.
self.angle += [-0.25, 0.25][self.angle < Mouse.Pi / 2]
elif math.sin(self.angle) < 0:
self.angle += 0.25
elif math.sin(self.angle) > 0:
self.angle -= 0.25
# Try not to crash with any other mice.
dangerMice = self.scene().items(QtGui.QPolygonF([self.mapToScene(0, 0),
self.mapToScene(-30, -50),
self.mapToScene(30, -50)]))
for item in dangerMice:
if item is self:
continue
lineToMouse = QtCore.QLineF(QtCore.QPointF(0, 0), self.mapFromItem(item, 0, 0))
angleToMouse = math.acos(lineToMouse.dx() / lineToMouse.length())
if lineToMouse.dy() < 0:
angleToMouse = Mouse.TwoPi - angleToMouse
angleToMouse = Mouse.normalizeAngle((Mouse.Pi - angleToMouse) + Mouse.Pi / 2)
if angleToMouse >= 0 and angleToMouse < Mouse.Pi / 2:
# Rotate right.
self.angle += 0.5
elif angleToMouse <= Mouse.TwoPi and angleToMouse > (Mouse.TwoPi - Mouse.Pi / 2):
# Rotate left.
self.angle -= 0.5
# Add some random movement.
if len(dangerMice) > 1 and (QtCore.qrand() % 10) == 0:
if QtCore.qrand() % 1:
self.angle += (QtCore.qrand() % 100) / 500.0
else:
self.angle -= (QtCore.qrand() % 100) / 500.0
self.speed += (-50 + QtCore.qrand() % 100) / 100.0
dx = math.sin(self.angle) * 10
self.mouseEyeDirection = [dx / 5, 0.0][QtCore.qAbs(dx / 5) < 1]
self.rotate(dx)
self.setPos(self.mapToParent(0, -(3 + math.sin(self.speed) * 3)))
if __name__ == '__main__':
import sys
MouseCount = 7
app = QtGui.QApplication(sys.argv)
QtCore.qsrand(QtCore.QTime(0,0,0).secsTo(QtCore.QTime.currentTime()))
scene = QtGui.QGraphicsScene()
scene.setSceneRect(-300, -300, 600, 600)
scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
for i in range(MouseCount):
mouse = Mouse()
mouse.setPos(math.sin((i * 6.28) / MouseCount) * 200,
math.cos((i * 6.28) / MouseCount) * 200)
scene.addItem(mouse)
view = QtGui.QGraphicsView(scene)
view.setRenderHint(QtGui.QPainter.Antialiasing)
view.setBackgroundBrush(QtGui.QBrush(QtGui.QPixmap(':/images/cheese.jpg')))
view.setCacheMode(QtGui.QGraphicsView.CacheBackground)
view.setViewportUpdateMode(QtGui.QGraphicsView.BoundingRectViewportUpdate)
view.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)
view.setWindowTitle("Colliding Mice")
view.resize(400, 300)
view.show()
sys.exit(app.exec_())
|
<reponame>xcorail/OTB
/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
#ifndef otbRandomForestsMachineLearningModel_hxx
#define otbRandomForestsMachineLearningModel_hxx
#include <fstream>
#include "itkMacro.h"
#include "otbRandomForestsMachineLearningModel.h"
#include "otbOpenCVUtils.h"
namespace otb
{
template <class TInputValue, class TOutputValue>
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::RandomForestsMachineLearningModel() :
#ifdef OTB_OPENCV_3
m_RFModel(CvRTreesWrapper::create()),
#else
m_RFModel (new CvRTreesWrapper),
#endif
m_MaxDepth(5),
m_MinSampleCount(10),
m_RegressionAccuracy(0.01),
m_ComputeSurrogateSplit(false),
m_MaxNumberOfCategories(10),
m_CalculateVariableImportance(false),
m_MaxNumberOfVariables(0),
m_MaxNumberOfTrees(100),
m_ForestAccuracy(0.01),
m_TerminationCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS), // identic for v3 ?
m_ComputeMargin(false)
{
this->m_ConfidenceIndex = true;
this->m_IsRegressionSupported = true;
}
template <class TInputValue, class TOutputValue>
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::~RandomForestsMachineLearningModel()
{
#ifndef OTB_OPENCV_3
delete m_RFModel;
#endif
}
template <class TInputValue, class TOutputValue>
float
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::GetTrainError()
{
#ifdef OTB_OPENCV_3
// TODO
cv::Mat samples;
otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples);
cv::Mat labels;
otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(),labels);
cv::Mat var_type = cv::Mat(this->GetInputListSample()->GetMeasurementVectorSize() + 1, 1, CV_8U );
var_type.setTo(cv::Scalar(CV_VAR_NUMERICAL) ); // all inputs are numerical
if(this->m_RegressionMode)
var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_NUMERICAL;
else
var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_CATEGORICAL;
return m_RFModel->calcError(
cv::ml::TrainData::create(
samples,
cv::ml::ROW_SAMPLE,
labels,
cv::noArray(),
cv::noArray(),
cv::noArray(),
var_type),
false,
cv::noArray());
#else
return m_RFModel->get_train_error();
#endif
}
/** Train the machine learning model */
template <class TInputValue, class TOutputValue>
void
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::Train()
{
//convert listsample to opencv matrix
cv::Mat samples;
otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples);
cv::Mat labels;
otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(),labels);
cv::Mat var_type = cv::Mat(this->GetInputListSample()->GetMeasurementVectorSize() + 1, 1, CV_8U );
var_type.setTo(cv::Scalar(CV_VAR_NUMERICAL) ); // all inputs are numerical
if(this->m_RegressionMode)
var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_NUMERICAL;
else
var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_CATEGORICAL;
//Mat var_type = Mat(ATTRIBUTES_PER_SAMPLE + 1, 1, CV_8U );
//std::cout << "priors " << m_Priors[0] << std::endl;
//Define random forests paramneters
//FIXME do this in the constructor?
#ifdef OTB_OPENCV_3
m_RFModel->setMaxDepth(m_MaxDepth);
m_RFModel->setMinSampleCount(m_MinSampleCount);
m_RFModel->setRegressionAccuracy(m_RegressionAccuracy);
m_RFModel->setUseSurrogates(m_ComputeSurrogateSplit);
m_RFModel->setMaxCategories(m_MaxNumberOfCategories);
m_RFModel->setPriors(cv::Mat(m_Priors) ); // TODO
m_RFModel->setCalculateVarImportance(m_CalculateVariableImportance);
m_RFModel->setActiveVarCount(m_MaxNumberOfVariables);
m_RFModel->setTermCriteria( cv::TermCriteria(
m_TerminationCriteria,
m_MaxNumberOfTrees,
m_ForestAccuracy) );
m_RFModel->train(cv::ml::TrainData::create(
samples,
cv::ml::ROW_SAMPLE,
labels,
cv::noArray(),
cv::noArray(),
cv::noArray(),
var_type));
#else
float * priors = m_Priors.empty() ? nullptr : &m_Priors.front();
CvRTParams params = CvRTParams(m_MaxDepth, // max depth
m_MinSampleCount, // min sample count
m_RegressionAccuracy, // regression accuracy: N/A here
m_ComputeSurrogateSplit, // compute surrogate split, no missing data
m_MaxNumberOfCategories, // max number of categories (use sub-optimal algorithm for larger numbers)
priors, // the array of priors
m_CalculateVariableImportance, // calculate variable importance
m_MaxNumberOfVariables, // number of variables randomly selected at node and used to find the best split(s).
m_MaxNumberOfTrees, // max number of trees in the forest
m_ForestAccuracy, // forest accuracy
m_TerminationCriteria // termination criteria
);
//train the RT model
m_RFModel->train(samples, CV_ROW_SAMPLE, labels,
cv::Mat(), cv::Mat(), var_type, cv::Mat(), params);
#endif
}
template <class TInputValue, class TOutputValue>
typename RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::TargetSampleType
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::DoPredict(const InputSampleType & value, ConfidenceValueType *quality) const
{
TargetSampleType target;
//convert listsample to Mat
cv::Mat sample;
otb::SampleToMat<InputSampleType>(value,sample);
double result = m_RFModel->predict(sample);
target[0] = static_cast<TOutputValue>(result);
if (quality != nullptr)
{
if(m_ComputeMargin)
(*quality) = m_RFModel->predict_margin(sample);
else
(*quality) = m_RFModel->predict_confidence(sample);
}
return target[0];
}
template <class TInputValue, class TOutputValue>
void
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::Save(const std::string & filename, const std::string & name)
{
#ifdef OTB_OPENCV_3
cv::FileStorage fs(filename, cv::FileStorage::WRITE);
fs << (name.empty() ? m_RFModel->getDefaultName() : cv::String(name)) << "{";
m_RFModel->write(fs);
fs << "}";
fs.release();
#else
if (name == "")
m_RFModel->save(filename.c_str(), nullptr);
else
m_RFModel->save(filename.c_str(), name.c_str());
#endif
}
template <class TInputValue, class TOutputValue>
void
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::Load(const std::string & filename, const std::string & name)
{
#ifdef OTB_OPENCV_3
cv::FileStorage fs(filename, cv::FileStorage::READ);
m_RFModel->read(name.empty() ? fs.getFirstTopLevelNode() : fs[name]);
#else
if (name == "")
m_RFModel->load(filename.c_str(), nullptr);
else
m_RFModel->load(filename.c_str(), name.c_str());
#endif
}
template <class TInputValue, class TOutputValue>
bool
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::CanReadFile(const std::string & file)
{
std::ifstream ifs;
ifs.open(file);
if(!ifs)
{
std::cerr<<"Could not read file "<<file<<std::endl;
return false;
}
while (!ifs.eof())
{
std::string line;
std::getline(ifs, line);
//if (line.find(m_RFModel->getName()) != std::string::npos)
if (line.find(CV_TYPE_NAME_ML_RTREES) != std::string::npos
#ifdef OTB_OPENCV_3
|| line.find(m_RFModel->getDefaultName()) != std::string::npos
#endif
)
{
//std::cout<<"Reading a "<<CV_TYPE_NAME_ML_RTREES<<" model"<<std::endl;
return true;
}
}
ifs.close();
return false;
}
template <class TInputValue, class TOutputValue>
bool
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::CanWriteFile(const std::string & itkNotUsed(file))
{
return false;
}
template <class TInputValue, class TOutputValue>
typename RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::VariableImportanceMatrixType
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::GetVariableImportance()
{
cv::Mat cvMat = m_RFModel->getVarImportance();
VariableImportanceMatrixType itkMat(cvMat.rows,cvMat.cols);
for(int i =0; i<cvMat.rows; i++)
{
for(int j =0; j<cvMat.cols; j++)
{
itkMat(i,j)=cvMat.at<float>(i,j);
}
}
return itkMat;
}
template <class TInputValue, class TOutputValue>
void
RandomForestsMachineLearningModel<TInputValue,TOutputValue>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
// Call superclass implementation
Superclass::PrintSelf(os,indent);
}
} //end namespace otb
#endif
|
<filename>Algorithm/src/main/java/com/leetcode/Solution_395.java
package com.leetcode;
import java.util.Arrays;
public class Solution_395 {
public int longestSubstring(String s, int k) {
int ans = 0;
int[] slidFre = new int[26];
for (int i = 1; i <= 26; i++) {
int l = 0, r = 0, slidCharType = 0, slidLargerKCount = 0;
while (r < s.length()) {
int index = s.charAt(r) - 'a';
if (slidFre[index] == 0) slidCharType++;
slidFre[index]++;
if (slidFre[index] == k) slidLargerKCount++;
if (slidCharType == i && slidLargerKCount == slidCharType) ans = Math.max(ans, r - l + 1);
while (slidCharType > i) {
int lIndex = s.charAt(l) - 'a';
slidFre[lIndex]--;
if (slidFre[lIndex] == 0) slidCharType--;
if (slidFre[lIndex] == k - 1) slidLargerKCount--;
l++;
}
r++;
}
Arrays.fill(slidFre, 0);
}
return ans;
}
}
|
<gh_stars>0
import React, { Component } from 'react';
import { Redirect } from 'react-router'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { newUser } from '../../actions';
import AdminBar from '../../components/admin/parts/AdminBar';
//import PropTypes from 'prop-types';
class NewUser extends Component {
constructor(props) {
super(props);
this.state = {
user: { name: '' }, redirectnew: false
};
}
generateFormUser() {
return (
<div className="box-body table-responsive no-padding">
<div className="new-product row">
<div className="col-sm-3">
</div>
<div className="col-sm-6">
<div className="row">
<h2 className="col-sm-12 display-5">Create User</h2>
<p className="col-sm-12 lead">Add new user!!!.</p>
</div>
<form className="row">
<p className="col-sm-12">
<input
className="col-sm-12"
type="text"
placeholder="name"
name= "name"
value={this.state.user.name}
onChange={this.onChangeInput}
/>
</p>
<p className="col-sm-12">
<button type="submit" className="btn btn-primary col-sm-12" onClick={this.handleSubmit}>Salvar</button>
</p>
</form>
</div>
<div className="col-sm-3">
</div>
</div>
</div>
)
}
onChangeInput = (event) => {
this.setState(
{
...this.state,
user: { [event.target.name] : event.target.value}
}
);
}
handleSubmit = (event) => {
event.preventDefault();
let user = this.state.user;
this.saveUser(user);
}
componentWillReceiveProps(nextProps) {
if (nextProps.redirectnew) {
//this.state.redirectnew = nextProps.redirectnew;
this.setState(...this.state, {redirectnew : nextProps.redirectnew});
}
}
componentDidMount() {
//this.state.redirectnew = false;
//this.setState(this.state);
this.setState(...this.state, {redirectnew : false});
}
saveUser(user) {
this.props.newUser(user)
}
render() {
return (
<div>
<div className="top-bar">
<AdminBar />
</div>
{this.state.redirectnew ? <Redirect to="/users" /> : <div className="contenido"> {this.generateFormUser()} </div>}
</div>
);
}
}
function mapStateToProps(state, props) {
return {
user: state.user.user,
redirectnew: state.user.redirectnew
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ newUser }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(NewUser);
|
function fibonacci(n){
if(n<3){
return 1;
}
return fibonacci(n-1) + fibonacci(n-2);
}
console.log(fibonacci(4)); // 3 |
package org.jooby.rocker;
import static org.easymock.EasyMock.expect;
import org.jooby.Env;
import org.jooby.Renderer;
import org.jooby.test.MockUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.google.inject.Binder;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.multibindings.Multibinder;
import com.typesafe.config.Config;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Rockerby.class, RockerRenderer.class, Multibinder.class })
public class RockerbyTest {
@SuppressWarnings({"rawtypes", "unchecked" })
@Test
public void newInstance() throws Exception {
new MockUnit(Env.class, Config.class, Binder.class)
.expect(unit -> {
RockerRenderer renderer = unit.constructor(RockerRenderer.class)
.build("", ".rocker.html");
Binder binder = unit.get(Binder.class);
unit.mockStatic(Multibinder.class);
Multibinder mb = unit.mock(Multibinder.class);
LinkedBindingBuilder lbb = unit.mock(LinkedBindingBuilder.class);
lbb.toInstance(renderer);
expect(mb.addBinding()).andReturn(lbb);
expect(Multibinder.newSetBinder(binder, Renderer.class)).andReturn(mb);
})
.run(unit -> {
new Rockerby().configure(unit.get(Env.class), unit.get(Config.class),
unit.get(Binder.class));
});
}
}
|
z="
";lz='clea';qz=' "${';Nz='32;1';DBz='t ${';Dz='1m" ';Pz='een';mz='r';Wz='•>bl';Ez='#•>B';sz=' ╔══';SBz='{b} ';kz='ite';hz='w="\';Rz='33;1';jz='•>wh';Lz='d';Oz='•>gr';xz='ilah';tz='════';ZBz='t Py';Jz='m" #';az='•>cy';KBz=' ║ ';cz='pu="';cBz='_*"';Bz='\033';NBz='Pali';Uz='b="\';fz='urpl';IBz=' ${r';RBz='er $';uz='═╗"';ABz='simp';vz=' ║ $';Zz='35;1';EBz='g}PY';Vz='34;1';WBz='═╝"';Az='bl="';yz='kan ';QBz='Fold';YBz=' En';Hz='033[';FBz='THON';Gz='r="\';oz='(){';OBz='ng L';VBz=' ╚══';Iz='31;1';HBz='}nya';Tz='llow';JBz='}║ "';rz='r} ';UBz='b} ';CBz='crip';Sz='•>ye';dBz='}';pz='echo';nz='kata';XBz='w} ';gz='e';ez='#•>p';TBz=' ║ "';BBz='an s';bz='an';wz='{w}S';aBz='thon';Kz='•>Re';GBz=' ${w';iz='39;1';dz='[36;';MBz='}di ';Cz='[30;';PBz='uar ';Mz='g="\';Xz='ue';Fz='lack';LBz=' ';bBz=' 2 *';Yz='c="\';Qz='y="\';
eval "$Az$Bz$Cz$Dz$Ez$Fz$z$Gz$Hz$Iz$Jz$Kz$Lz$z$Mz$Hz$Nz$Jz$Oz$Pz$z$Qz$Hz$Rz$Jz$Sz$Tz$z$Uz$Hz$Vz$Jz$Wz$Xz$z$Yz$Hz$Zz$Jz$az$bz$z$cz$Bz$dz$Dz$ez$fz$gz$z$hz$Hz$iz$Jz$jz$kz$z$lz$mz$z$nz$oz$z$pz$qz$rz$sz$tz$tz$tz$tz$tz$tz$tz$tz$uz$z$pz$qz$rz$vz$wz$xz$yz$ABz$BBz$CBz$DBz$EBz$FBz$GBz$HBz$IBz$JBz$z$pz$qz$rz$KBz$LBz$GBz$MBz$NBz$OBz$PBz$QBz$RBz$SBz$LBz$TBz$z$pz$qz$UBz$VBz$tz$tz$tz$tz$tz$tz$tz$tz$WBz$z$pz$qz$XBz$LBz$LBz$YBz$CBz$ZBz$aBz$bBz$cBz$z$pz$z$pz$z$dBz$z$lz$mz$z$nz"
|
<filename>src/main/java/org/olat/modules/appointments/ui/TopicsRunController.java
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.modules.appointments.ui;
import static java.util.Collections.emptyList;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.date.DateComponentFactory;
import org.olat.core.gui.components.date.DateElement;
import org.olat.core.gui.components.form.flexible.FormItem;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.FormLink;
import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.stack.BreadcrumbedStackedPanel;
import org.olat.core.gui.components.util.SelectionValues;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.generic.closablewrapper.CloseableModalController;
import org.olat.core.gui.control.generic.dtabs.Activateable2;
import org.olat.core.gui.control.winmgr.CommandFactory;
import org.olat.core.helpers.Settings;
import org.olat.core.id.OLATResourceable;
import org.olat.core.id.context.ContextEntry;
import org.olat.core.id.context.StateEntry;
import org.olat.core.util.CodeHelper;
import org.olat.core.util.DateUtils;
import org.olat.core.util.StringHelper;
import org.olat.core.util.Util;
import org.olat.core.util.coordinate.CoordinatorManager;
import org.olat.core.util.resource.OresHelper;
import org.olat.modules.appointments.Appointment;
import org.olat.modules.appointments.Appointment.Status;
import org.olat.modules.appointments.AppointmentSearchParams;
import org.olat.modules.appointments.AppointmentsSecurityCallback;
import org.olat.modules.appointments.AppointmentsService;
import org.olat.modules.appointments.Organizer;
import org.olat.modules.appointments.Participation;
import org.olat.modules.appointments.ParticipationSearchParams;
import org.olat.modules.appointments.Topic;
import org.olat.modules.appointments.TopicLight.Type;
import org.olat.modules.appointments.TopicRef;
import org.olat.modules.bigbluebutton.BigBlueButtonMeeting;
import org.olat.modules.bigbluebutton.BigBlueButtonModule;
import org.olat.modules.bigbluebutton.BigBlueButtonRecordingReference;
import org.olat.modules.bigbluebutton.manager.AvatarMapper;
import org.olat.modules.bigbluebutton.model.BigBlueButtonErrors;
import org.olat.modules.bigbluebutton.ui.BigBlueButtonUIHelper;
import org.olat.modules.bigbluebutton.ui.EditBigBlueButtonMeetingController;
import org.olat.modules.teams.TeamsMeeting;
import org.olat.modules.teams.model.TeamsErrors;
import org.olat.modules.teams.ui.TeamsMeetingEvent;
import org.olat.modules.teams.ui.TeamsUIHelper;
import org.olat.repository.RepositoryEntry;
import org.olat.user.DisplayPortraitManager;
import org.olat.user.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Initial date: 20 Apr 2020<br>
* @author uhensler, <EMAIL>, http://www.frentix.com
*
*/
public class TopicsRunController extends FormBasicController implements Activateable2 {
private static final long PARTICIPANTS_RENDER_LIMIT = 3;
private static final String CMD_MORE = "more";
private static final String CMD_OPEN = "open";
private static final String CMD_JOIN = "join";
private static final String CMD_EMAIL = "email";
private static final String CMD_RECORDING = "recording";
private final BreadcrumbedStackedPanel stackPanel;
private CloseableModalController cmc;
private AppointmentListSelectionController topicRunCtrl;
private OrganizerMailController mailCtrl;
private String avatarUrl;
private final RepositoryEntry entry;
private final String subIdent;
private final AppointmentsSecurityCallback secCallback;
private List<TopicWrapper> topics;
private Set<Topic> acknowlededRecordings = new HashSet<>();
private int counter;
private final Set<Long> showAllParticipationsTopicKeys = new HashSet<>();
@Autowired
private AppointmentsService appointmentsService;
@Autowired
private UserManager userManager;
@Autowired
private BigBlueButtonModule bigBlueButtonModule;
@Autowired
private DisplayPortraitManager displayPortraitManager;
public TopicsRunController(UserRequest ureq, WindowControl wControl, BreadcrumbedStackedPanel stackPanel,
RepositoryEntry entry, String subIdent, AppointmentsSecurityCallback secCallback) {
super(ureq, wControl, "topics_run");
setTranslator(Util.createPackageTranslator(EditBigBlueButtonMeetingController.class, getLocale(), getTranslator()));
this.stackPanel = stackPanel;
this.entry = entry;
this.subIdent = subIdent;
this.secCallback = secCallback;
initForm(ureq);
}
@Override
public void activate(UserRequest ureq, List<ContextEntry> entries, StateEntry state) {
if (topics.size() == 1
&& (topics.get(0).getSelectedAppointments() == null
|| topics.get(0).getSelectedAppointments().intValue() == 0)) {
doOpenTopic(ureq, topics.get(0).getTopic());
}
}
@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
topics = loadTopicWrappers();
flc.contextPut("topics", topics);
}
private List<TopicWrapper> loadTopicWrappers() {
List<Topic> topics = appointmentsService.getRestictedTopic(entry, subIdent, getIdentity());
ParticipationSearchParams myParticipationsParams = new ParticipationSearchParams();
myParticipationsParams.setEntry(entry);
myParticipationsParams.setSubIdent(subIdent);
myParticipationsParams.setIdentity(getIdentity());
myParticipationsParams.setFetchAppointments(true);
myParticipationsParams.setFetchTopics(true);
List<Participation> participations = appointmentsService.getParticipations(myParticipationsParams);
Map<Long, List<Participation>> topicKeyToMyEnrollmentParticipation = participations.stream()
.collect(Collectors.groupingBy(p -> p.getAppointment().getTopic().getKey()));
// Add topics with participations even if participant has no access anymore.
participations.stream()
.map(p -> p.getAppointment().getTopic())
.distinct()
.filter(topic -> !topics.contains(topic))
.forEach(topic -> topics.add(topic));
List<Topic> topicsFinding = topics.stream()
.filter(topic -> Type.finding == topic.getType())
.collect(Collectors.toList());
AppointmentSearchParams confirmedFindingsParams = new AppointmentSearchParams();
confirmedFindingsParams.setTopics(topicsFinding);
confirmedFindingsParams.setStatus(Status.confirmed);
Set<Long> findingConfirmedKeys = appointmentsService
.getAppointments(confirmedFindingsParams).stream()
.map(a -> a.getTopic().getKey())
.collect(Collectors.toSet());
AppointmentSearchParams freeAppointmentsParams = new AppointmentSearchParams();
freeAppointmentsParams.setTopics(topics);
Map<Long, Long> topicKeyToAppointmentCount = appointmentsService.getTopicKeyToAppointmentCount(freeAppointmentsParams, true);
Map<Long, List<Organizer>> topicKeyToOrganizer = appointmentsService
.getOrganizers(entry, subIdent).stream()
.collect(Collectors.groupingBy(o -> o.getTopic().getKey()));
topics.sort((t1, t2) -> t1.getTitle().toLowerCase().compareTo(t2.getTitle().toLowerCase()));
List<TopicWrapper> wrappers = new ArrayList<>(topics.size());
for (Topic topic : topics) {
TopicWrapper wrapper = new TopicWrapper(topic);
List<Organizer> organizers = topicKeyToOrganizer.getOrDefault(topic.getKey(), emptyList());
wrapOrganizers(wrapper, organizers);
wrapAppointment(wrapper, topicKeyToAppointmentCount, findingConfirmedKeys, topicKeyToMyEnrollmentParticipation);
wrappers.add(wrapper);
}
return wrappers;
}
private void wrapOrganizers(TopicWrapper wrapper, List<Organizer> organizers) {
wrapper.setOrganizerNames(AppointmentsUIFactory.formatOrganizers(organizers));
wrapper.setOrganizers(organizers);
if (!organizers.isEmpty()) {
FormLink link = uifactory.addFormLink("email" + counter++, CMD_EMAIL, "", null, flc, Link.NONTRANSLATED);
link.setIconLeftCSS("o_icon o_icon_mail");
link.setElementCssClass("o_mail");
link.setUserObject(wrapper);
wrapper.setEmailLinkName(link.getName());
}
}
private void wrapAppointment(TopicWrapper wrapper, Map<Long, Long> topicKeyToAppointmentCount,
Set<Long> findingConfirmedKeys,
Map<Long, List<Participation>> topicKeyToMyEnrollmentParticipation) {
Topic topic = wrapper.getTopic();
Long freeAppointments = topicKeyToAppointmentCount.getOrDefault(topic.getKey(), Long.valueOf(0));
wrapper.setFreeAppointments(freeAppointments);
List<Participation> myTopicParticipations = topicKeyToMyEnrollmentParticipation.getOrDefault(topic.getKey(), emptyList());
wrapper.setSelectedAppointments(Integer.valueOf(myTopicParticipations.size()));
if (Type.finding == topic.getType()) {
wrapFindindAppointment(wrapper, myTopicParticipations);
} else {
wrapEnrollmentAppointment(wrapper, myTopicParticipations);
}
if (topic.isMultiParticipation()) {
wrapOpenLink(wrapper, topic, "appointments.select");
} else {
wrapOpenLink(wrapper, topic, "appointment.select");
}
wrapMessage(wrapper, findingConfirmedKeys);
}
private void wrapFindindAppointment(TopicWrapper wrapper, List<Participation> myTopicParticipations) {
Optional<Appointment> firstAppointment = myTopicParticipations.stream()
.map(Participation::getAppointment)
.filter(a -> a.getStatus() == Status.confirmed)
.findFirst();
if (firstAppointment.isPresent()) {
Appointment appointment = firstAppointment.get();
ParticipationSearchParams allParticipationParams = new ParticipationSearchParams();
allParticipationParams.setAppointment(appointment);
List<Participation> appointmentParticipations = appointmentsService.getParticipations(allParticipationParams);
wrapAppointmentView(wrapper, appointment, appointmentParticipations);
}
}
private void wrapEnrollmentAppointment(TopicWrapper wrapper, List<Participation> myTopicParticipations) {
if (!myTopicParticipations.isEmpty()) {
Date now = new Date();
Optional<Appointment> nextAppointment = myTopicParticipations.stream()
.map(Participation::getAppointment)
.filter(a -> appointmentsService.isEndAfter(a, now))
.sorted((a1, a2) -> a1.getStart().compareTo(a2.getStart()))
.findFirst();
Appointment appointment = nextAppointment.isPresent()
? nextAppointment.get() // Next appointment ...
: myTopicParticipations.stream()
.map(Participation::getAppointment)
.sorted((a1, a2) -> a2.getStart().compareTo(a1.getStart()))
.findFirst().get(); // ... or the most recent one.
wrapper.setFuture(Boolean.valueOf(appointment.getStart().after(now)));
ParticipationSearchParams allParticipationParams = new ParticipationSearchParams();
allParticipationParams.setAppointment(appointment);
List<Participation> appointmentParticipations = appointmentsService.getParticipations(allParticipationParams);
wrapAppointmentView(wrapper, appointment, appointmentParticipations);
if (wrapper.getTopic().isParticipationVisible()) {
wrapParticipants(wrapper, appointmentParticipations);
}
}
}
private void wrapAppointmentView(TopicWrapper wrapper, Appointment appointment, List<Participation> appointmentParticipations) {
wrapper.setAppointment(appointment);
Locale locale = getLocale();
Date begin = appointment.getStart();
Date end = appointment.getEnd();
String date = null;
String date2 = null;
String time = null;
boolean sameDay = DateUtils.isSameDay(begin, end);
boolean sameTime = DateUtils.isSameTime(begin, end);
String startDate = StringHelper.formatLocaleDateFull(begin.getTime(), locale);
String startTime = StringHelper.formatLocaleTime(begin.getTime(), locale);
String endDate = StringHelper.formatLocaleDateFull(end.getTime(), locale);
String endTime = StringHelper.formatLocaleTime(end.getTime(), locale);
if (sameDay) {
StringBuilder timeSb = new StringBuilder();
if (sameTime) {
timeSb.append(translate("full.day"));
} else {
timeSb.append(startTime);
timeSb.append(" - ");
timeSb.append(endTime);
}
time = timeSb.toString();
} else {
StringBuilder dateSbShort1 = new StringBuilder();
dateSbShort1.append(startDate);
dateSbShort1.append(" ");
dateSbShort1.append(startTime);
dateSbShort1.append(" -");
date = dateSbShort1.toString();
StringBuilder dateSb2 = new StringBuilder();
dateSb2.append(endDate);
dateSb2.append(" ");
dateSb2.append(endTime);
date2 = dateSb2.toString();
}
wrapper.setDate(date);
wrapper.setDate2(date2);
wrapper.setTime(time);
wrapper.setLocation(AppointmentsUIFactory.getDisplayLocation(getTranslator(), appointment));
wrapper.setDetails(appointment.getDetails());
String dayName = "day_" + counter++;
DateElement dateEl = DateComponentFactory.createDateElementWithYear(dayName, appointment.getStart());
flc.add(dayName, dateEl);
wrapper.setDayName(dayName);
wrapper.setStatus(appointment.getStatus());
wrapper.setTranslatedStatus(translate("appointment.status." + appointment.getStatus().name()));
wrapper.setStatusCSS("o_ap_status_" + appointment.getStatus().name());
if (appointmentsService.isBigBlueButtonEnabled()) {
if (secCallback.canJoinBBBMeeting(appointment, wrapper.getOrganizers(), appointmentParticipations)) {
wrapBBBMeeting(wrapper, appointment);
}
if (secCallback.canWatchRecording(wrapper.getOrganizers(), appointmentParticipations)) {
List<BigBlueButtonRecordingReference> recordingReferences = appointmentsService
.getBBBRecordingReferences(Collections.singletonList(appointment))
.getOrDefault(appointment.getKey(), Collections.emptyList());
wrapRecordings(wrapper, recordingReferences);
}
}
if (appointmentsService.isTeamsEnabled()
&& secCallback.canJoinTeamsMeeting(appointment, wrapper.getOrganizers(), appointmentParticipations)) {
wrapTeamsMeeting(wrapper);
}
}
private void wrapBBBMeeting(TopicWrapper wrapper, Appointment appointment) {
BigBlueButtonMeeting meeting = appointment.getBBBMeeting();
boolean serverDisabled = isServerDisabled(meeting);
if (serverDisabled) {
wrapper.setServerWarning(translate("error.serverDisabled"));
}
boolean meetingOpen = secCallback.isBBBMeetingOpen(appointment, wrapper.getOrganizers());
if (!serverDisabled && !meetingOpen) {
wrapper.setMeetingWarning(translate("error.meeting.not.open"));
}
FormLink joinButton = uifactory.addFormLink("join" + counter++, CMD_JOIN, "meeting.join.button", null, flc, Link.BUTTON_LARGE);
joinButton.setNewWindow(true, true, true);
joinButton.setTextReasonForDisabling(translate("warning.no.access"));
joinButton.setEnabled(!serverDisabled && meetingOpen);
joinButton.setPrimary(joinButton.isEnabled());
joinButton.setUserObject(wrapper);
wrapper.setJoinLinkName(joinButton.getName());
if (BigBlueButtonUIHelper.isRecord(meeting)) {
SelectionValues acknowledgeKeyValue = new SelectionValues();
acknowledgeKeyValue.add(SelectionValues.entry("agree", translate("meeting.acknowledge.recording.agree")));
MultipleSelectionElement acknowledgeRecordingEl = uifactory.addCheckboxesHorizontal("ack_" + counter++, null, flc,
acknowledgeKeyValue.keys(), acknowledgeKeyValue.values());
if (acknowlededRecordings.contains(wrapper.getTopic())) {
acknowledgeRecordingEl.select(acknowledgeRecordingEl.getKey(0), true);
}
acknowledgeRecordingEl.addActionListener(FormEvent.ONCHANGE);
acknowledgeRecordingEl.setUserObject(wrapper);
wrapper.setAcknowledgeRecordingEl(acknowledgeRecordingEl);
}
}
private void wrapRecordings(TopicWrapper wrapper, List<BigBlueButtonRecordingReference> recordingReferences) {
recordingReferences.sort((r1, r2) -> r1.getStartDate().compareTo(r2.getStartDate()));
List<String> recordingLinkNames = new ArrayList<>(recordingReferences.size());
for (int i = 0; i < recordingReferences.size(); i++) {
BigBlueButtonRecordingReference recording = recordingReferences.get(i);
FormLink link = uifactory.addFormLink("rec_" + counter++, CMD_RECORDING, null, null, flc, Link.NONTRANSLATED);
String name = translate("recording");
if (recordingReferences.size() > 1) {
name = name + " " + (i+1);
}
name = name + " ";
link.setLinkTitle(name);
link.setIconLeftCSS("o_icon o_icon_lg o_vc_icon");
link.setNewWindow(true, true, true);
link.setUserObject(recording);
recordingLinkNames.add(link.getName());
}
wrapper.setRecordingLinkNames(recordingLinkNames);
}
private void wrapTeamsMeeting(TopicWrapper wrapper) {
boolean meetingOpen = secCallback.isTeamsMeetingOpen(wrapper.getAppointment(), wrapper.getOrganizers());
if (!meetingOpen) {
wrapper.setMeetingWarning(translate("error.meeting.not.open"));
}
FormLink joinButton = uifactory.addFormLink("join" + counter++, CMD_JOIN, "meeting.join.button", null, flc, Link.BUTTON_LARGE);
joinButton.setNewWindow(true, true, true);
joinButton.setTextReasonForDisabling(translate("warning.no.access"));
joinButton.setEnabled(meetingOpen);
joinButton.setPrimary(joinButton.isEnabled());
joinButton.setUserObject(wrapper);
wrapper.setJoinLinkName(joinButton.getName());
}
private boolean isServerDisabled(BigBlueButtonMeeting meeting) {
return meeting != null && meeting.getServer() != null && !meeting.getServer().isEnabled();
}
private void wrapParticipants(TopicWrapper wrapper, List<Participation> participations) {
long limit = showAllParticipationsTopicKeys.contains(wrapper.getTopic().getKey())? Long.MAX_VALUE: PARTICIPANTS_RENDER_LIMIT;
List<String> participants = participations.stream()
.map(p -> userManager.getUserDisplayName(p.getIdentity().getKey()))
.sorted(String.CASE_INSENSITIVE_ORDER)
.limit(limit)
.collect(Collectors.toList());
wrapper.setParticipants(participants);
if (participations.size() > PARTICIPANTS_RENDER_LIMIT) {
String name = "more_" + wrapper.getTopic().getKey();
FormLink showMoreLink = uifactory.addFormLink(name, CMD_MORE, "", null, flc, Link.LINK + Link.NONTRANSLATED);
long hiddenParticipations = participations.size() - PARTICIPANTS_RENDER_LIMIT;
String displayText = showAllParticipationsTopicKeys.contains(wrapper.getTopic().getKey())
? translate("show.less")
: translate("show.more", new String[] { String.valueOf(hiddenParticipations)} );
showMoreLink.setI18nKey(displayText);
showMoreLink.setUserObject(wrapper.getTopic());
wrapper.setShowMoreLinkName(showMoreLink.getName());
}
}
private void wrapOpenLink(TopicWrapper wrapper, TopicRef topic, String i18n) {
FormLink link = uifactory.addFormLink("open" + counter++, CMD_OPEN, i18n, null, flc, Link.LINK);
link.setIconRightCSS("o_icon o_icon_start");
link.setUserObject(topic);
wrapper.setOpenLinkName(link.getName());
}
private void wrapMessage(TopicWrapper wrapper, Set<Long> findingConfirmedKeys) {
Topic topic = wrapper.getTopic();
int selectedAppointments = wrapper.getSelectedAppointments() != null
? wrapper.getSelectedAppointments().intValue()
: 0;
Long freeAppointments = wrapper.getFreeAppointments();
Status status = wrapper.getStatus();
List<String> messages = new ArrayList<>(2);
if (selectedAppointments == 0) {
if (Type.finding != topic.getType()) {
if (freeAppointments != null) {
if (freeAppointments.longValue() == 1) {
messages.add(translate("appointments.free.one"));
} else if (freeAppointments.longValue() > 1) {
messages.add(translate("appointments.free", new String[] { freeAppointments.toString() }));
}
}
}
if (Type.finding == topic.getType() && findingConfirmedKeys.contains(topic.getKey())) {
messages.add(translate("appointments.finding.confirmed"));
} else if (freeAppointments != null && freeAppointments.longValue() == 0) {
messages.add(translate("appointments.free.no"));
} else if (topic.isMultiParticipation()) {
messages.add(translate("appointments.select.multi.message"));
} else {
messages.add(translate("appointments.select.one.message"));
}
}
if (selectedAppointments > 0) {
if (Type.finding == topic.getType()) {
if (status == null) {
messages.add(translate("appointments.selected.not.confirmed"));
}
} else {
if (topic.isMultiParticipation()) {
if (selectedAppointments > 1) {
messages.add(translate("appointments.selected", new String[] { String.valueOf(selectedAppointments) }));
}
}
}
}
String message = messages.isEmpty()? null: messages.stream().collect(Collectors.joining("<br>"));
wrapper.setMessage(message);
}
@Override
protected void event(UserRequest ureq, Controller source, Event event) {
if (source == topicRunCtrl) {
if (event == Event.DONE_EVENT) {
initForm(ureq);
}
stackPanel.popUpToRootController(ureq);
cleanUp();
} else if (source == mailCtrl) {
cmc.deactivate();
cleanUp();
} else if (source == cmc) {
cleanUp();
}
super.event(ureq, source, event);
}
private void cleanUp() {
removeAsListenerAndDispose(topicRunCtrl);
removeAsListenerAndDispose(mailCtrl);
removeAsListenerAndDispose(cmc);
topicRunCtrl = null;
mailCtrl = null;
cmc = null;
}
@Override
protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
if (source instanceof FormLink) {
FormLink link = (FormLink)source;
String cmd = link.getCmd();
if (CMD_MORE.equals(cmd)) {
Topic topic = (Topic)link.getUserObject();
doToggleShowMoreParticipations(ureq, topic);
} else if (CMD_OPEN.equals(cmd)) {
Topic topic = (Topic)link.getUserObject();
doOpenTopic(ureq, topic);
} else if (CMD_EMAIL.equals(cmd)) {
TopicWrapper wrapper = (TopicWrapper)link.getUserObject();
doOrganizerEmail(ureq, wrapper.getTopic(), wrapper.getOrganizers());
} else if (CMD_JOIN.equals(cmd)) {
TopicWrapper wrapper = (TopicWrapper)link.getUserObject();
doJoin(wrapper);
} else if (CMD_RECORDING.equals(cmd)) {
BigBlueButtonRecordingReference recordingReference = (BigBlueButtonRecordingReference)link.getUserObject();
doOpenRecording(ureq, recordingReference);
}
} else if (source instanceof MultipleSelectionElement) {
MultipleSelectionElement mse = (MultipleSelectionElement)source;
Topic topic = ((TopicWrapper)mse.getUserObject()).getTopic();
if (mse.isAtLeastSelected(1)) {
acknowlededRecordings.add(topic);
} else {
acknowlededRecordings.remove(topic);
}
}
super.formInnerEvent(ureq, source, event);
}
@Override
public void event(UserRequest ureq, Component source, Event event) {
super.event(ureq, source, event);
}
private void doToggleShowMoreParticipations(UserRequest ureq, Topic topic) {
if (showAllParticipationsTopicKeys.contains(topic.getKey())) {
showAllParticipationsTopicKeys.remove(topic.getKey());
} else {
showAllParticipationsTopicKeys.add(topic.getKey());
}
initForm(ureq);
}
private void doOpenTopic(UserRequest ureq, Topic topic) {
removeAsListenerAndDispose(topicRunCtrl);
topicRunCtrl = new AppointmentListSelectionController(ureq, getWindowControl(), topic, secCallback);
listenTo(topicRunCtrl);
String title = topic.getTitle();
String panelTitle = title.length() > 50? title.substring(0, 50) + "...": title;
stackPanel.pushController(panelTitle, topicRunCtrl);
}
private void doOrganizerEmail(UserRequest ureq, Topic topic, Collection<Organizer> organizers) {
mailCtrl = new OrganizerMailController(ureq, getWindowControl(), topic, organizers);
listenTo(mailCtrl);
cmc = new CloseableModalController(getWindowControl(), translate("close"), mailCtrl.getInitialComponent(), true,
translate("email.title"));
listenTo(cmc);
cmc.activate();
}
private void doJoin(TopicWrapper wrapper) {
AppointmentSearchParams params = new AppointmentSearchParams();
params.setAppointment(wrapper.getAppointment());
params.setFetchTopic(true);
params.setFetchMeetings(true);
List<Appointment> appointments = appointmentsService.getAppointments(params);
Appointment appointment = null;
if (!appointments.isEmpty()) {
appointment = appointments.get(0);
}
if (appointment == null || (appointment.getBBBMeeting() == null && appointment.getTeamsMeeting() == null)) {
showWarning("warning.no.meeting");
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
return;
}
if (appointment.getBBBMeeting() != null) {
doJoinBBBMeeting(wrapper, appointment);
} else if (appointment.getTeamsMeeting() != null) {
doJoinTeamsMeeting(appointment);
}
}
private void doJoinBBBMeeting(TopicWrapper wrapper, Appointment appointment) {
if (BigBlueButtonUIHelper.isRecord(appointment.getBBBMeeting()) && !acknowlededRecordings.contains(appointment.getTopic())) {
wrapper.getAcknowledgeRecordingEl().setErrorKey("form.legende.mandatory", null);
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
return;
} else if (wrapper.getAcknowledgeRecordingEl() != null) {
wrapper.getAcknowledgeRecordingEl().clearError();
}
if(avatarUrl == null && bigBlueButtonModule.isAvatarEnabled()) {
File portraitFile = displayPortraitManager.getBigPortrait(getIdentity());
if(portraitFile != null) {
String rnd = "r" + getIdentity().getKey() + CodeHelper.getRAMUniqueID();
avatarUrl = Settings.createServerURI()
+ registerCacheableMapper(null, rnd, new AvatarMapper(portraitFile), 5 * 60 * 60)
+ "/" + portraitFile.getName();
}
}
BigBlueButtonErrors errors = new BigBlueButtonErrors();
String meetingUrl = appointmentsService.joinBBBMeeting(appointment, getIdentity(), avatarUrl, errors);
redirectTo(meetingUrl, errors);
}
private void redirectTo(String meetingUrl, BigBlueButtonErrors errors) {
if(errors.hasErrors()) {
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
} else if(StringHelper.containsNonWhitespace(meetingUrl)) {
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowRedirectTo(meetingUrl));
} else {
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
showWarning("warning.no.access");
}
}
private void doOpenRecording(UserRequest ureq, BigBlueButtonRecordingReference recordingReference) {
String url = appointmentsService.getBBBRecordingUrl(ureq.getUserSession(), recordingReference);
if(StringHelper.containsNonWhitespace(url)) {
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowRedirectTo(url));
} else {
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
showWarning("warning.recording.not.found");
}
}
private void doJoinTeamsMeeting(Appointment appointment) {
TeamsErrors errors = new TeamsErrors();
TeamsMeeting meeting = appointmentsService.joinTeamsMeeting(appointment, getIdentity(), errors);
if(meeting == null) {
showWarning("warning.no.meeting");
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
return;
} else if(errors.hasErrors()) {
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
getWindowControl().setError(TeamsUIHelper.formatErrors(getTranslator(), errors));
return;
}
String joinUrl = meeting.getOnlineMeetingJoinUrl();
if(StringHelper.containsNonWhitespace(joinUrl)) {
TeamsMeetingEvent event = new TeamsMeetingEvent(meeting.getKey(), getIdentity().getKey());
OLATResourceable meetingOres = OresHelper.createOLATResourceableInstance(TeamsMeeting.class.getSimpleName(), meeting.getKey());
CoordinatorManager.getInstance().getCoordinator().getEventBus().fireEventToListenersOf(event, meetingOres);
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowRedirectTo(joinUrl));
} else {
getWindowControl().getWindowBackOffice().sendCommandTo(CommandFactory.createNewWindowCancelRedirectTo());
showWarning("warning.no.access");
}
}
@Override
protected void formOK(UserRequest ureq) {
//
}
public static final class TopicWrapper {
private final Topic topic;
private Collection<Organizer> organizers;
private String organizerNames;
private String emailLinkName;
private Appointment appointment;
private List<String> participants;
private String showMoreLinkName;
private Boolean future;
private String dayName;
private String date;
private String date2;
private String time;
private String location;
private String details;
private Appointment.Status status;
private String translatedStatus;
private String statusCSS;
private String message;
private Long freeAppointments;
private Integer selectedAppointments;
private MultipleSelectionElement acknowledgeRecordingEl;
private String openLinkName;
private String joinLinkName;
private String serverWarning;
private String meetingWarning;
private List<String> recordingLinkNames;
public TopicWrapper(Topic topic) {
this.topic = topic;
}
public Topic getTopic() {
return topic;
}
public String getTitle() {
return topic.getTitle();
}
public String getDescription() {
return topic.getDescription();
}
public Collection<Organizer> getOrganizers() {
return organizers;
}
public void setOrganizers(Collection<Organizer> organizers) {
this.organizers = organizers;
}
public String getOrganizerNames() {
return organizerNames;
}
public void setOrganizerNames(String organizerNames) {
this.organizerNames = organizerNames;
}
public String getEmailLinkName() {
return emailLinkName;
}
public void setEmailLinkName(String emailLinkName) {
this.emailLinkName = emailLinkName;
}
public Appointment getAppointment() {
return appointment;
}
public void setAppointment(Appointment appointment) {
this.appointment = appointment;
}
public List<String> getParticipants() {
return participants;
}
public void setParticipants(List<String> participants) {
this.participants = participants;
}
public String getShowMoreLinkName() {
return showMoreLinkName;
}
public void setShowMoreLinkName(String showMoreLinkName) {
this.showMoreLinkName = showMoreLinkName;
}
public Boolean getFuture() {
return future;
}
public void setFuture(Boolean future) {
this.future = future;
}
public String getDayName() {
return dayName;
}
public void setDayName(String dayName) {
this.dayName = dayName;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDate2() {
return date2;
}
public void setDate2(String date2) {
this.date2 = date2;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public Appointment.Status getStatus() {
return status;
}
public void setStatus(Appointment.Status status) {
this.status = status;
}
public String getTranslatedStatus() {
return translatedStatus;
}
public void setTranslatedStatus(String translatedStatus) {
this.translatedStatus = translatedStatus;
}
public String getStatusCSS() {
return statusCSS;
}
public void setStatusCSS(String statusCSS) {
this.statusCSS = statusCSS;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getFreeAppointments() {
return freeAppointments;
}
public void setFreeAppointments(Long freeAppointments) {
this.freeAppointments = freeAppointments;
}
public Integer getSelectedAppointments() {
return selectedAppointments;
}
public void setSelectedAppointments(Integer selectedAppointments) {
this.selectedAppointments = selectedAppointments;
}
public String getOpenLinkName() {
return openLinkName;
}
public void setOpenLinkName(String openLinkName) {
this.openLinkName = openLinkName;
}
public MultipleSelectionElement getAcknowledgeRecordingEl() {
return acknowledgeRecordingEl;
}
public void setAcknowledgeRecordingEl(MultipleSelectionElement acknowledgeRecordingEl) {
this.acknowledgeRecordingEl = acknowledgeRecordingEl;
}
public String getAcknowledgeName() {
return acknowledgeRecordingEl != null? acknowledgeRecordingEl.getName(): null;
}
public String getJoinLinkName() {
return joinLinkName;
}
public void setJoinLinkName(String joinLinkName) {
this.joinLinkName = joinLinkName;
}
public String getServerWarning() {
return serverWarning;
}
public void setServerWarning(String serverWarning) {
this.serverWarning = serverWarning;
}
public String getMeetingWarning() {
return meetingWarning;
}
public void setMeetingWarning(String meetingWarning) {
this.meetingWarning = meetingWarning;
}
public List<String> getRecordingLinkNames() {
return recordingLinkNames;
}
public void setRecordingLinkNames(List<String> recordingLinkNames) {
this.recordingLinkNames = recordingLinkNames;
}
}
}
|
const { Message } = require("discord.js")
module.exports = {
name : 'ping',
description : 'Pong!',
execute(client, message, args) {
message.channel.send("Pong!")
}
} |
class Foo:
def __init__(self, val):
self.val = val
def method1(self, x, y):
return self.val * x + y |
package istu.bacs.externalapi.sybon;
import istu.bacs.db.problem.Problem;
import istu.bacs.db.problem.ResourceName;
import istu.bacs.db.submission.Submission;
import istu.bacs.db.submission.SubmissionResult;
import istu.bacs.externalapi.ExternalApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static istu.bacs.db.problem.ResourceName.SYBON;
import static istu.bacs.db.submission.Verdict.PENDING;
import static istu.bacs.externalapi.sybon.SybonContinueCondition.Always;
import static java.lang.Integer.parseInt;
import static java.util.Collections.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
@Slf4j
public class SybonApi implements ExternalApi {
private static final SybonSubmitResultConverter submitResultConverter = new SybonSubmitResultConverter();
private static final SybonLanguageConverter languageConverter = new SybonLanguageConverter();
private static final SybonProblemConverter problemConverter = new SybonProblemConverter();
private final SybonApiEndpointConfiguration config;
private final RestTemplate restTemplate;
public SybonApi(SybonApiEndpointConfiguration config, RestTemplateBuilder restTemplateBuilder) {
this.config = config;
this.restTemplate = restTemplateBuilder.build();
}
@Override
public List<Problem> getAllProblems() {
String url = buildUrl(config.getCollectionUrl(), singletonMap("id", 1));
try {
List<SybonProblem> problems = restTemplate.getForObject(url, SybonProblemCollection.class).getProblems();
return problems.stream()
.map(problemConverter::convert)
.collect(toList());
} catch (Exception e) {
log.warn("Unable to get problems using url '{}': {}", url, e.getMessage(), e);
return emptyList();
}
}
@Override
public boolean submit(Submission submission) {
return submit(singletonList(submission));
}
@Override
public boolean submit(List<Submission> submissions) {
if (submissions.isEmpty())
return false;
List<SybonSubmit> sybonSubmits = submissions.stream()
.map(this::createSubmit)
.collect(toList());
String url = buildUrl(config.getSubmitAllUrl(), emptyMap());
try {
int[] submissionIds = restTemplate.postForObject(url, sybonSubmits, int[].class);
for (int i = 0; i < submissions.size(); i++) {
Submission submission = submissions.get(i);
submission.getResult().setVerdict(PENDING);
submission.setExternalSubmissionId(submissionIds[i]);
}
return true;
} catch (Exception e) {
String ids = submissions.stream().map(Submission::getSubmissionId).map(Object::toString).collect(joining(","));
log.warn("Unable to submit submissions {}", ids, e);
return false;
}
}
private SybonSubmit createSubmit(Submission submission) {
SybonSubmit submit = new SybonSubmit();
submit.setCompilerId(languageConverter.convert(submission.getLanguage()));
submit.setSolution(Base64.getEncoder().encodeToString(submission.getSolution().getBytes()));
submit.setSolutionFileType("Text");
submit.setProblemId(parseInt(submission.getProblem().getProblemId().getResourceProblemId()));
submit.setPretestsOnly(submission.isPretestsOnly());
submit.setContinueCondition(Always);
return submit;
}
@Override
public boolean checkSubmissionResult(Submission submission) {
return checkSubmissionResult(singletonList(submission));
}
@Override
public boolean checkSubmissionResult(List<Submission> submissions) {
if (submissions.isEmpty())
return false;
String ids = submissions.stream()
.map(sub -> sub.getExternalSubmissionId() + "")
.collect(joining(","));
String url = buildUrl(config.getResultsUrl(), emptyMap(), singletonMap("ids", ids));
try {
SybonSubmitResult[] sybonResults = restTemplate.getForObject(url, SybonSubmitResult[].class);
boolean anySuccess = false;
for (int i = 0; i < submissions.size(); i++) {
SubmissionResult result = submitResultConverter.convert(sybonResults[i]);
updateSubmissionResult(submissions.get(i).getResult(), result);
anySuccess |= result.getVerdict() != PENDING;
}
return anySuccess;
} catch (Exception e) {
log.warn("Unable to check submission results for submissions {}", ids, e);
return false;
}
}
private void updateSubmissionResult(SubmissionResult myRes, SubmissionResult newRes) {
myRes.setBuildInfo(newRes.getBuildInfo());
myRes.setVerdict(newRes.getVerdict());
myRes.setTestsPassed(newRes.getTestsPassed());
myRes.setTimeUsedMillis(newRes.getTimeUsedMillis());
myRes.setMemoryUsedBytes(newRes.getMemoryUsedBytes());
}
private String buildUrl(String url, Map<String, ?> urlParams, Map<String, ?> queryParams) {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
queryParams.forEach(builder::queryParam);
builder.queryParam("api_key", config.getApiKey());
return builder.buildAndExpand(urlParams).toString();
}
private String buildUrl(String url, Map<String, ?> urlParams) {
return buildUrl(url, urlParams, emptyMap());
}
@Override
public ResourceName getResourceName() {
return SYBON;
}
} |
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestFramework {
// initialize driver
WebDriver driver;
public void setup() {
// setup Chrome driver
System.setProperty("webdriver.chrome.driver","path/to/chromedriver");
driver = new ChromeDriver();
}
public void run() {
// open the site
driver.get("http://www.example.com");
// run test cases
...
}
public void teardown() {
// close the browser
driver.quit();
}
}
1 12 Instruction: Create a MySQL table with foreign key constraints that stores order information.
12. Input:
Not applicable
12. Output:
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
order_date DATETIME,
CONSTRAINT fk_customers FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
); |
package dev.webfx.kit.mapper.peers.javafxcontrols.base;
import javafx.scene.control.ButtonBase;
/**
* @author <NAME>
*/
public class ButtonBasePeerBase
<N extends ButtonBase, NB extends ButtonBasePeerBase<N, NB, NM>, NM extends ButtonBasePeerMixin<N, NB, NM>>
extends LabeledPeerBase<N, NB, NM> {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.