text
stringlengths 27
775k
|
|---|
import React from 'react';
import {
Provider,
} from 'react-redux';
import './App.css';
import Store from './store/Store';
import PageLoader from './pageRenderer/PageLoader';
function App() {
return (
<Provider store={Store}>
<PageLoader />
</Provider>
);
}
export default App;
|
import {Module} from "../module";
import {Util} from "../util";
import {PuzzleJs} from "../puzzle";
import {EVENT, LOG_COLORS} from "../enums";
export interface IFragmentInfo {
[fragmentName: string]: {
[name: string]: any
}
}
export class Fragments extends Module {
set(fragmentInfo: IFragmentInfo) {
Util.wrapGroup('PuzzleJs', 'Debug Mode - Fragments', () => {
Object.keys(fragmentInfo).forEach(fragmentName => {
Util.wrapGroup('PuzzleJs', fragmentName, () => {
Util.log(fragmentInfo[fragmentName]);
}, LOG_COLORS.BLUE);
});
});
}
}
|
@extends('layouts.backend')
@section('content')
<div class="page-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-xl-3 col-lg-4 col-md-12 theiaStickySidebar">
<aside class="sidebar sidebar-user">
<div class="card ctm-border-radius shadow-sm">
<div class="card-body py-4">
<div class="row">
<div class="col-md-12 mr-auto text-left">
<div class="custom-search input-group">
<div class="custom-breadcrumb">
<ol class="breadcrumb no-bg-color d-inline-block p-0 m-0 mb-2">
<li class="breadcrumb-item d-inline-block"><a href="{{url('/')}}" class="text-dark">Home</a></li>
<li class="breadcrumb-item d-inline-block active">Dashboard</li>
</ol>
<h4 class="text-dark">Admin Dashboard</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</aside>
</div>
<div class="col-xl-9 col-lg-8 col-md-12">
<!-- Widget -->
<div class="row">
<div class="col-xl-3 col-lg-6 col-md-6 col-sm-6 col-12">
<div class="card dash-widget ctm-border-radius shadow-sm">
<div class="card-body">
<div class="card-icon bg-primary">
<i class="fa fa-users" aria-hidden="true"></i>
</div>
<div class="card-right">
<h4 class="card-title">Employees</h4>
<p class="card-text">700</p>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-sm-6 col-12">
<div class="card dash-widget ctm-border-radius shadow-sm">
<div class="card-body">
<div class="card-icon bg-warning">
<i class="fa fa-building-o"></i>
</div>
<div class="card-right">
<h4 class="card-title">Companies</h4>
<p class="card-text">30</p>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-sm-6 col-12">
<div class="card dash-widget ctm-border-radius shadow-sm">
<div class="card-body">
<div class="card-icon bg-danger">
<i class="fa fa-suitcase" aria-hidden="true"></i>
</div>
<div class="card-right">
<h4 class="card-title">Leaves</h4>
<p class="card-text">3</p>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-sm-6 col-12">
<div class="card dash-widget ctm-border-radius shadow-sm">
<div class="card-body">
<div class="card-icon bg-success">
<i class="fa fa-money" aria-hidden="true"></i>
</div>
<div class="card-right">
<h4 class="card-title">Salary</h4>
<p class="card-text">$5.8M</p>
</div>
</div>
</div>
</div>
</div>
<!-- / Widget -->
</div>
</div>
</div>
</div>
<!--/Content-->
@endsection
|
import './model/article.model'
import './model/banner.model'
import './model/category.model'
import './model/equipment.model'
import './model/hero.model'
import './model/rune.model'
import './model/homeHeroBanner.model'
import './model/homeVideo.model'
/** @description {引入一遍所有的model,避免一部分model没有被引入,populate时查询不到对应的model } */
export {}
|
import Redis from 'ioredis';
import { EventEmitter } from 'events';
import RVDNode from './RVDNode';
import getLogger, { LoggerClass } from './logger';
const { debug, printinfo, printerror } = getLogger().getContext('flow');
export class RVDController extends EventEmitter {
constructor(params = {}) {
super(params);
const {
redisparam,
SESSION_TIMEOUT = 40,
USSD_SAVE_TRANSACTION = 'NONE',
defaultRVDJson = {},
defaultWorkSpace,
defaultErrorMsg,
} = params;
if (!redisparam) {
throw new Error('Redis parameters are required');
}
if (typeof redisparam !== 'object') {
throw new Error('Invalid Redis parameters');
}
this.redis = new Redis({ keyPrefix: 'paic:', ...redisparam });
// is save transaction enabled. possible values ALL, END, or default NONE
this.isSaveTransEnabled = USSD_SAVE_TRANSACTION;
this.SESSION_TIMEOUT = SESSION_TIMEOUT;
this.rvdjson = defaultRVDJson;
this.defaultWorkSpace = defaultWorkSpace;
this.defaultErrorMsg = defaultErrorMsg || 'Error processing request';
}
/**
* Read the current subscriber session from the database.
* If the session doesn't exist return null
* @param {String} sessionid The USSD GW sessionID
* @param {String} msisdn The subscriber number
* @memberof USSDFlowController
*/
getSessionData = async (sessionid, msisdn) => {
try {
// check if the subscriber key exist
const sessionsubdata = await this.redis.get(sessionid || msisdn);
if (sessionsubdata) {
return JSON.parse(sessionsubdata);
}
} catch (error) {
printerror('ERROR: %s', error.message);
}
return null;
};
/**
* Save the subscriber session to database with the default timeout
* @param {String} sessionid the USSD GW session ID
* @param {String} msisdn The subscriber number
* @param {Object} data the information to be save to database
* @memberof USSDFlowController
*/
saveSessionData = async (sessionid, msisdn, data = {}) => {
try {
await this.redis.setex(sessionid || msisdn, this.SESSION_TIMEOUT, JSON.stringify(data));
} catch (error) {
printerror('ERROR: %s', error.message);
}
};
/**
* emit the data to be save to the transaction table
* @param {Object} pResponse The object contains all data to be stored in the database
* @param {String} reply the reply message to the subscriber
* @memberof USSDFlowController
*/
saveTransaction = async (pRespons, reply, updateOnly = false) => {
try {
const { rvdmodule = {}, data, next } = pRespons;
const toDatabase = { ...rvdmodule };
toDatabase.msisdn = data.$core_From;
toDatabase.cellid = data.$cell_id;
toDatabase.sessionid = data.$session_id;
toDatabase.imsi = data.$imsi;
toDatabase.shortcode = data.$shortcode;
toDatabase.flowend = next;
toDatabase.replyMessage = reply;
if (updateOnly) {
this.emit('updatetrans', { dbobject: { ...toDatabase } });
} else {
this.emit('savetrans', { dbobject: { ...toDatabase } });
}
} catch (error) {
printerror(`ERROR: ${error.message} - saveTransaction`);
}
};
/**
* The endpoint to process the RVD Node. The main entry point for the application.
* The sid is the default SID for the shortcode. if the sid does not exist, the rvdjson will be
* used. NOTE: if the session does not exist, the input is the same as the shortcode
* @param {Object} request An object containing the msisdn, cellid,sessionid,input,imsi & sid
* @memberof USSDFlowController
*/
entryPoint = async (request) => {
try {
const { msisdn, imsi, cellid, sessionid, input, sid, shortcode } = request;
printinfo('REQ: %o', request);
// get the session. if the session does not exist then process the first stage of rvd
const subSession = await this.getSessionData(sessionid || msisdn);
// application state
const state = {
$core_From: msisdn,
$cell_id: cellid,
$session_id: sessionid,
$imsi: imsi,
$core_Body: input,
$cellid: cellid,
};
if (!subSession) {
// the first time request, the input is the same as the shortcode
state.$shortcode = shortcode || input;
}
const rvdController = new RVDNode({
session: subSession,
state,
cache: this.redis,
rvdjson: this.rvdjson,
config: {
workSpaceDir: this.defaultWorkSpace,
sid,
},
});
const response = await rvdController.rvd(input);
const Freeflow = response.next ? 'FC' : 'FB';
// check if storing session is needed
if (response.data && Freeflow === 'FC') {
await this.saveSessionData(sessionid, msisdn, response.data);
}
let reply = response.message;
if (!reply) {
debug(`${msisdn}: No reply message found. Replying default message`);
reply = this.defaultErrorMsg;
}
if (this.isSaveTransEnabled === 'ALL') {
await this.saveTransaction(response, reply);
} else if (this.isSaveTransEnabled === 'END' && Freeflow === 'FB') {
await this.saveTransaction(response, reply);
} else if (this.isSaveTransEnabled === 'UPDATE') {
await this.saveTransaction(response, reply, true);
} else if (this.isSaveTransEnabled === 'STARTEND') {
if (!subSession || Freeflow === 'FB') {
await this.saveTransaction(response, reply);
}
}
return {
status: 200,
header: {
Freeflow,
Expires: -1,
'Cache-Control': 'max-age=0',
Pragma: 'no-cache',
},
message: reply,
};
} catch (error) {
printerror(error.message);
return {
status: 401,
header: {
Freeflow: 'FB',
Expires: -1,
'Cache-Control': 'max-age=0',
Pragma: 'no-cache',
},
message: this.defaultErrorMsg,
};
}
};
}
export { LoggerClass };
export { default as ensureArray } from './ensureArray';
|
#!/usr/bin/env sh
if [ "$#" -ne "2" ]; then
echo "Two arguments must be set e.g. ./update-user.sh email user(json)"
exit 1
fi
curl -X PUT --data "$2" "username:password@localhost:8080/v1/admin/users/$1" -v
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace BForms.Grid
{
public class BsGridRowConfigurator<TRow> where TRow : new()
{
private Func<TRow, Dictionary<string, object>> htmlAttributes;
private Func<TRow, string> highlighter;
private Func<TRow, bool> details;
private Func<TRow, bool> checkbox;
private Func<TRow, string> _detailsTemplate;
internal Func<TRow, Dictionary<string, object>> HtmlAttr
{
get
{
return this.htmlAttributes;
}
}
internal Func<TRow, bool> Details
{
get
{
return this.details;
}
}
internal Func<TRow, bool> Checkbox
{
get
{
return this.checkbox;
}
}
internal Func<TRow, string> Highlight
{
get
{
return this.highlighter;
}
}
internal Func<TRow, string> DetailsTmpl
{
get
{
return this._detailsTemplate;
}
}
public BsGridRowConfigurator()
{
}
public BsGridRowConfigurator<TRow> HtmlAttributes(Func<TRow, Dictionary<string, object>> htmlAttributes)
{
this.htmlAttributes = htmlAttributes;
return this;
}
public BsGridRowConfigurator<TRow> Highlighter(Func<TRow, string> highlighter)
{
this.highlighter = highlighter;
return this;
}
public BsGridRowConfigurator<TRow> HasDetails(Func<TRow, bool> details)
{
this.details = details;
return this;
}
public BsGridRowConfigurator<TRow> HasCheckbox(Func<TRow, bool> checkbox)
{
this.checkbox = checkbox;
return this;
}
public BsGridRowConfigurator<TRow> DetailsTemplate(Func<TRow,string> detailsTemplate)
{
this._detailsTemplate = detailsTemplate;
return this;
}
public BsGridRowConfigurator<TRow> DetailsTemplate(Func<TRow, MvcHtmlString> detailsTemplate)
{
Func<TRow, string> detailsAsString = t => detailsTemplate(t).ToString();
this._detailsTemplate = detailsAsString;
return this;
}
}
}
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'application#index'
# Provide a route for :provider strategies to "call back" to
# after the authenticating 3rd party decides whether the user has passed or failed authentication
# handshake
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
# Handshake - when user login to github, github sends them back to my application - callback URL
# How Github redirects user back to my app and provides app with secret code representing Github user
# App sends secret code back to GitHuhb - Git Hub confirms code
# GitHub sends back user's data
get '/auth/github/callback', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
# Users
resources :users, only: [:index, :new, :create, :show] do
# Sends as nested resources of a user
resources :sends
# Aliased path names
get '/sends/sort/easiest', to: 'sends#easiest', as: :easiest_sends
get '/sends/sort/hardest', to: 'sends#hardest', as: :hardest_sends
get '/sends/sort/favorites', to: 'sends#favorites', as: :favorite_sends
get '/sends/sort/color', to: 'sends#color', as: :selected_color_sends
end
# Problems
resources :problems, only: [:index, :show, :new, :create]
get '/problems/sort/easiest', to: 'problems#easiest', as: :easiest_problems
get '/problems/sort/hardest', to: 'problems#hardest', as: :hardest_problems
# get '/problems/filter/style', to: 'problems#style' # maybe
# get '/problems/filter/wall', to: 'problems#wall' # maybe
resources :rewards, only: [:index, :show, :new, :create]
end
|
[瞎搞系列之上一篇:vue转react系列-API封装](https://juejin.cn/post/6964316996531929125)
你是否在为reduce各种switch而烦恼,是不是对各种case代码而落泪,想要代码写的优雅,请你继续往下看
又是一个vue转react的娱乐封装,下面展示利用vuex的写法去改造reducer
## vuex温习
- state
- mutations
- actions
- getters
```javascript
const store = {
state: {
list: []
},
// 派生
getters: {
todoList(state, getter) {
return state.list.concat(getter.todos)
},
todos() {
return ['玩', '写']
}
},
// 修改state
mutations: {
setList(state, payload) {
state.list.push(payload)
}
},
// 提交修改
actions({state, commit}, payload) {
commit('setList', payload)
}
}
```
你看划分的就很清晰嘛,职责分离,也不用到处case,就喜欢这种vuex的写法,不用到处判断。
## 晒代码
> 看完了vuex的使用,我们结合redux,尝试把switch改变成有一定结构的写法
```javascript
export default function RX(store) {
const { state, getters = {}, mutations, actions } = store;
// getter本身是可以聚合自身属性和state属性,所以利用get惰性去求值,以便在每个getter里定义的方法能拿到getters
function getter() {
const getterProxy = {};
Object.keys(getters).forEach((key) => {
// eslint-disable-next-line no-multi-assign
Object.defineProperty(getterProxy, key, {
configurable: false,
enumerable: true,
get() {
return getters[key](state, getterProxy);
},
});
});
// 这块就是为了把get去掉,不让state带有属性get
Object.assign(state, getterProxy);
}
// 修改state完需要更新一下getter,因为可能存在引用state的数据,保证数据正确
function commit(actionName, payload) {
mutations[actionName](state, payload);
getter();
}
// 提交mutations操作,这里先判断下type,因为redux在第一次调用是会传入type=@@redux/init,防止报错
function dispatch(initState = state, option) {
const { type, payload } = option;
const commitFun = actions[type];
if (!commitFun) {
return initState;
}
// 正式提交mutations
commitFun({ commit, initState }, payload);
// 返回新的state,这样redux才能判断俩个reducer出来的不一样才能出发视图更新
return Object.create(state);
}
return dispatch;
}
```
## 使用
```javascript
const reduxStore = createStore(RX({
state: {
list: []
},
mutations: {
append(state, item) {
console.log(state.first)
state.list.push(item)
}
},
actions: {
commitAppend({state, commit}, payload) {
commit('append', payload)
}
},
getters: {
first(state, getters) {
return state.list[0] + getters.name
},
name() {
return '岁'
}
}
}))
reduxStore.dispatch({
type: 'commitAppend',
payload: 2
})
console.log(reduxStore.getState())
{
list: [2],
name: '岁',
first: '2岁'
}
```
## 最后
菜鸟手写,有不恰当的处理请指(轻)教(喷),欢迎一起讨论!谢(讨)谢(好)!
|
<?php
namespace Oro\Bundle\CalendarBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Persistence\ManagerRegistry;
use Oro\Bundle\SecurityBundle\SecurityFacade;
use Oro\Bundle\UserBundle\Entity\User;
use Oro\Bundle\CalendarBundle\Entity\CalendarEvent;
use Oro\Bundle\CalendarBundle\Entity\Repository\CalendarRepository;
class EventsToUsersTransformer implements DataTransformerInterface
{
/**
* @var ManagerRegistry
*/
protected $registry;
/**
* @var SecurityFacade
*/
protected $securityFacade;
/**
* @param ManagerRegistry $registry
* @param SecurityFacade $securityFacade
*/
public function __construct(ManagerRegistry $registry, SecurityFacade $securityFacade)
{
$this->registry = $registry;
$this->securityFacade = $securityFacade;
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
if (null === $value) {
return null;
}
$users = new ArrayCollection();
/** @var CalendarEvent $event */
foreach ($value as $event) {
$users->add($event->getCalendar()->getOwner());
}
return $users;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
if (!$value) {
return [];
}
/** @var CalendarRepository $calendarRepository */
$calendarRepository = $this->registry->getRepository('OroCalendarBundle:Calendar');
$organizationId = $this->securityFacade->getOrganizationId();
if (!$organizationId) {
throw new TransformationFailedException('Can\'t get current organization');
}
$events = new ArrayCollection();
/** @var User $user */
$userIds = [];
foreach ($value as $user) {
$userIds[] = $user->getId();
}
$calendars = $calendarRepository->findDefaultCalendars($userIds, $organizationId);
foreach ($calendars as $calendar) {
$event = new CalendarEvent();
$event->setCalendar($calendar);
$events->add($event);
}
return $events;
}
}
|
package com.android.taitasciore.privaliatest.data.repository
import com.android.taitasciore.privaliatest.domain.model.Movie
import io.reactivex.Observable
interface MovieRepository {
fun getPopularMovies(page: Int): Observable<List<Movie>>
fun searchMovies(query: String, page: Int): Observable<List<Movie>>
}
|
package com.pechuro.bsuirschedule.domain.interactor
import com.pechuro.bsuirschedule.domain.common.BaseInteractor
import com.pechuro.bsuirschedule.domain.entity.Lesson
import com.pechuro.bsuirschedule.domain.entity.WeekNumber
import com.pechuro.bsuirschedule.domain.repository.IScheduleRepository
import javax.inject.Inject
class GetLessonWeeks @Inject constructor(
private val scheduleRepository: IScheduleRepository
) : BaseInteractor<List<WeekNumber>, GetLessonWeeks.Params>() {
override suspend fun run(params: Params): List<WeekNumber> {
return scheduleRepository.getLessonWeeks(params.lesson)
}
data class Params(
val lesson: Lesson
)
}
|
package com.github.davidmoten.bigsorter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.function.Consumer;
import com.github.davidmoten.guavamini.Preconditions;
import com.github.davidmoten.guavamini.annotations.VisibleForTesting;
//NotThreadSafe
public final class Sorter<T> {
private final InputStream input;
private final Serializer<T> serializer;
private final File output;
private final Comparator<? super T> comparator;
private final int maxFilesPerMerge;
private final int maxItemsPerPart;
private final Consumer<? super String> log;
private final int bufferSize;
private final File tempDirectory;
private long count = 0;
Sorter(InputStream input, Serializer<T> serializer, File output,
Comparator<? super T> comparator, int maxFilesPerMerge, int maxItemsPerFile,
Consumer<? super String> log, int bufferSize, File tempDirectory) {
Preconditions.checkNotNull(input, "input must be specified");
Preconditions.checkNotNull(serializer, "serializer must be specified");
Preconditions.checkNotNull(output, "output must be specified");
Preconditions.checkNotNull(comparator, "comparator must be specified");
this.input = input;
this.serializer = serializer;
this.output = output;
this.comparator = comparator;
this.maxFilesPerMerge = maxFilesPerMerge;
this.maxItemsPerPart = maxItemsPerFile;
this.log = log;
this.bufferSize = bufferSize;
this.tempDirectory = tempDirectory;
}
public static <T> Builder<T> serializer(Serializer<T> serializer) {
Preconditions.checkNotNull(serializer, "serializer cannot be null");
return new Builder<T>(serializer);
}
public static <T> Builder<String> serializerLinesUtf8() {
return serializer(Serializer.linesUtf8());
}
public static <T> Builder<String> serializerLines(Charset charset) {
return serializer(Serializer.lines(charset));
}
public static <T> Builder2<String> lines(Charset charset) {
return serializer(Serializer.lines(charset)).comparator(Comparator.naturalOrder());
}
public static <T> Builder2<String> linesUtf8() {
return serializer(Serializer.linesUtf8()).comparator(Comparator.naturalOrder());
}
public static final class Builder<T> {
private static final DateTimeFormatter DATE_TIME_PATTERN = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.Sxxxx");
private InputStream input;
private final Serializer<T> serializer;
private File output;
private Comparator<? super T> comparator;
private int maxFilesPerMerge = 100;
private int maxItemsPerFile = 100000;
private File inputFile;
private Consumer<? super String> logger = null;
private int bufferSize = 8192;
private File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
Builder(Serializer<T> serializer) {
this.serializer = serializer;
}
public Builder2<T> comparator(Comparator<? super T> comparator) {
Preconditions.checkNotNull(comparator, "comparator cannot be null");
this.comparator = comparator;
return new Builder2<T>(this);
}
}
public static final class Builder2<T> {
private final Builder<T> b;
Builder2(Builder<T> b) {
this.b = b;
}
public Builder3<T> input(String string, Charset charset) {
Preconditions.checkNotNull(string, "string cannot be null");
Preconditions.checkNotNull(charset, "charset cannot be null");
return input(new ByteArrayInputStream(string.getBytes(charset)));
}
public Builder3<T> input(String string) {
Preconditions.checkNotNull(string);
return input(string, StandardCharsets.UTF_8);
}
public Builder3<T> input(InputStream input) {
Preconditions.checkNotNull(input, "input cannot be null");
b.input = input;
return new Builder3<T>(b);
}
public Builder3<T> input(File inputFile) {
Preconditions.checkNotNull(inputFile, "inputFile cannot be null");
b.inputFile = inputFile;
return new Builder3<T>(b);
}
}
public static final class Builder3<T> {
private final Builder<T> b;
Builder3(Builder<T> b) {
this.b = b;
}
public Builder4<T> output(File output) {
Preconditions.checkNotNull(output, "output cannot be null");
b.output = output;
return new Builder4<T>(b);
}
}
public static final class Builder4<T> {
private final Builder<T> b;
Builder4(Builder<T> b) {
this.b = b;
}
public Builder4<T> maxFilesPerMerge(int value) {
Preconditions.checkArgument(value > 1, "maxFilesPerMerge must be greater than 1");
b.maxFilesPerMerge = value;
return this;
}
public Builder4<T> maxItemsPerFile(int value) {
Preconditions.checkArgument(value > 0, "maxItemsPerFile must be greater than 0");
b.maxItemsPerFile = value;
return this;
}
public Builder4<T> logger(Consumer<? super String> logger) {
Preconditions.checkNotNull(logger, "logger cannot be null");
b.logger = logger;
return this;
}
// public Builder4<T> async() {
// b.executor = Executors.newSingleThreadExecutor();
// return this;
// }
public Builder4<T> loggerStdOut() {
return logger(new Consumer<String>() {
@Override
public void accept(String msg) {
System.out.println(ZonedDateTime.now().truncatedTo(ChronoUnit.MILLIS)
.format(Builder.DATE_TIME_PATTERN) + " " + msg);
}
});
}
public Builder4<T> bufferSize(int bufferSize) {
Preconditions.checkArgument(bufferSize > 0, "bufferSize must be greater than 0");
b.bufferSize = bufferSize;
return this;
}
public Builder4<T> tempDirectory(File directory) {
Preconditions.checkNotNull(directory, "tempDirectory cannot be null");
b.tempDirectory = directory;
return this;
}
/**
* Sorts the input and writes the result to the given output file. If an
* {@link IOException} occurs then it is thrown wrapped in
* {@link UncheckedIOException}.
*/
public void sort() {
try {
if (b.inputFile != null) {
try (InputStream in = openFile(b.inputFile, b.bufferSize)) {
sort(in);
}
} else {
sort(b.input);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void sort(InputStream input) {
Sorter<T> sorter = new Sorter<T>(input, b.serializer, b.output, b.comparator,
b.maxFilesPerMerge, b.maxItemsPerFile, b.logger, b.bufferSize, b.tempDirectory);
try {
sorter.sort();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
static InputStream openFile(File file, int bufferSize) throws FileNotFoundException {
return new BufferedInputStream(new FileInputStream(file), bufferSize);
}
private void log(String msg, Object... objects) {
if (log != null) {
String s = String.format(msg, objects);
log.accept(s);
}
}
private File sort() throws IOException {
tempDirectory.mkdirs();
// read the input into sorted small files
long time = System.currentTimeMillis();
count = 0;
List<File> files = new ArrayList<>();
log("starting sort");
try (Reader<T> reader = serializer.createReader(input)) {
int i = 0;
List<T> list = new ArrayList<>();
while (true) {
T t = reader.read();
if (t != null) {
list.add(t);
i++;
}
if (t == null || i == maxItemsPerPart) {
i = 0;
if (list.size() > 0) {
File f = sortAndWriteToFile(list);
files.add(f);
list.clear();
}
}
if (t == null) {
break;
}
}
}
log("completed inital split and sort, starting merge");
File result = merge(files);
Files.move( //
result.toPath(), //
output.toPath(), //
StandardCopyOption.ATOMIC_MOVE, //
StandardCopyOption.REPLACE_EXISTING);
log("sort of " + count + " records completed in "
+ (System.currentTimeMillis() - time) / 1000.0 + "s");
return output;
}
@VisibleForTesting
File merge(List<File> files) {
// merge the files in chunks repeatededly until only one remains
// TODO make a better guess at the chunk size so groups are more even
try {
while (files.size() > 1) {
List<File> nextRound = new ArrayList<>();
for (int i = 0; i < files.size(); i += maxFilesPerMerge) {
File merged = mergeGroup(files.subList(i, Math.min(files.size(), i + maxFilesPerMerge)));
nextRound.add(merged);
}
files = nextRound;
}
File result;
if (files.isEmpty()) {
output.delete();
output.createNewFile();
result = output;
} else {
result = files.get(0);
}
return result;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private File mergeGroup(List<File> list) throws IOException {
log("merging %s files", list.size());
if (list.size() == 1) {
return list.get(0);
}
List<State<T>> states = new ArrayList<>();
for (File f : list) {
State<T> st = createState(f);
// note that st.value will be present otherwise the file would be empty
// and an empty file would not be passed to this method
states.add(st);
}
File output = nextTempFile();
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(output), bufferSize);
Writer<T> writer = serializer.createWriter(out)) {
PriorityQueue<State<T>> q = new PriorityQueue<>(
(x, y) -> comparator.compare(x.value, y.value));
q.addAll(states);
while (!q.isEmpty()) {
State<T> state = q.poll();
writer.write(state.value);
state.value = state.reader.readAutoClosing();
if (state.value != null) {
q.offer(state);
} else {
// delete intermediate files
state.file.delete();
}
}
// TODO if an IOException occurs then we should attempt to close and delete
// temporary files
}
return output;
}
private State<T> createState(File f) throws IOException {
InputStream in = openFile(f, bufferSize);
Reader<T> reader = serializer.createReader(in);
T t = reader.readAutoClosing();
return new State<T>(f, reader, t);
}
private static final class State<T> {
final File file;
Reader<T> reader;
T value;
State(File file, Reader<T> reader, T value) {
this.file = file;
this.reader = reader;
this.value = value;
}
}
private File sortAndWriteToFile(List<T> list) throws FileNotFoundException, IOException {
File file = nextTempFile();
long t = System.currentTimeMillis();
Collections.sort(list, comparator);
writeToFile(list, file);
DecimalFormat df = new DecimalFormat("0.000");
count += list.size();
log("total=%s, sorted %s records to file %s in %ss", //
count, //
list.size(), //
file.getName(), //
df.format((System.currentTimeMillis() - t) / 1000.0));
return file;
}
private void writeToFile(List<T> list, File f) throws FileNotFoundException, IOException {
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(f), bufferSize);
Writer<T> writer = serializer.createWriter(out)) {
for (T t : list) {
writer.write(t);
}
}
}
private File nextTempFile() throws IOException {
return File.createTempFile("big-sorter", "", tempDirectory);
}
}
|
module Types
class MutationType < Types::BaseObject
field :create_draft_prospect, mutation: Mutations::CreateDraftProspect
end
end
|
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/','User\HomeController@index');
Route::get('dia-chi','User\HomeController@map');
//Route danh sach san pham
Route::get('san-pham/{link}', 'User\ProductController@show');
Route::get('danh-muc/{link}', 'User\HomeController@category');
Route::get('danh-sach/san-pham-moi', 'User\ListProductController@sanphammoi');
Route::get('danh-sach/san-pham-duoc-quan-tam', 'User\ListProductController@sanphamxemnhieu');
Route::get('danh-sach/san-pham-dang-giam-gia', 'User\ListProductController@sanphamgiamgia');
Route::get('danh-sach/san-pham-hot', 'User\ListProductController@sanphamhot');
//Route tim kiem san pham
Route::post('tag','User\HomeController@tag');
Route::get('tim-kiem','User\HomeController@search');
//Route tin tuc
Route::get('tin-tuc', 'User\NewsController@index');
Route::get('tin-tuc/{link}', 'User\NewsController@show');
// Registration routes...
Route::get('dang-ky', 'Auth\AuthController@getRegister');
Route::post('dang-ky', 'Auth\AuthController@postRegister');
Route::get('dang-nhap-tai-khoan', 'Auth\AuthController@Login');
Route::post('dang-nhap', 'Auth\AuthController@postLogin');
Route::get('dang-xuat', 'Auth\AuthController@getLogout');
//route Login with facebook
Route::get('auth/facebook', 'Auth\AuthController@redirectToProvider');
Route::get('auth/facebook/callback', 'Auth\AuthController@handleProviderCallback');
//Mua san pham
Route::get('mua-san-pham/{link}',['as'=>'muahang','uses'=>'User\ShoppingController@muahang']);
Route::get('gio-hang', 'User\ShoppingController@giohang');
Route::get('thanh-toan', 'User\ShoppingController@thanhtoan');
Route::post('cam-on', 'User\ShoppingController@thanhtoan');
Route::get('xoa-san-pham/{id}',['as'=>'xoasanpham','uses'=>'User\ShoppingController@xoasanpham']);
Route::get('cap-nhat-gio-hang/{id}/{qty}',['as'=>'capnhatgiohang','uses'=>'User\ShoppingController@capnhatgiohang'] );
// Authentication routes...
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset', 'Auth\PasswordController@postReset');
Route::group(array('before' => 'admin', 'middleware'=> 'auth'),function(){
Route::get('admin', 'Admin\HomeController@index');
// Route Quản lý thành viên
Route::get('admin/thanh-vien/danh-sach', 'Admin\UserController@index');
Route::get('admin/thanh-vien/xoa/{id}/', 'Admin\UserController@destroy');
Route::get('admin/thanh-vien/them-moi', 'Admin\UserController@create');
Route::post('admin/thanh-vien/them-moi', 'Admin\UserController@store');
Route::get('admin/thanh-vien/xem/{id}', 'Admin\UserController@show');
Route::patch('admin/thanh-vien/cap-nhat/{id}', 'Admin\UserController@update');
Route::post('admin/thanh-vien/tim-kiem','Admin\UserController@search');
Route::get('admin/thanh-vien/ket-qua-tim-kiem','Admin\UserController@searchResult');
//cate
Route::get('admin/danh-muc/danh-sach', 'Admin\CategoryController@index');
Route::get('admin/danh-muc/danh-sach-2', 'Admin\CategoryController@index2');
Route::get('admin/danh-muc/them-moi', 'Admin\CategoryController@create');
Route::post('admin/danh-muc/them-moi', 'Admin\CategoryController@store');
Route::get('admin/danh-muc/xoa/{id}', 'Admin\CategoryController@destroy');
Route::get('admin/danh-muc/cap-nhat/{id}', 'Admin\CategoryController@edit');
Route::patch('admin/danh-muc/cap-nhat/{id}', 'Admin\CategoryController@update');
//products
Route::group(array('before' => 'admin', 'middleware'=> 'auth'),function(){
Route::get('admin/san-pham/danh-sach', 'Admin\ProductsController@index');
Route::get('admin/san-pham/them-moi', 'Admin\ProductsController@create');
Route::post('admin/san-pham/them-moi', 'Admin\ProductsController@store');
Route::get('admin/san-pham/xem/{id}', 'Admin\ProductsController@show');
Route::get('admin/san-pham/xoa/{id}', 'Admin\ProductsController@destroy');
Route::patch('admin/san-pham/cap-nhat/{id}', 'Admin\ProductsController@update');
Route::post('admin/danh-muc/san-pham', 'Admin\ProductsController@getList');
Route::get('admin/san-pham/theo-danh-muc', 'Admin\ProductsController@showList');
Route::post('admin/san-pham/tim-kiem','Admin\ProductsController@search');
Route::get('admin/san-pham/ket-qua-tim-kiem','Admin\ProductsController@searchResult');
});
//Order
Route::get('admin/don-hang/danh-sach', 'Admin\OrderController@index');
Route::get('admin/don-hang/xem/{id}', 'Admin\OrderController@show');
Route::get('admin/don-hang/them-moi', 'Admin\OrderController@create');
Route::post('admin/don-hang/them-moi', 'Admin\OrderController@store');
Route::patch('admin/don-hang/cap-nhat/{id}', 'Admin\OrderController@update');
//news
Route::get('admin/tin-tuc/danh-sach', 'Admin\NewsController@index');
Route::get('admin/tin-tuc/them-moi', 'Admin\NewsController@create');
Route::post('admin/tin-tuc/them-moi', 'Admin\NewsController@store');
});
Route::group(array('middleware'=> 'auth'),function(){
//route thong tin ca nhan
Route::get('thong-tin-ca-nhan','User\UserController@show');
Route::get('cap-nhat-thong-tin','User\UserController@edit');
Route::patch('cap-nhat-thong-tin','User\UserController@update');
Route::get('doi-mat-khau','User\UserController@editPassword');
Route::patch('doi-mat-khau','User\UserController@changePassword');
// Route::get('thong-tin-ca-nhan/kich-hoat','User\UsersController@sendMail');
// Route::get('yeu-thich/{id}','User\ProductController@addWishList');
// Route::get('yeu-thich','User\ProductController@wishList');
// Route::get('xoa-yeu-thich/{id}','User\ProductController@delWishList');
Route::get('yeu-thich/{id}','User\UserController@addWishList');
Route::get('san-pham-yeu-thich', 'User\UserController@wishList');
});
|
<?php
trait Company {
public function getName() {
return 'Facebook';
}
}
class English {
use Company;
public function getHi() {
return "Hi ";
}
public function sayHello() {
echo $this->getHi() . $this->getName();
}
}
$e = new English();
$e->sayHello();
?>
|
package com.chetantuteja.easy_binding_tutorial.activites
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.chetantuteja.easy_binding_tutorial.R
import com.chetantuteja.easy_binding_tutorial.fragments.ExampleFragment
import com.chetantuteja.easy_binding_tutorial.utils.performFragmentTransaction
import kotlinx.android.synthetic.main.activity_main.*
/**
* @author Chetan Tuteja (chetan.tuteja@gmail.com)
* @since 21-Feb-21
*/
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "MainActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupViews()
}
private fun setupViews() {
// Set Text using Kotlin Synthetics.
tvWelcomeMsg.text = getString(R.string.synthetic_activity)
// Set onClick Action using Kotlin Synthetics.
btnLoadFrag.setOnClickListener {
performFragmentTransaction(
ExampleFragment(), ExampleFragment.TAG
)
}
}
}
|
<?php
namespace ComunidadAEI\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str as Str;
use Illuminate\Support\Facades\Storage;
use ComunidadAEI\Perfil_Empresa;
class MisLogrosController extends Controller
{
public function Index($slug_empresa)
{
$perfilU = Perfil_Empresa::where('slug_empresa',$slug_empresa)->first();
return view('Perfiles.Logros.Mis_Logros')->with('MisLogros',$perfilU);
}
public function store(Request $request)
{
return view('form.campo')->with('dato', $request);
}
//
public function edit($slug_empresa)
{
$perfilU = Perfil_Empresa::where('slug_empresa',$slug_empresa)->first();
return view('Perfiles.Logros.EditarMis_Logros')->with('MisLogros',$perfilU);
}
public function update(Request $request)
{
$perfilU = Perfil_Empresa::where('id_usuario',Auth::id())->first();
$perfilU->mis_logros=Str::upper($request->MisLogros);
if($request->hasFile('img_logros')){
Storage::delete(str_replace("/storage", "public", $perfilU->img_logros));
$img_logros= $request->file('img_logros')->store('public/logros_img');
$perfilU->img_logros=str_replace("public","/storage",$img_logros);
}
$perfilU->save();
return redirect('MisLogros/'.$perfilU->slug_empresa);
}
}
|
package powercraft.api.gres;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.inventory.Slot;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import powercraft.api.registry.PC_LangRegistry;
import powercraft.api.registry.PC_TextureRegistry;
import powercraft.api.tileentity.PC_ITileEntityWatcher;
import powercraft.api.utils.PC_ClientUtils;
import powercraft.api.utils.PC_Color;
import powercraft.api.utils.PC_RectI;
import powercraft.api.utils.PC_VecI;
import powercraft.launcher.mod_PowerCraft;
/**
* Base class for GUI-system
*
* @authors XOR19, Rapus95, MightyPork
* @copy (c) 2012
*/
public abstract class PC_GresWidget extends Gui implements PC_ITileEntityWatcher {
/** zero coord */
public static final PC_VecI zerosize = new PC_VecI(0, 0);
/** Minecraft instance */
protected static Minecraft mc = PC_ClientUtils.mc();
protected static String imgdir = PC_TextureRegistry.getGresImgDir();
protected enum MouseOver {
NON, THIS, CHILD
}
/**
* align vertical
*
* @authors XOR19 & Rapus95
* @copy (c) 2012
*/
public enum PC_GresAlign {
/** LEFT */
LEFT,
/** RIGHT */
RIGHT,
/** TOP */
TOP,
/** BOTTOM */
BOTTOM,
/** CENTER */
CENTER,
/** STRETCH */
STRETCH,
/** JUSTIFIED */
JUSTIFIED
}
@SuppressWarnings("javadoc")
public static final int textColorEnabled = 0, textColorShadowEnabled = 1, textColorDisabled = 2,
textColorShadowDisabled = 3, textColorHover = 4, textColorClicked = 5;
/** Array of text colors */
protected int color[] = { 0x000000, 0, 0x333333, 0, 0x000000, 0x000000 };
/** Parent widget */
protected PC_GresWidget parent = null;
/** List of children */
protected ArrayList<PC_GresWidget> childs = new ArrayList<PC_GresWidget>();
protected ArrayList<PC_GresWidgetTab> tabs = new ArrayList<PC_GresWidgetTab>();
/** Font renderer */
protected FontRenderer fontRenderer = null;
/** pos of left top corner */
protected PC_VecI pos = new PC_VecI(0, 0);
/** Widget size */
protected PC_VecI size = new PC_VecI(0, 0);
/** Minimal allowed widget size */
protected PC_VecI minSize = new PC_VecI(0, 0);
/** Distance from other widgets in group. */
protected int widgetMargin = 4;
/** Counter used for the automatic resizing */
protected int cursorCounter = 0;
/** Can add child widgets */
protected boolean canAddWidget = true;
/** Is mouse over this widget? */
protected boolean isMouseOver = false;
/** Is widget enabled = clickable */
protected boolean enabled = true;
/** Is widget focused (used mainly for text edits) */
protected boolean hasFocus = false;
/** Is visible */
protected boolean visible = true;
protected String textLangKey = "";
protected String textValue = "";
/** Widget's label (text in title or on button or whatever) */
protected String text = "";
/** Horizontal Align */
protected PC_GresAlign alignH = PC_GresAlign.CENTER;
/** Vertical Align */
protected PC_GresAlign alignV = PC_GresAlign.CENTER;
/** Container Manager */
protected PC_IGresGui gui = null;
/** Widget ID (general purpose) */
public int id = -1;
/** Additional widget tag (general purpose) */
public String tag = "";
protected String tooltipLangKey = "";
protected String tooltipValue = "";
protected String tooltip;
protected String tileEnityObjectKey;
/**
* A widget
*/
public PC_GresWidget() {
PC_VecI minSize = getMinSize();
this.size = minSize.copy();
this.minSize = minSize.copy();
}
/**
* A widget
*
* @param labelKey widget's label / text
*/
public PC_GresWidget(String labelKey) {
setTextLangKey(labelKey);
PC_VecI minSize = getMinSize();
this.size = minSize.copy();
this.minSize = minSize.copy();
}
/**
* A widget
*
* @param labelKey widget's label / text
* @param labelValue widget's label / text
*/
public PC_GresWidget(String labelKey, String langValue) {
setText(labelKey, langValue);
PC_VecI minSize = getMinSize();
this.size = minSize.copy();
this.minSize = minSize.copy();
}
/**
* A widget
*
* @param width widget minWidth
* @param height widget minHeight
*/
public PC_GresWidget(int width, int height) {
PC_VecI minSize = new PC_VecI(width, height);
this.size = minSize.copy();
this.minSize = minSize.copy();
}
/**
* A widget
*
* @param width widget minWidth
* @param height widget minHeight
* @param label widget label / text
*/
public PC_GresWidget(int width, int height, String labelKey) {
this(width, height);
setTextLangKey(labelKey);
}
/**
* A widget
*
* @param width widget minWidth
* @param height widget minHeight
* @param label widget label / text
*/
public PC_GresWidget(int width, int height, String labelKey, String langValue) {
this(width, height);
setText(labelKey, langValue);
}
/**
* Set visibility. Invisible widgets dont take space in layouts. Same as css
* display:none
*
* @param show flag visible
* @return this
*/
public PC_GresWidget setVisible(boolean show) {
visible = show;
updateVisible(show);
return this;
}
private void updateVisible(boolean show) {
visibleChanged(show);
for (PC_GresWidget w : childs) {
w.updateVisible(show);
}
for (PC_GresWidget w : tabs) {
w.updateVisible(show);
}
}
protected void visibleChanged(boolean show) {
}
public void setTileEnityObjectKey(String tileEnityObjectKey) {
this.tileEnityObjectKey = tileEnityObjectKey;
}
/**
* @return true if is visible
*/
public boolean isVisible() {
return visible;
}
/**
* Set widget ID
*
* @param id
* @return this
*/
public PC_GresWidget setId(int id) {
this.id = id;
return this;
}
/**
* Get widget ID
*
* @return id
*/
public int getId() {
return this.id;
}
/**
* Get widget tag
*
* @return tag
*/
public String getTag() {
return tag;
}
/**
* Set widget tag
*
* @param tag the tag
* @return this
*/
public PC_GresWidget setTag(String tag) {
this.tag = tag;
return this;
}
/**
* Get widget tooltip
*
* @return tooltip
*/
public String getTooltip() {
return tooltip;
}
/**
* Set widget tooltip
*
* @param tooltip the tooltip
* @return this
*/
public PC_GresWidget setTooltip(String tooltip) {
this.tooltip = tooltip;
return this;
}
public PC_GresWidget setTooltip(String tooltipLangKey, String tooltipValue) {
this.tooltipLangKey = tooltipLangKey;
this.tooltipValue = tooltipValue;
tooltip = PC_LangRegistry.tr(tooltipLangKey, tooltipValue);
return this;
}
public String getTooltipLangKey() {
return tooltipLangKey;
}
public PC_GresWidget setTooltipLangKey(String tooltipLangKey) {
this.tooltipLangKey = tooltipLangKey;
tooltip = PC_LangRegistry.tr(tooltipLangKey, tooltipValue);
return this;
}
public String getTooltipValue() {
return tooltipValue;
}
public PC_GresWidget setTooltipValue(String tooltipValue) {
this.tooltipValue = tooltipValue;
tooltip = PC_LangRegistry.tr(tooltipLangKey, tooltipValue);
return this;
}
/**
* @return widget's text / label
*/
public String getText() {
return text;
}
/**
* Set widget's label, resize if needed
*
* @param text new text / label
* @return this
*/
public PC_GresWidget setText(String text) {
this.text = text;
return this;
}
public PC_GresWidget setText(String textLangKey, String textValue) {
this.textLangKey = textLangKey;
this.textValue = textValue;
text = PC_LangRegistry.tr(textLangKey, textValue);
return this;
}
public String getTextLangKey() {
return textLangKey;
}
public PC_GresWidget setTextLangKey(String textLangKey) {
this.textLangKey = textLangKey;
text = PC_LangRegistry.tr(textLangKey, textValue);
return this;
}
public String getTextValue() {
return textValue;
}
public PC_GresWidget setTextValue(String textValue) {
this.textValue = textValue;
text = PC_LangRegistry.tr(textLangKey, textValue);
return this;
}
/**
* @return widget's font renderer
*/
public FontRenderer getFontRenderer() {
if (fontRenderer == null) {
return mc.fontRenderer;
}
return fontRenderer;
}
/**
* Set widget's font renderer
*
* @param fontRenderer the font renderer
* @return this
*/
public PC_GresWidget setFontRenderer(FontRenderer fontRenderer) {
this.fontRenderer = fontRenderer;
for (PC_GresWidget w : childs) {
w.setFontRenderer(fontRenderer);
}
for (PC_GresWidget w : tabs) {
w.setFontRenderer(fontRenderer);
}
return this;
}
/**
* Get horizontal align
*
* @return horizontal align
*/
public PC_GresAlign getAlignH() {
return alignH;
}
/**
* Set horizontal align
*
* @param alignHorizontal horizontal align
* @return this
*/
public PC_GresWidget setAlignH(PC_GresAlign alignHorizontal) {
this.alignH = alignHorizontal;
return this;
}
/**
* Get vertical align
*
* @return vertical align
*/
public PC_GresAlign getAlignV() {
return alignV;
}
/**
* Set vertical align
*
* @param alignVertical vertical align
* @return this
*/
public PC_GresWidget setAlignV(PC_GresAlign alignVertical) {
this.alignV = alignVertical;
return this;
}
/**
* @return has focus
*/
public boolean getFocus() {
return hasFocus;
}
/**
* Set focus state
*
* @param focus focused
* @return this
*/
public PC_GresWidget setFocus(boolean focus) {
this.hasFocus = focus;
return this;
}
/**
* Increment cursor counter, used for text field animations
*/
public void updateCursorCounter() {
cursorCounter++;
}
/**
* @return minimal size, {width,height}
*/
public PC_VecI getMinSize() {
if (!visible)
return new PC_VecI(0, 0);
return calcSize().copy();
}
/**
* @param minSize the minSize to set
* @return this
*/
public PC_GresWidget setMinSize(PC_VecI minSize) {
this.minSize = minSize;
return this;
}
/**
* set min size
*
* @param w width
* @param h height
* @return this
*/
public PC_GresWidget setMinSize(int w, int h) {
this.minSize.setTo(w, h, 0);
return this;
}
/**
* set min size width
*
* @param w width
* @return this
*/
public PC_GresWidget setMinWidth(int w) {
this.minSize.setTo(w, this.minSize.y, 0);
return this;
}
/**
* set min size height
*
* @param h height
* @return this
*/
public PC_GresWidget setMinHeight(int h) {
this.minSize.setTo(this.minSize.x, h, 0);
return this;
}
/**
* Set widget margin
*
* @param widgetMargin
* @return this
*/
public PC_GresWidget setWidgetMargin(int widgetMargin) {
this.widgetMargin = widgetMargin;
return this;
}
/**
* @return newly calculated size, {width, height}
*/
public abstract PC_VecI calcSize();
/**
* Get the Container Manager
*
* @return the Container Manager
*/
public PC_IGresGui getGui() {
return gui;
}
/**
* Set the Container Manager
*
* @param containerManager the new Container Manager
* @return this
*/
public PC_GresWidget setGui(PC_IGresGui gui) {
this.gui = gui;
for (PC_GresWidget w : childs) {
w.setGui(gui);
}
for (PC_GresWidget w : tabs) {
w.setGui(gui);
}
return this;
}
/**
* Get widget size
*
* @return {width, height}
*/
public PC_VecI getSize() {
if (!visible)
return new PC_VecI(0, 0);
return size.copy();
}
/**
* Set widget size
*
* @param width width
* @param height height
* @param calcParent flag whether to ask parent for position recalculation
* @return this
*/
public PC_GresWidget setSize(int width, int height, boolean calcParent) {
this.size.setTo(width, height, 0);
if (parent != null && calcParent) {
parent.calcChildPositions();
}
return this;
}
/**
* Set size, recalculate position
*
* @param width width
* @param height height
* @return this
*/
public PC_GresWidget setSize(int width, int height) {
return setSize(width, height, true);
}
/**
* Set size, recalculate position
*
* @param gswidth width
* @param gsheight height
* @return this
*/
public PC_GresWidget setSize(PC_VecI size) {
this.size.setTo(size);
return this;
}
/**
* Get position
*
* @return {x, y}
*/
public PC_VecI getPosition() {
return pos;
}
/**
* Set position of the widget
*
* @param x x
* @param y y
* @return this
*/
public PC_GresWidget setPosition(int x, int y) {
this.pos.setTo(x, y, 0);
return this;
}
/**
* @return is enabled?
*/
public boolean isEnabled() {
return enabled;
}
/**
* set "enabled" flag
*
* @param enabled state
* @return this
*/
public PC_GresWidget enable(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Refresh calculated children positions
*/
public abstract void calcChildPositions();
/**
* Default implementation of child position calculation
*/
public void calcChildPositionsDefault() {
int maxh = 0, xx = 0, yy = 0;
if (childs != null) {
for (int i = 0; i < childs.size(); i++) {
childs.get(i).calcChildPositions();
PC_VecI childSize = childs.get(i).calcSize();
if (!childs.get(i).isVisible())
childSize = new PC_VecI(0, 0);
if (childSize.y > maxh) {
maxh = childSize.y;
}
if (childSize.x > size.x || childSize.y > size.y) {
if (childSize.x > size.x) {
size.x = childSize.x;
}
if (childSize.y > size.y) {
size.y = childSize.y;
}
if (parent != null) {
parent.calcChildPositions();
}
calcChildPositions();
return;
}
if (xx + childSize.x > size.x) {
xx = 0;
yy += maxh + widgetMargin;
}
childs.get(i).setPosition(xx, yy);
xx += size.x + widgetMargin;
}
}
}
/**
* @return parent widget
*/
public PC_GresWidget getParent() {
return parent;
}
/**
* Add child widget
*
* @param newwidget new widget
* @return this
*/
public PC_GresWidget add(PC_GresWidget newwidget) {
if (newwidget instanceof PC_GresWidgetTab) {
newwidget.parent = this;
newwidget.setFontRenderer(fontRenderer);
newwidget.setGui(gui);
tabs.add((PC_GresWidgetTab) newwidget);
newwidget.callAddedToWidget();
return this;
}
if (!canAddWidget) {
return null;
}
newwidget.parent = this;
newwidget.setFontRenderer(fontRenderer);
newwidget.setGui(gui);
childs.add(newwidget);
newwidget.callAddedToWidget();
calcChildPositions();
return this;
}
/**
* Remove child widget, even from children's lists
*
* @param removewidget widget to remove from child list
* @return this
*/
public PC_GresWidget remove(PC_GresWidget removewidget) {
if (!childs.remove(removewidget)) {
for (int i = 0; i < childs.size(); i++) {
childs.get(i).remove(removewidget);
}
}
calcChildPositions();
return this;
}
/**
* Remove all children
*
* @return this
*/
public PC_GresWidget removeAll() {
childs.removeAll(childs);
if (parent != null) {
parent.calcChildPositions();
}
return this;
}
/**
* Set color to index
*
* @param colorIndex color index (constant)
* @param color the color, eg. 0xFFFFFF.
* @return this
*/
public PC_GresWidget setColor(int colorIndex, int color) {
if (colorIndex < 0 || colorIndex > 5) {
return this;
}
this.color[colorIndex] = color;
return this;
}
/**
* Get color for index
*
* @param colorIndex color index (constant)
* @return color number, eg. 0xFFFFFF
*/
public int getColor(int colorIndex) {
if (colorIndex < 0 || colorIndex > 5) {
return 0;
}
return color[colorIndex];
}
/**
* Get string length from font renderer
*
* @param text the string
* @return length in pixels
*/
public int getStringWidth(String text) {
FontRenderer fr = getFontRenderer();
return fr.getStringWidth(text);
}
/**
* Get char height
*
* @return height in pixels
*/
protected int getLineHeight() {
return getFontRenderer().FONT_HEIGHT;
}
/**
* Draw string, using colors from the color array.
*
* @param text text to draw (usually the label)
* @param x pos x
* @param y pos y
*/
protected void drawString(String text, int x, int y) {
FontRenderer fr = getFontRenderer();
if (color[enabled ? textColorShadowEnabled : textColorShadowDisabled] != 0) {
fr.drawString(text, x + 1, y + 1, color[enabled ? textColorShadowEnabled : textColorShadowDisabled]);
}
fr.drawString(text, x, y,
color[enabled ? (isMouseOver ? textColorHover : textColorEnabled) : textColorDisabled]);
}
/**
* Draw string, using overide color
*
* @param text text to draw (usually the label)
* @param x pos x
* @param y pos y
* @param colorOverride custom color
*/
protected void drawStringColor(String text, int x, int y, int colorOverride) {
FontRenderer fr = getFontRenderer();
if (color[enabled ? textColorShadowEnabled : textColorShadowDisabled] != 0) {
fr.drawString(text, x + 1, y + 1, color[enabled ? textColorShadowEnabled : textColorShadowDisabled]);
}
fr.drawString(text, x, y, colorOverride);
}
public static PC_RectI setDrawRect(PC_RectI old, PC_RectI _new, double scale) {
PC_RectI rect;
if (old == null) {
rect = _new.copy();
} else {
rect = old.averageQuantity(_new);
}
if (rect.width <= 0 || rect.height <= 0)
return null;
int h = mc.displayHeight;
GL11.glScissor((int) (rect.x * scale), h - (int) ((rect.y + rect.height) * scale), (int) (rect.width * scale),
(int) (rect.height * scale));
return rect;
}
/**
* Render this and all children at correct positions
*
* @param posOffset offset from top left
*/
public void updateRenderer(PC_VecI posOffset, PC_RectI scissorOld, double scale) {
if (!visible)
return;
tabRenderer(posOffset.offset(pos), null, scale);
PC_RectI scissorNew = setDrawRect(scissorOld,
new PC_RectI(posOffset.x + pos.x, posOffset.y + pos.y, size.x, size.y), scale);
if (scissorNew == null)
return;
PC_RectI rect = render(posOffset, scissorNew, scale);
if (rect != null)
scissorNew = setDrawRect(scissorNew, rect, scale);
childRenderer(posOffset.offset(pos), scissorNew, scale);
}
public void childRenderer(PC_VecI posOffset, PC_RectI scissorNew, double scale) {
if (childs != null) {
for (int i = 0; i < childs.size(); i++) {
if (childs.get(i).visible)
childs.get(i).updateRenderer(posOffset, scissorNew, scale);
}
}
}
public void tabRenderer(PC_VecI posOffset, PC_RectI scissorNew, double scale) {
if (tabs != null) {
int y = 5;
for (int i = 0; i < tabs.size(); i++) {
if (tabs.get(i).visible) {
tabs.get(i).setPosition(size.x - 2, y);
tabs.get(i).updateRenderer(posOffset, scissorNew, scale);
y += tabs.get(i).getSize().y + 2;
}
}
}
}
/**
* Do render this widget
*
* @param posOffset offset from top left
*/
protected abstract PC_RectI render(PC_VecI posOffset, PC_RectI scissorOld, double scale);
/**
* Get the widget under mouse cursor. First tries children, then self, null at
* last.
*
* @param mousePos mouse absolute x
* @return the widget under mouse
*/
public PC_GresWidget getWidgetUnderMouse(PC_VecI mousePos) {
if (!visible)
return null;
PC_GresWidget widget;
PC_VecI mpos = mousePos.copy().add(-pos.x, -pos.y, 0);
MouseOver mo = MouseOver.NON;
// mouse not over this widget
if (mpos.x < 0 || mpos.x >= getSize().x || mpos.y < 0 || mpos.y >= getSize().y
|| (mo = mouseOver(mpos)) != MouseOver.CHILD) {
this.isMouseOver = false;
if (childs != null) {
for (int i = 0; i < childs.size(); i++) {
childs.get(i).getWidgetUnderMouse(new PC_VecI(-1, -1));
}
for (int i = 0; i < childs.size(); i++) {
childs.get(i).getTabUnderMouse(new PC_VecI(-1, -1));
}
}
if (mo == MouseOver.THIS) {
this.isMouseOver = true;
return this;
}
return getTabUnderMouse(mousePos);
}
this.isMouseOver = true;
if (childs != null) {
for (int i = 0; i < childs.size(); i++) {
widget = childs.get(i).getWidgetUnderMouse(mpos);
if (widget != null) {
for (i++; i < childs.size(); i++) {
childs.get(i).getWidgetUnderMouse(new PC_VecI(-1, -1));
}
for (i = 0; i < childs.size(); i++) {
childs.get(i).getTabUnderMouse(new PC_VecI(-1, -1));
}
return widget;
}
}
}
return this;
}
public PC_GresWidget getTabUnderMouse(PC_VecI mousePos) {
if (!visible)
return null;
PC_GresWidget widget;
PC_VecI mpos = mousePos.copy().add(-pos.x, -pos.y, 0);
if (childs != null) {
for (int i = 0; i < childs.size(); i++) {
widget = childs.get(i).getTabUnderMouse(mpos);
if (widget != null) {
for (i++; i < childs.size(); i++) {
childs.get(i).getTabUnderMouse(new PC_VecI(-1, -1));
}
return widget;
}
}
}
if (tabs != null) {
for (int i = 0; i < tabs.size(); i++) {
widget = tabs.get(i).getWidgetUnderMouse(mpos);
if (widget != null) {
for (i++; i < tabs.size(); i++) {
tabs.get(i).getWidgetUnderMouse(new PC_VecI(-1, -1));
}
return widget;
}
}
}
return null;
}
/**
* Get absolute position on screen
*
* @return coord of top left.
*/
public PC_VecI getPositionOnScreen() {
PC_VecI position;
if (parent != null) {
position = parent.getPositionOnScreen().copy().add(pos);
} else {
position = pos.copy();
}
return position;
}
/**
* Render textured rect with Alpha support at given position.
*
* @param offset offset relative to root top left
* @param texture texture to render (filename)
* @param rectSize size of the rendered texture
* @param imgOffset offset within the texture image (from top left)
*/
protected void renderImage(PC_VecI offset, String texture, PC_VecI rectSize, PC_VecI imgOffset) {
renderImage_static(this, texture, offset.offset(pos), rectSize, imgOffset);
}
/**
* Render textured rect with Alpha support at given position.
*
* @param gui the gui being drawed on
* @param texture texture to render (filename)
* @param startPos left top corner absolute position
* @param rectSize size of the rendered texture
* @param imgOffset offset within the texture image (from top left)
*/
protected static void renderImage_static(Gui gui, String texture, PC_VecI startPos, PC_VecI rectSize,
PC_VecI imgOffset) {
mc.renderEngine.bindTexture(new ResourceLocation(mod_PowerCraft.MODID, texture));
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
gui.drawTexturedModalRect(startPos.x, startPos.y, imgOffset.x, imgOffset.y, rectSize.x, rectSize.y);
GL11.glDisable(GL11.GL_BLEND);
}
/**
* Render texture using 9patch-like scaling method.<br>
*
* @param offset offset relative to root top left
* @param texture texture to render (filename)
* @param rectSize rectangle size
* @param imgOffset offset within the texture image (from top left)
* @param imgSize size of the whole "scalable" region in texture file (eg. the
* whole huge "button" field)
*/
protected void renderTextureSliced(PC_VecI offset, String texture, PC_VecI rectSize, PC_VecI imgOffset,
PC_VecI imgSize) {
renderTextureSliced_static(this, offset.offset(pos), texture, rectSize, imgOffset, imgSize,
new PC_RectI(0, 0, 0, 0));
}
protected void renderTextureSliced(PC_VecI offset, String texture, PC_VecI rectSize, PC_VecI imgOffset,
PC_VecI imgSize, PC_RectI frame) {
renderTextureSliced_static(this, offset.offset(pos), texture, rectSize, imgOffset, imgSize, frame);
}
protected void renderTextureSlicedColored(PC_VecI offset, String texture, PC_VecI rectSize, PC_VecI imgOffset,
PC_VecI imgSize) {
renderTextureSliced_static(this, offset.offset(pos), texture, rectSize, imgOffset, imgSize,
new PC_RectI(0, 0, 0, 0),
color[enabled ? (isMouseOver ? textColorHover : textColorEnabled) : textColorDisabled]);
}
protected void renderTextureSlicedColored(PC_VecI offset, String texture, PC_VecI rectSize, PC_VecI imgOffset,
PC_VecI imgSize, PC_RectI frame) {
renderTextureSliced_static(this, offset.offset(pos), texture, rectSize, imgOffset, imgSize, frame,
color[enabled ? (isMouseOver ? textColorHover : textColorEnabled) : textColorDisabled]);
}
/**
* Render texture using 9patch-like scaling method.<br>
*
* @param gui the gui being drawed on
* @param startPos offset relative to parent top left
* @param texture texture to render (filename)
* @param rectSize rectangle size
* @param imgOffset offset within the texture image (from top left)
* @param imgSize size of the whole "scalable" region in texture file (eg. the
* whole huge "button" field)
*/
protected static void renderTextureSliced_static(Gui gui, PC_VecI startPos, String texture, PC_VecI rectSize,
PC_VecI imgOffset, PC_VecI imgSize) {
renderTextureSliced_static(gui, startPos, texture, rectSize, imgOffset, imgSize, new PC_RectI(0, 0, 0, 0));
}
private static void renderTextureSliced_static(Gui gui, PC_VecI startPos, PC_VecI rectSize, PC_VecI imgOffset,
PC_VecI imgSize) {
for (int x = 0; x < rectSize.x; x += imgSize.x) {
for (int y = 0; y < rectSize.y; y += imgSize.y) {
int sx = imgSize.x;
int sy = imgSize.y;
if (x + sx > rectSize.x) {
sx = rectSize.x - x;
}
if (y + sy > rectSize.y) {
sy = rectSize.y - y;
}
gui.drawTexturedModalRect(startPos.x + x, startPos.y + y, imgOffset.x, imgOffset.y, sx, sy);
}
}
}
protected static void renderTextureSliced_static(Gui gui, PC_VecI startPos, String texture, PC_VecI rectSize,
PC_VecI imgOffset, PC_VecI imgSize, PC_RectI frame) {
renderTextureSliced_static(gui, startPos, texture, rectSize, imgOffset, imgSize, frame, 0xFFFFFFFF);
}
protected static void renderTextureSliced_static(Gui gui, PC_VecI startPos, String texture, PC_VecI rectSize,
PC_VecI imgOffset, PC_VecI imgSize, PC_RectI frame, int color) {
GL11.glColor4f(PC_Color.red(color), PC_Color.green(color), PC_Color.blue(color), 1.0f);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
mc.getTextureManager().bindTexture(new ResourceLocation(mod_PowerCraft.MODID, texture));
if (frame.y > 0) {
if (frame.x > 0) {
gui.drawTexturedModalRect(startPos.x, startPos.y, imgOffset.x, imgOffset.y, frame.x, frame.y);
}
renderTextureSliced_static(gui, new PC_VecI(startPos.x + frame.x, startPos.y),
new PC_VecI(rectSize.x - frame.x - frame.width, frame.y),
new PC_VecI(imgOffset.x + frame.x, imgOffset.y),
new PC_VecI(imgSize.x - frame.x - frame.width, imgSize.y));
if (frame.width > 0) {
gui.drawTexturedModalRect(startPos.x + rectSize.x - frame.width, startPos.y, imgSize.x - frame.width,
imgOffset.y, frame.width, frame.y);
}
}
if (frame.x > 0) {
renderTextureSliced_static(gui, new PC_VecI(startPos.x, startPos.y + frame.y),
new PC_VecI(frame.x, rectSize.y - frame.y - frame.height),
new PC_VecI(imgOffset.x, imgOffset.y + frame.y),
new PC_VecI(imgSize.x, imgSize.y - frame.y - frame.height));
}
renderTextureSliced_static(gui, new PC_VecI(startPos.x + frame.x, startPos.y + frame.y),
new PC_VecI(rectSize.x - frame.x - frame.width, rectSize.y - frame.y - frame.height),
new PC_VecI(imgOffset.x + frame.x, imgOffset.y + frame.y),
new PC_VecI(imgSize.x - frame.x - frame.width, imgSize.y - frame.y - frame.height));
if (frame.width > 0) {
renderTextureSliced_static(gui, new PC_VecI(startPos.x + rectSize.x - frame.width, startPos.y + frame.y),
new PC_VecI(frame.width, rectSize.y - frame.y - frame.height),
new PC_VecI(imgOffset.x + imgSize.x - frame.width, imgOffset.y + frame.y),
new PC_VecI(frame.width, imgSize.y - frame.y - frame.height));
}
if (frame.height > 0) {
if (frame.x > 0) {
gui.drawTexturedModalRect(startPos.x, startPos.y + rectSize.y - frame.height, imgOffset.x,
imgOffset.y + imgSize.y - frame.height, frame.x, frame.height);
}
renderTextureSliced_static(gui, new PC_VecI(startPos.x + frame.x, startPos.y + rectSize.y - frame.height),
new PC_VecI(rectSize.x - frame.x - frame.width, frame.height),
new PC_VecI(imgOffset.x + frame.x, imgOffset.y + imgSize.y - frame.height),
new PC_VecI(imgSize.x - frame.x - frame.width, frame.height));
if (frame.width > 0) {
gui.drawTexturedModalRect(startPos.x + rectSize.x - frame.width, startPos.y + rectSize.y - frame.height,
imgOffset.x + imgSize.x - frame.width, imgOffset.y + imgSize.y - frame.height, frame.width,
frame.height);
}
}
GL11.glDisable(GL11.GL_BLEND);
}
protected static void drawTexturedModalRectWithIcon(int x, int y, int sizeX, int sizeY, IIcon icon,
String texture) {
Tessellator tessellator = Tessellator.instance;
float f3 = icon.getMinU();
float f4 = icon.getMaxU();
float f5 = icon.getMinV();
float f6 = icon.getMaxV();
tessellator.startDrawingQuads();
tessellator.setNormal(0.0F, 1.0F, 0.0F);
tessellator.addVertexWithUV(x, y + sizeY, 0.0D, (double) f3, (double) f6);
tessellator.addVertexWithUV(x + sizeX, y + sizeY, 0.0D, (double) f4, (double) f6);
tessellator.addVertexWithUV(x + sizeX, y, 0.0D, (double) f4, (double) f5);
tessellator.addVertexWithUV(x, y, 0.0D, (double) f3, (double) f5);
tessellator.draw();
}
/**
* Check if mouse is over widget.<br>
* The given coordinate is relative to widget's top left corner.
*
* @param mousePos mouse position
* @return is over
*/
public abstract MouseOver mouseOver(PC_VecI mousePos);
/**
* Mouse clicked on widget.
*
* @param mousePos mouse position
* @param key mouse button index, -1 = mouse up.
* @return event accepted
*/
public abstract boolean mouseClick(PC_VecI mousePos, int key);
/**
* On mouse moved. Last focused widget gets mouse move events.
*
* @param mousePos current mouse position.
*/
public abstract void mouseMove(PC_VecI mousePos);
/**
* On mouse wheel moved. Last focused widget gets wheel move events.
*
* @param i wheelmoved direction
*/
public abstract void mouseWheel(int i);
/**
* On key pressed.
*
* @param c character of the key
* @param key key index
* @return true if key was valid and was used.
*/
public abstract boolean keyTyped(char c, int key);
/**
* Called when Widget added to another widget
*/
public void callAddedToWidget() {
addedToWidget();
for (PC_GresWidget w : childs) {
w.callAddedToWidget();
}
}
/**
* Called when Widget added to another widget
*/
public abstract void addedToWidget();
protected static void drawButton(PC_GresWidget widget, PC_VecI pos, PC_VecI size, String text, int state) {
int txC = 0xe0e0e0;
if (state == 0) {
txC = 0xa0a0a0; // dark
}
if (state == 1) {
txC = 0xe0e0e0; // light
}
if (state > 1) {
txC = 0xffffa0; // yellow
}
renderTextureSliced_static(widget, pos, imgdir + "button.png", size, new PC_VecI(0, state * 50),
new PC_VecI(256, 50), new PC_RectI(2, 2, 2, 3));
widget.drawCenteredString(widget.getFontRenderer(), text, pos.x + size.x / 2,
pos.y + (size.y - widget.getFontRenderer().FONT_HEIGHT) / 2, txC);
}
public Slot getSlotUnderMouse(PC_VecI mousePos) {
return null;
}
public List<String> getTooltip(PC_VecI mousePos) {
if (tooltip == null || tooltip.equals("")) {
return null;
}
List<String> l = new ArrayList<String>();
l.add(tooltip);
return l;
}
public void keyChange(String key, Object value) {
if (key.equals(tileEnityObjectKey)) {
onObjectChange(value);
}
for (PC_GresWidget w : childs) {
w.keyChange(key, value);
}
}
protected void onObjectChange(Object value) {
}
public void tick() {
if (childs != null) {
for (int i = 0; i < childs.size(); i++) {
childs.get(i).tick();
}
}
if (tabs != null) {
for (int i = 0; i < tabs.size(); i++) {
tabs.get(i).tick();
}
}
onTick();
}
protected void onTick() {
}
}
|
package fonts
import (
"fmt"
"github.com/faiface/pixel"
"github.com/faiface/pixel/text"
"github.com/golang/freetype/truetype"
"image/color"
"io/ioutil"
"os"
"retro-carnage/engine/geometry"
"retro-carnage/logging"
"unicode"
)
const (
defaultFontPath = "./fonts/XXII-DIRTY-ARMY.ttf"
maxFontSize = 52
)
var (
SizeToFontAtlas map[int]*text.Atlas
textDimensionCache map[string]*geometry.Point
windowWidth float64
)
func Initialize(width float64) {
SizeToFontAtlas = make(map[int]*text.Atlas)
textDimensionCache = make(map[string]*geometry.Point)
windowWidth = width
defaultFont, err := loadTTF(defaultFontPath)
if nil != err {
logging.Error.Panicf("Failed to load font %s: %v", defaultFontPath, err)
}
for i := 12; i <= maxFontSize; i += 2 {
var fontFace = truetype.NewFace(defaultFont, &truetype.Options{
Size: float64(i),
GlyphCacheEntries: 1,
})
SizeToFontAtlas[i] = text.NewAtlas(fontFace, text.ASCII, text.RangeTable(unicode.Latin))
}
}
func DefaultFontSize() int {
if windowWidth <= 1024 {
return 24
}
if windowWidth <= 1280 {
return 26
}
if windowWidth <= 1440 {
return 28
}
if windowWidth <= 1600 {
return 30
}
if windowWidth <= 2560 {
return 36
}
if windowWidth <= 3440 {
return 48
}
return maxFontSize
}
func loadTTF(path string) (*truetype.Font, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
bytes, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
font, err := truetype.Parse(bytes)
if err != nil {
return nil, err
}
return font, nil
}
func GetTextDimensions(fontSize int, input ...string) map[string]*geometry.Point {
var result = make(map[string]*geometry.Point)
for _, line := range input {
result[line] = GetTextDimension(fontSize, line)
}
return result
}
func GetTextDimension(fontSize int, input string) *geometry.Point {
var key = fmt.Sprintf("%d___%s", fontSize, input)
var value = textDimensionCache[key]
if nil == value {
var txt = text.New(pixel.V(0, 0), SizeToFontAtlas[fontSize])
_, _ = fmt.Fprint(txt, input)
value = &geometry.Point{X: txt.Bounds().W(), Y: txt.Bounds().H()}
textDimensionCache[key] = value
}
return value
}
func GetMaxTextWidth(fontSize int, input []string) float64 {
var txt = text.New(pixel.V(0, 0), SizeToFontAtlas[fontSize])
for _, line := range input {
_, _ = fmt.Fprintln(txt, line)
}
return txt.Bounds().W()
}
func BuildText(position pixel.Vec, fontSize int, color color.Color, content string) *text.Text {
var txt = text.New(position, SizeToFontAtlas[fontSize])
txt.Color = color
_, _ = fmt.Fprint(txt, content)
return txt
}
func BuildMultiLineText(position pixel.Vec, fontSize int, color color.Color, content []string) *text.Text {
var txt = text.New(position, SizeToFontAtlas[fontSize])
txt.Color = color
for _, line := range content {
_, _ = fmt.Fprintln(txt, line)
}
return txt
}
|
namespace Assets.Scripts.Manager.Input
{
/// <summary>
/// UI用のマップIDを定義する定数クラス
/// </summary>
public static class UIMapId
{
public const int Menu = 1;
public const int Num = 1;
}
/// <summary>
/// キャラクター用のマップIDを定義する定数クラス
/// </summary>
public static class PMapId
{
public const int Normal = 1;
public const int Num = 1;
}
}
|
#!/bin/sh
mkdir -p result
dataset="kdd"
#dataset="synthetic"
T=11
P=10
Q=5
R1=100
R2=10000
K=20
theta=0.01
./blesimrank $dataset $T $P $Q $R1 $R2 $K $theta | tee info.log |ccze
|
package api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// CreateAlertRequest the API request to be made to
// create a victorops alert
type CreateAlertRequest struct {
MessageType MessageType `json:"message_type,omitempty"`
EntityID string `json:"entity_id,omitempty"`
EntityDisplayName string `json:"entity_display_name,omitempty"`
StateMessage string `json:"state_message,omitempty"`
StateStartTime int64 `json:"state_start_time,omitempty"`
TriggerURL string `json:"trigger_url,omitempty"`
ImageURL string `json:"image_url,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
MonitoringTool string `json:"monitoring_tool,omitempty"`
}
// MessageType is the type of a victorops alert
type MessageType string
// Various possible MessageTypes
const (
Critical MessageType = "CRITICAL"
Warning MessageType = "WARNING"
Acknowledgement MessageType = "ACKNOWLEDGEMENT"
Info MessageType = "INFO"
Recovery MessageType = "RECOVERY"
)
// CreateAlert creates a new alert in the victorops timeline
func (client *Client) CreateAlert(routingKey string, alert CreateAlertRequest) error {
if alert.MessageType == "" {
return fmt.Errorf("field MessageType cannot be empty")
}
body, err := json.Marshal(alert)
if err != nil {
return fmt.Errorf("error while encoding json: %s", err)
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/%s", client.routingURL, routingKey), bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
resp, err := client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("error while making the request to victorops: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 { //nolint
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("victorops API request resulted in error with status %v: %v", resp.StatusCode, string(body))
}
return nil
}
|
using Commander.NET.Attributes;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZemberekDotNet.Classification;
using ZemberekDotNet.Core;
using static ZemberekDotNet.Core.Embeddings.FastText;
namespace ZemberekDotNet.Apps.FastText
{
public class EvaluateClassifier : ConsoleApp<EvaluateClassifier>
{
[Parameter("--input", "-i",
Required = Required.Yes,
Description = "Input test set with correct labels.")]
string input;
[Parameter("--model", "-m",
Required = Required.Yes,
Description = "Model file.")]
string model;
[Parameter("--output", "-o",
Description = "Output file where prediction results will be written."
+ " If not provided, [input].predictions will be generated.")]
string predictions;
[Parameter("--maxPrediction", "-k",
Description = "Amount of top predictions. "
+ "Predictions with lower than --threshold values will not be included.")]
int maxPrediction = 1;
[Parameter("--threshold", "th",
Description = "Minimum score threshold. Lower values will not be included in predictions.")]
float threshold = -100f;
public override string Description()
{
return "Evaluates classifier with a test set.";
}
public override void Run()
{
Console.WriteLine("Loading classification model...");
FastTextClassifier classifier = FastTextClassifier.Load(model);
EvaluationResult result = classifier.Evaluate(input, maxPrediction, threshold);
Console.WriteLine("Result = " + result.ToString());
if (predictions == null)
{
string name = Path.GetFileName(input);
predictions = Path.GetFullPath(name + ".predictions");
}
string[] testLines = File.ReadAllLines(input, Encoding.UTF8);
try
{
using (FileStream fs = File.OpenWrite(predictions))
{
using (StreamWriter pw = new StreamWriter(fs, Encoding.UTF8))
{
foreach (string testLine in testLines)
{
List<ScoredItem<String>> res = classifier.Predict(testLine, maxPrediction);
res = res.Where(s => s.Score >= threshold).ToList();
List<String> predictedCategories = new List<string>();
foreach (ScoredItem<string> re in res)
{
predictedCategories.Add(string.Format(CultureInfo.InvariantCulture, "{0} ({1:N6})",
re.Item.Replace("__label__", ""),
Math.Exp(re.Score)));
}
pw.WriteLine(testLine);
pw.WriteLine("Predictions = " + String.Join(", ", predictedCategories));
pw.WriteLine();
}
}
}
}
catch
{
}
Console.WriteLine("Predictions are written to " + predictions);
}
}
}
|
using System;
using System.Diagnostics;
using System.Windows.Forms;
using ResourceManager;
namespace GitExtensions.AzureDevOpsCommitMessage
{
public class LinkLabelOpener : LinkLabel
{
private static readonly string LinkInvalid = new TranslationString("The link to open is invalid").Text;
private static readonly string OpenLinkFailed = new TranslationString("Fail to open the link").Text;
public LinkLabelOpener()
{
Click += LinkLabelOpener_Click;
}
private void LinkLabelOpener_Click(object sender, EventArgs e)
{
OpenLink();
}
public void OpenLink()
{
if (Tag == null || !(Tag is string url) || string.IsNullOrWhiteSpace(url))
{
MessageBox.Show(LinkInvalid);
return;
}
try
{
Process.Start(url);
}
catch (Exception)
{
MessageBox.Show(OpenLinkFailed);
}
}
}
}
|
module DatabaseTransactions
extend ActiveSupport::Concern
included do
around_action :wrap_in_transaction, if: :should_wrap_in_transaction?
end
def wrap_in_transaction
ActiveRecord::Base.transaction do
yield if block_given?
end
end
def should_wrap_in_transaction?
request.put? || request.patch? || request.post?
end
end
|
namespace Melville.FileSystem
{
/// <summary>
// Converts a file path into an IFile
/// </summary>
public interface IDiskFileSystemConnector
{
/// <summary>
/// Returns an IFile corresponding to a given file path
/// </summary>
/// <param name="path">the path of the file to retrieve</param>
/// <returns>An IFile instance representing that file, which may not exist.</returns>
IFile FileFromPath(string path);
IDirectory DirectoryFromPath(string path);
}
public class DiskFileSystemConnector : IDiskFileSystemConnector
{
public IFile FileFromPath(string path) => new FileSystemFile(path);
public IDirectory DirectoryFromPath(string path) => new FileSystemDirectory(path);
}
}
|
package com.prasan.kotlinmvvmhiltflowapp.data.datamodel
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Photo(
@Json(name = "aperture")
val aperture: String?,
@Json(name = "camera")
val camera: String?,
@Json(name = "category")
val category: Int?,
@Json(name = "comments_count")
val commentsCount: Int?,
@Json(name = "created_at")
val createdAt: String?,
@Json(name = "description")
val description: String?,
@Json(name = "editored_by")
val editoredBy: Any?,
@Json(name = "editors_choice")
val editorsChoice: Boolean?,
@Json(name = "editors_choice_date")
val editorsChoiceDate: Any?,
@Json(name = "feature")
val feature: String?,
@Json(name = "feature_date")
val featureDate: String?,
@Json(name = "fill_switch")
val fillSwitch: FillSwitch,
@Json(name = "focal_length")
val focalLength: String?,
@Json(name = "has_nsfw_tags")
val hasNsfwTags: Boolean,
@Json(name = "height")
val height: Int,
@Json(name = "highest_rating")
val highestRating: Double?,
@Json(name = "highest_rating_date")
val highestRatingDate: String?,
@Json(name = "id")
val id: Int?,
@Json(name = "image_format")
val imageFormat: String?,
@Json(name = "image_url")
val imageUrl: List<String>?,
@Json(name = "images")
val images: List<Image>,
@Json(name = "iso")
val iso: String?,
@Json(name = "latitude")
val latitude: Double?,
@Json(name = "lens")
val lens: String?,
@Json(name = "liked")
val liked: Any?,
@Json(name = "location")
val location: String?,
@Json(name = "longitude")
val longitude: Double?,
@Json(name = "name")
val name: String?,
@Json(name = "nsfw")
val nsfw: Boolean?,
@Json(name = "positive_votes_count")
val positiveVotesCount: Int?,
@Json(name = "privacy")
val privacy: Boolean?,
@Json(name = "privacy_level")
val privacyLevel: Int?,
@Json(name = "profile")
val profile: Boolean?,
@Json(name = "rating")
val rating: Double?,
@Json(name = "shutter_speed")
val shutterSpeed: String?,
@Json(name = "status")
val status: Int?,
@Json(name = "taken_at")
val takenAt: Any?,
@Json(name = "times_viewed")
val timesViewed: Int?,
@Json(name = "url")
val url: String?,
@Json(name = "user")
val user: User?,
@Json(name = "user_id")
val userId: Int?,
@Json(name = "voted")
val voted: Any?,
@Json(name = "votes_count")
val votesCount: Int?,
@Json(name = "watermark")
val watermark: Boolean?,
@Json(name = "width")
val width: Int?
)
|
use crate::{
constants::*,
nlas::{WgPeer, WgPeerAttrs},
};
use anyhow::Context;
use byteorder::{ByteOrder, NativeEndian};
use netlink_packet_utils::{
nla::{Nla, NlaBuffer, NlasIterator},
parsers::*,
traits::*,
DecodeError,
};
use std::{convert::TryInto, mem::size_of_val};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WgDeviceAttrs {
Unspec(Vec<u8>),
IfIndex(u32),
IfName(String),
PrivateKey([u8; WG_KEY_LEN]),
PublicKey([u8; WG_KEY_LEN]),
ListenPort(u16),
Fwmark(u32),
Peers(Vec<WgPeer>),
Flags(u32),
}
impl Nla for WgDeviceAttrs {
fn value_len(&self) -> usize {
match self {
WgDeviceAttrs::Unspec(bytes) => bytes.len(),
WgDeviceAttrs::IfIndex(v) => size_of_val(v),
WgDeviceAttrs::IfName(v) => v.as_bytes().len() + 1,
WgDeviceAttrs::PrivateKey(v) => size_of_val(v),
WgDeviceAttrs::PublicKey(v) => size_of_val(v),
WgDeviceAttrs::ListenPort(v) => size_of_val(v),
WgDeviceAttrs::Fwmark(v) => size_of_val(v),
WgDeviceAttrs::Peers(nlas) => nlas.iter().map(|op| op.buffer_len()).sum(),
WgDeviceAttrs::Flags(v) => size_of_val(v),
}
}
fn kind(&self) -> u16 {
match self {
WgDeviceAttrs::Unspec(_) => WGDEVICE_A_UNSPEC,
WgDeviceAttrs::IfIndex(_) => WGDEVICE_A_IFINDEX,
WgDeviceAttrs::IfName(_) => WGDEVICE_A_IFNAME,
WgDeviceAttrs::PrivateKey(_) => WGDEVICE_A_PRIVATE_KEY,
WgDeviceAttrs::PublicKey(_) => WGDEVICE_A_PUBLIC_KEY,
WgDeviceAttrs::ListenPort(_) => WGDEVICE_A_LISTEN_PORT,
WgDeviceAttrs::Fwmark(_) => WGDEVICE_A_FWMARK,
WgDeviceAttrs::Peers(_) => WGDEVICE_A_PEERS,
WgDeviceAttrs::Flags(_) => WGDEVICE_A_FLAGS,
}
}
fn emit_value(&self, buffer: &mut [u8]) {
match self {
WgDeviceAttrs::Unspec(bytes) => buffer.copy_from_slice(bytes),
WgDeviceAttrs::IfIndex(v) => NativeEndian::write_u32(buffer, *v),
WgDeviceAttrs::IfName(s) => {
buffer[..s.len()].copy_from_slice(s.as_bytes());
buffer[s.len()] = 0;
}
WgDeviceAttrs::PrivateKey(v) => buffer.copy_from_slice(v),
WgDeviceAttrs::PublicKey(v) => buffer.copy_from_slice(v),
WgDeviceAttrs::ListenPort(v) => NativeEndian::write_u16(buffer, *v),
WgDeviceAttrs::Fwmark(v) => NativeEndian::write_u32(buffer, *v),
WgDeviceAttrs::Peers(nlas) => {
let mut len = 0;
for op in nlas {
op.emit(&mut buffer[len..]);
len += op.buffer_len();
}
}
WgDeviceAttrs::Flags(v) => NativeEndian::write_u32(buffer, *v),
}
}
fn is_nested(&self) -> bool {
matches!(self, WgDeviceAttrs::Peers(_))
}
}
impl<'a, T: AsRef<[u8]> + ?Sized> Parseable<NlaBuffer<&'a T>> for WgDeviceAttrs {
fn parse(buf: &NlaBuffer<&'a T>) -> Result<Self, DecodeError> {
let payload = buf.value();
Ok(match buf.kind() {
WGDEVICE_A_UNSPEC => Self::Unspec(payload.to_vec()),
WGDEVICE_A_IFINDEX => {
Self::IfIndex(parse_u32(payload).context("invalid WGDEVICE_A_IFINDEX value")?)
}
WGDEVICE_A_IFNAME => {
Self::IfName(parse_string(payload).context("invalid WGDEVICE_A_IFNAME value")?)
}
WGDEVICE_A_PRIVATE_KEY => Self::PrivateKey(
payload
.try_into()
.context("invalid WGDEVICE_A_PRIVATE_KEY value")?,
),
WGDEVICE_A_PUBLIC_KEY => Self::PublicKey(
payload
.try_into()
.context("invalid WGDEVICE_A_PUBLIC_KEY value")?,
),
WGDEVICE_A_LISTEN_PORT => Self::ListenPort(
parse_u16(payload).context("invalid WGDEVICE_A_LISTEN_PORT value")?,
),
WGDEVICE_A_FWMARK => {
Self::Fwmark(parse_u32(payload).context("invalid WGDEVICE_A_FWMARK value")?)
}
WGDEVICE_A_PEERS => {
let error_msg = "failed to parse WGDEVICE_A_PEERS";
let mut peers = Vec::new();
for nlas in NlasIterator::new(payload) {
let nlas = &nlas.context(error_msg)?;
let mut group = Vec::new();
for nla in NlasIterator::new(nlas.value()) {
let nla = &nla.context(error_msg)?;
let parsed = WgPeerAttrs::parse(nla).context(error_msg)?;
group.push(parsed);
}
peers.push(WgPeer(group));
}
Self::Peers(peers)
}
WGDEVICE_A_FLAGS => {
Self::Flags(parse_u32(payload).context("invalid WGDEVICE_A_FLAGS value")?)
}
kind => return Err(DecodeError::from(format!("invalid NLA kind: {}", kind))),
})
}
}
|
#!/bin/sh
write_file() {
eval touch DB.txt
echo "Type the first name and phone number"
eval cat >DB.txt
}
write_file
exit 0
|
:- module(main, []).
/** <module> The main module */
:- use_module(library(bc/bc_env)).
:- dynamic(started/0).
% Catch uncaught errors/warnings before start and shut down
% when they occur.
user:message_hook(Term, Type, _):-
\+ started,
( Type = error ; Type = warning ),
message_to_string(Term, String),
writeln(user_error, String),
halt(1).
:- use_module(library(bc/bc_main)).
:- use_module(library(bc/bc_type)).
:- use_module(lib/routes).
:- use_module(lib/config).
:- use_module(library(bc/bc_router)).
:- use_module(library(bc/bc_data)).
:- use_module(library(http/http_unix_daemon)).
:- use_module(library(http/thread_httpd)).
% Enables preview for posts.
:- bc_register_preview(post, '/post/<slug>').
% Initialize the serving daemon.
http_unix_daemon:http_server_hook(Options):-
assertz(started),
config(db, File),
bc_data_open(File),
http_server(bc_route, Options).
|
import 'base.dart';
import 'package:ynab/extensions/ynab_datetime.dart';
import 'response.dart';
class MonthsApi extends BaseApi {
MonthsApi(Configuration configuration) : super(configuration);
Future<YNABResponse> getMonths(
String budgetId, [
int lastKnowledgeOfServer,
]) =>
makeRequest(
path: '/v1/budgets/$budgetId/months',
lastKnowledgeOfServer: lastKnowledgeOfServer,
);
Future<YNABResponse> getBudgetMonth(
String budgetId,
DateTime date, [
int lastKnowledgeOfServer,
]) {
final firstOfMonthDate = DateTime(date.year, date.month, 1);
return makeRequest(
path: '/v1/budgets/$budgetId/months/${firstOfMonthDate.toYNABFormat()}',
lastKnowledgeOfServer: lastKnowledgeOfServer,
);
}
}
|
package com.booking.pages;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.booking.utilities.PropertyManager.getProperty;
public class GetawaySalePage extends BasePageObject {
private static final String GETAWAY_SALE_TOPIC = getProperty("main.page.banner1.topic");
private By BASE_ELEMENT = By.xpath("//div[@class='deals-page-header-text']/h1");
private String buiBox = "//div[@class='bui-box']";
private By GETAWAY_DEAL = By.xpath(buiBox);
private String getawayIcon = "(%s//*[@class='bui-badge bui-badge--callout'])[%d]";
private String getawayPrice= "(%s//*[@class='deal-price-card'])[%d]";
private List<Integer> prices = new ArrayList<Integer>();
GetawaySalePage(WebDriver driver, Logger log) {
super(driver, log);
}
@Override
public void isOpenedRightPage() {
log.info("Checking that opened right page: GetawaySalePage");
Assert.assertEquals(find(BASE_ELEMENT).getText(), GETAWAY_SALE_TOPIC, "Invalid page open");
}
public ResultPage chooseTheCheapestOffer() {
log.info("Check offers and find the cheapest");
List<WebElement> getawayDeals = findAll(GETAWAY_DEAL);
for (int i = 0; i < getawayDeals.size(); i++) {
By GETAWAY_ICON = By.xpath(String.format(getawayIcon, buiBox, i + 1));
if (!isElementPresent(GETAWAY_ICON)) {
log.error("Not valid deal");
}
By GETAWAY_PRICE = By.xpath(String.format(getawayPrice, buiBox, i + 1));
prices.add(Integer.parseInt(find(GETAWAY_PRICE).getText().replaceAll("[^0-9]","")));
}
By CHEAPEST_OFFER = By.xpath(String.format("(%s)[%d]", buiBox, prices.indexOf(Collections.min(prices)) + 1));
find(CHEAPEST_OFFER).click();
return new ResultPage(driver, log);
}
}
|
# frozen_string_literal: true
module ActiveRecordShards
module Model
def not_sharded
if self != ActiveRecord::Base && self != base_class
raise "You should only call not_sharded on direct descendants of ActiveRecord::Base"
end
self.sharded = false
end
def is_sharded? # rubocop:disable Naming/PredicateName
if self == ActiveRecord::Base
sharded != false && supports_sharding?
elsif self == base_class
if sharded.nil?
ActiveRecord::Base.is_sharded?
else
sharded != false
end
else
base_class.is_sharded?
end
end
def on_replica_by_default?
if self == ActiveRecord::Base
false
else
base = base_class
if base.instance_variable_defined?(:@on_replica_by_default)
base.instance_variable_get(:@on_replica_by_default)
end
end
end
alias_method :on_slave_by_default?, :on_replica_by_default?
def on_replica_by_default=(value)
if self == ActiveRecord::Base
raise ArgumentError, "Cannot set on_replica_by_default on ActiveRecord::Base"
else
base_class.instance_variable_set(:@on_replica_by_default, value)
end
end
alias_method :on_slave_by_default=, :on_replica_by_default=
module InstanceMethods
def initialize_shard_and_replica
@from_replica = !!self.class.current_shard_selection.options[:replica]
@from_shard = self.class.current_shard_selection.options[:shard]
end
alias_method :initialize_shard_and_slave, :initialize_shard_and_replica
def from_replica?
@from_replica
end
alias_method :from_slave?, :from_replica?
def from_shard
@from_shard
end
end
def self.extended(base)
base.send(:include, InstanceMethods)
base.after_initialize :initialize_shard_and_replica
end
private
attr_accessor :sharded
end
end
|
import React from 'react';
import { Flex, Link } from '@seno/core';
import { Trans } from '@lingui/macro';
import { Route, Switch, useRouteMatch } from 'react-router-dom';
import LayoutMain from '../layout/LayoutMain';
import PlotOverview from './overview/PlotOverview';
import PlotAdd from './add/PlotAdd';
import { PlotHeaderTarget } from './PlotHeader';
export default function Plot() {
const { path } = useRouteMatch();
return (
<LayoutMain
title={(
<>
<Link to="/dashboard/plot" color="textPrimary">
<Trans>Plot</Trans>
</Link>
<PlotHeaderTarget />
</>
)}
>
<Flex flexDirection="column" gap={3}>
<Switch>
<Route path={path} exact>
<PlotOverview />
</Route>
<Route path={`${path}/add`}>
<PlotAdd />
</Route>
</Switch>
</Flex>
</LayoutMain>
);
}
|
package com.flashoverride.ambientcreatures.entity.passive;
import net.minecraft.entity.passive.EntityAmbientCreature;
import net.minecraft.world.World;
public class EntityAmbientCreatureTFC extends EntityAmbientCreature
{
public EntityAmbientCreatureTFC(World world)
{
super(world);
}
public boolean isInsect()
{
return false;
}
}
|
import crypto from "crypto";
import { CacheAdmin } from "../Cache/Admin.cache";
import { CacheCategories } from "../Cache/Categories.cache";
import { CacheCustomer } from "../Cache/Customer.cache";
import { CacheImages } from "../Cache/Image.cache";
import { CacheInvoice } from "../Cache/Invoices.cache";
import { CacheOrder } from "../Cache/Order.cache";
import { CacheProduct } from "../Cache/Product.cache";
import { CacheTransactions } from "../Cache/Transactions.cache";
import { IAdministrator } from "../Interfaces/Admin/Administrators.interface";
import { ICategory } from "../Interfaces/Categories.interface";
import { IConfigurableOptions } from "../Interfaces/ConfigurableOptions.interface";
import { ICustomer } from "../Interfaces/Customer.interface";
import { IImage } from "../Interfaces/Images.interface";
import { IInvoice } from "../Interfaces/Invoice.interface";
import { IOrder } from "../Interfaces/Orders.interface";
import { IProduct } from "../Interfaces/Products.interface";
import { IQuotes } from "../Interfaces/Quotes.interface";
import { ITransactions } from "../Interfaces/Transactions.interface";
export function idCustomer(): ICustomer["uid"]
{
let uid: ICustomer["uid"] = `CUS_${crypto.randomBytes(20).toString("hex")}`;
while(CacheCustomer.get(uid))
uid = `CUS_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idCategory(): ICategory["uid"]
{
let uid: ICategory["uid"] = `CAT_${crypto.randomBytes(20).toString("hex")}`;
while(CacheCategories.get(uid))
uid = `CAT_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idProduct(): IProduct["uid"]
{
let uid: IProduct["uid"] = `PROD_${crypto.randomBytes(20).toString("hex")}`;
while(CacheProduct.get(uid))
uid = `PROD_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idAdmin(): IAdministrator["uid"]
{
let uid: IAdministrator["uid"] = `ADM_${crypto.randomBytes(20).toString("hex")}`;
while(CacheAdmin.get(uid))
uid = `ADM_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idOrder(): IOrder["uid"]
{
let uid: IOrder["uid"] = `ORD_${crypto.randomBytes(20).toString("hex")}`;
while(CacheOrder.get(uid))
uid = `ORD_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idInvoice(): IInvoice["uid"]
{
let uid: IInvoice["uid"] = `INV_${crypto.randomBytes(20).toString("hex")}`;
while(CacheInvoice.get(uid))
uid = `INV_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idTransicitons(): ITransactions["uid"]
{
let uid: ITransactions["uid"] = `TRAN_${crypto.randomBytes(20).toString("hex")}`;
while(CacheTransactions.get(uid))
uid = `TRAN_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idImages(): IImage["uid"]
{
let uid: IImage["uid"] = `IMG_${crypto.randomBytes(20).toString("hex")}`;
while(CacheImages.get(uid))
uid = `IMG_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idConfigurableOptions(): IConfigurableOptions["uid"]
{
const uid: IConfigurableOptions["uid"] = `CO_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
export function idQuotes(): IQuotes["uid"]
{
const uid: IQuotes["uid"] = `QUO_${crypto.randomBytes(20).toString("hex")}`;
return uid;
}
|
# Geospatial MetaData ToolKit is one component of the GeoHydra head
module GeoHydra
end
require 'geohydra/version'
require 'geohydra/geonetwork'
require 'geohydra/transform'
require 'geohydra/solr'
require 'geohydra/accession'
require 'geohydra/utils'
require 'geohydra/gazetteer'
require 'geohydra/workflow/task'
require 'geohydra/workflow/gisAssemblyWF'
require 'geohydra/workflow/gisDeliveryWF'
require 'geohydra/workflow/gisDiscoveryWF'
|
<?php
namespace CaseConverter\Tests\Unit;
use CaseConverter\CamelCaseConverter;
use CaseConverter\CaseFactory;
use CaseConverter\KebabCaseConverter;
use CaseConverter\SnakeCaseConverter;
use CaseConverter\StandardCaseConverter;
use CaseConverter\StudlyCapsCaseConverter;
use CaseConverter\TypeCase;
use PHPUnit\Framework\TestCase;
class CaseFactoryTest extends TestCase
{
/** @test */
public function it_returns_the_correct_converter_class()
{
$factory = new CaseFactory;
$converters = [
'camel' => $factory->getConverter('camel'),
'snake' => $factory->getConverter('snake'),
'studly' => $factory->getConverter('studly'),
'kebab' => $factory->getConverter('kebab'),
'standard' => $factory->getConverter('standard'),
];
foreach ($converters as $converter) {
$this->assertInstanceOf(TypeCase::class, $converter);
}
$this->assertInstanceOf(CamelCaseConverter::class, $converters['camel']);
$this->assertInstanceOf(SnakeCaseConverter::class, $converters['snake']);
$this->assertInstanceOf(StudlyCapsCaseConverter::class, $converters['studly']);
$this->assertInstanceOf(KebabCaseConverter::class, $converters['kebab']);
$this->assertInstanceOf(StandardCaseConverter::class, $converters['standard']);
}
}
|
<?php declare(strict_types=1);
/**
* @package s9e\TextFormatter
* @copyright Copyright (c) 2010-2021 The s9e authors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\TextFormatter\Configurator\RendererGenerators\PHP\XPathConvertor\Convertors;
class PHP80Functions extends AbstractConvertor
{
/**
* {@inheritdoc}
*/
public function getMatchers(): array
{
$groups = 'Boolean:BooleanFunction:';
return [
$groups . 'Contains' => 'contains \\( ((?&String)) , ((?&String)) \\)',
$groups . 'EndsWith' => 'ends-with \\( ((?&String)) , ((?&String)) \\)',
$groups . 'NotContains' => 'not \\( contains \\( ((?&String)) , ((?&String)) \\) \\)',
$groups . 'NotEndsWith' => 'not \\( ends-with \\( ((?&String)) , ((?&String)) \\) \\)',
$groups . 'NotStartsWith' => 'not \\( starts-with \\( ((?&String)) , ((?&String)) \\) \\)',
$groups . 'StartsWith' => 'starts-with \\( ((?&String)) , ((?&String)) \\)'
];
}
/**
* Convert a call to contains()
*
* @param string $haystack Expression for the haystack part of the call
* @param string $needle Expression for the needle part of the call
* @return string
*/
public function parseContains(string $haystack, string $needle): string
{
return 'str_contains(' . $this->recurse($haystack) . ',' . $this->recurse($needle) . ')';
}
/**
* Convert a call to ends-with()
*
* @param string $string Expression for the string part of the call
* @param string $substring Expression for the substring part of the call
* @return string
*/
public function parseEndsWith(string $string, string $substring): string
{
return 'str_ends_with(' . $this->recurse($string) . ',' . $this->recurse($substring) . ')';
}
/**
* Convert a call to not(contains())
*
* @param string $haystack Expression for the haystack part of the call
* @param string $needle Expression for the needle part of the call
* @return string
*/
public function parseNotContains(string $haystack, string $needle): string
{
return '!str_contains(' . $this->recurse($haystack) . ',' . $this->recurse($needle) . ')';
}
/**
* Convert a call to not(ends-with())
*
* @param string $string Expression for the string part of the call
* @param string $substring Expression for the substring part of the call
* @return string
*/
public function parseNotEndsWith(string $string, string $substring): string
{
return '!str_ends_with(' . $this->recurse($string) . ',' . $this->recurse($substring) . ')';
}
/**
* Convert a call to not(starts-with())
*
* @param string $string Expression for the string part of the call
* @param string $substring Expression for the substring part of the call
* @return string
*/
public function parseNotStartsWith(string $string, string $substring): string
{
return '!str_starts_with(' . $this->recurse($string) . ',' . $this->recurse($substring) . ')';
}
/**
* Convert a call to starts-with()
*
* @param string $string Expression for the string part of the call
* @param string $substring Expression for the substring part of the call
* @return string
*/
public function parseStartsWith(string $string, string $substring): string
{
return 'str_starts_with(' . $this->recurse($string) . ',' . $this->recurse($substring) . ')';
}
}
|
// Copyright 2019 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.12.2
// source: google/cloud/tasks/v2/task.proto
package tasks
import (
reflect "reflect"
sync "sync"
_ "google.golang.org/genproto/googleapis/api/annotations"
status "google.golang.org/genproto/googleapis/rpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
durationpb "google.golang.org/protobuf/types/known/durationpb"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// The view specifies a subset of [Task][google.cloud.tasks.v2.Task] data.
//
// When a task is returned in a response, not all
// information is retrieved by default because some data, such as
// payloads, might be desirable to return only when needed because
// of its large size or because of the sensitivity of data that it
// contains.
type Task_View int32
const (
// Unspecified. Defaults to BASIC.
Task_VIEW_UNSPECIFIED Task_View = 0
// The basic view omits fields which can be large or can contain
// sensitive data.
//
// This view does not include the
// [body in AppEngineHttpRequest][google.cloud.tasks.v2.AppEngineHttpRequest.body].
// Bodies are desirable to return only when needed, because they
// can be large and because of the sensitivity of the data that you
// choose to store in it.
Task_BASIC Task_View = 1
// All information is returned.
//
// Authorization for [FULL][google.cloud.tasks.v2.Task.View.FULL] requires
// `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/)
// permission on the [Queue][google.cloud.tasks.v2.Queue] resource.
Task_FULL Task_View = 2
)
// Enum value maps for Task_View.
var (
Task_View_name = map[int32]string{
0: "VIEW_UNSPECIFIED",
1: "BASIC",
2: "FULL",
}
Task_View_value = map[string]int32{
"VIEW_UNSPECIFIED": 0,
"BASIC": 1,
"FULL": 2,
}
)
func (x Task_View) Enum() *Task_View {
p := new(Task_View)
*p = x
return p
}
func (x Task_View) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Task_View) Descriptor() protoreflect.EnumDescriptor {
return file_google_cloud_tasks_v2_task_proto_enumTypes[0].Descriptor()
}
func (Task_View) Type() protoreflect.EnumType {
return &file_google_cloud_tasks_v2_task_proto_enumTypes[0]
}
func (x Task_View) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Task_View.Descriptor instead.
func (Task_View) EnumDescriptor() ([]byte, []int) {
return file_google_cloud_tasks_v2_task_proto_rawDescGZIP(), []int{0, 0}
}
// A unit of scheduled work.
type Task struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Optionally caller-specified in [CreateTask][google.cloud.tasks.v2.CloudTasks.CreateTask].
//
// The task name.
//
// The task name must have the following format:
// `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`
//
// * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]),
// hyphens (-), colons (:), or periods (.).
// For more information, see
// [Identifying
// projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects)
// * `LOCATION_ID` is the canonical ID for the task's location.
// The list of available locations can be obtained by calling
// [ListLocations][google.cloud.location.Locations.ListLocations].
// For more information, see https://cloud.google.com/about/locations/.
// * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or
// hyphens (-). The maximum length is 100 characters.
// * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]),
// hyphens (-), or underscores (_). The maximum length is 500 characters.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
// Required. The message to send to the worker.
//
// Types that are assignable to MessageType:
// *Task_AppEngineHttpRequest
// *Task_HttpRequest
MessageType isTask_MessageType `protobuf_oneof:"message_type"`
// The time when the task is scheduled to be attempted or retried.
//
// `schedule_time` will be truncated to the nearest microsecond.
ScheduleTime *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"`
// Output only. The time that the task was created.
//
// `create_time` will be truncated to the nearest second.
CreateTime *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"`
// The deadline for requests sent to the worker. If the worker does not
// respond by this deadline then the request is cancelled and the attempt
// is marked as a `DEADLINE_EXCEEDED` failure. Cloud Tasks will retry the
// task according to the [RetryConfig][google.cloud.tasks.v2.RetryConfig].
//
// Note that when the request is cancelled, Cloud Tasks will stop listing for
// the response, but whether the worker stops processing depends on the
// worker. For example, if the worker is stuck, it may not react to cancelled
// requests.
//
// The default and maximum values depend on the type of request:
//
// * For [HTTP tasks][google.cloud.tasks.v2.HttpRequest], the default is 10 minutes. The deadline
// must be in the interval [15 seconds, 30 minutes].
//
// * For [App Engine tasks][google.cloud.tasks.v2.AppEngineHttpRequest], 0 indicates that the
// request has the default deadline. The default deadline depends on the
// [scaling
// type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling)
// of the service: 10 minutes for standard apps with automatic scaling, 24
// hours for standard apps with manual and basic scaling, and 60 minutes for
// flex apps. If the request deadline is set, it must be in the interval [15
// seconds, 24 hours 15 seconds]. Regardless of the task's
// `dispatch_deadline`, the app handler will not run for longer than than
// the service's timeout. We recommend setting the `dispatch_deadline` to
// at most a few seconds more than the app handler's timeout. For more
// information see
// [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts).
//
// `dispatch_deadline` will be truncated to the nearest millisecond. The
// deadline is an approximate deadline.
DispatchDeadline *durationpb.Duration `protobuf:"bytes,6,opt,name=dispatch_deadline,json=dispatchDeadline,proto3" json:"dispatch_deadline,omitempty"`
// Output only. The number of attempts dispatched.
//
// This count includes attempts which have been dispatched but haven't
// received a response.
DispatchCount int32 `protobuf:"varint,7,opt,name=dispatch_count,json=dispatchCount,proto3" json:"dispatch_count,omitempty"`
// Output only. The number of attempts which have received a response.
ResponseCount int32 `protobuf:"varint,8,opt,name=response_count,json=responseCount,proto3" json:"response_count,omitempty"`
// Output only. The status of the task's first attempt.
//
// Only [dispatch_time][google.cloud.tasks.v2.Attempt.dispatch_time] will be set.
// The other [Attempt][google.cloud.tasks.v2.Attempt] information is not retained by Cloud Tasks.
FirstAttempt *Attempt `protobuf:"bytes,9,opt,name=first_attempt,json=firstAttempt,proto3" json:"first_attempt,omitempty"`
// Output only. The status of the task's last attempt.
LastAttempt *Attempt `protobuf:"bytes,10,opt,name=last_attempt,json=lastAttempt,proto3" json:"last_attempt,omitempty"`
// Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2.Task] has
// been returned.
View Task_View `protobuf:"varint,11,opt,name=view,proto3,enum=google.cloud.tasks.v2.Task_View" json:"view,omitempty"`
}
func (x *Task) Reset() {
*x = Task{}
if protoimpl.UnsafeEnabled {
mi := &file_google_cloud_tasks_v2_task_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Task) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Task) ProtoMessage() {}
func (x *Task) ProtoReflect() protoreflect.Message {
mi := &file_google_cloud_tasks_v2_task_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Task.ProtoReflect.Descriptor instead.
func (*Task) Descriptor() ([]byte, []int) {
return file_google_cloud_tasks_v2_task_proto_rawDescGZIP(), []int{0}
}
func (x *Task) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (m *Task) GetMessageType() isTask_MessageType {
if m != nil {
return m.MessageType
}
return nil
}
func (x *Task) GetAppEngineHttpRequest() *AppEngineHttpRequest {
if x, ok := x.GetMessageType().(*Task_AppEngineHttpRequest); ok {
return x.AppEngineHttpRequest
}
return nil
}
func (x *Task) GetHttpRequest() *HttpRequest {
if x, ok := x.GetMessageType().(*Task_HttpRequest); ok {
return x.HttpRequest
}
return nil
}
func (x *Task) GetScheduleTime() *timestamppb.Timestamp {
if x != nil {
return x.ScheduleTime
}
return nil
}
func (x *Task) GetCreateTime() *timestamppb.Timestamp {
if x != nil {
return x.CreateTime
}
return nil
}
func (x *Task) GetDispatchDeadline() *durationpb.Duration {
if x != nil {
return x.DispatchDeadline
}
return nil
}
func (x *Task) GetDispatchCount() int32 {
if x != nil {
return x.DispatchCount
}
return 0
}
func (x *Task) GetResponseCount() int32 {
if x != nil {
return x.ResponseCount
}
return 0
}
func (x *Task) GetFirstAttempt() *Attempt {
if x != nil {
return x.FirstAttempt
}
return nil
}
func (x *Task) GetLastAttempt() *Attempt {
if x != nil {
return x.LastAttempt
}
return nil
}
func (x *Task) GetView() Task_View {
if x != nil {
return x.View
}
return Task_VIEW_UNSPECIFIED
}
type isTask_MessageType interface {
isTask_MessageType()
}
type Task_AppEngineHttpRequest struct {
// HTTP request that is sent to the App Engine app handler.
//
// An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2.AppEngineHttpRequest] set.
AppEngineHttpRequest *AppEngineHttpRequest `protobuf:"bytes,2,opt,name=app_engine_http_request,json=appEngineHttpRequest,proto3,oneof"`
}
type Task_HttpRequest struct {
// HTTP request that is sent to the worker.
//
// An HTTP task is a task that has [HttpRequest][google.cloud.tasks.v2.HttpRequest] set.
HttpRequest *HttpRequest `protobuf:"bytes,3,opt,name=http_request,json=httpRequest,proto3,oneof"`
}
func (*Task_AppEngineHttpRequest) isTask_MessageType() {}
func (*Task_HttpRequest) isTask_MessageType() {}
// The status of a task attempt.
type Attempt struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Output only. The time that this attempt was scheduled.
//
// `schedule_time` will be truncated to the nearest microsecond.
ScheduleTime *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"`
// Output only. The time that this attempt was dispatched.
//
// `dispatch_time` will be truncated to the nearest microsecond.
DispatchTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=dispatch_time,json=dispatchTime,proto3" json:"dispatch_time,omitempty"`
// Output only. The time that this attempt response was received.
//
// `response_time` will be truncated to the nearest microsecond.
ResponseTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=response_time,json=responseTime,proto3" json:"response_time,omitempty"`
// Output only. The response from the worker for this attempt.
//
// If `response_time` is unset, then the task has not been attempted or is
// currently running and the `response_status` field is meaningless.
ResponseStatus *status.Status `protobuf:"bytes,4,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"`
}
func (x *Attempt) Reset() {
*x = Attempt{}
if protoimpl.UnsafeEnabled {
mi := &file_google_cloud_tasks_v2_task_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Attempt) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Attempt) ProtoMessage() {}
func (x *Attempt) ProtoReflect() protoreflect.Message {
mi := &file_google_cloud_tasks_v2_task_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Attempt.ProtoReflect.Descriptor instead.
func (*Attempt) Descriptor() ([]byte, []int) {
return file_google_cloud_tasks_v2_task_proto_rawDescGZIP(), []int{1}
}
func (x *Attempt) GetScheduleTime() *timestamppb.Timestamp {
if x != nil {
return x.ScheduleTime
}
return nil
}
func (x *Attempt) GetDispatchTime() *timestamppb.Timestamp {
if x != nil {
return x.DispatchTime
}
return nil
}
func (x *Attempt) GetResponseTime() *timestamppb.Timestamp {
if x != nil {
return x.ResponseTime
}
return nil
}
func (x *Attempt) GetResponseStatus() *status.Status {
if x != nil {
return x.ResponseStatus
}
return nil
}
var File_google_cloud_tasks_v2_task_proto protoreflect.FileDescriptor
var file_google_cloud_tasks_v2_task_proto_rawDesc = []byte{
0x0a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x74,
0x61, 0x73, 0x6b, 0x73, 0x2f, 0x76, 0x32, 0x2f, 0x74, 0x61, 0x73, 0x6b, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x12, 0x15, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64,
0x2e, 0x74, 0x61, 0x73, 0x6b, 0x73, 0x2e, 0x76, 0x32, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x22, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f,
0x75, 0x64, 0x2f, 0x74, 0x61, 0x73, 0x6b, 0x73, 0x2f, 0x76, 0x32, 0x2f, 0x74, 0x61, 0x72, 0x67,
0x65, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74,
0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x22, 0xc8, 0x06, 0x0a, 0x04, 0x54, 0x61, 0x73, 0x6b, 0x12, 0x12, 0x0a, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12,
0x64, 0x0a, 0x17, 0x61, 0x70, 0x70, 0x5f, 0x65, 0x6e, 0x67, 0x69, 0x6e, 0x65, 0x5f, 0x68, 0x74,
0x74, 0x70, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b,
0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e,
0x74, 0x61, 0x73, 0x6b, 0x73, 0x2e, 0x76, 0x32, 0x2e, 0x41, 0x70, 0x70, 0x45, 0x6e, 0x67, 0x69,
0x6e, 0x65, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x00, 0x52,
0x14, 0x61, 0x70, 0x70, 0x45, 0x6e, 0x67, 0x69, 0x6e, 0x65, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x47, 0x0a, 0x0c, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x72, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x74, 0x61, 0x73, 0x6b, 0x73,
0x2e, 0x76, 0x32, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48,
0x00, 0x52, 0x0b, 0x68, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x3f,
0x0a, 0x0d, 0x73, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18,
0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d,
0x70, 0x52, 0x0c, 0x73, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12,
0x3b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x05,
0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70,
0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x46, 0x0a, 0x11,
0x64, 0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e,
0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x52, 0x10, 0x64, 0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x44, 0x65, 0x61, 0x64,
0x6c, 0x69, 0x6e, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x64, 0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68,
0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0d, 0x64, 0x69,
0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x25, 0x0a, 0x0e, 0x72,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x08, 0x20,
0x01, 0x28, 0x05, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x43, 0x6f, 0x75,
0x6e, 0x74, 0x12, 0x43, 0x0a, 0x0d, 0x66, 0x69, 0x72, 0x73, 0x74, 0x5f, 0x61, 0x74, 0x74, 0x65,
0x6d, 0x70, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x74, 0x61, 0x73, 0x6b, 0x73, 0x2e, 0x76,
0x32, 0x2e, 0x41, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x52, 0x0c, 0x66, 0x69, 0x72, 0x73, 0x74,
0x41, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x12, 0x41, 0x0a, 0x0c, 0x6c, 0x61, 0x73, 0x74, 0x5f,
0x61, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e,
0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x74, 0x61, 0x73,
0x6b, 0x73, 0x2e, 0x76, 0x32, 0x2e, 0x41, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x52, 0x0b, 0x6c,
0x61, 0x73, 0x74, 0x41, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x12, 0x34, 0x0a, 0x04, 0x76, 0x69,
0x65, 0x77, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x20, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x74, 0x61, 0x73, 0x6b, 0x73, 0x2e, 0x76, 0x32,
0x2e, 0x54, 0x61, 0x73, 0x6b, 0x2e, 0x56, 0x69, 0x65, 0x77, 0x52, 0x04, 0x76, 0x69, 0x65, 0x77,
0x22, 0x31, 0x0a, 0x04, 0x56, 0x69, 0x65, 0x77, 0x12, 0x14, 0x0a, 0x10, 0x56, 0x49, 0x45, 0x57,
0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x09,
0x0a, 0x05, 0x42, 0x41, 0x53, 0x49, 0x43, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x46, 0x55, 0x4c,
0x4c, 0x10, 0x02, 0x3a, 0x68, 0xea, 0x41, 0x65, 0x0a, 0x1e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x74,
0x61, 0x73, 0x6b, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x54, 0x61, 0x73, 0x6b, 0x12, 0x43, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63,
0x74, 0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x6c, 0x6f, 0x63,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x7d, 0x2f, 0x71, 0x75, 0x65, 0x75, 0x65, 0x73, 0x2f, 0x7b, 0x71, 0x75, 0x65, 0x75, 0x65, 0x7d,
0x2f, 0x74, 0x61, 0x73, 0x6b, 0x73, 0x2f, 0x7b, 0x74, 0x61, 0x73, 0x6b, 0x7d, 0x42, 0x0e, 0x0a,
0x0c, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x22, 0x89, 0x02,
0x0a, 0x07, 0x41, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x12, 0x3f, 0x0a, 0x0d, 0x73, 0x63, 0x68,
0x65, 0x64, 0x75, 0x6c, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b,
0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0c, 0x73, 0x63,
0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x3f, 0x0a, 0x0d, 0x64, 0x69,
0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28,
0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0c, 0x64,
0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x3f, 0x0a, 0x0d, 0x72,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0c,
0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x3b, 0x0a, 0x0f,
0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18,
0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72,
0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x0e, 0x72, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x42, 0x64, 0x0a, 0x19, 0x63, 0x6f, 0x6d,
0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x74, 0x61,
0x73, 0x6b, 0x73, 0x2e, 0x76, 0x32, 0x42, 0x09, 0x54, 0x61, 0x73, 0x6b, 0x50, 0x72, 0x6f, 0x74,
0x6f, 0x50, 0x01, 0x5a, 0x3a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61,
0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f,
0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64,
0x2f, 0x74, 0x61, 0x73, 0x6b, 0x73, 0x2f, 0x76, 0x32, 0x3b, 0x74, 0x61, 0x73, 0x6b, 0x73, 0x62,
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_google_cloud_tasks_v2_task_proto_rawDescOnce sync.Once
file_google_cloud_tasks_v2_task_proto_rawDescData = file_google_cloud_tasks_v2_task_proto_rawDesc
)
func file_google_cloud_tasks_v2_task_proto_rawDescGZIP() []byte {
file_google_cloud_tasks_v2_task_proto_rawDescOnce.Do(func() {
file_google_cloud_tasks_v2_task_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_cloud_tasks_v2_task_proto_rawDescData)
})
return file_google_cloud_tasks_v2_task_proto_rawDescData
}
var file_google_cloud_tasks_v2_task_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_google_cloud_tasks_v2_task_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_google_cloud_tasks_v2_task_proto_goTypes = []interface{}{
(Task_View)(0), // 0: google.cloud.tasks.v2.Task.View
(*Task)(nil), // 1: google.cloud.tasks.v2.Task
(*Attempt)(nil), // 2: google.cloud.tasks.v2.Attempt
(*AppEngineHttpRequest)(nil), // 3: google.cloud.tasks.v2.AppEngineHttpRequest
(*HttpRequest)(nil), // 4: google.cloud.tasks.v2.HttpRequest
(*timestamppb.Timestamp)(nil), // 5: google.protobuf.Timestamp
(*durationpb.Duration)(nil), // 6: google.protobuf.Duration
(*status.Status)(nil), // 7: google.rpc.Status
}
var file_google_cloud_tasks_v2_task_proto_depIdxs = []int32{
3, // 0: google.cloud.tasks.v2.Task.app_engine_http_request:type_name -> google.cloud.tasks.v2.AppEngineHttpRequest
4, // 1: google.cloud.tasks.v2.Task.http_request:type_name -> google.cloud.tasks.v2.HttpRequest
5, // 2: google.cloud.tasks.v2.Task.schedule_time:type_name -> google.protobuf.Timestamp
5, // 3: google.cloud.tasks.v2.Task.create_time:type_name -> google.protobuf.Timestamp
6, // 4: google.cloud.tasks.v2.Task.dispatch_deadline:type_name -> google.protobuf.Duration
2, // 5: google.cloud.tasks.v2.Task.first_attempt:type_name -> google.cloud.tasks.v2.Attempt
2, // 6: google.cloud.tasks.v2.Task.last_attempt:type_name -> google.cloud.tasks.v2.Attempt
0, // 7: google.cloud.tasks.v2.Task.view:type_name -> google.cloud.tasks.v2.Task.View
5, // 8: google.cloud.tasks.v2.Attempt.schedule_time:type_name -> google.protobuf.Timestamp
5, // 9: google.cloud.tasks.v2.Attempt.dispatch_time:type_name -> google.protobuf.Timestamp
5, // 10: google.cloud.tasks.v2.Attempt.response_time:type_name -> google.protobuf.Timestamp
7, // 11: google.cloud.tasks.v2.Attempt.response_status:type_name -> google.rpc.Status
12, // [12:12] is the sub-list for method output_type
12, // [12:12] is the sub-list for method input_type
12, // [12:12] is the sub-list for extension type_name
12, // [12:12] is the sub-list for extension extendee
0, // [0:12] is the sub-list for field type_name
}
func init() { file_google_cloud_tasks_v2_task_proto_init() }
func file_google_cloud_tasks_v2_task_proto_init() {
if File_google_cloud_tasks_v2_task_proto != nil {
return
}
file_google_cloud_tasks_v2_target_proto_init()
if !protoimpl.UnsafeEnabled {
file_google_cloud_tasks_v2_task_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Task); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_cloud_tasks_v2_task_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Attempt); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_google_cloud_tasks_v2_task_proto_msgTypes[0].OneofWrappers = []interface{}{
(*Task_AppEngineHttpRequest)(nil),
(*Task_HttpRequest)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_google_cloud_tasks_v2_task_proto_rawDesc,
NumEnums: 1,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_google_cloud_tasks_v2_task_proto_goTypes,
DependencyIndexes: file_google_cloud_tasks_v2_task_proto_depIdxs,
EnumInfos: file_google_cloud_tasks_v2_task_proto_enumTypes,
MessageInfos: file_google_cloud_tasks_v2_task_proto_msgTypes,
}.Build()
File_google_cloud_tasks_v2_task_proto = out.File
file_google_cloud_tasks_v2_task_proto_rawDesc = nil
file_google_cloud_tasks_v2_task_proto_goTypes = nil
file_google_cloud_tasks_v2_task_proto_depIdxs = nil
}
|
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
module Thrift.Transport.IOBuffer
( WriteBuffer
, newWriteBuffer
, writeBuf
, flushBuf
, ReadBuffer
, newReadBuffer
, fillBuf
, readBuf
, peekBuf
) where
import Data.ByteString.Lazy.Builder
import Data.Functor
import Data.IORef
import Data.Monoid
import Data.Word
import qualified Data.ByteString.Lazy as LBS
type WriteBuffer = IORef Builder
type ReadBuffer = IORef LBS.ByteString
newWriteBuffer :: IO WriteBuffer
newWriteBuffer = newIORef mempty
writeBuf :: WriteBuffer -> LBS.ByteString -> IO ()
writeBuf w s = modifyIORef w ( <> lazyByteString s)
flushBuf :: WriteBuffer -> IO LBS.ByteString
flushBuf w = do
buf <- readIORef w
writeIORef w mempty
return $ toLazyByteString buf
newReadBuffer :: IO ReadBuffer
newReadBuffer = newIORef mempty
fillBuf :: ReadBuffer -> LBS.ByteString -> IO ()
fillBuf = writeIORef
readBuf :: ReadBuffer -> Int -> IO LBS.ByteString
readBuf r n = do
bs <- readIORef r
let (hd, tl) = LBS.splitAt (fromIntegral n) bs
writeIORef r tl
return hd
peekBuf :: ReadBuffer -> IO (Maybe Word8)
peekBuf r = (fmap fst . LBS.uncons) <$> readIORef r
|
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library test.source_maps_test;
import 'dart:convert';
import 'package:source_maps/source_maps.dart';
import 'package:test/test.dart';
import 'common.dart';
void main() {
test('builder - with span', () {
var map = (SourceMapBuilder()
..addSpan(inputVar1, outputVar1)
..addSpan(inputFunction, outputFunction)
..addSpan(inputVar2, outputVar2)
..addSpan(inputExpr, outputExpr))
.build(output.url.toString());
expect(map, equals(expectedMap));
});
test('builder - with location', () {
var str = (SourceMapBuilder()
..addLocation(inputVar1.start, outputVar1.start, 'longVar1')
..addLocation(inputFunction.start, outputFunction.start, 'longName')
..addLocation(inputVar2.start, outputVar2.start, 'longVar2')
..addLocation(inputExpr.start, outputExpr.start, null))
.toJson(output.url.toString());
expect(str, jsonEncode(expectedMap));
});
}
|
using InsightHub.Data.Entities;
using InsightHub.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace InsightHub.Services.Mappers
{
public class UserMapper
{
/// <summary>
/// Maps a User Model from an existing Entity
/// </summary>
/// <param name="user">The target User Entity</param>
/// <returns>User Model</returns>
public static UserModel MapModelFromEntity(User user)
{
return new UserModel
{
Id = user.Id,
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email,
CreatedOn = user.CreatedOn,
ModifiedOn = user.ModifiedOn,
DownloadedReportsCount = user.DownloadedReports.Count,
IndustrySubscriptionsCount = user.IndustrySubscriptions.Count,
IsPending = user.IsPending,
IsBanned = user.IsBanned,
BanReason = user.BanReason
};
}
}
}
|
package cn.springmvc.service;
import java.util.List;
import java.util.Map;
import cn.springmvc.model.RefrePrcModel;
public interface RefrePrcService {
public List<String> select();
public List<RefrePrcModel> selectCargoId(List<String> list);
// public Map<String, Object> selectCargoId(List<String> list);
public int update(List<RefrePrcModel> list);
}
|
#!/bin/sh
set -o errexit
set -o nounset
NGINX_BIN=nginx
if [ "${NGINX_DEBUG}" = "true" ]; then
NGINX_BIN=nginx-debug
fi
CONF_DIR=/etc/nginx/
cp "${CONF_DIR}/nginx.conf.tpl" "${CONF_DIR}/nginx.conf"
perl -pi -e 's/ENV_([_A-Z0-9]+)_ENV/$ENV{$1}/g' "${CONF_DIR}/nginx.conf"
${NGINX_BIN} -g 'daemon off;'
|
# Predicting Disease Progression and Outcome of COVID-19 Patients based on Temporal Deep Learning Method
Chenxi Sun, Shenda Hong, Moxian Song, Hongyan Li and Zhenjie Wang.
├── Readme.md // help
├── T-LSTM // method code
│ ├── LSTMtimedecay.py
│ ├── decaymain.py
├── baselines // baseline methods code
│ ├── LSTM.
│ ├── RNN.
│ ├── PNN
│ ├── DT
│ ├── k-NN
│ └── SVM
├── DataProcess // data processing code
│ ├── DataProcess.ipynb
│ ├── DataStatistics.ipynb
│ └── ResultsVis.ipynb
├── data // raw data.
├── BatchData // preprocessed data
├── figures // result figures
├── model // saved T-LSTM model
└── results // result files.
## Data

## Methods

## Prediction results



## Stage results




|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace SqlSugar
{
public partial class JsonUpdateableProvider : IJsonUpdateableProvider<JsonUpdateResult>
{
private void AppendWhere(JToken item)
{
Check.Exception(isList, "Batch updates cannot use Where, only WhereColumns can set columns", "批量更新不能使用Where,只能通过WhereColumns设置列");
var sqlObj = jsonCommonProvider.GetWhere(item, sugarUpdateable.UpdateBuilder.Context);
sugarUpdateable.Where(sqlObj.Key, sqlObj.Value);
}
}
}
|
package com.skeleton.common.page.repository
import org.apache.poi.ss.formula.functions.T
/**
* Created by LYT to 2021/09/07
*/
class QueryDslPage<T>(
val results: MutableList<T>,
val totalCount: Long
)
|
class AddConditionsToRuns < ActiveRecord::Migration[5.2]
def change
add_column :runs, :conditions, :string
end
end
|
try {
Push-Location $PSScriptRoot\shared\ext\bgfx
..\bin\genie --with-dynamic-runtime --vs=winstore100 vs2019
..\bin\genie --with-dynamic-runtime vs2019
Get-ChildItem .build\projects\vs2019 | ForEach-Object {
$content = Get-Content $_.FullName -Raw
$content = $content -replace '8.1', '10.0'
$content | Set-Content $_.FullName
}
Get-ChildItem .build\projects\vs2019-winstore100 | ForEach-Object {
$content = Get-Content $_.FullName -Raw
$content = $content -replace '8.1', '10.0'
$content | Set-Content $_.FullName
}
}
finally {
Pop-Location
}
|
class CustomCommand < Discordrb::Commands::Command
def to_json(*args)
json_hash = {
command: @command
}
attributes.each do |attr, val|
json_hash[attr] = val
end
json_hash.to_json(*args)
end
end
|
import { AbstractRequestContextHelper } from "../../abstract-request-context-helper";
export class PromoCodesContextHelper extends AbstractRequestContextHelper {
public async getAll(count: number, offset: number) {
const data = await this.context.helpers.rest.get({
path: "/promo-code/get-all",
params: {
count,
offset,
},
});
return data;
}
public async delete(id: string) {
return await await this.context.helpers.rest.delete({
path: `/promo-code/delete/${id}`,
});
}
public async update(
id: string,
data: {
name: string;
sale: string;
adminId: string;
QRCode: string;
},
) {
return await await this.context.helpers.rest.patch({
path: `/promo-code/update/${id}`,
data,
});
}
public async add(data: {
name: string;
sale: string;
adminId: string;
QRCode: string;
}) {
return await await this.context.helpers.rest.post({
path: "/promo-code/add",
data,
});
}
public async addMany(
data: Array<{
name: string;
sale: string;
adminId: string;
QRCodeId: string;
}>,
) {
return await await this.context.helpers.rest.post({
path: "/promo-code/add-many",
data: { promoCodes: data },
});
}
}
|
#
# Cookbook Name:: iptables-ng
# Recipe:: install
#
# Copyright 2013, Chris Aumann
#
# 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
# (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, see <http://www.gnu.org/licenses/>.
#
include_recipe 'iptables-ng::manage'
# Make sure iptables is installed
Array(node['iptables-ng']['packages']).each do |pkg|
package "iptables-ng::install - #{pkg} package" do
package_name pkg
notifies :run, 'execute[iptables-ng::install - systemctl daemon-reload]', :immediately
end
end
# Check to see if we're using systemd so we run systemctl daemon-reload to pick up new services
execute 'iptables-ng::install - systemctl daemon-reload' do
command 'systemctl daemon-reload'
action :nothing
only_if { IO.read('/proc/1/comm').chomp == 'systemd' }
end
# Make sure ufw is not installed on Ubuntu/Debian, as it might interfere
package 'iptables-ng::install - ufw package' do
package_name 'uwf'
action :remove
only_if { node['platform_family'] == 'debian' }
end
# Create directories
directory '/etc/iptables.d' do
mode 0o700
end
node['iptables-ng']['rules'].each do |table, chains|
# Skip deactivated tables
next unless node['iptables-ng']['enabled_tables'].include?(table)
directory "/etc/iptables.d/#{table}" do
mode 0o700
end
# Create default policies unless they exist
chains.each do |chain, policy|
iptables_ng_chain "default-policy-#{table}-#{chain}" do
chain chain
table table
policy policy['default']
action :create_if_missing
end
end
end
|
require 'rubygems'
require 'cgi'
require 'yaml'
require 'rest_client'
require 'xmlsimple'
require 'ostruct'
module Piwik
class ApiError < StandardError; end
class MissingConfiguration < ArgumentError; end
class UnknownSite < ArgumentError; end
class UnknownUser < ArgumentError; end
class UnknownGoal < ArgumentError; end
class Base
include Piwik::Typecast
include Piwik::ApiScope
@@template = <<-EOF
# .piwik
#
# Please fill in fields like this:
#
# piwik_url: http://your.piwik.site
# auth_token: secret
#
piwik_url:
auth_token:
EOF
# common constructor, using ostruct for attribute storage
attr_accessor :attributes
def initialize params = {}
@attributes = OpenStruct.new
params.map do |k,v|
@attributes.send(:"#{k}=",typecast(v))
end
end
def id_attr
self.class.id_attr
end
def save
if new?
resp = collection.add(attributes)
attributes = resp.attributes
true
else
collection.save(attributes)
end
end
alias :update :save
def delete
collection.delete(attributes)
end
alias :destroy :delete
# Returns <tt>true</tt> if the current site does not exists in the Piwik yet.
def new?
begin
if respond_to?(:id)
id.nil? && created_at.blank?
else
created_at.blank?
end
rescue Exception => e
nil
end
end
#id will try and return the value of the Piwik item id if it exists
def id
begin
if self.class == Piwik::Site
self.idsite
else
attributes.send(:"id#{self.class.to_s.gsub('Piwik::','')}")
end
rescue Exception => e
$stderr.puts e
end
end
#created_at will try and return the value of the Piwik item id if it exists
def created_at
attributes.send(:ts_created) rescue nil
end
# delegate attribute calls to @attributes storage
def method_missing(method,*args,&block)
if self.attributes.respond_to?(method)
self.attributes.send(method,*args,&block)
else
super
end
end
def parse_xml xml; self.class.parse_xml xml; end
# Calls the supplied Piwik API method, with the supplied parameters.
#
# Returns a string containing the XML reply from Piwik, or raises a
# <tt>Piwik::ApiError</tt> exception with the error message returned by Piwik
# in case it receives an error.
def call(method, params={})
self.class.call(method, params, config[:piwik_url], config[:auth_token])
end
def config
@config ||= self.class.load_config_from_file
end
def collection
self.class.collection
end
class << self
def collection
"#{self.to_s.pluralize}".safe_constantize
end
# This is required to normalize the API responses when the Rails XmlSimple version is used
def parse_xml xml
result = XmlSimple.xml_in(xml, {'ForceArray' => false})
result = result['result'] if result['result']
result
end
def load id
collection.get(id_attr => id)
end
alias :reload :load
# Calls the supplied Piwik API method, with the supplied parameters.
#
# Returns a string containing the XML reply from Piwik, or raises a
# <tt>Piwik::ApiError</tt> exception with the error message returned by Piwik
# in case it receives an error.
def call(method, params, piwik_url=nil, auth_token=nil)
params ||= {}
raise MissingConfiguration, "Please edit ~/.piwik to include your piwik url and auth_key" if piwik_url.nil? || auth_token.nil?
url = "#{piwik_url}/index.php?"
params.merge!({:module => 'API', :format => 'xml', :method => method})
params.merge!({:token_auth => auth_token}) unless auth_token.nil?
url << params.to_query
verbose_obj_save = $VERBOSE
$VERBOSE = nil # Suppress "warning: peer certificate won't be verified in this SSL session"
xml = RestClient.get(url)
$VERBOSE = verbose_obj_save
if xml.is_a?(String) && xml.force_encoding('BINARY').is_binary_data?
xml.force_encoding('BINARY')
elsif xml =~ /error message=/
result = XmlSimple.xml_in(xml, {'ForceArray' => false})
raise ApiError, result['error']['message'] if result['error']
else
xml
end
end
# Checks for the config, creates it if not found
def load_config_from_file
# Useful for testing or embedding credentials - although as always
# it is not recommended to embed any kind of credentials in source code for security reasons
return { :piwik_url => PIWIK_URL, :auth_token => PIWIK_TOKEN } if PIWIK_URL.present? and PIWIK_TOKEN.present?
config = {}
if defined?(RAILS_ROOT) and RAILS_ROOT != nil
home = RAILS_ROOT
filename = "config/piwik.yml"
else
home = ENV['HOME'] || ENV['USERPROFILE'] || ENV['HOMEPATH'] || "."
filename = ".piwik"
end
temp_config = if File.exists?(File.join(home,filename))
YAML::load(open(File.join(home,filename)))
else
open(File.join(home,filename),'w') { |f| f.puts @@template }
YAML::load(@@template)
end
temp_config.each { |k,v| config[k.to_sym] = v } if temp_config
if config[:piwik_url] == nil || config[:auth_token] == nil
if defined?(RAILS_ROOT) and RAILS_ROOT != nil
raise MissingConfiguration, "Please edit ./config/piwik.yml to include your piwik url and auth_key"
else
raise MissingConfiguration, "Please edit ~/.piwik to include your piwik url and auth_key"
end
end
config
end
end
end
end
|
package nak.data
/*
Copyright 2009 David Hall, Daniel Ramage
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.
*/
/**
* Represents a single example from a collection of data. Intentionally overly general.
*
* @author dlwh
*/
trait Example[+L,+T] extends Observation[T] with Labeled[L] with Serializable {outer=>
def id : String
def label: L
/**
* Converts the features in this example to a different one while still
* preserving label and id.
*/
override def map[U](f: T=>U):Example[L, U] = new Example[L,U] {
val label = outer.label
val id = outer.id
val features = f(outer.features)
}
/**
* Converts the label in this example to a different one while still
* preserving features and id.
*/
def relabel[L2](f: L=>L2):Example[L2, T] = new Example[L2,T] {
val label = f(outer.label)
val id = outer.id
val features = outer.features
}
/**
* Converts the features in this example to a different one while still
* preserving label and id.
*/
override def flatMap[U](f: T=>U) = map(f)
override def toString = {
"Example { id =" + id + ", label = " + label + ", features = " + features + "}"
}
}
object Example {
/**
* Create a new Example.
*/
def apply[L,T](label: L, features: T, id:String=""): Example[L,T] = {
val l = label
val f = features
val i = id
new Example[L,T] {
val id = i
val label = l
val features = f
}
}
/**
* Lifts a function to operate over Examples,
* Rather than the contained object.
*/
def lift[T,U,L](f: T=>U) = (o : Example[L,T]) => o.map(f)
}
/**
* Indexes the labels and features of a series of examples. Can be made much
* more general, but just doing what is needed for the time being.
*/
class ExampleIndexer(addDummyFirstIndex: Boolean = true)
extends (Example[String,Seq[FeatureObservation[String]]]
=> Example[Int,Seq[FeatureObservation[Int]]]) {
import nak.NakContext._
import nak.util.GrowableIndex
private[this] val lmap = new GrowableIndex[String]()
private[this] val fmap = new GrowableIndex[String]()
if (addDummyFirstIndex)
fmap("DUMMY FEATURE BECAUSE LIBLINEAR STARTS WITH 1-BASED INDEX")
def apply(ex: Example[String,Seq[FeatureObservation[String]]]) =
ex.relabel(lmap)
.map(_.map(feature => feature.map(fmap)))
.map(condense)
def getMaps = (lmap.toMap, fmap.toMap)
}
/**
* Indexes the labels and features of a series of examples. Can be made much
* more general, but just doing what is needed for the time being.
*/
class BinomialExampleIndexer(
successLabel: String = "Y",
failureLabel: String = "N",
addDummyFirstIndex: Boolean = true
) extends (Example[(Int,Int),Seq[FeatureObservation[String]]]
=> Example[(Int,Int),Seq[FeatureObservation[Int]]]) {
import nak.NakContext._
import nak.util.GrowableIndex
private[this] val lmap = Map(successLabel->0,failureLabel->1)
private[this] val fmap = new GrowableIndex[String]()
if (addDummyFirstIndex)
fmap("DUMMY FEATURE BECAUSE LIBLINEAR STARTS WITH 1-BASED INDEX")
def apply(ex: Example[(Int,Int),Seq[FeatureObservation[String]]]) =
ex.map(_.map(feature => feature.map(fmap)))
.map(condense)
def getMaps = (lmap, fmap.toMap)
}
/**
* Indexes the labels and features of a series of examples. Can be made much
* more general, but just doing what is needed for the time being.
*/
class HashedExampleIndexer(requestedHighestFeatureIndex: Int)
extends (Example[String,Seq[FeatureObservation[String]]]
=> Example[Int,Seq[FeatureObservation[Int]]]) {
import nak.NakContext._
import nak.util.GrowableIndex
private[this] val lmap = new GrowableIndex[String]()
private[this] val fmap = HashedFeatureMap(requestedHighestFeatureIndex)
val highestFeatureIndex = fmap.maxNumberOfFeatures
def apply(ex: Example[String,Seq[FeatureObservation[String]]]) =
ex.relabel(lmap)
.map(_.map(feature => feature.map(f=>fmap.indexOfFeature(f).get)))
.map(condense)
def getMaps = (lmap.toMap, fmap)
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using UnmanagedInspector;
namespace DebugInspector.Controls.UnManaged.ThreadStacks
{
internal class ThreadStackNodeManager
{
private readonly TreeView r_treeview;
private String _appName;
private Boolean _hexValues;
private Boolean _moduleNames;
private Boolean _lineNumbers;
private Boolean _offsets;
private ThreadStackManager _tsm;
private Dictionary<int, String> _threadNames;
private RootNode _rootNodeNew;
public ThreadStackNodeManager(TreeView treeview, String appName)
{
if (treeview == null)
throw new ArgumentNullException("treeview");
if (appName == null)
throw new ArgumentNullException("appName");
_appName = appName;
r_treeview = treeview;
_hexValues = true;
_moduleNames = true;
_lineNumbers = true;
_offsets = true;
_tsm = null;
}
public String ApplicationName { get { return _appName; } }
public ThreadStackManager ThreadStackManager { get { return _tsm; } }
public Boolean HexValue
{
get { return _hexValues; }
set { _hexValues = value; }
}
public Boolean ModuleNames
{
get { return _moduleNames; }
set { _moduleNames = value; }
}
public Boolean LineNumbers
{
get { return _lineNumbers; }
set { _lineNumbers = value; }
}
public Boolean Offsets
{
get { return _offsets; }
set { _offsets = value; }
}
internal String GetValue(Int64 value)
{
return GetValue((Int32)value);
//return _hexValues ? "0x" + value.ToString("X") : value.ToString();
}
internal String GetValue(UInt64 value)
{
return GetValue((UInt32)value);
//return _hexValues ? "0x" + value.ToString("X") : value.ToString();
}
internal String GetValue(UInt32 value)
{
return _hexValues ? "0x" + value.ToString("X") : value.ToString();
}
internal String GetValue(Int32 value)
{
return _hexValues ? "0x" + value.ToString("X") : value.ToString();
}
internal void Refresh(Exception ex)
{
r_treeview.Nodes.Clear();
r_treeview.Nodes.Add(ex.ToString());
_rootNodeNew = null;
}
public void Refresh(ThreadStackManager manager, IDebugProcess process, Dictionary<int, String> threadNames)
{
_tsm = manager;
//_procInfo = process;
_appName = process.Name;
_threadNames = threadNames; // seems to hang if we iterate the threads object here
if (_rootNodeNew == null)
{
_rootNodeNew = new RootNode(this, r_treeview);
}
else
{
_rootNodeNew.Refresh();
}
}
}
}
|
package com.zhyea.bamboo.general
import android.graphics.Rect
import com.zhyea.bamboo.reader.common.Pool
class RectPool : Pool<Rect>() {
override fun newInstance(): Rect {
return Rect()
}
override fun reset(t: Rect) {
t.setEmpty()
}
}
|
import { cms } from '@tensei/cms'
import SupertestSession from 'supertest-session'
import Supertest, { SuperTest as SI } from 'supertest'
import { setup, fakeUser, setupFakeMailer, getFakeMailer } from './setup'
export const getCmsCsrfToken = async (client: SI<any>): Promise<string> => {
const response = await client.get(`/cms/api/csrf`)
return response.headers['set-cookie'][0].split(';')[0].split('=')[1]
}
test('can passwordlessly register a new administrator user', async () => {
const mailerMock = getFakeMailer()
const email = fakeUser().email
const {
app,
ctx: {
orm: { em }
}
} = await setup([cms().plugin(), setupFakeMailer(mailerMock)], false)
await em.nativeDelete('AdminUserSession', {})
const client = (SupertestSession(app) as unknown) as SI<any>
const csrf = await getCmsCsrfToken(client)
// Clear all existing administrators and passwordless tokens.
await em.nativeDelete('AdminToken', {})
await em.nativeDelete('AdminUser', {})
const response = await client
.post('/cms/api/passwordless/email/register')
.set('X-XSRF-TOKEN', csrf)
.send({
email
})
expect(response.status).toBe(204)
const [{ token }] = await em.find<{
token: string
}>('AdminToken', {})
const loginResponse = await client.get(`/cms/api/passwordless/token/${token}`)
expect(loginResponse.status).toBe(302)
expect(loginResponse.headers['location']).toBe('/cms')
const session = await em.find<{
data: string
}>('AdminUserSession', {})
const authUser = await em.findOne<{
id: string
email: string
}>('AdminUser', {
email
})
const sessionData = JSON.parse(session[0].data)
expect(sessionData?.user?.id?.toString()).toBe(authUser.id.toString())
})
test('cannot register another administrator if a super admin already exists', async () => {
const mailerMock = getFakeMailer()
const email = fakeUser().email
const {
app,
ctx: {
orm: { em }
}
} = await setup([cms().plugin(), setupFakeMailer(mailerMock)], false)
const client = (SupertestSession(app) as unknown) as SI<any>
const csrf = await getCmsCsrfToken(client)
// Clear all existing administrators and passwordless tokens.
await em.nativeDelete('AdminToken', {})
await em.nativeDelete('AdminUser', {})
await client
.post('/cms/api/passwordless/email/register')
.set('X-XSRF-TOKEN', csrf)
.send({
email
})
// attempt to register an administrator again
const response = await client
.post('/cms/api/passwordless/email/register')
.set('X-XSRF-TOKEN', csrf)
.send({
email
})
expect(response.status).toBe(400)
expect(response.body.message).toBe('Unauthorized.')
})
test('can passwordlessly login an existing administrator user', async () => {
const mailerMock = getFakeMailer()
const email = fakeUser().email
const {
app,
ctx: {
orm: { em }
}
} = await setup([cms().plugin(), setupFakeMailer(mailerMock)], false)
const client = (SupertestSession(app) as unknown) as SI<any>
const csrf = await getCmsCsrfToken(client)
// Clear all existing administrators and passwordless tokens.
await em.nativeDelete('AdminToken', {})
await em.nativeDelete('AdminUser', {})
await client
.post('/cms/api/passwordless/email/register')
.set('X-XSRF-TOKEN', csrf)
.send({
email
})
// clear registration token
await em.nativeDelete('AdminToken', {})
const response = await client
.post('/cms/api/passwordless/email/login')
.set('X-XSRF-TOKEN', csrf)
.send({
email
})
const [{ token }] = await em.find<{
token: string
}>('AdminToken', {})
const loginResponse = await client.get(`/cms/api/passwordless/token/${token}`)
expect(loginResponse.status).toBe(302)
expect(loginResponse.headers['location']).toBe('/cms')
})
test('redirects user to login when token is invalid or malformed', async () => {
const mailerMock = getFakeMailer()
const email = fakeUser().email
const {
app,
ctx: {
orm: { em }
}
} = await setup([cms().plugin(), setupFakeMailer(mailerMock)], false)
const client = (SupertestSession(app) as unknown) as SI<any>
const csrf = await getCmsCsrfToken(client)
// Clear all existing administrators and passwordless tokens.
await em.nativeDelete('AdminToken', {})
await em.nativeDelete('AdminUser', {})
await client
.post('/cms/api/passwordless/email/register')
.set('X-XSRF-TOKEN', csrf)
.send({
email
})
const loginResponse = await client.get(
`/cms/api/passwordless/token/WRONG_TOKEN`
)
expect(loginResponse.status).toBe(302)
expect(loginResponse.headers['location']).toBe(
'/cms/auth/login?error=Your%20login%20credentials%20are%20invalid.%20Please%20try%20again.'
)
})
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
-- | K3 code generation interface.
module Language.K3.Codegen where
import Language.K3.Core.Common
import Language.K3.Core.Annotation
import Language.K3.Core.Declaration
import Language.K3.Core.Expression
import Language.K3.Core.Type
{- Disabled while HaskellCG is deprecated
--import qualified Language.K3.Codegen.Haskell as HG
-}
class Compilable a where
typ :: K3 Type -> a
expression :: K3 Expression -> a
declaration :: K3 Declaration -> a
generate :: Identifier -> K3 Declaration -> a
compile :: a -> Either String String
-- | Generates K3 code, essentially a pretty printer.
data IdentityEmbedding
= IdDecl (K3 Declaration)
| IdExpression (K3 Expression)
| IdType (K3 Type)
instance Compilable IdentityEmbedding where
typ t = IdType t
expression e = IdExpression e
declaration d = IdDecl d
generate = undefined
compile = undefined
-- | DEPRECATED: Haskell code generation.
{-
instance Compilable (HG.CodeGeneration HG.HaskellEmbedding) where
typ = HG.typ
expression = HG.expression
declaration = HG.declaration
generate = HG.generate
compile = HG.compile
-}
|
import type { ModuleMetadata, Type } from '@nestjs/common/interfaces';
import type { ClientOptions } from 'blockcypher-apis';
export type BlockCypherModuleOptions = ClientOptions;
export interface BlockCypherOptionsFactory {
createBlockCypherOptions():
| Promise<BlockCypherModuleOptions>
| BlockCypherModuleOptions;
}
export interface BlockCypherModuleAsyncOptions
extends Pick<ModuleMetadata, 'imports'> {
useExisting?: Type<BlockCypherOptionsFactory>;
useClass?: Type<BlockCypherOptionsFactory>;
useFactory?: (
...args: any[]
) => Promise<BlockCypherModuleOptions> | BlockCypherModuleOptions;
inject?: any[];
}
|
import datetime
from methinks.db import Entry
import pytest
from server.app import create_app
from server.app import db as _db
from sqlalchemy import event
from sqlalchemy.orm import sessionmaker
@pytest.fixture(scope="session")
def app(request):
"""
Returns session-wide application.
"""
return create_app()
@pytest.fixture(scope="session")
def db(app, request):
"""
Returns session-wide initialised database.
"""
with app.app_context():
_db.drop_all()
_db.create_all()
@pytest.fixture(scope="function", autouse=True)
def session(app, db, request):
"""
Returns function-scoped session.
"""
with app.app_context():
conn = _db.engine.connect()
txn = conn.begin()
options = dict(bind=conn, binds={})
sess = _db.create_scoped_session(options=options)
# establish a SAVEPOINT just before beginning the test
# (http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#using-savepoint)
sess.begin_nested()
@event.listens_for(sess(), 'after_transaction_end')
def restart_savepoint(sess2, trans):
# Detecting whether this is indeed the nested transaction of the test
if trans.nested and not trans._parent.nested:
# The test should have normally called session.commit(),
# but to be safe we explicitly expire the session
sess2.expire_all()
sess.begin_nested()
_db.session = sess
yield sess
# Cleanup
sess.remove()
# This instruction rollsback any commit that were executed in the tests.
txn.rollback()
conn.close()
def test_insert(session):
e = Entry(text='My example', date=datetime.date.today())
session.add(e)
session.commit()
def test_delete(session):
e = Entry(text='My example', date=datetime.date.today())
session.add(e)
session.commit()
session.delete(e)
session.commit()
def test_find_by_hash(session):
e = Entry(text='My example', date=datetime.date.today())
session.add(e)
session.commit()
first = Entry.query.filter(Entry.hexid == e.hash).first()
assert first == e
|
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { TeamSignInPage } from '../team-sign-in/team-sign-in';
import { TeamCreationPage } from '../team-creation/team-creation';
import { AuthState, Database, Player } from '../../providers/my-data/my-data';
import { HomePage } from '../home/home';
/*
Generated class for the LandingPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
templateUrl: 'build/pages/landing/landing.html',
})
export class LandingPage {
teamSignInPage: any = TeamSignInPage;
teamCreationPage: any = TeamCreationPage;
constructor(private navCtrl: NavController, public db: Database) {
this.db.onAuthState()
.subscribe((a: AuthState) => {
console.log('landing', 'constructor', '>>>', a);
if (a) {
this.db.getPlayer(a.playerID)
.then((player: Player) => this.navCtrl.setRoot(HomePage, player));
}
});
}
}
|
class SmsCancellationSuccessJob < NotifyJobBase
STANDARD_TEMPLATE_ID = 'fd90b779-03e1-471d-b9e4-34afa9622410'.freeze
BSL_TEMPLATE_ID = '43fb57ed-1abe-4115-81ca-10f5042e23ca'.freeze
def perform(appointment)
return unless api_key
client.send_sms(
phone_number: appointment.canonical_sms_number,
template_id: template_for(appointment),
reference: appointment.to_param,
personalisation: {
date: "#{appointment.start_at.to_s(:govuk_date_short)} (#{appointment.timezone})"
}
)
end
private
def template_for(appointment)
if appointment.bsl_video?
BSL_TEMPLATE_ID
else
STANDARD_TEMPLATE_ID
end
end
end
|
class LinkTypeValidator < ActiveModel::Validator
def validate(record)
return if record.link_type == "taxons"
record.errors[:link_type] << I18n.t("tag_import.errors.invalid_link_types")
end
end
|
using HillPigeon.ApplicationParts;
using Microsoft.AspNetCore.Http;
using System;
namespace HillPigeon.Orleans.Configuration
{
public class OrleansRoutingOptions
{
public Func<ControllerModel, string> ControllerNameRule { get; set; }
public Action<HttpContext, HttpRequestContext> HttpRequestContext { get; set; }
}
}
|
package protocol
import (
"github.com/tendermint/go-crypto"
"github.com/zbo14/pos/crypto/tndr"
"github.com/zbo14/pos/graph"
"github.com/zbo14/pos/merkle"
. "github.com/zbo14/pos/util"
)
type CommitProof struct {
ParentProofs [][]*merkle.Proof `json:"parent_proofs"`
Proofs []*merkle.Proof `json:"proofs"`
PubKey crypto.PubKeyEd25519 `json:"public_key"`
Seed []byte `json:"seed"`
Size int64 `json:"size"`
}
type SpaceProof struct {
Proofs []*merkle.Proof `json:"proofs"`
PubKey crypto.PubKeyEd25519 `json:"public_key"`
Seed []byte `json:"seed"`
Size int64 `json:"size"`
}
type Prover struct {
Commit []byte //merkle root hash
graph *graph.Graph
Priv crypto.PrivKeyEd25519
tree *merkle.Tree
}
func NewProver(priv crypto.PrivKeyEd25519) *Prover {
return &Prover{
Priv: priv,
}
}
func (p *Prover) PubKey() crypto.PubKeyEd25519 {
return tndr.PubKey(p.Priv)
}
func (p *Prover) MerkleTree(id int) {
p.tree = merkle.NewTree(id)
}
func (p *Prover) Graph(id int, _type string) {
switch _type {
case graph.DOUBLE_BUTTERFLY:
p.graph = graph.DefaultDoubleButterfly(id)
case graph.LINEAR_SUPER_CONCENTRATOR:
p.graph = graph.DefaultLinearSuperConcentrator(id)
case graph.STACKED_EXPANDERS:
p.graph = graph.DefaultStackedExpanders(id)
default:
Panicf("Unexpected graph type: %s\n", _type)
}
}
func (p *Prover) GraphDoubleButterfly(id int) {
p.Graph(id, graph.DOUBLE_BUTTERFLY)
}
func (p *Prover) GraphLinearSuperConcentrator(id int) {
p.Graph(id, graph.LINEAR_SUPER_CONCENTRATOR)
}
func (p *Prover) GraphStackedExpanders(id int) {
p.Graph(id, graph.STACKED_EXPANDERS)
}
func (p *Prover) MakeCommit() {
pub := p.PubKey()
p.graph.SetValues(pub)
numLeaves := p.graph.Size()
p.tree.Init(numLeaves)
var idx int64
for ; idx < numLeaves; idx++ {
nd := p.graph.Get(idx)
if !p.tree.AddLeaf(nd.Value) {
panic("Could not add leaf")
}
}
p.tree.HashLevels()
p.Commit = p.tree.Root()
}
func (p *Prover) NewCommitProof(parentProofs [][]*merkle.Proof, proofs []*merkle.Proof) *CommitProof {
pub := p.PubKey()
size := p.graph.Size()
return &CommitProof{
ParentProofs: parentProofs,
Proofs: proofs,
PubKey: pub,
Size: size,
}
}
func (p *Prover) ProveCommit(challenges []int64) *CommitProof {
if p.graph == nil {
panic("Graph is not set")
}
if p.tree == nil {
panic("Tree is not set")
}
var parents Int64s
proofs := make([]*merkle.Proof, len(challenges))
parentProofs := make([][]*merkle.Proof, len(challenges))
for i, c := range challenges {
sibling := p.graph.Get(c ^ 1)
nd := p.graph.Get(c)
proofs[i] = p.tree.ComputeProof(c, sibling.Value, nd.Value)
parents = p.graph.GetParents(c)
if len(parents) > 0 {
parentProofs[i] = make([]*merkle.Proof, len(parents))
for j, parent := range parents { //should be sorted
sibling = p.graph.Get(parent ^ 1)
nd = p.graph.Get(parent)
parentProofs[i][j] = p.tree.ComputeProof(parent, sibling.Value, nd.Value)
}
}
}
return p.NewCommitProof(parentProofs, proofs)
}
func (p *Prover) NewSpaceProof(proofs []*merkle.Proof) *SpaceProof {
pub := p.PubKey()
size := p.graph.Size()
return &SpaceProof{
Proofs: proofs,
PubKey: pub,
Size: size,
}
}
func (p *Prover) ProveSpace(challenges []int64) *SpaceProof {
if p.graph == nil {
panic("Graph is not set")
}
if p.tree == nil {
panic("Tree is not set")
}
proofs := make([]*merkle.Proof, len(challenges))
for i, c := range challenges {
sibling := p.graph.Get(c ^ 1)
nd := p.graph.Get(c)
proofs[i] = p.tree.ComputeProof(c, sibling.Value, nd.Value)
}
return p.NewSpaceProof(proofs)
}
|
package never.ui
import never.repository.{RepositoryReadApi, RepositoryWriteApi}
import never.ui.TaskEditorModel.EditingExistingNode
import org.scalatest.Inspectors
class TaskEditorModelImplTest extends BaseTest {
val readApi = mock[RepositoryReadApi]
val writeApi = mock[RepositoryWriteApi]
val impl = new TaskEditorModelImpl(readApi, writeApi)
val accessor = mock[TaskEditorAreaAccessor]
when(accessor.content).thenReturn("")
when(accessor.tags).thenReturn(Set.empty)
val listener = mock[TaskEditorListener]
impl.setStateAccessor(accessor)
impl.addListener(listener)
val SomeTags = Set("tag1", "tag2")
"model" should {
"do nothing on save when in empty editing state" in {
// given
impl.setEmptyEditingState()
reset(listener)
// when
impl.save()
// then
verifyNoMoreInteractions(writeApi, listener)
}
"do nothing if the new node is empty or blank" in Inspectors.forAll(Seq("", " ")) { text =>
// given
impl.editNewNode(None, Set.empty)
when(accessor.content).thenReturn(text)
reset(listener)
// when
impl.save()
// then
verifyNoMoreInteractions(writeApi, listener)
}
"add node if the new node is not empty" in {
// given
impl.editNewNode(None, Set.empty)
when(accessor.content).thenReturn("abc")
val node = someNodeView()
val updatedNode = node.copy(content = "abc")
when(readApi.nodeById(*)).thenReturn(Some(updatedNode))
reset(listener)
// when
impl.save()
// then
verify(writeApi).addNode("TODO", "abc")
verify(listener).nodeSaved(*)
verify(listener).editingNodeChanged(EditingExistingNode, Some(updatedNode))
verifyNoMoreInteractions(writeApi, listener)
}
"add data node if the new node is not empty" in {
// given
impl.editNewNode(Some("DATA"), Set.empty)
when(accessor.content).thenReturn("abc")
val node = someNodeView()
val updatedNode = node.copy(content = "abc")
when(readApi.nodeById(*)).thenReturn(Some(updatedNode))
reset(listener)
// when
impl.save()
// then
verify(writeApi).addNode("DATA", "abc")
verify(listener).nodeSaved(*)
verify(listener).editingNodeChanged(EditingExistingNode, Some(updatedNode))
verifyNoMoreInteractions(writeApi, listener)
}
"add node if the new node is not empty and set tags" in {
// given
impl.editNewNode(None, Set.empty)
when(accessor.content).thenReturn("abc")
when(accessor.tags).thenReturn(SomeTags)
val node = someNodeView()
val updatedNode = node.copy(content = "abc", tags = SomeTags)
when(readApi.nodeById(*)).thenReturn(Some(updatedNode))
reset(listener)
// when
impl.save()
// then
verify(writeApi).addNode("TODO", "abc")
verify(writeApi).setTags(*, eqTo(SomeTags))
verify(listener).nodeSaved(*)
verify(listener).editingNodeChanged(EditingExistingNode, Some(updatedNode))
verifyNoMoreInteractions(writeApi, listener)
}
"save changes for existing node" in {
// given
val node = someNodeView()
when(readApi.nodeById(node.id)).thenReturn(Some(node))
impl.editNode(node.id, focusEditor = false)
reset(readApi, listener)
val updatedNode = node.copy(content = "abc")
when(readApi.nodeById(node.id)).thenReturn(Some(updatedNode))
when(accessor.content).thenReturn("abc")
// when
impl.save()
// then
verify(writeApi).changeNodeContent(node.id, "abc")
verify(listener).nodeSaved(*)
verify(listener).editingNodeChanged(EditingExistingNode, Some(updatedNode))
verifyNoMoreInteractions(writeApi, listener)
}
"save changes in tags for existing node" in {
// given
val node = someNodeView()
when(readApi.nodeById(node.id)).thenReturn(Some(node))
impl.editNode(node.id, focusEditor = false)
reset(readApi, listener)
val updatedNode = node.copy(tags = SomeTags)
when(readApi.nodeById(node.id)).thenReturn(Some(updatedNode))
when(accessor.content).thenReturn(node.content)
when(accessor.tags).thenReturn(SomeTags)
// when
impl.save()
// then
verify(writeApi, never).changeNodeContent(*, *)
verify(writeApi).setTags(node.id, SomeTags)
verify(listener).nodeSaved(*)
verify(listener).editingNodeChanged(EditingExistingNode, Some(updatedNode))
verifyNoMoreInteractions(writeApi, listener)
}
"do nothing on save if content didn't change for existing node" in {
// given
val node = someNodeView()
when(readApi.nodeById(node.id)).thenReturn(Some(node))
impl.editNode(node.id, focusEditor = false)
when(accessor.content).thenReturn(node.content)
reset(listener)
// when
impl.save()
// then
verifyNoMoreInteractions(writeApi, listener)
}
"do nothing on save if tags didn't change for existing node" in {
// given
val node = someNodeView(tags = SomeTags)
when(readApi.nodeById(node.id)).thenReturn(Some(node))
impl.editNode(node.id, focusEditor = false)
when(accessor.content).thenReturn(node.content)
when(accessor.tags).thenReturn(SomeTags)
reset(listener)
// when
impl.save()
// then
verifyNoMoreInteractions(writeApi, listener)
}
"return editing node id" in {
// given
val node = someNodeView()
when(readApi.nodeById(node.id)).thenReturn(Some(node))
impl.editNode(node.id, focusEditor = false)
// when
val id = impl.editingNodeId
// then
id.value shouldBe node.id
}
"return empty editing node id" in {
// expect
impl.editingNodeId shouldBe empty
}
"do nothing on edit node if already editing node with the same id" in {
// given
val node = someNodeView()
when(readApi.nodeById(node.id)).thenReturn(Some(node))
impl.editNode(node.id, focusEditor = false)
reset(listener)
// when
impl.editNode(node.id, focusEditor = false)
// then
verifyNoMoreInteractions(writeApi, listener)
}
"save previous content on edit node if already editing node with the another id" in {
// given
val node = someNodeView()
val node2 = someNodeView()
when(readApi.nodeById(node.id)).thenReturn(Some(node))
impl.editNode(node.id, focusEditor = false)
reset(listener, readApi)
val updatedNode = node.copy(content = "abc", tags = SomeTags)
when(readApi.nodeById(node.id)).thenReturn(Some(updatedNode))
when(readApi.nodeById(node2.id)).thenReturn(Some(node2))
when(accessor.content).thenReturn("abc")
when(accessor.tags).thenReturn(SomeTags)
// when
impl.editNode(node2.id, focusEditor = false)
// then
verify(writeApi).changeNodeContent(node.id, "abc")
verify(writeApi).setTags(node.id, SomeTags)
verify(listener).nodeSaved(node.id)
verify(listener).editingNodeChanged(EditingExistingNode, Some(updatedNode))
verify(listener).editingNodeChanged(EditingExistingNode, Some(node2))
verifyNoMoreInteractions(writeApi, listener)
}
"lose focus" in {
// when
impl.loseFocus()
// then
verify(listener).loseFocus()
}
"request focus when creating new node" in {
// when
impl.editNewNode(None, Set.empty)
// then
verify(accessor).requestFocus()
}
}
}
|
""" Helper module for handling common options """
import tornado.options
from tornado.options import define, options
define("debug", default=True, type=bool,
metavar="True|False", help="debug mode")
define("config", default="config/ms3.conf", type=str,
metavar="CONFIG FILE", help="Alternative configuration file")
define("datadir", default="data", type=str, metavar="DATA DIR",
help="The directory where the files should be stored")
def get_options():
""" Alias for tornado.options.options """
return tornado.options.options
def parse_options(args=None):
""" Helper for parsing the options in a consistent fashion """
tornado.options.parse_command_line(args=args)
try:
tornado.options.parse_config_file(options.config)
except IOError:
pass
tornado.options.parse_command_line(args=args)
|
class User < ApplicationRecord
validates :email, presence: true, email: true
delegate :admin?, :read?, :manage_results?, :manage_assignments?,
:department_slugs, to: :permissions
def username
email.split("@").first
end
def permissions
@permissions ||= PermissionSet.for(username)
end
def departments
Department.where(slug: department_slugs)
end
end
|
@section('title')
Quản Lý Danh Mục Sản Phẩm
@stop
@extends('admin.general.master')
@section('content')
<link rel="stylesheet" type="text/css" href="{{url('')}}/assets/dhtmlxgrid.css">
<script src="{{url('')}}/assets/dhtmlxgrid.js" type="text/javascript"></script>
<div class="content-body">
<section id="validation-scenario">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Validation Scenario</h4>
<a class="heading-elements-toggle"><i class="la la-ellipsis-v font-medium-3"></i></a>
<div class="heading-elements">
<ul class="list-inline mb-0">
<li><a data-action="collapse"><i class="ft-minus"></i></a></li>
<li><a data-action="reload"><i class="ft-rotate-cw"></i></a></li>
<li><a data-action="expand"><i class="ft-maximize"></i></a></li>
<li><a data-action="close"><i class="ft-x"></i></a></li>
</ul>
</div>
</div>
<div class="card-content collapse show">
<div class="card-body card-dashboard ">
<!-- <div id="validation"></div> -->
<div id="grid_here" style="width: 600px; height: 400px;"></div>
<script type="text/javascript" charset="utf-8">
mygrid = new dhtmlXGridObject('grid_here');
mygrid.setHeader("Start date,End date,Text");
mygrid.init();
mygrid.load("./grid_data");
var dp = new dataProcessor("./grid_data");
dp.init(mygrid);
</script>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
@stop
|
FactoryGirl.define do
factory :food_information, class: Spree::FoodInformation do
description "test description"
end
end
|
package com.team_no_yes.matzip_exe.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.team_no_yes.matzip_exe.R
import com.team_no_yes.matzip_exe.adapter.RecycleAboutUsAdapter
import com.team_no_yes.matzip_exe.databinding.ActivityAboutUsBinding
import com.team_no_yes.matzip_exe.model.ModelAboutUsJson
import com.team_no_yes.matzip_exe.model.ModelRecycleAboutUs
import com.google.gson.Gson
class AboutUs : AppCompatActivity() {
private lateinit var activityAboutUsBinding: ActivityAboutUsBinding
private val item = ArrayList<ModelRecycleAboutUs>()
private lateinit var manager: LinearLayoutManager
private lateinit var recycleAboutUsAdapter: RecycleAboutUsAdapter
private lateinit var aboutUsJson: ModelAboutUsJson
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityAboutUsBinding = DataBindingUtil.setContentView(this, R.layout.activity_about_us)
init()
}
private fun init(){
toolbarInit()
getJson()
recycleInit()
}
private fun toolbarInit(){
setSupportActionBar(activityAboutUsBinding.toolbarAboutus)
supportActionBar!!.title = getString(R.string.AboutUs)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
private fun getJson(){
try{
val gson = Gson()
val inputStream = this.assets.open("json/AboutUs.json")
val json = inputStream.bufferedReader().use {
it.readText()
}
aboutUsJson = gson.fromJson(json, ModelAboutUsJson::class.java)
itemInit()
}
catch (e: Exception){
e.printStackTrace()
}
}
private fun itemInit(){
for (i in aboutUsJson.items){
item.add(ModelRecycleAboutUs(i.Position, i.Name, i.Email))
}
}
private fun recycleInit(){
activityAboutUsBinding.recycleAboutus.setHasFixedSize(true)
manager = LinearLayoutManager(this)
activityAboutUsBinding.recycleAboutus.layoutManager = manager
recycleAboutUsAdapter = RecycleAboutUsAdapter(item)
activityAboutUsBinding.recycleAboutus.adapter = recycleAboutUsAdapter
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
android.R.id.home->{
finish()
}
}
return super.onOptionsItemSelected(item)
}
}
|
<?php
/**
* Class Sheep_Debug_Test_Helper_Config
*
* @category Sheep
* @package Sheep_Subscription
* @license Copyright: Pirate Sheep, 2016
* @link https://piratesheep.com
*
* @covers Sheep_Debug_Helper_Config
* @codeCoverageIgnore
*/
class Sheep_Debug_Test_Helper_Config extends EcomDev_PHPUnit_Test_Case
{
/** @var Sheep_Debug_Helper_Config */
protected $helper;
protected function setUp()
{
$this->helper = Mage::helper('sheep_debug/config');
}
public function testGetMagentoVersion()
{
$actual = $this->helper->getMagentoVersion();
$this->assertNotNull($actual);
}
public function testGetExtensionRequirements()
{
$actual = $this->helper->getExtensionRequirements();
$this->assertNotNull($actual);
$this->assertContains('simplexml', $actual);
}
public function testGetExtensionStatus()
{
$helper = $this->getHelperMock('sheep_debug/config', array('getExtensionRequirements'));
$helper->expects($this->once())->method('getExtensionRequirements')->willReturn(array('mcrypt', 'xdebug'));
$actual = $helper->getExtensionStatus();
$this->assertNotNull($actual);
$this->assertCount(2, $actual);
$this->assertArrayHasKey('mcrypt', $actual);
$this->assertTrue($actual['mcrypt']);
}
public function testGetModules()
{
$helper = $this->getHelperMock('sheep_debug/config', array('getMagentoVersion'));
$helper->expects($this->any())->method('getMagentoVersion')->willReturn('1.3.0');
$modules = $helper->getModules();
$this->assertNotNull($modules);
$this->assertGreaterThan(2, count($modules));
$this->assertEquals('Magento', $modules[0]['module']);
$this->assertEquals('core', $modules[0]['codePool']);
$this->assertTrue($modules[0]['active']);
$this->assertEquals('1.3.0', $modules[0]['version']);
$this->assertEquals('Mage_Core', $modules[1]['module']);
$this->assertEquals('core', $modules[1]['codePool']);
$this->assertTrue($modules[1]['active']);
$this->assertNotNull($modules[1]['version']);
}
}
|
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:iot_firestore_flutter_app/auth_helper.dart';
import 'package:iot_firestore_flutter_app/const/custom_styles.dart';
import 'package:iot_firestore_flutter_app/route/routing_constants.dart';
import 'package:iot_firestore_flutter_app/widgets/my_password_field.dart';
import 'package:iot_firestore_flutter_app/widgets/my_text_button.dart';
import 'package:iot_firestore_flutter_app/widgets/my_text_field.dart';
import 'package:flutter/material.dart';
class SignUpScreen extends StatefulWidget {
const SignUpScreen({Key? key}) : super(key: key);
@override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
bool passwordVisibility = true;
final TextEditingController _email = TextEditingController();
final TextEditingController _password = TextEditingController();
final TextEditingController _passwordConfirm = TextEditingController();
@override
void dispose() {
_email.dispose();
_password.dispose();
_passwordConfirm.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding:
const EdgeInsets.only(left: 16, right: 16, top: 40, bottom: 30),
child: CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20,
),
child: Column(
children: [
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Image(
width: 24,
color: Colors.white,
image: AssetImage('assets/images/back_arrow.png'),
),
),
Text(
"Register",
style: kHeadline,
),
Text(
"Create new account to get started.",
style: kBodyText2,
),
SizedBox(
height: 50,
),
MyTextField(
hintText: 'Email',
inputType: TextInputType.emailAddress,
textEditingController: _email,
),
MyPasswordField(
hintText: 'Password',
textEditingController: _password,
isPasswordVisible: passwordVisibility,
onTap: () {
setState(() {
passwordVisibility = !passwordVisibility;
});
},
),
MyPasswordField(
hintText: 'Password Confirm',
textEditingController: _passwordConfirm,
isPasswordVisible: passwordVisibility,
onTap: () {
setState(() {
passwordVisibility = !passwordVisibility;
});
},
)
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Already have an account? ",
style: kBodyText,
),
GestureDetector(
onTap: () {
Navigator.pushNamedAndRemoveUntil(
context,
SignInScreenRoute,
(Route<dynamic> route) => false);
},
child: Text(
"Sign In",
style: kBodyText.copyWith(
color: Colors.white,
),
),
),
],
),
SizedBox(
height: 20,
),
MyTextButton(
buttonName: 'Register',
onTap: _signUp,
bgColor: Colors.white,
textColor: Colors.black87,
)
],
),
),
),
],
),
),
);
}
_signUp() async {
var email = _email.text.trim();
var pw = _password.text.trim();
var pwConfirm = _passwordConfirm.text.trim();
if (email.isEmpty || pw.isEmpty || pw != pwConfirm) {
await showOkAlertDialog(
context: context,
message: 'Check your email or password',
);
return;
}
var obj = await AuthHelper.signUp(email, pw);
if (obj is User) {
Navigator.pushNamedAndRemoveUntil(
context, DashboardScreenRoute, (Route<dynamic> route) => false);
} else {
await showOkAlertDialog(
context: context,
message: obj,
);
}
}
}
|
<?php
use Illuminate\Database\Seeder;
use App\Country;
class CountrySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
// Read CSV file.
$file_path = resource_path('assets/data/country_list.csv');
$file = fopen( $file_path, 'r');
$all_data = array();
$header = true;
$keys = null;
while ( $line = fgetcsv( $file, 1000, ",") ){
if ( !$keys ) {
$keys = $line;
} else {
$line = array_combine( $keys, $line );
Country::updateOrCreate($line, ['id' => $line['id']]);
}
}
}
}
|
package PIA::Agent::Logo; ###### Logo Agent
### $Id$
##############################################################################
# The contents of this file are subject to the Ricoh Source Code Public
# License Version 1.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.risource.org/RPL
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# This code was initially developed by Ricoh Silicon Valley, Inc. Portions
# created by Ricoh Silicon Valley, Inc. are Copyright (C) 1995-1999. All
# Rights Reserved.
#
# Contributor(s):
#
##############################################################################
###
### routines for creating PIA logos and icons. Uses GD drawing package.
### Callable either as query or as <type><height>.
push(@ISA,PIA::Agent);
use GD;
sub re_initialize {
my $self = shift;
## Called from initialize.if after installing as class
print " ", $self->name, " re-initialized.\n" unless $main::quiet;
return bless $self;
}
### Stuff we need for drawing pentagons (wonder why?)
### Blythely ignore the fact that the coordinate system is upside-down,
### which puts theta=0 on the bottom. Bletch.
$pi = 3.1415926575;
$a = ($pi*2.0)/5.0; # central angle between vertices (72 degrees)
sub cx {
my ($rho, $theta) = @_;
## Cartesian x from polar (rho, theta)
$rho * sin($theta);
}
sub cy {
my ($rho, $theta) = @_;
## Cartesian y from polar (rho, theta)
$rho * cos($theta);
}
### Drawing Substrate:
local ($white, $black, $red, $blue, $rred);
local ($lw, $sp); # line width, inter-word spacing.
sub make_image {
my ($width, $height) = @_;
## Make an image to draw into.
## allocate basic colors; make white transparent.
my $im = new GD::Image($width,$height);
# allocate some colors
$white = $im->colorAllocate(255,255,255);
$black = $im->colorAllocate(0,0,0);
$red = $im->colorAllocate(255,0,0);
$rred= $im->colorAllocate(196,0,38);
$blue = $im->colorAllocate(0,0,255);
# make the background transparent and interlaced
$im->transparent($white);
$im;
}
### Pieces:
sub make_pentagon {
my ($im, $r, $x0, $y0, $n, $start) = @_;
## Make a pentagon of radius $r centered at ($x0,$y0)
## Draw $n segments (default 5) starting at $pi + $start*$a
my $theta = $pi + $start*$a; # start at the top
my $next, $i;
$n = 5 unless $n;
for ($i = 0; $i < $n; $i++) {
$next = $theta + $a;
$im->line(cx($r, $theta) + $x0, cy($r, $theta) + $y0,
cx($r, $next) + $x0, cy($r, $next) + $y0, $rred);
$theta = $next;
}
$im;
}
sub make_lines {
my ($im, $rmin, $rmax, $x0, $y0) = @_;
## Make radial lines from $rmin to $rmax centered at $x0 $y0
my $theta = $pi; # start at the top
my $i;
for ($i = 0; $i < 5; $i++) {
$im->line(cx($rmin, $theta) + $x0, cy($rmin, $theta) + $y0,
cx($rmax, $theta) + $x0, cy($rmax, $theta) + $y0, $rred);
$theta += $a;
}
$im;
}
sub make_logo {
my ($im, $width, $height, $x0, $y0, $n, $start) = @_;
## Make a pentagon + lines logo centered at $x0 $y0
## Fill $n segments (default 0) starting at $pi + $start*$a
## Segments are numbered counterclockwise from the top.
$x0 = ($width / 2) unless $x0;
$y0 = ($height/ 2) unless $y0;
my $rmax = $width/2 - 1;
$rmax = ($height/2 - 1) if $height < $width;
## === need to rescale $r, $y0 so it's full scale vertically.
## === need to adjust width after doing that.
$adj = $rmax/10; # approximate so far
$rmax += $adj;
$y0 += $adj;
$x0 += $adj/2;
my $rmin = $rmax / 3;
my $rmid = $rmin * 2;
return 2*$rmax + $adj unless $im;
make_pentagon($im, $rmin, $x0, $y0);
make_pentagon($im, $rmid, $x0, $y0);
make_pentagon($im, $rmax, $x0, $y0);
make_lines($im, $rmin, $rmax, $x0, $y0);
if ($n) {
fill_pentagon_segments($im, $rmid, $rmax, $x0, $y0, $n, $start);
}
2*$rmax + $adj; # approximation of actual width
}
sub fill_pentagon_segments {
my ($im, $r0, $r1, $x0, $y0, $n, $start) = @_;
if ($r1 < 15) {
## Filling this way is slower, but much more reliable than flood fill
## for small pentagons. Unfortunately it has moire streaks, so
## flood fill is better for large ones.
my $rfill;
for ($rfill = $r0; $rfill <= $r1; $rfill += 0.2) {
make_pentagon($im, $rfill, $x0, $y0, $n, $start);
}
return;
}
my $r = ($r0+$r1)/2;
my $theta = $pi + $start*$a;
my $i;
for ($i = 0; $i < $n; $i++) {
my ($x1, $y1) = (cx($r0, $theta), cy($r0, $theta));
my ($x2, $y2) = (cx($r1, $theta+$a), cy($r1, $theta+$a));
$im->fill(($x1+$x2)/2 + $x0, ($y1+$y2)/2 + $y0, $rred);
$theta += $a;
}
}
### Hash table:
%logos = ('logo' => \&make_LOGO,
'dofs' => \&make_DOFS,
'pia' => \&make_PIA,
'cia' => \&make_CIA,
'fbi' => \&make_FBI,
'pent' => \&make_pent,
);
### Letters.
### All take $im, $w, $h, $x0, $y0 and return width.
### local $lw and $sp are line width and spacing, respectively
### If $im is not a reference, just returns width required.
### Some letters may take additional parameters after $y0
$logos{'*'} = \&make_pent;
sub make_pent {
my ($im, $w, $h, $x0, $y0) = @_;
my $i;
## pentagon logo
$x0 += $h/2;
$y0 += $h/2;
make_logo($im, $h, $h, $x0, $y0, 0, 0);
}
$logos{'A'} = $logos{'a'} = \&make_A;
sub make_A {
my ($im, $w, $h, $x0, $y0) = @_;
my $i;
## A -- logo with upper 4/5 filled in
$x0 += $h/2;
$y0 += $h/2;
make_logo($im, $h, $h, $x0, $y0, 4, -2);
}
$logos{'B'} = $logos{'b'} = \&make_B;
sub make_B {
my ($im, $w, $h, $x0, $y0) = @_;
my $r = $h/4;
my $d = $sp;
return $lw + $d + $r unless ref $im;
## Make a w * h rectangle and fill it.
$im->filledRectangle($x0, $y0, $x0+$lw, $y0+$h, $rred);
## make a semicircle of radius $r, $w + $d from the left.
$im->line($x0+$lw+$d, $y0, $x0+$lw+$d, $y0+$h, $rred);
$im->arc($x0+$lw+$d, $y0+$r, # center
2*$r, 2*$r, # w, h
270, 90, $rred); # start, end, color
$im->fill($x0+$lw+$d+2, $y0+$r, $rred);
$im->arc($x0+$lw+$d, $y0+3*$r, # center
2*$r, 2*$r, # w, h
270, 90, $rred); # start, end, color
$im->fill($x0+$lw+$d+2, $y0+3*$r, $rred);
return $lw + $d + $r;
}
$logos{'C'} = $logos{'c'} = \&make_C;
sub make_C {
my ($im, $w, $h, $x0, $y0) = @_;
my $i;
## C
$x0 += $h/2;
$y0 += $h/2;
make_logo($im, $h, $h, $x0, $y0, 4, -1);
}
$logos{'D'} = $logos{'d'} = \&make_D;
sub make_D {
my ($im, $w, $h, $x0, $y0) = @_;
## D -- a simple semicircle of radius $h/2
## $x0 $y0 is the upper left corner.
## make a semicircle of radius $h/2 and fill it.
my $r = $h/2;
return $r unless ref $im;
$im->line($x0, $y0, $x0, $y0+2*$r, $rred);
$im->arc($x0, $y0+$r, # center
2*$r, $h, # w, h
270, 90, $rred); # start, end, color
$im->fill($x0+$r/2, $y0+$r, $rred);
$r;
}
$logos{'E'} = $logos{'e'} = \&make_E;
sub make_E {
my ($im, $w, $h, $x0, $y0) = @_;
## E
my $ww = $h/3;
my $hh = ($h - $lw) / 2;
return $lw + $ww unless ref $im;
$im->filledRectangle($x0, $y0, $x0+$lw, $y0+$h, $rred);
$im->filledRectangle($x0+$lw, $y0, $x0+$lw+$ww, $y0+$lw, $rred);
$im->filledRectangle($x0+$lw, $y0+$hh, $x0+$lw+$ww/2, $y0+$hh+$lw, $rred);
$im->filledRectangle($x0+$lw, $y0+$h-$lw, $x0+$lw+$ww, $y0+$h, $rred);
$lw + $ww;
}
$logos{'F'} = $logos{'f'} = \&make_F;
sub make_F {
my ($im, $w, $h, $x0, $y0) = @_;
## F
my $ww = $h/3;
my $hh = ($h - $lw) / 2;
return $lw + $ww unless ref $im;
$im->filledRectangle($x0, $y0, $x0+$lw, $y0+$h, $rred);
$im->filledRectangle($x0+$lw, $y0, $x0+$lw+$ww, $y0+$lw, $rred);
$im->filledRectangle($x0+$lw, $y0+$hh, $x0+$lw+$ww/2, $y0+$hh+$lw, $rred);
$lw + $ww;
}
$logos{'G'} = $logos{'g'} = \&make_G;
sub make_G {
my ($im, $w, $h, $x0, $y0) = @_;
my $i;
## A -- logo with upper 4/5 filled in
$x0 += $h/2;
$y0 += $h/2;
make_logo($im, $h, $h, $x0, $y0, 4, 0);
}
$logos{'I'} = $logos{'i'} = \&make_I;
sub make_I {
my ($im, $w, $h, $x0, $y0) = @_;
## I -- Make a w * h rectangle and fill it.
return $lw unless ref $im;
$im->filledRectangle($x0, $y0, $x0+$lw, $y0+$h, $rred) if ref $im;
$lw;
}
$logos{'L'} = $logos{'l'} = \&make_L;
sub make_L {
my ($im, $w, $h, $x0, $y0) = @_;
## E
my $ww = $h/3;
return $lw + $ww unless ref $im;
$im->filledRectangle($x0, $y0, $x0+$lw, $y0+$h, $rred);
$im->filledRectangle($x0+$lw, $y0+$h-$lw, $x0+$lw+$ww, $y0+$h, $rred);
$lw + $ww;
}
$logos{'O'} = $logos{'o'} = \&make_O;
sub make_O {
my ($im, $w, $h, $x0, $y0) = @_;
## O -- pentagon with the outer segments filled
$x0 += $h/2;
$y0 += $h/2;
make_logo($im, $h, $h, $x0, $y0, 5, 0);
}
$logos{'P'} = $logos{'p'} = \&make_P;
sub make_P {
my ($im, $w, $h, $x0, $y0) = @_;
my $r = $h/4;
my $d = $sp;
return $lw + $d + $r unless ref $im;
## Make a w * h rectangle and fill it.
$im->filledRectangle($x0, $y0, $x0+$lw, $y0+$h, $rred);
## make a semicircle of radius $r, $w + $d from the left.
$im->line($x0+$lw+$d, $y0, $x0+$lw+$d, $y0+2*$r, $rred);
$im->arc($x0+$lw+$d, $y0+$r, # center
2*$r, 2*$r, # w, h
270, 90, $rred); # start, end, color
$im->fill($x0+$lw+$d+2, $y0+$r, $rred);
return $lw + $d + $r;
}
$logos{'S'} = $logos{'s'} = \&make_S;
sub make_S {
my ($im, $w, $h, $x0, $y0) = @_;
my $r = $h/4;
return 2 * $r unless ref $im;
## make a semicircle of radius $r, $r from the left.
$im->line($x0+$r, $y0, $x0+$r, $y0+$h, $rred);
$im->arc($x0+$r, $y0+$r, # center
2*$r, 2*$r, # w, h
90, 270, $rred); # start, end, color
$im->fill($x0+$r-2, $y0+$r, $rred);
## Now one going the other way underneath. Crude.
$im->arc($x0+$r, $y0+3*$r, # center
2*$r, 2*$r, # w, h
270, 90, $rred); # start, end, color
$im->fill($x0+$r+2, $y0+3*$r, $rred);
return 2 * $r;
}
### Combinations:
sub make_str {
my ($im, $w, $h, $x0, $y0, $s) = @_;
my @chrs = split(//, $s);
my $sub;
## Make a logo out of a string;
foreach $c (@chrs) {
$sub = $logos{$c};
$x0 += &$sub($im, $w, $h, $x0, $y0) + $sp if defined $sub;
}
$x0 - $sp;
}
sub make_PIA {
my ($im, $w, $h, $x0, $y0) = @_;
## Make a PIA logo.
$x0 += make_P($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_I($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_A($im, $w, $h, $x0, $y0);
}
sub make_CIA {
my ($im, $w, $h, $x0, $y0) = @_;
## Make a CIA logo.
$x0 += make_C($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_I($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_A($im, $w, $h, $x0, $y0);
}
sub make_FBI {
my ($im, $w, $h, $x0, $y0) = @_;
## Make a FBI logo.
$x0 += make_F($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_B($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_I($im, $w, $h, $x0, $y0);
}
sub make_DOFS {
my ($im, $w, $h, $x0, $y0) = @_;
## Make a w x h rectangle and fill it.
$x0 += make_D($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_O($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_F($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_S($im, $w, $h, $x0, $y0);
}
sub make_LOGO {
my ($im, $w, $h, $x0, $y0) = @_;
## Make a w x h rectangle and fill it.
$x0 += make_L($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_O($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_G($im, $w, $h, $x0, $y0) + $sp;
$x0 += make_O($im, $w, $h, $x0, $y0);
}
sub respond {
my($self, $request, $resolver)=@_;
my %hash=%{$request->parameters};
## See if we have a filename of the form <type><height>[.ext]
## Height may be 0, in which case the default is used.
## The extension defaults to "gif"
my $url = $request->url;
my $path = $url->path;
$path =~ m:/([a-zA-Z]+)([0-9]+)(.[a-zA-Z]*)?$:;
if (defined $1 && defined $2) {
$hash{'type'} = $1;
$hash{'height'} = $2;
$hash{'ext'} = $3 if defined $3;
}
print "logo/" . $hash{'type'} . $hash{'height'} . "($path)\n"
if $main::debugging;
if (! exists $hash{'height'}) {
return $self->respond_to_interform($request,$url, $resolver);
}
## Get parameters out of query string:
my $height = $hash{'height'};
$height = $self->option('default-height') if $height == 0;
my $width = $hash{'width'};
my $type = $hash{'type'};
my $w = $hash{'w'};
my $h = $hash{'h'}; # height of a letter ($height - 2*$bw)
## Propagate these down:
local $bw = $hash{'bw'}; # border width (1)
local $sp = $hash{'sp'}; # inter-word space
local $lw = $hash{'lw'}; # width of a line
## Compute defaults:
$bw = ($height <= 20? 0 : 1) unless defined $bw;
$type = 'pent' unless defined $type;
$h = $height - 2 * $bw unless defined $h;
$w = $width - 2 * $bw if defined $width;
$lw = 15*$h/100 unless defined $lw;
$sp = 10*$h/100 unless defined $sp;
## Look up the appropriate routine:
my $sub = $logos{$type};
$sub = \&make_str unless defined $sub;
## Do it:
$width = &$sub(0, $w, $h, $bw, $bw, $type)+$bw unless defined $width;
my $im = make_image($width, $height);
&$sub($im, $w, $h, $bw, $bw, $type);
## Create response:
my $response=HTTP::Response->new(&HTTP::Status::RC_OK,"OK");
$response->content_length(length($im->gif));
$response->content_type('image/gif');
$response->content($im->gif);
$response->header('Version', $self->version);
return $request->respond_with($response);
}
1;
|
package trikita.router;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Pair;
import android.util.Property;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.lang.reflect.InvocationTargetException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.HashMap;
public class ViewRouter {
private final static String tag = "ViewRouter";
public final static int NO_HISTORY = 1;
// Bundle keys
final static String KEY_CLASSNAME = "className";
final static String KEY_STATE = "state";
final static String KEY_BACKSTACK = "backstack";
private static final Map<Context, SoftReference<ViewRouter>> CACHE = new WeakHashMap<>();
private ViewGroup mParent;
private ArrayList<String> mBackstack = new ArrayList<>();
private List<Pair<String, Class<? extends View>>> mRouting =
new ArrayList<>();
public ViewRouter(ViewGroup parent) {
mParent = parent;
if (!CACHE.containsKey(parent.getContext())) {
CACHE.put(parent.getContext(), new SoftReference<>(this));
}
}
public ViewRouter(Activity a) {
CACHE.put(a, new SoftReference<>(this));
mParent = new FrameLayout(a);
a.setContentView(mParent);
}
public static ViewRouter get(View v) {
SoftReference<ViewRouter> ref = CACHE.get(v.getContext());
return (ref != null ? ref.get() : null);
}
// TODO validate uri, throw RuntimeException if it's invalid
public ViewRouter add(String uri, Class<? extends View> a) {
mRouting.add(new Pair(uri, a));
return this;
}
public boolean route(String uri) {
return route(uri, 0);
}
public String route() {
if (mBackstack.size() > 0) {
return mBackstack.get(mBackstack.size() - 1);
} else {
return null;
}
}
public boolean route(String uri, int flags) {
Map<String, String> properties = new HashMap<String, String>();
for (Pair<String, Class<? extends View>> entry : mRouting) {
properties.clear();
if (Utils.matchUri(uri, entry.first, properties)) {
View v = createView(entry.second, properties);
if ((flags & NO_HISTORY) == 0) {
mBackstack.add(uri);
}
// navigate to the matched view
mParent.removeAllViews();
mParent.addView(v);
return true;
}
}
return false;
}
public void save(Bundle b) {
b.putStringArrayList(KEY_BACKSTACK, mBackstack);
}
public void load(Bundle b) {
for (String uri : b.getStringArrayList(KEY_BACKSTACK)) {
route(uri);
}
}
public boolean back() {
if (mBackstack.size() > 1) {
mBackstack.remove(mBackstack.size() - 1);
if (mBackstack.size() > 0) {
route(mBackstack.get(mBackstack.size() - 1), NO_HISTORY);
return true;
}
}
return false;
}
private <T extends View> T createView(Class<T> cls, Map<String, String> props) {
try {
T v = cls.getConstructor(Context.class).newInstance(mParent.getContext());
// copy parsed uri params into the view properties
for (Map.Entry<String, String> p : props.entrySet()) {
Property<T, String> property = Property.of(cls, String.class, p.getKey());
property.set(v, p.getValue());
}
return v;
} catch (NoSuchMethodException|InstantiationException|
IllegalAccessException|InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
|
## Minimal HN
<p align="center">
<img src="graphics/feature graphic.png" alt="Minimal HN" />
</p>
Mininal HN is an open-source Hacker News client written with React Native.
[Download from Google Play](https://play.google.com/store/apps/details?id=com.hadaclay.minimalhn)
### Libraries Used:
- [React Navigation](https://reactnavigation.org/)
- [React Native Elements](https://react-native-training.github.io/react-native-elements/)
- [react-native-htmlview](https://github.com/jsdf/react-native-htmlview)
- [react-native-vector-icons](https://oblador.github.io/react-native-vector-icons/)
- [react-native-admob](https://github.com/sbugert/react-native-admob)
|
package dk.bayes.dsl.demo
import org.junit._
import Assert._
import dk.bayes.dsl.variable.Categorical
import dk.bayes.dsl.infer
import dk.bayes.clustergraph.testutil.AssertUtil._
class MontyHallProblemTest {
val carDoor = Categorical(Vector(1d / 3, 1d / 3, 1d / 3))
val guestDoor = Categorical(Vector(1d / 3, 1d / 3, 1d / 3))
val montyDoor = Categorical(carDoor, guestDoor, Vector(
0, 0.5, 0.5,
0, 0, 1,
0, 1, 0,
0, 0, 1,
0.5, 0, 0.5,
1, 0, 0,
0, 1, 0,
1, 0, 0,
0.5, 0.5, 0))
@Test def test:Unit = {
guestDoor.setValue(0) //Guest chooses door 1
montyDoor.setValue(1) //Monty opens door 2
assertVector(Array(1d / 3, 0, 2d / 3), infer(carDoor).cpd, 0.0001)
}
}
|
source "${BASH_SOURCE%/*}/../helpers.bash"
set -x
function cleanup {
set +e
polycubectl simplebridge del br1
polycubectl router del r1
delete_veth 4
}
trap cleanup EXIT
echo ' ##### SETTING TEST ENVIROMENT ######'
create_veth 4
polycubectl simplebridge add br1 #loglevel=TRACE #type=XDP_SKB
polycubectl lbrp add lb1 loglevel=TRACE #type=XDP_SKB
#config lb1
polycubectl lbrp lb1 ports add veth1 peer=veth1 type=FRONTEND #BACKEND 0
polycubectl lbrp lb1 ports add p1 peer=lb1 type=BACKEND #FRONTEND 1
polycubectl simplebridge br1 ports add p1
polycubectl simplebridge br1 ports add p2
polycubectl simplebridge br1 ports add p3
polycubectl simplebridge br1 ports add p4
polycubectl simplebridge br1 ports add p5
polycubectl simplebridge br1 ports add p6
polycubectl simplebridge br1 ports p1 set peer=enx000ec6fe1bfc
polycubectl simplebridge br1 ports p2 set peer=veth1
polycubectl simplebridge br1 ports p3 set peer=veth2
polycubectl simplebridge br1 ports p4 set peer=veth3
polycubectl simplebridge br1 ports p6 set peer=veth4
polycubectl router add r1 #loglevel=TRACE #type=XDP_SKB
polycubectl router r1 ports add p5 netmask=255.255.255.0 ip=10.0.0.254
#polycubectl router r1 ports p5 secondaryip add 20.0.0.254 255.255.255.0
polycubectl router r1 ports p5 set peer=br1:p5
polycubectl simplebridge br1 ports p5 set peer=r1:p5
polycubectl lbrp lb1 service add 192.168.0.1 180 ALL name=service1
polycubectl lbrp lb1 service 192.168.0.1 180 TCP backend add 10.0.0.4 name=B4 port=80
polycubectl lbrp lb1 service 192.168.0.1 180 TCP backend add 10.0.0.3 name=B3 port=80
polycubectl lbrp lb1 service 192.168.0.1 180 TCP backend add 10.0.0.2 name=B2 port=80
polycubectl lbrp lb1 service 192.168.0.1 180 TCP backend add 10.0.0.1 name=B1 port=80 weight=0
polycubectl lbrp lb1 service 192.168.0.1 180 UDP backend add 10.0.0.4 name=B4 port=80
polycubectl lbrp lb1 service 192.168.0.1 180 UDP backend add 10.0.0.3 name=B3 port=80
polycubectl lbrp lb1 service 192.168.0.1 180 UDP backend add 10.0.0.2 name=B2 port=80
polycubectl lbrp lb1 service 192.168.0.1 180 UDP backend add 10.0.0.1 name=B1 port=80 weight=0
polycubectl lbrp lb1 service 192.168.0.1 0 ICMP backend add 10.0.0.4 name=B4 port=80
polycubectl lbrp lb1 service 192.168.0.1 0 ICMP backend add 10.0.0.3 name=B3 port=80
polycubectl lbrp lb1 service 192.168.0.1 0 ICMP backend add 10.0.0.2 name=B2 port=80
polycubectl lbrp lb1 service 192.168.0.1 0 ICMP backend add 10.0.0.1 name=B1 port=80 weight=0
echo ' ##### STARTING 2 SERVERS IN NS2 AND NS3 ######'
sudo ip netns exec ns1 node s.js &
sudo ip netns exec ns2 node s.js &
sudo ip netns exec ns3 node s.js &
sudo ip netns exec ns4 node s.js &
read
|
const typeforce = require('typeforce');
const UINT31_MAX: number = Math.pow(2, 31) - 1;
export function UInt31(value: number): boolean {
return typeforce.UInt32(value) && value <= UINT31_MAX;
}
export function BIP32Path(value: string): boolean {
return typeforce.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/);
}
BIP32Path.toJSON = (): string => {
return 'BIP32 derivation path';
};
export function Signer(obj: any): boolean {
return (
(typeforce.Buffer(obj.publicKey) ||
typeof obj.getPublicKey === 'function') &&
typeof obj.sign === 'function'
);
}
const SATOSHI_MAX: number = 21 * 1e14;
export function Satoshi(value: number): boolean {
return typeforce.UInt53(value) && value <= SATOSHI_MAX;
}
// external dependent types
export const ECPoint = typeforce.quacksLike('Point');
// exposed, external API
export const Network = typeforce.compile({
messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String),
bip32: {
public: typeforce.UInt32,
private: typeforce.UInt32,
},
pubKeyHash: typeforce.UInt8,
scriptHash: typeforce.UInt8,
wif: typeforce.UInt8,
});
export const Buffer256bit = typeforce.BufferN(32);
export const Hash160bit = typeforce.BufferN(20);
export const Hash256bit = typeforce.BufferN(32);
export const Number = typeforce.Number; // tslint:disable-line variable-name
export const Array = typeforce.Array;
export const Boolean = typeforce.Boolean; // tslint:disable-line variable-name
export const String = typeforce.String; // tslint:disable-line variable-name
export const Buffer = typeforce.Buffer;
export const Hex = typeforce.Hex;
export const maybe = typeforce.maybe;
export const tuple = typeforce.tuple;
export const UInt8 = typeforce.UInt8;
export const UInt32 = typeforce.UInt32;
export const UInt64 = typeforce.UInt64;
export const Function = typeforce.Function;
export const BufferN = typeforce.BufferN;
export const Null = typeforce.Null;
export const oneOf = typeforce.oneOf;
|
# GameOfLife.jl
A toy package to demonstrate (and practice) parallel programming techniques
in Julia. Inspired by an example of the [DistributedArrays.jl documentation][1].
[1]: https://pkg.julialang.org/docs/DistributedArrays/Gfdem/0.6.1/#Distributed-Array-Operations-1
|
import { DrawingParametersEnum } from 'opensheetmusicdisplay';
import { useEffect, useState } from 'react';
import { useDevice } from '../../../ctx/device';
import { MusicDisplay, OpenSheetMusicDisplay } from '../../../lib/MusicDisplay';
import { NoopMusicDisplay } from '../../../lib/MusicDisplay/NoopMusicDisplay';
import { Nullable } from '../../../util/types';
import * as helpers from '../helpers';
import { RenderableNotation } from '../types';
export const useMusicDisplay = (
notation: Nullable<RenderableNotation>,
musicDisplayContainer: Nullable<HTMLDivElement>,
scrollContainer: Nullable<HTMLDivElement>
): [MusicDisplay, boolean] => {
const [loading, setLoading] = useState(false);
const [musicDisplay, setMusicDisplay] = useState<MusicDisplay>(() => new NoopMusicDisplay());
const device = useDevice();
useEffect(() => {
if (!notation) {
return;
}
if (!notation.musicXmlUrl) {
return;
}
if (!musicDisplayContainer) {
return;
}
if (!scrollContainer) {
return;
}
const musicDisplay = new OpenSheetMusicDisplay(musicDisplayContainer, {
syncSettings: { deadTimeMs: notation.deadTimeMs, durationMs: notation.durationMs },
svgSettings: { eventNames: helpers.getSvgEventNames(device) },
scrollContainer,
drawingParameters: device.mobile ? DrawingParametersEnum.compacttight : DrawingParametersEnum.default,
});
setMusicDisplay(musicDisplay);
const startLoading = () => setLoading(true);
const stopLoading = () => setLoading(false);
const eventBusIds = [
musicDisplay.eventBus.subscribe('loadstarted', startLoading),
musicDisplay.eventBus.subscribe('loadended', stopLoading),
musicDisplay.eventBus.subscribe('resizestarted', startLoading),
musicDisplay.eventBus.subscribe('resizeended', stopLoading),
];
musicDisplay.load(notation.musicXmlUrl);
return () => {
setMusicDisplay(new NoopMusicDisplay());
musicDisplay.eventBus.unsubscribe(...eventBusIds);
musicDisplay.dispose();
};
}, [notation, device, musicDisplayContainer, scrollContainer]);
return [musicDisplay, loading];
};
|
'use strict';
/*global $:true*/
/*eslint no-undef: 2*/
window.onload = function() {
var source = $('#section').html();
var template = window.Handlebars.compile(source);
var itemSource = $('#item').html();
var itemTemplate = window.Handlebars.compile(itemSource);
$('.links').html('');
var iframe = $('<iframe frameborder="0" width=100% name=nav id=nav src="https://www.baidu.com"/>');
iframe.on('load', function() {
document.getElementById('nav').height = $('.root').height();
});
$('.content').html(iframe);
function sort(a, b) {
var left = a.order || 10000;
var right = b.order || 10000;
if (left > right) {
return 1;
}
if (left < right) {
return -1;
}
return 0;
}
function getItem(item) {
var sub = [];
if (!item) {
return '';
}
if (item.items && item.items.length) {
var items = item.items.sort(sort);
for (var j = 0; j < items.length; j++) {
if (items[j]) {
sub.push(getItem(items[j]));
}
}
return template({
name: item.name,
sub: sub.join('')
});
} else {
if (!item.url) {
return '';
}
item.favicon = item.favicon || item.url + '/favicon.ico';
return itemTemplate(item);
}
}
function updateSites(json) {
console.log(json);
var data = $('<ul class="root">').append(getItem(json));
$('.links').append(data);
$('img').each(function() {
this.setAttribute('src', this.getAttribute('ng-src'));
});
$('img').on('error', function() {
this.src = 'https://assets-cdn.github.com/favicon.ico';
});
$('.title > h3').on('mouseover', function() {
// this.style.display = 'block';
});
$('.title > h3').on('mouseout', function() {
// this.style.display = 'none';
});
}
$.ajax({
url: 'data/sites.json',
method: 'get',
dataType: 'JSON',
success: updateSites
});
var url;
url = 'https://www.google.com.hk/?q=';
window.select = function(node) {
switch (node) {
case 'google':
url = 'https://www.google.com.hk/?q=';
$('#searches').html('Google <span class="caret"></span>');
iframe.attr('src', 'https://www.google.com');
break;
case 'baidu':
url = 'https://www.baidu.com/s?wd=';
$('#searches').html('Baidu <span class="caret"></span>');
iframe.attr('src', 'https://www.baidu.com');
break;
case 'bing':
url = 'https://global.bing.com/search?q=';
$('#searches').html('Bing <span class="caret"></span>');
iframe.attr('src', 'https://www.bing.com');
break;
}
$('.btn-query').attr('href', url + $('#q').val());
};
$('#q').keyup(function() {
$('.btn-query').attr('href', url + $('#q').val());
});
};
|
package vad
import (
"bufio"
"errors"
"fmt"
webRTCVAD "github.com/baabaaox/go-webrtcvad"
"io"
"os"
"time"
)
// GetVADInfoFromAudio 分析音频文件,得到 VAD 分析信息,看样子是不支持并发的,只能单线程使用
// 无需使用插值的函数
func GetVADInfoFromAudio(audioInfo AudioInfo, insert bool) ([]VADInfo, error) {
var (
frameIndex = 0
frameSize = audioInfo.SampleRate / 1000 * FrameDuration
frameBuffer = make([]byte, audioInfo.SampleRate/1000*FrameDuration*audioInfo.BitDepth/8)
frameActive = false
vadInfos = make([]VADInfo, 0)
)
audioFile, err := os.Open(audioInfo.FileFullPath)
if err != nil {
return nil, err
}
defer audioFile.Close()
reader := bufio.NewReader(audioFile)
vadInst := webRTCVAD.Create()
defer webRTCVAD.Free(vadInst)
err = webRTCVAD.Init(vadInst)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
err = webRTCVAD.SetMode(vadInst, Mode)
if err != nil {
return nil, err
}
if ok := webRTCVAD.ValidRateAndFrameLength(audioInfo.SampleRate, frameSize); !ok {
return nil, errors.New(fmt.Sprintf("invalid rate or frame length, %v", audioInfo.FileFullPath))
}
var offset int
report := func() {
t := time.Duration(offset) * time.Second / time.Duration(audioInfo.SampleRate) / 2
//log.Printf("Frame: %v, offset: %v, Active: %v, t = %v", frameIndex, offset, frameActive, t)
vadInfos = append(vadInfos, *NewVADInfo(
frameIndex,
offset,
frameActive,
t,
))
}
for {
_, err = io.ReadFull(reader, frameBuffer)
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
tmpFrameActive, err := webRTCVAD.Process(vadInst, audioInfo.SampleRate, frameBuffer, frameSize)
if err != nil {
return nil, err
}
if tmpFrameActive != frameActive || offset == 0 {
frameActive = tmpFrameActive
if insert == false {
report()
}
}
if insert == true {
report()
}
offset += len(frameBuffer)
frameIndex++
}
report()
return vadInfos, nil
}
// GetFloatSlice 返回 1 -1 归一化的数组
func GetFloatSlice(inVADs []VADInfo) []float64 {
outVADFloats := make([]float64, len(inVADs))
for i, vad := range inVADs {
if vad.Active == true {
outVADFloats[i] = 1
} else {
outVADFloats[i] = -1
}
}
return outVADFloats
}
// GetAudioIndex2Time 从 Audio 的 OffsetIndex 推算出它所在的时间,返回 float64 的秒
func GetAudioIndex2Time(index int) float64 {
return float64(index*FrameDuration) / 1000.0
}
const (
// Mode vad mode,VAD 的模式 0-3
Mode = 3
// FrameDuration frame duration,分析的时间窗口
FrameDuration = 10
)
|
package cafe.caption
import cafe.caption.db.TransactionManager
import cafe.caption.db.TransactionManagerImpl
import cafe.caption.db.repositories.UserRepository
import cafe.caption.db.repositories.UserRepositoryImpl
import org.flywaydb.core.Flyway
import org.jetbrains.exposed.sql.Database
interface ApplicationModule {
val db: Database
val flyway: Flyway
val dbUrl: String
val transactionManager: TransactionManager
val userRepository: UserRepository
class Impl : ApplicationModule {
override val dbUrl = "jdbc:postgresql://db:5432/" + System.getenv("POSTGRES_DB")
override val db: Database by lazy {
Database.connect(
dbUrl,
driver = "org.postgresql.Driver",
user = System.getenv("POSTGRES_USER"),
password = System.getenv("POSTGRES_PASSWORD")
)
}
override val flyway: Flyway by lazy {
Flyway.configure()
.locations("classpath:db/migrations")
.dataSource(dbUrl, System.getenv("POSTGRES_USER"), System.getenv("POSTGRES_PASSWORD"))
.load()
}
override val transactionManager: TransactionManager by lazy { TransactionManagerImpl(db) }
override val userRepository: UserRepository by lazy { UserRepositoryImpl(db) }
}
}
interface Context : ApplicationModule {
class Impl(applicationModule: ApplicationModule) : Context,
ApplicationModule by applicationModule
}
fun createContext(): Context {
val applicationModule = ApplicationModule.Impl()
return Context.Impl(applicationModule)
}
|
ddd;
create database test;
use test;
DROP table IF EXISTS Contact;
DROP table IF EXISTS Company;
CREATE TABLE Company (
id INT NOT NULL AUTO_INCREMENT,
duns VARCHAR(9) UNIQUE,
name VARCHAR(255),
address VARCHAR(255),
zip_code VARCHAR(5),
company_creation Date,
website VARCHAR(255),
phone_number VARCHAR(255),
city VARCHAR(255),
PRIMARY KEY(id)
);
CREATE TABLE Contact (
id VARCHAR(255),
email VARCHAR (255) NOT NULL UNIQUE,
age INT,
name VARCHAR (255),
firstname VARCHAR (255),
company_id INT,
PRIMARY KEY(id),
FOREIGN KEY (company_id) REFERENCES Company(id)
);
CREATE USER 'test'@'localhost' IDENTIFIED BY 'test';
GRANT ALL PRIVILEGES ON *.* TO 'test'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
CREATE TABLE table3
(
id INTEGER PRIMARY KEY NOT NULL,
nom VARCHAR(100)
);
CREATE TABLE table2
(
id INTEGER PRIMARY KEY NOT NULL,
nom VARCHAR(100),
id_table3 INTEGER,
nom_table3 VARCHAR(100)
);
CREATE TABLE `table1` (
`id` int(11) NOT NULL,
`nom` varchar(100) DEFAULT NULL,
`dt` date DEFAULT NULL,
`num` int(11) DEFAULT NULL,
`id_table2` int(11) DEFAULT NULL,
`id_table3` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id_table2` (`id_table2`),
KEY `id_table3` (`id_table3`),
CONSTRAINT `table1_ibfk_1` FOREIGN KEY (`id_table2`) REFERENCES `table2` (`id`),
CONSTRAINT `table1_ibfk_2` FOREIGN KEY (`id_table3`) REFERENCES `table3` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE table3
ADD CONSTRAINT u_table3
UNIQUE (id, nom);
ALTER TABLE table2
ADD CONSTRAINT fk_table2_table3
FOREIGN KEY (id_table3, nom_table3)
REFERENCES table3(id, nom)
ON UPDATE CASCADE
ON DELETE RESTRICT;
|
DELETE FROM "public"."reports" WHERE "id" = 0;
DROP TABLE "public"."Reports";
|
export {default as error} from './error';
export {default as info} from './info';
|
package enigma
import (
"fmt"
)
type (
// Error extends the built in error type with extra error information provided by the Qlik Associative Engine
Error interface {
error
Code() int
Parameter() string
Message() string
}
qixError struct {
ErrorCode int `json:"code"`
ErrorParameter string `json:"parameter"`
ErrorMessage string `json:"message"`
}
)
func (err *qixError) Error() string {
return fmt.Sprintf("%s: %s (%d)", err.ErrorParameter, err.ErrorMessage, err.ErrorCode)
}
func (err *qixError) Code() int {
return err.ErrorCode
}
func (err *qixError) Parameter() string {
return err.ErrorParameter
}
func (err *qixError) Message() string {
return err.ErrorMessage
}
|
/*
* Sun Public License Notice
*
* The contents of this file are subject to the Sun Public License
* Version 1.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://www.sun.com/
*
* The Original Code is NetBeans. The Initial Developer of the Original
* Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
* Microsystems, Inc. All Rights Reserved.
*/
package org.netbeans.editor;
import javax.swing.text.BadLocationException;
/**
* Attempt to insert or remove from the guarded block has been done.
*
* @version 1.0
* @author Miloslav Metelka
*/
public class GuardedException extends BadLocationException {
static final long serialVersionUID =-8139460534188487509L;
public GuardedException(String s, int offs) {
super (s, offs);
}
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.tasks;
import static com.android.build.gradle.internal.scope.InternalArtifactType.GENERATED_PROGUARD_FILE;
import com.android.SdkConstants;
import com.android.annotations.NonNull;
import com.android.build.gradle.FeaturePlugin;
import com.android.build.gradle.internal.scope.BuildArtifactsHolder;
import com.android.build.gradle.internal.scope.GlobalScope;
import com.android.build.gradle.internal.scope.InternalArtifactType;
import com.android.build.gradle.internal.scope.VariantScope;
import com.android.build.gradle.internal.tasks.factory.TaskCreationAction;
import com.android.builder.errors.EvalIssueException;
import java.io.IOException;
import org.gradle.api.Project;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskProvider;
/** Configuration action for a merge-Proguard-files task. */
public abstract class MergeConsumerProguardFilesTask extends MergeFileTask {
private boolean isDynamicFeature;
private boolean isBaseFeature;
private boolean hasFeaturePlugin;
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
public abstract ConfigurableFileCollection getConsumerProguardFiles();
@Override
public void doTaskAction() throws IOException {
final Project project = getProject();
// We check for default files unless it's a base feature, which can include default files.
if (!isBaseFeature) {
ExportConsumerProguardFilesTask.checkProguardFiles(
project,
isDynamicFeature,
hasFeaturePlugin,
getConsumerProguardFiles().getFiles(),
errorMessage -> {
throw new EvalIssueException(errorMessage);
});
}
super.doTaskAction();
}
public static class CreationAction extends TaskCreationAction<MergeConsumerProguardFilesTask> {
@NonNull private final VariantScope variantScope;
public CreationAction(@NonNull VariantScope variantScope) {
this.variantScope = variantScope;
}
@NonNull
@Override
public String getName() {
return variantScope.getTaskName("merge", "ConsumerProguardFiles");
}
@NonNull
@Override
public Class<MergeConsumerProguardFilesTask> getType() {
return MergeConsumerProguardFilesTask.class;
}
@Override
public void handleProvider(
@NonNull TaskProvider<? extends MergeConsumerProguardFilesTask> taskProvider) {
super.handleProvider(taskProvider);
variantScope
.getArtifacts()
.producesFile(
InternalArtifactType.MERGED_CONSUMER_PROGUARD_FILE.INSTANCE,
BuildArtifactsHolder.OperationType.INITIAL,
taskProvider,
MergeConsumerProguardFilesTask::getOutputFile,
SdkConstants.FN_PROGUARD_TXT);
}
@Override
public void configure(@NonNull MergeConsumerProguardFilesTask task) {
task.setVariantName(variantScope.getFullVariantName());
GlobalScope globalScope = variantScope.getGlobalScope();
Project project = globalScope.getProject();
task.hasFeaturePlugin = project.getPlugins().hasPlugin(FeaturePlugin.class);
task.isBaseFeature =
task.hasFeaturePlugin && globalScope.getExtension().getBaseFeature();
if (task.isBaseFeature) {
task.isDynamicFeature = variantScope.getType().isDynamicFeature();
}
task.getConsumerProguardFiles()
.from(variantScope.getConsumerProguardFilesForFeatures());
ConfigurableFileCollection inputFiles =
project.files(
task.getConsumerProguardFiles(),
variantScope
.getArtifacts()
.getFinalProduct(GENERATED_PROGUARD_FILE.INSTANCE));
task.setInputFiles(inputFiles);
}
}
}
|
package others.easy.ltwenty;
import tools.ListNode;
/**
* 876 Middle of the Linked List
*/
public class MiddleOfTheLinkedList {
public ListNode middleNode(ListNode head) {
int step = 0;
ListNode res = head;
while (head != null) {
head = head.next;
step++;
if (step % 2 == 0)
res = res.next;
}
return res;
}
}
|
#pragma once
#include "Fractal/Fractal.h"
#include "UI/FractalViewerUI.h"
namespace RM
{
namespace UI
{
struct FractalCompileData
{
Ref<Fractal> Fractal;
uint32_t Begin;
uint32_t End;
uint32_t Iterations;
};
class FractalManagerUI
{
public:
static void LoadFromDisk();
static void CreateFractal(const std::string& fractalName = "Fractal");
static void AddFractal(const Ref<Fractal>& fractal);
static void DeleteFractal();
static void DrawFractalUI();
static void RequestReload(const Ref<Fractal>& fractal);
private:
static bool s_EditorOpen;
static std::string s_InputFractalName;
static std::vector<Ref<FractalViewerUI>> s_Views;
static Ref<FractalViewerUI> s_ActiveViewer;
};
}
}
|
package lib
import kotlin.platform.*
[platformName("bar")]
fun foo() = "foo"
var v: Int = 1
[platformName("vget")]
get
[platformName("vset")]
set
|
(in-package :cl-user)
(defpackage :cl-firebird-asd
(:use :cl :asdf))
(in-package :cl-firebird-asd)
(defsystem cl-firebird
:version "0.3"
:author "Kirill Zverev"
:license "MIT"
:description "Firebird database remote protocol client"
:depends-on (:flexi-streams
#-sbcl :usocket
:ironclad
:nibbles
:log4cl
:crypt)
:components ((:module "src"
:serial t
:components ((:file "packages")
(:file "consts")
(:file "specials")
(:file "ironclad")
(:file "utils")
(:file "conditions")
(:file "messages")
(:file "srp")
(:file "classes")
(:file "wireprotocol")
(:file "blob")
(:file "xsqlvar")
(:file "transaction")
(:file "statement")
(:file "connection")
(:file "metadata")))))
|
<?php
////////////////////////////////////////////////////////////////////////
// //
// test_text_submit.php //
// //
// //
// //
// Test script for Unicode text functions defined in jcqtypes.php. //
// //
// This script receives its input from test_text_form.html which must //
// be in the same directory as this script to work correctly. //
// //
////////////////////////////////////////////////////////////////////////
// Import Jacques-Types module
//
require_once __DIR__ . '/jcqtypes.php';
// If we received something other than a POST, redirect to the
// submission form
//
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
// Determine if HTTPS was used for this request
$uses_https = false;
if (isset($_SERVER['HTTPS'])) {
$uses_https = true;
}
// Determine protocol
$prot = 'http://';
if ($uses_https) {
$prot = 'https://';
}
// Get the server name and script name
$server_name = $_SERVER['SERVER_NAME'];
$script_name = $_SERVER['SCRIPT_NAME'];
// Get the index of the last / in the script name
$last_sep = strrpos($script_name, '/');
// If there is a / in the script name, the parent directory is
// everything up to and including it; else, the parent directory is /
$parent_dir = NULL;
if ($last_sep !== false) {
// Parent directory is everything up to and including last separator
$parent_dir = substr($script_name, 0, $last_sep + 1);
} else {
// Didn't find any / so parent directory is root
$parent_dir = '/';
}
// Form the path to the form
$form_path = $prot . $server_name . $parent_dir .
'test_text_form.html';
// Redirect to form
http_response_code(302);
header("Location: $form_path");
exit;
}
// Attempt to read the string from the POSTed value
//
$str = '';
if (array_key_exists('txt', $_POST)) {
$str = $_POST['txt'];
}
// Convert to Unicode string
//
$str = JCQTypes::makeUniString($str, true);
// Do XML escaping
//
$str = JCQTypes::xmlUniString($str, JCQTypes::CDATA);
// Decode backslash codes
//
$str = JCQTypes::decodeUniString($str, true);
// Convert formatting codes
//
$str = str_replace("\t", " ", $str);
$str = str_replace("\n", "<br/>", $str);
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Text testing result - Jacques-Types</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0"/>
<style>
th {
text-align: left;
font-weight: bold;
}
td {
padding-left: 1em;
}
.tsec {
text-align: left;
text-decoration: underline;
padding-bottom: 0.5em;
padding-top: 1.0em;
padding-left: 0;
}
hr {
margin-top: 2em;
}
</style>
</head>
<body>
<h1>Text testing result</h1>
<p><?php echo $str; ?></p>
<hr/>
<p>
<i>return to
<a href="test_text_form.html">testing form</a></i>
</p>
</body>
</html>
|
Este repositório mudou de local!
Acesse aqui: https://woliveiras.com.br/my-precious-links
|
import React from 'react';
import './styles/formInput.scss';
export interface FormInputProps {
handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
label: string;
value?: string;
type: 'text' | 'email' | 'number' | 'password' | 'date';
name?: string;
required?: boolean;
}
const FormInput: React.SFC<FormInputProps> = ({
handleChange,
label,
value,
type,
name,
required,
...restProps
}) => {
return (
<div className='group'>
<input
type={type}
name={name}
value={value}
className='form-input'
onChange={handleChange}
id={name}
required={required}
/>
{label ? (
<label
htmlFor={name}
className={`${value?.length ? 'shrink' : ''} form-input-label `}>
{label}
</label>
) : null}
</div>
);
};
export default FormInput;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.