repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
fyahfox/NemCommunityClient | nem-client-api/src/main/java/org/nem/ncc/services/WalletMapper.java | <gh_stars>10-100
package org.nem.ncc.services;
import org.nem.core.time.TimeProvider;
import org.nem.ncc.controller.viewmodels.WalletViewModel;
import org.nem.ncc.wallet.Wallet;
import java.util.stream.Collectors;
/**
* Helper class that is able to map a Wallet to a WalletViewModel.
*/
public class WalletMapper {
private final AccountMapper accountMapper;
private final TimeProvider timeProvider;
/**
* Creates a wallet mapper.
*
* @param accountMapper The account mapper.
* @param timeProvider The time provider.
*/
public WalletMapper(
final AccountMapper accountMapper,
final TimeProvider timeProvider) {
this.accountMapper = accountMapper;
this.timeProvider = timeProvider;
}
/**
* Converts the specified model to a view model.
*
* @param model The model.
* @return The view model.
*/
public WalletViewModel toViewModel(final Wallet model) {
return new WalletViewModel(
model.getName(),
this.accountMapper.toViewModel(model.getPrimaryAccount()),
model.getOtherAccounts().stream()
.map(this.accountMapper::toViewModel)
.collect(Collectors.toList()),
this.timeProvider.getCurrentTime());
}
} |
ramatronics/emodb | sor/src/test/java/com/bazaarvoice/emodb/sor/core/WriteCloseableDatastoreTest.java | <filename>sor/src/test/java/com/bazaarvoice/emodb/sor/core/WriteCloseableDatastoreTest.java
package com.bazaarvoice.emodb.sor.core;
import com.bazaarvoice.emodb.common.api.ServiceUnavailableException;
import com.bazaarvoice.emodb.common.uuid.TimeUUIDs;
import com.bazaarvoice.emodb.sor.api.AuditBuilder;
import com.bazaarvoice.emodb.sor.api.DataStore;
import com.bazaarvoice.emodb.sor.api.Update;
import com.bazaarvoice.emodb.sor.delta.Deltas;
import com.bazaarvoice.emodb.table.db.TableBackingStore;
import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import org.testng.annotations.Test;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
public class WriteCloseableDatastoreTest {
@Test
public void testShutdown() throws InterruptedException, ExecutionException {
Iterable<Update> updateIterable = Iterables.cycle(
new Update("table-name", "key-name", TimeUUIDs.newUUID(),
Deltas.literal(ImmutableMap.of("empty", "empty")),
new AuditBuilder().setComment("empty value").build())
);
DataStore dataStore = mock(DataStore.class);
Semaphore iteratorLock = new Semaphore(1);
Semaphore closeWritesLock = new Semaphore(1);
doAnswer(invocation -> {
Iterable<Update> updates = (Iterable<Update>) invocation.getArguments()[0];
int count = 0;
for (Update update : updates) {
count++;
if (count == 5) {
iteratorLock.release();
closeWritesLock.acquireUninterruptibly();
}
}
// Check to make sure that writes were closed and the iterator cut off when it was supposed to
assertEquals(count, 5);
return null;
}).when(dataStore).updateAll(any(), any());
WriteCloseableDataStore writeCloseableDataStore = new WriteCloseableDataStore(dataStore,
mock(TableBackingStore.class), new MetricRegistry()) {
@Override
protected void postWritesClosed() {
closeWritesLock.release();
}
};
iteratorLock.acquireUninterruptibly();
closeWritesLock.acquireUninterruptibly();
Future updateAllFuture = Executors.newSingleThreadExecutor().submit(() -> {
try {
writeCloseableDataStore.updateAll(updateIterable);
fail("Write succeeded when it should have failed due to shutdown. Should have thrown a" +
"ServiceUnavailablException.");
} catch (ServiceUnavailableException e) { }
});
iteratorLock.acquireUninterruptibly();
Future writeCloserFuture = Executors.newSingleThreadExecutor().submit(writeCloseableDataStore::closeWrites);
updateAllFuture.get();
writeCloserFuture.get();
verify(dataStore).updateAll(any(), any());
}
}
|
larc/competitive_programming | codeforces/1131F.cpp | <gh_stars>1-10
#include <cstdio>
#include <vector>
#define N 150001
std::vector<int> T[N];
void dfs(const int & u)
{
printf("%d ", u);
for(const int & v: T[u])
dfs(v);
}
int comp[N];
void init(const int & n)
{
for(int i = 1; i <= n; ++i)
comp[i] = i;
}
int find(const int & x)
{
return comp[x] == x ? x : comp[x] = find(comp[x]);
}
void join(int x, int y)
{
x = find(x);
y = find(y);
comp[y] = x;
T[x].push_back(y);
}
int main()
{
int n, a, b;
scanf("%d", &n);
init(n);
for(int i = 1; i < n; ++i)
{
scanf("%d %d", &a, &b);
join(a, b);
}
for(a = 1; a <= n; ++a)
if(comp[a] == a) break;
dfs(a); putchar('\n');
return 0;
}
|
vsolank2/MaterialUI-master | app/src/main/java/com/dedsec/materialui/activity/progressactivity/ProgressOnScroll.java | package com.dedsec.materialui.activity.progressactivity;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.dedsec.materialui.R;
import com.dedsec.materialui.adapter.AdapterGridScrollProgress;
import com.dedsec.materialui.data.DataGenerator;
import com.dedsec.materialui.model.ProgressImage;
import com.dedsec.materialui.utils.Tools;
import java.util.ArrayList;
import java.util.List;
public class ProgressOnScroll extends AppCompatActivity {
private View parent_view;
private int item_per_display = 6;
private RecyclerView recyclerView;
private AdapterGridScrollProgress mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_on_scroll);
parent_view = findViewById(android.R.id.content);
initToolbar();
initComponent();
}
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_menu_white);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Tools.setSystemBarColor(this, R.color.colorPrimary);
}
private void initComponent() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterGridScrollProgress(this, item_per_display, generateListItems(item_per_display));
recyclerView.setAdapter(mAdapter);
mAdapter.setOnLoadMoreListener(new AdapterGridScrollProgress.OnLoadMoreListener() {
@Override
public void onLoadMore(int current_page) {
loadNextData();
}
});
}
private void loadNextData() {
mAdapter.setLoading();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mAdapter.insertData(generateListItems(item_per_display));
}
}, 1500);
}
private List<ProgressImage> generateListItems(int count) {
List<Integer> items_img = DataGenerator.getNatureImages(this);
items_img.addAll(DataGenerator.getNatureImages(this));
List<ProgressImage> items = new ArrayList<>();
for (Integer i : items_img) {
items.add(new ProgressImage(i, "IMG_" + i + ".jpg", false));
}
return items.subList(0, count);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_default_light, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
} else {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
|
Rockbox-Chinese-Community/Rockbox-RCC | uisimulator/common/sim_icons.c | <gh_stars>10-100
/***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
* $Id$
*
* Copyright (C) 2002 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
#include <stdio.h>
#include "config.h"
#include <lcd.h>
#include <kernel.h>
#include <string.h>
#include <debug.h>
extern void lcd_print_icon(int x, int icon_line, bool enable, char **icon);
static char* icon_battery_bit[]=
{
"-----",
" ",
"*****",
"*****",
"*****",
"*****",
"*****",
"*****",
" ",
"-----",
NULL
};
static char* icon_battery[]=
{
"********************* ",
"* * ",
"* ----- ----- ----- * ",
"* ----- ----- ----- ***",
"* ----- ----- ----- * *",
"* ----- ----- ----- * *",
"* ----- ----- ----- ***",
"* ----- ----- ----- * ",
"* * ",
"********************* ",
NULL
};
static char* icon_volume[]=
{
" ",
" ",
" ",
" ",
"* * * ",
"* * * ",
" * * *** * ",
" * * * * * ",
" * * * * ",
" * *** * ",
NULL
};
static char* icon_volume_1[]=
{
" ",
" ",
" ",
" ",
"**",
"**",
"**",
"**",
"**",
"**",
NULL
};
static char* icon_volume_2[]=
{
" ",
" ",
" ",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
NULL
};
static char* icon_volume_3[]=
{
" ",
" ",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
NULL
};
static char* icon_volume_4[]=
{
" ",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
NULL
};
static char* icon_volume_5[]=
{
"**",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
"**",
NULL
};
static char* icon_pause[]=
{
" **** **** ",
" **** **** ",
" **** **** ",
" **** **** ",
" **** **** ",
" **** **** ",
" **** **** ",
" **** **** ",
" **** **** ",
" **** **** ",
NULL
};
static char* icon_play[]=
{
"** ",
"***** ",
"******* ",
"********* ",
"*********** ",
"********* ",
"******* ",
"***** ",
"** ",
" ",
NULL
};
static char* icon_record[]=
{
" *** ",
" ***** ",
" ******* ",
" ********* ",
" ********* ",
" ********* ",
" ******* ",
" ***** ",
" *** ",
" ",
NULL
};
static char* icon_usb[]=
{
" ********* ",
" ** ** ",
" * ",
" ** * ** ",
"***********************",
" ** * ** ",
" * ",
" ** ** ",
" ******** ",
" ** ",
NULL
};
static char* icon_audio[]=
{
" *************************** ",
" ** ** ",
"* ** * * **** * *** *",
"* * * * * * * * * * *",
"* * * * * * * * * * *",
"* ****** * * * * * * * *",
"* * * * * * * * * * *",
"* * * *** **** * *** *",
" ** ** ",
" *************************** ",
NULL
};
static char* icon_param[]=
{
" ********************************* ",
" ** ** ",
"* **** ** **** ** ** ** *",
"* * * * * * * * * ** ** *",
"* * * * * * * * * * * * * *",
"* **** ****** **** ****** * * * * *",
"* * * * * * * * * * * *",
"* * * * * * * * * * * *",
" ** ** ",
" ********************************* ",
NULL
};
static char* icon_repeat[]=
{
" ",
" *************",
" * ",
" * ",
"* ",
"* ",
"* ** ",
" * **** ",
" * ****** ",
" *************",
NULL
};
static char* icon_repeat2[]=
{
" ",
" *",
" **",
"***",
" *",
" *",
" *",
" *",
" *",
" *",
NULL
};
struct icon_info
{
char** bitmap;
int xpos;
int row;
};
#define ICON_VOLUME_POS 102
#define ICON_VOLUME_SIZE 14
#define ICON_VOLUME_X_SIZE 2
static struct icon_info icons [] =
{
{icon_battery, 0, 0},
{icon_battery_bit, 2, 0},
{icon_battery_bit, 8, 0},
{icon_battery_bit, 14, 0},
{icon_usb, 0, 1},
{icon_play, 36, 0},
{icon_record, 48, 0},
{icon_pause, 60, 0},
{icon_audio, 37, 1},
{icon_repeat, 74, 0},
{icon_repeat2, 94, 0},
{icon_volume, ICON_VOLUME_POS, 0},
{icon_volume_1, ICON_VOLUME_POS+ICON_VOLUME_SIZE, 0},
{icon_volume_2, ICON_VOLUME_POS+ICON_VOLUME_SIZE+(1*ICON_VOLUME_X_SIZE)+1, 0},
{icon_volume_3, ICON_VOLUME_POS+ICON_VOLUME_SIZE+(2*ICON_VOLUME_X_SIZE)+2, 0},
{icon_volume_4, ICON_VOLUME_POS+ICON_VOLUME_SIZE+(3*ICON_VOLUME_X_SIZE)+3, 0},
{icon_volume_5, ICON_VOLUME_POS+ICON_VOLUME_SIZE+(4*ICON_VOLUME_X_SIZE)+4, 0},
{icon_param, 90, 1}
};
void
lcd_icon(int icon, bool enable)
{
lcd_print_icon(icons[icon].xpos, icons[icon].row, enable,
icons[icon].bitmap);
}
|
lorenzo-cavazzi/renku-python | renku/core/utils/doi.py | <reponame>lorenzo-cavazzi/renku-python<filename>renku/core/utils/doi.py
# -*- coding: utf-8 -*-
#
# Copyright 2020 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# 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.
"""Helper utils for handling DOIs."""
import re
doi_regexp = re.compile(
r'(doi:\s*|(?:https?://)?(?:dx\.)?doi\.org/)?(10\.\d+(.\d+)*/.+)$',
flags=re.I
)
"""See http://en.wikipedia.org/wiki/Digital_object_identifier."""
def is_doi(uri):
"""Check if uri is DOI."""
return doi_regexp.match(uri)
def extract_doi(uri):
"""Return the DOI in a string if there is one."""
match = doi_regexp.match(uri)
if match:
return match.group(2)
|
duanshuyong0/Descart | src/components/MailChimpSignup/index.js | <reponame>duanshuyong0/Descart<filename>src/components/MailChimpSignup/index.js<gh_stars>100-1000
export { default } from './MailChimpSignup'
|
pjsaksa/femc-driver | utils.c | <filename>utils.c
/* Femc Driver
* Copyright (C) 2015-2020 <NAME>
*
* Licensed under The MIT License, see file LICENSE.txt in this source tree.
*/
#include "utils.h"
#include "error_stack.h"
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#ifndef UNIX_PATH_MAX
enum { UNIX_PATH_MAX = 108 };
#endif
// ------------------------------------------------------------
fdu_memory_area init_memory_area(unsigned char* begin, const uint32_t size)
{
return (fdu_memory_area){begin, begin+size};
}
fdu_memory_area init_memory_area_cont(unsigned char** beginp, const uint32_t size)
{
unsigned char* const begin = *beginp;
unsigned char* const end = (*beginp) += size;
return (fdu_memory_area){begin, end};
}
/*------------------------------------------------------------
*
* Buffered I/O services
*
*/
enum {
MinimumBufferSize = 64,
MaximumBufferSize = 1024*1024,
};
typedef enum {
bufio_input,
bufio_output,
} fdu_bufio_service_type;
enum { // cs = callstack
bufio_cs_active = 1,
bufio_cs_closed = 1 << 1,
bufio_cs_freed = 1 << 2,
};
struct fdu_bufio_service_ {
fdu_bufio_service_type type;
fdu_bufio_buffer buffer;
union {
fdd_service_input input_service;
fdd_service_output output_service;
};
void* context;
fdu_bufio_notify_func notify;
fdu_bufio_close_func close;
int close_errno;
unsigned int callstack;
};
const unsigned int sizeof_fdu_bufio_service = sizeof(fdu_bufio_service);
//
#define CALLSTACK (service->callstack)
#define CAN_XFER (service->buffer.can_xfer)
#define CONTEXT (service->context)
#define DATA (service->buffer.data)
#define FD (service->buffer.fd)
#define FILLED (service->buffer.filled)
#define NOTIFY (service->notify)
#define SIZE (service->buffer.size)
static bool fdu_bufio_got_input(void* service_v, int fd)
{
fdu_bufio_service* service = (fdu_bufio_service*) service_v;
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_bufio)))
return false;
//
if (!service
|| fd < 0)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
FDE_ASSERT( service->type == bufio_input , "invalid service type" , false );
FDE_ASSERT( fd == FD , "fd corrupted" , false );
FDE_ASSERT( FILLED <= SIZE , "filled > size (1)" , false );
//
if (FILLED == SIZE) {
CAN_XFER = true;
return fdd_remove_input(fd)
&& fde_pop_context(fdu_context_bufio, ectx);
}
const int i = read(fd, &DATA[FILLED], SIZE - FILLED);
if (CAN_XFER) {
CAN_XFER = false;
if (!fdd_add_input(fd, &service->input_service))
return false;
}
bool lazy_close = false;
if (i > 0) {
FILLED += i;
FDE_ASSERT_DEBUG( FILLED <= SIZE , "filled > size (2)" , false );
if (NOTIFY) {
CALLSTACK |= bufio_cs_active;
lazy_close = (!NOTIFY(&service->buffer, CONTEXT)
|| (CALLSTACK & (bufio_cs_closed | bufio_cs_freed)));
CALLSTACK &= ~(bufio_cs_active | bufio_cs_closed);
}
}
else if (!i) {
lazy_close = true;
}
else if (errno != EINTR
&& errno != EAGAIN)
{
// assert: i < 0 && errno == something_serious
lazy_close = true;
service->close_errno = errno;
}
if (lazy_close)
fdu_bufio_close(&service->buffer);
return fde_safe_pop_context(fdu_context_bufio, ectx);
}
static bool fdu_bufio_got_output(void* service_v, int fd)
{
fdu_bufio_service* service = (fdu_bufio_service*) service_v;
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_bufio)))
return false;
//
if (!service
|| fd < 0)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
FDE_ASSERT( service->type == bufio_output , "invalid service type" , false );
FDE_ASSERT( fd == FD , "fd corrupted" , false );
FDE_ASSERT( FILLED <= SIZE , "filled > size" , false );
//
if (!FILLED) {
CAN_XFER = true;
return fdd_remove_output(fd)
&& fde_pop_context(fdu_context_bufio, ectx);
}
const int i = write(fd, DATA, FILLED);
if (CAN_XFER) {
CAN_XFER = false;
if (!fdd_add_output(fd, &service->output_service))
return false;
}
bool lazy_close = false;
if (i > 0) {
FDE_ASSERT_DEBUG( (unsigned int)i <= FILLED , "i > filled" , false );
FILLED -= i;
if (FILLED)
memmove(DATA, &DATA[i], FILLED);
if (NOTIFY) {
CALLSTACK |= bufio_cs_active;
lazy_close = (!NOTIFY(&service->buffer, CONTEXT)
|| (CALLSTACK & (bufio_cs_closed | bufio_cs_freed)));
CALLSTACK &= ~(bufio_cs_active | bufio_cs_closed);
}
}
else if (errno == EPIPE) {
lazy_close = true;
}
else if (errno != EINTR
&& errno != EAGAIN)
{
lazy_close = true;
service->close_errno = errno;
}
if (lazy_close)
fdu_bufio_close(&service->buffer);
return fde_safe_pop_context(fdu_context_bufio, ectx);
}
// CALLSTACK undefined later
#undef CAN_XFER
#undef CONTEXT
#undef DATA
#undef FD
#undef FILLED
#undef NOTIFY
#undef SIZE
bool fdu_bufio_touch(fdu_bufio_buffer* buffer)
{
fdu_bufio_service* service;
if (!buffer
|| !(service = buffer->service)
|| (service->type != bufio_input
&& service->type != bufio_output))
{
fde_push_context(fdu_context_bufio);
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
if (buffer->fd < 0)
return false;
if (!buffer->can_xfer)
return true;
const fde_node_t* ectx;
if (!(ectx = fde_push_context(fdu_context_bufio)))
return false;
switch (service->type) {
case bufio_input:
if (buffer->filled < buffer->size)
fdu_bufio_got_input(service, buffer->fd);
break;
case bufio_output:
if (service->buffer.filled)
fdu_bufio_got_output(service, buffer->fd);
break;
default: return false;
}
return fde_safe_pop_context(fdu_context_bufio, ectx);
}
void fdu_bufio_close(fdu_bufio_buffer* buffer)
{
fdu_bufio_service* service;
if (!buffer
|| !(service = buffer->service)
|| buffer->fd < 0) // already closed
{
return;
}
FDE_ASSERT( service->type == bufio_input
|| service->type == bufio_output ,
"invalid service type" , );
if (CALLSTACK & bufio_cs_active) {
CALLSTACK |= bufio_cs_closed;
return;
}
const int fd = buffer->fd;
buffer->fd = -1;
const fde_node_t* ectx = fde_push_context(fdu_context_bufio);
if (!buffer->can_xfer) {
switch (service->type) {
case bufio_input: fdd_remove_input(fd); break;
case bufio_output: fdd_remove_output(fd); break;
}
}
//
CALLSTACK |= bufio_cs_active;
service->close(&service->buffer, service->context, fd, service->close_errno);
const bool lazy_free = (CALLSTACK & bufio_cs_freed);
CALLSTACK &= ~(bufio_cs_active | bufio_cs_freed);
//
if (lazy_free)
free(service);
//
if (ectx)
fde_safe_pop_context(fdu_context_bufio, ectx);
}
void fdu_bufio_free(fdu_bufio_buffer* buffer)
{
fdu_bufio_service* service;
if (!buffer
|| !(service = buffer->service))
{
return;
}
if (CALLSTACK & bufio_cs_active) {
CALLSTACK |= bufio_cs_freed;
return;
}
//
if (fdu_bufio_is_closed(buffer)) {
free(service);
}
else {
CALLSTACK |= bufio_cs_freed;
fdu_bufio_close(buffer);
}
}
#undef CALLSTACK
unsigned int fdu_bufio_transfer(fdu_bufio_buffer* dst,
fdu_bufio_buffer* src)
{
if (!dst
|| !src)
{
return 0;
}
const unsigned int offer = src->filled;
const unsigned int space = dst->size - dst->filled;
const unsigned int bytes = (offer < space) ? offer : space;
if (!bytes)
return 0;
memcpy(&dst->data[dst->filled],
src->data,
bytes);
dst->filled += bytes;
src->filled -= bytes;
if (src->filled)
memmove(src->data, &src->data[bytes], src->filled);
return bytes;
}
// ------------------------------------------------------------
fdu_bufio_buffer* fdu_new_input_bufio(const int fd,
const unsigned int size,
void* const context,
const fdu_bufio_notify_func notify_callback,
const fdu_bufio_close_func close_callback)
{
const size_t total_size = sizeof_fdu_bufio_service + size;
unsigned char* const allocated = malloc(total_size);
if (!allocated) {
fde_push_context(fdu_context_bufio);
fde_push_resource_failure_id(fde_resource_memory_allocation);
return 0;
}
unsigned char* counter = allocated;
const fdu_memory_area
service_memory = init_memory_area_cont(&counter, sizeof_fdu_bufio_service),
buffer_memory = init_memory_area_cont(&counter, size);
fdu_bufio_buffer* const bufio
= fdu_new_input_bufio_inplace(fd,
service_memory,
buffer_memory,
context,
notify_callback,
close_callback);
if (!bufio)
free(allocated);
return bufio;
}
fdu_bufio_buffer* fdu_new_output_bufio(const int fd,
const unsigned int size,
void* const context,
const fdu_bufio_notify_func notify_callback,
const fdu_bufio_close_func close_callback)
{
const size_t total_size = sizeof_fdu_bufio_service + size;
unsigned char* const allocated = malloc(total_size);
if (!allocated) {
fde_push_context(fdu_context_bufio);
fde_push_resource_failure_id(fde_resource_memory_allocation);
return 0;
}
unsigned char* counter = allocated;
const fdu_memory_area
service_memory = init_memory_area_cont(&counter, sizeof_fdu_bufio_service),
buffer_memory = init_memory_area_cont(&counter, size);
fdu_bufio_buffer* const bufio
= fdu_new_output_bufio_inplace(fd,
service_memory,
buffer_memory,
context,
notify_callback,
close_callback);
if (!bufio)
free(allocated);
return bufio;
}
fdu_bufio_buffer* fdu_new_input_bufio_inplace(const int fd,
const fdu_memory_area service_memory,
const fdu_memory_area buffer_memory,
void* const context,
const fdu_bufio_notify_func notify_callback,
const fdu_bufio_close_func close_callback)
{
const fde_node_t* ectx;
if (!(ectx = fde_push_context(fdu_context_bufio)))
return 0;
//
if (fd < 0
|| !service_memory.begin
|| !buffer_memory.begin
|| service_memory.begin > service_memory.end
|| buffer_memory.begin > buffer_memory.end)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return 0;
}
//
const unsigned int service_size = service_memory.end - service_memory.begin;
const unsigned int buffer_size = buffer_memory.end - buffer_memory.begin;
if (service_size < sizeof_fdu_bufio_service
|| (buffer_size
&& buffer_size < MinimumBufferSize)
|| buffer_size > MaximumBufferSize)
{
fde_push_resource_failure_id(fde_resource_memory_allocation);
return 0;
}
fdu_bufio_service* service = (fdu_bufio_service*) service_memory.begin;
service->type = bufio_input;
service->context = context;
service->notify = notify_callback;
service->close = close_callback;
service->callstack = 0;
service->close_errno = 0;
service->buffer.fd = fd;
service->buffer.can_xfer = false;
service->buffer.data = buffer_size ? buffer_memory.begin : 0;
service->buffer.size = buffer_size;
service->buffer.filled = 0;
service->buffer.service = service;
fdd_init_service_input(&service->input_service,
service,
&fdu_bufio_got_input);
if (fdd_add_input(fd, &service->input_service)) {
if (fde_pop_context(fdu_context_bufio, ectx))
return &service->buffer; // <-- normal exit
fdd_remove_input(fd);
}
return 0;
}
fdu_bufio_buffer* fdu_new_output_bufio_inplace(const int fd,
const fdu_memory_area service_memory,
const fdu_memory_area buffer_memory,
void* const context,
const fdu_bufio_notify_func notify_callback,
const fdu_bufio_close_func close_callback)
{
const fde_node_t* ectx;
if (!(ectx = fde_push_context(fdu_context_bufio)))
return 0;
//
if (fd < 0
|| !service_memory.begin
|| !buffer_memory.begin
|| service_memory.begin > service_memory.end
|| buffer_memory.begin > buffer_memory.end)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return 0;
}
//
const unsigned int service_size = service_memory.end - service_memory.begin;
const unsigned int buffer_size = buffer_memory.end - buffer_memory.begin;
if (service_size < sizeof_fdu_bufio_service
|| (buffer_size
&& buffer_size < MinimumBufferSize)
|| buffer_size > MaximumBufferSize)
{
fde_push_resource_failure_id(fde_resource_memory_allocation);
return 0;
}
fdu_bufio_service* service = (fdu_bufio_service*) service_memory.begin;
if (!service) {
fde_push_resource_failure_id(fde_resource_memory_allocation);
return 0;
}
service->type = bufio_output;
service->context = context;
service->notify = notify_callback;
service->close = close_callback;
service->buffer.fd = fd;
service->buffer.can_xfer = false;
service->buffer.data = buffer_size ? buffer_memory.begin : 0;
service->buffer.size = buffer_size;
service->buffer.filled = 0;
service->buffer.service = service;
fdd_init_service_output(&service->output_service,
service,
&fdu_bufio_got_output);
if (fdd_add_output(fd, &service->output_service)) {
if (fde_pop_context(fdu_context_bufio, ectx))
return &service->buffer; // <-- normal exit
fdd_remove_output(fd);
}
return 0;
}
/*------------------------------------------------------------
*
* Pending connect()
*
*/
typedef struct {
fdd_service_output oserv;
fdu_notify_connect_func connect_func;
void* context;
} fdu_pending_connect_data;
static bool fdu_pending_connect_callback(void* pcd_v,
int fd)
{
fdu_pending_connect_data* pcd = (fdu_pending_connect_data*) pcd_v;
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_connect)))
return false;
#ifdef FD_DEBUG
if (!pcd
|| fd < 0)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
#endif
//
int connect_error;
socklen_t len = sizeof(connect_error);
if (!fdd_remove_output(fd))
return false;
// check the real status of connect() ...
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &connect_error, &len) < 0) {
connect_error = -1;
fde_push_stdlib_error("getsockopt", errno);
}
// ... and return it with the given callback
fdu_notify_connect_func func = pcd->connect_func;
void* context = pcd->context;
free(pcd);
return func(context, fd, connect_error)
&& fde_safe_pop_context(fdu_context_connect, ectx);
}
bool fdu_pending_connect(int fd, fdu_notify_connect_func callback, void* callback_context)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_connect)))
return false;
// allocate and initialize service
fdu_pending_connect_data* pcd = malloc(sizeof(fdu_pending_connect_data));
if (!pcd) {
fde_push_resource_failure_id(fde_resource_memory_allocation);
return false;
}
fdd_init_service_output(&pcd->oserv,
pcd, // context
&fdu_pending_connect_callback); // notify
pcd->connect_func = callback;
pcd->context = callback_context;
// start service
return fdd_add_output(fd, &pcd->oserv)
&& fde_safe_pop_context(fdu_context_connect, ectx);
}
/*------------------------------------------------------------
*
* Non-blocking DNS lookup
*
*/
typedef struct fdu_dns_service_query_v1 {
struct fdu_dns_service_query_v1* next;
fdu_dnsserv_notify_func notify;
void* context;
} fdu_dns_service_query;
typedef struct {
fdd_service_input iserv;
int pid, fd_in, fd_out;
fdu_dns_service_query* head;
fdu_dns_service_query* tail;
} fdu_dns_service;
// -----
static fdu_dns_service_query* free_dns_query_nodes = 0;
static fdu_dns_service* dns_service = 0;
// -----
static fdu_dns_service_query* new_dns_query_node(fdu_dnsserv_notify_func notify, void* ctx)
{
fdu_dns_service_query* node;
if (!free_dns_query_nodes)
node = malloc(sizeof(fdu_dns_service_query));
else {
node = free_dns_query_nodes;
free_dns_query_nodes = free_dns_query_nodes->next;
}
if (!node)
return 0;
node->next = 0;
node->notify = notify;
node->context = ctx;
return node;
}
// -----
static void free_dns_query_node(fdu_dns_service_query* tbd)
{
tbd->next = free_dns_query_nodes;
free_dns_query_nodes = tbd;
}
// -----
static void fdu_dns_service_shutdown(void)
{
const fde_node_t* ectx = fde_push_context(fdu_context_dnsserv);
//
const int old_pid = dns_service->pid;
if (kill(dns_service->pid, SIGKILL) < 0)
fde_push_stdlib_error("kill", errno);
if (dns_service->head) {
fdd_remove_input(dns_service->fd_in);
while (dns_service->head) {
fdu_dns_service_query* tbd = dns_service->head;
dns_service->head = dns_service->head->next;
tbd->notify(tbd->context, 0);
free_dns_query_node(tbd);
}
}
fdu_safe_close(dns_service->fd_in);
fdu_safe_close(dns_service->fd_out);
free(dns_service);
dns_service = 0;
if (waitpid(old_pid, 0, 0) < -1)
fde_push_stdlib_error("waitpid", errno);
if (ectx)
fde_safe_pop_context(fdu_context_dnsserv, ectx);
}
// -----
static bool fdu_dns_service_got_answer(void* context, int fd)
{
//
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_dnsserv)))
return false;
//
if (context != dns_service) {
fde_push_consistency_failure("context != dns_service");
return false;
}
//
enum { buffer_size = 256 };
static char buffer[buffer_size];
static int filled = 0;
const int i = read(fd, buffer + filled, buffer_size - filled);
if (i <= 0) {
fde_push_stdlib_error("pipe", errno);
fdu_dns_service_shutdown();
return false;
}
filled += i;
//
char* ptr = buffer;
const char* const end = buffer + filled;
char* entry = 0; // start of entry
char* consumed = buffer; // start of next entry
while ((ptr =memchr(ptr, '\n', end - ptr)))
{
*ptr++ = 0;
entry = consumed;
consumed = ptr;
if (!dns_service->head)
{
#ifdef FD_DEBUG
fde_push_consistency_failure("DNS query node list empty");
return false;
#else
continue;
#endif
}
fdu_dns_service_query* current = dns_service->head;
fdu_dnsserv_notify_func local_notify = current->notify;
void* local_context = current->context;
dns_service->head = dns_service->head->next;
if (!dns_service->head) {
dns_service->tail = 0;
fdd_remove_input(dns_service->fd_in);
}
free_dns_query_node(current);
//
local_notify(local_context, *entry ? entry : 0);
}
if (consumed
&& consumed > buffer)
{
filled -= (consumed-buffer);
if (filled)
memmove(buffer, consumed, filled);
}
FDE_ASSERT_DEBUG( filled == end - consumed , "pointer math is corrupted" , false );
return fde_safe_pop_context(fdu_context_dnsserv, ectx);
}
// -----
static bool fdu_dns_service_start(void)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_dnsserv)))
return false;
//
int pid = 0;
int fds_read[2] = {-1, -1};
int fds_write[2] = {-1, -1};
// create pipes for communication
if (pipe(fds_read) != 0
|| pipe(fds_write) != 0)
{
fde_push_stdlib_error("pipe", errno);
if (fds_read[0] >= 0) fdu_safe_close(fds_read[0]);
if (fds_read[1] >= 0) fdu_safe_close(fds_read[1]);
if (fds_write[0] >= 0) fdu_safe_close(fds_write[0]);
if (fds_write[1] >= 0) fdu_safe_close(fds_write[1]);
return false;
}
// spawn process
if ((pid =vfork()) < 0) {
fde_push_stdlib_error("vfork", errno);
fdu_safe_close(fds_read[0]);
fdu_safe_close(fds_read[1]);
fdu_safe_close(fds_write[0]);
fdu_safe_close(fds_write[1]);
return false;
}
else if (pid == 0) // child
{
fdu_safe_close(fds_read[0]);
fdu_safe_close(fds_write[1]);
if (fdu_move_fd(fds_write[0], STDIN_FILENO)
&& fdu_move_fd(fds_read[1], STDOUT_FILENO))
{
execl("./dns-service", "dns-service", (char*) 0);
}
_exit(-1);
}
// parent
fdu_safe_close(fds_read[1]);
fdu_safe_close(fds_write[0]);
/* verify operation:
* dns-service replies to invalid requests with empty line, so
* simple '\n' should be replied with '\n'
*/
{
char buffer[2];
if (write(fds_write[1], "\n", 1) != 1
|| read(fds_read[0], buffer, 1) != 1
|| buffer[0] != '\n')
{
fde_push_resource_failure("dns_service:startup test");
fdu_safe_close(fds_read[0]);
fdu_safe_close(fds_write[1]);
kill(pid, SIGKILL);
waitpid(pid, 0, 0);
return false;
}
}
// init dns_service struct
dns_service = malloc(sizeof(fdu_dns_service));
if (!dns_service) {
fde_push_resource_failure_id(fde_resource_memory_allocation);
fdu_dns_service_shutdown();
return false;
}
fdd_init_service_input(&dns_service->iserv, dns_service, &fdu_dns_service_got_answer);
dns_service->head = 0;
dns_service->tail = 0;
dns_service->pid = pid;
dns_service->fd_in = fds_read[0];
dns_service->fd_out = fds_write[1];
return fde_safe_pop_context(fdu_context_dnsserv, ectx);
}
bool fdu_dnsserv_lookup(const char* name, fdu_dnsserv_notify_func notify, void* ctx)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_dnsserv)))
return false;
//
const unsigned int name_len = name ? strlen(name) : 0;
if (!name
|| name_len <= 2
|| !notify)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
if (!dns_service
&& !fdu_dns_service_start()
&& !dns_service)
{
fde_push_resource_failure("dns_service:startup");
return false;
}
// send dns-name to dns-service
enum { tmp_buffer_size = 255 };
if (name_len >= tmp_buffer_size) {
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
unsigned char buffer[tmp_buffer_size +1];
memcpy(buffer, name, name_len);
buffer[name_len] = '\n';
const bool write_ok = fdu_safe_write(dns_service->fd_out, buffer, buffer + name_len + 1);
//
if (!write_ok) {
fde_push_resource_failure("dns_service:write");
fdu_dns_service_shutdown();
return false;
}
// create new query
fdu_dns_service_query* new_query = new_dns_query_node(notify, ctx);
if (!new_query) {
fde_push_resource_failure_id(fde_resource_memory_allocation);
return false;
}
// add it to the list
if (dns_service->tail)
{
dns_service->tail->next = new_query;
dns_service->tail = new_query;
}
else {
dns_service->head = new_query;
dns_service->tail = new_query;
fdd_add_input(dns_service->fd_in, &dns_service->iserv);
}
return fde_safe_pop_context(fdu_context_dnsserv, ectx);
}
/*------------------------------------------------------------
*
* Auto-accept connection (aac)
*
*/
struct aac_service_s {
fdd_service_input listening_service;
fdd_notify_func callback;
void* callback_context;
int server_fd;
};
static bool fdu_aac_new_connection(void* service_v,
int server_fd)
{
aac_service_t* service = (aac_service_t*) service_v;
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_aac)))
return false;
//
int new_socket;
retry:
new_socket = accept(server_fd, 0, 0);
if (new_socket < 0) {
if (errno == EINTR
|| errno == EAGAIN)
{
goto retry;
}
fde_push_stdlib_error("accept", errno);
fdd_remove_input(server_fd);
fdu_safe_close(server_fd);
free(service);
return false;
}
return service->callback(service->callback_context, new_socket)
&& fde_pop_context(fdu_context_aac, ectx);
}
aac_service_t* fdu_auto_accept_connection(int server_fd,
fdd_notify_func callback,
void* callback_context)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_aac)))
return 0;
//
if (server_fd < 0
|| !callback)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
fdu_safe_close(server_fd);
return 0;
}
//
aac_service_t* service = malloc(sizeof(aac_service_t));
if (!service) {
fde_push_resource_failure_id(fde_resource_memory_allocation);
fdu_safe_close(server_fd);
return 0;
}
service->callback = callback;
service->callback_context = callback_context;
service->server_fd = server_fd;
fdd_init_service_input(&service->listening_service,
service,
&fdu_aac_new_connection);
if (!fdd_add_input(server_fd, &service->listening_service)) {
free(service);
fdu_safe_close(server_fd);
return 0;
}
fde_pop_context(fdu_context_aac, ectx);
return service;
}
bool fdu_close_auto_accept(aac_service_t* service)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_aac)))
return false;
//
if (!service) {
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
fdd_remove_input(service->server_fd);
fdu_safe_close(service->server_fd);
free(service);
return fde_safe_pop_context(fdu_context_aac, ectx);
}
/*------------------------------------------------------------
*
* Signal-fd
*
*/
static bool handle_signalfd_input(void* void_service, int fd)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_signalfd)))
return false;
//
if (!void_service) {
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
fdu_signalfd_service* service = (fdu_signalfd_service*) void_service;
if (service->fd != fd) {
fde_push_consistency_failure("handle_signalfd_input() called with invalid fd");
return false;
}
if (!service->callback) {
fde_push_consistency_failure("handle_signalfd_input() called with invalid callback");
return false;
}
//
enum {
buffer_units = 8,
one_info_size = sizeof(struct signalfd_siginfo),
buffer_size = buffer_units * one_info_size,
};
struct signalfd_siginfo info[buffer_units];
const int bytes = read(service->fd, &info, buffer_size);
bool total_callback_success = true;
if (bytes > 0)
{
if (bytes % one_info_size != 0) {
fde_push_data_corruption("signalfd read returned data of invalid size");
return false;
}
const struct signalfd_siginfo * ptr = info;
const struct signalfd_siginfo *const end = &info[bytes / one_info_size];
for (;
ptr < end;
++ptr)
{
const bool success = (*service->callback)(service->callback_context,
ptr->ssi_signo);
if (!success)
total_callback_success = false;
}
}
else if (!bytes)
{
fde_push_stdlib_error("signalfd read", 0);
return false;
}
else /* if (bytes < 0) */
{
fde_push_stdlib_error("signalfd read", errno);
return false;
}
return total_callback_success
&& fde_safe_pop_context(fdu_context_signalfd, ectx);
}
bool fdu_signalfd_init(fdu_signalfd_service* service,
const sigset_t* signal_mask,
fdd_notify_func callback,
void* callback_context)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_signalfd)))
return false;
//
if (!service
|| !signal_mask
|| !callback)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
fdd_init_service_input(&service->input_service, service, handle_signalfd_input);
service->callback = callback;
service->callback_context = callback_context;
service->fd = signalfd(-1, signal_mask, SFD_CLOEXEC);
if (service->fd < 0) {
fde_push_stdlib_error("signalfd", errno);
return false;
}
return fdd_add_input(service->fd, &service->input_service)
&& fde_safe_pop_context(fdu_context_signalfd, ectx);
}
bool fdu_signalfd_reset(fdu_signalfd_service* service,
const sigset_t* signal_mask)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_signalfd)))
return false;
//
if (!service
|| !signal_mask)
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
if (service->fd < 0) {
fde_push_consistency_failure("service must have been previously initialized");
return false;
}
//
if (signalfd(service->fd, signal_mask, 0) < 0) {
fde_push_stdlib_error("signalfd", errno);
return false;
}
return fde_safe_pop_context(fdu_context_signalfd, ectx);
}
bool fdu_signalfd_close(fdu_signalfd_service* service)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_signalfd)))
return false;
//
if (!service) {
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
bool success = true;
if (! fdd_remove_input(service->fd) ) success = false;
if (! fdu_safe_close(service->fd) ) success = false;
service->fd = -1;
return success
&& fde_safe_pop_context(fdu_context_signalfd, ectx);
}
/*------------------------------------------------------------
*
* General utilities
*
*/
int fdu_listen_inet4(unsigned short port, unsigned int options)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_listen)))
return -1;
//
const unsigned int protocol = (options & FDU_SOCKET_PROTOCOL_MASK);
if (!port
|| (options & ~(FDU_SOCKET_PROTOCOL_MASK
|FDU_SOCKET_LOCAL
|FDU_SOCKET_NOREUSE
|FDU_SOCKET_BROADCAST))
|| (protocol != FDU_SOCKET_STREAM
&& protocol != FDU_SOCKET_DGRAM
&& protocol != FDU_SOCKET_SEQPACKET)
|| (options & FDU_SOCKET_BROADCAST
&& (options & FDU_SOCKET_LOCAL
|| protocol != FDU_SOCKET_DGRAM)))
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return -1;
}
// open socket
const int socketfd = socket(PF_INET,
(protocol == FDU_SOCKET_DGRAM) ? SOCK_DGRAM
: (protocol == FDU_SOCKET_SEQPACKET) ? SOCK_SEQPACKET
: SOCK_STREAM,
0);
if (socketfd < 0) {
fde_push_stdlib_error("socket", errno);
return -1;
}
// optionally set SO_REUSEADDR for faster restart
if (!(options & FDU_SOCKET_NOREUSE))
{
int parameter = 1;
if (setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR,
¶meter, sizeof(parameter)) < 0)
{
fde_push_stdlib_error("setsockopt(SO_REUSEADDR)", errno);
fdu_safe_close(socketfd);
return -1;
}
}
// optionally set SO_BROADCAST
if (options & FDU_SOCKET_BROADCAST)
{
int parameter = 1;
if (setsockopt(socketfd, SOL_SOCKET, SO_BROADCAST,
¶meter, sizeof(parameter)) < 0)
{
fde_push_stdlib_error("setsockopt(SO_BROADCAST)", errno);
fdu_safe_close(socketfd);
return -1;
}
}
// bind
{
struct sockaddr_in sa;
memset(&sa, 0, sizeof(struct sockaddr_in));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
sa.sin_addr.s_addr = (options & FDU_SOCKET_LOCAL) ? htonl(INADDR_LOOPBACK) : INADDR_ANY;
if (bind(socketfd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
fde_push_stdlib_error("bind", errno);
fdu_safe_close(socketfd);
return -1;
}
}
// listen
if (protocol != FDU_SOCKET_DGRAM) {
if (listen(socketfd, 64) == -1) {
fde_push_stdlib_error("listen", errno);
fdu_safe_close(socketfd);
return -1;
}
}
if (!fde_safe_pop_context(fdu_context_listen, ectx)) {
fdu_safe_close(socketfd);
return -1;
}
return socketfd;
}
int fdu_listen_unix(const char* path, unsigned int options)
{
const fde_node_t* ectx = 0;
if (!(ectx =fde_push_context(fdu_context_listen)))
return -1;
//
const unsigned int protocol = (options & FDU_SOCKET_PROTOCOL_MASK);
if (!path
|| !path[0]
|| (options & ~FDU_SOCKET_PROTOCOL_MASK)
|| (protocol != FDU_SOCKET_STREAM
&& protocol != FDU_SOCKET_DGRAM
&& protocol != FDU_SOCKET_SEQPACKET))
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return -1;
}
//
const int socketfd = socket(PF_UNIX,
(protocol == FDU_SOCKET_DGRAM) ? SOCK_DGRAM
: (protocol == FDU_SOCKET_SEQPACKET) ? SOCK_SEQPACKET
: SOCK_STREAM,
0);
if (socketfd < 0) {
fde_push_stdlib_error("socket", errno);
return -1;
}
// bind
{
struct sockaddr_un sa;
memset(&sa, 0, sizeof(struct sockaddr_un));
sa.sun_family = AF_UNIX;
strncpy(sa.sun_path, path, UNIX_PATH_MAX);
sa.sun_path[UNIX_PATH_MAX-1] = 0;
if (bind(socketfd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
fde_push_stdlib_error("bind", errno);
fdu_safe_close(socketfd);
return -1;
}
}
// listen
if (protocol != FDU_SOCKET_DGRAM) {
if (listen(socketfd, 64) == -1) {
fde_push_stdlib_error("listen", errno);
fdu_safe_close(socketfd);
return -1;
}
}
if (!fde_safe_pop_context(fdu_context_listen, ectx)) {
fdu_safe_close(socketfd);
return -1;
}
return socketfd;
}
bool fdu_lazy_connect(struct sockaddr_in* addr,
fdu_notify_connect_func connect_func,
void* context,
unsigned int options)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_connect)))
return false;
//
const unsigned int protocol = (options & FDU_SOCKET_PROTOCOL_MASK);
if (!addr
|| !connect_func
|| options & ~FDU_SOCKET_PROTOCOL_MASK
|| (protocol != FDU_SOCKET_STREAM
&& protocol != FDU_SOCKET_DGRAM
&& protocol != FDU_SOCKET_SEQPACKET))
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
int socketfd = socket(PF_INET,
(protocol == FDU_SOCKET_DGRAM) ? SOCK_DGRAM
: (protocol == FDU_SOCKET_SEQPACKET) ? SOCK_SEQPACKET
: SOCK_STREAM,
0);
if (socketfd < 0) {
fde_push_stdlib_error("socket", errno);
return false;
}
// set O_NONBLOCK
int flags;
if ((flags =fcntl(socketfd, F_GETFL)) == -1) {
fde_push_stdlib_error("fcntl(F_GETFL)", errno);
fdu_safe_close(socketfd);
return false;
}
if ((flags & O_NONBLOCK) == 0) {
if (fcntl(socketfd, F_SETFL, flags|O_NONBLOCK) == -1) {
fde_push_stdlib_error("fcntl(F_SETFL)", errno);
fdu_safe_close(socketfd);
return false;
}
}
// the actual connect
int connect_errno = 0;
bool close_succeed = true;
if (connect(socketfd, (struct sockaddr*) addr, sizeof(struct sockaddr_in)) != 0) {
if (errno == EINPROGRESS) {
fdu_pending_connect(socketfd, connect_func, context);
return true;
}
connect_errno = errno;
close_succeed = fdu_safe_close(socketfd);
socketfd = -1;
}
return connect_func(context, socketfd, connect_errno)
&& close_succeed
&& fde_pop_context(fdu_context_connect, ectx);
}
// ------------------------------------------------------------
bool fdu_safe_read(int fd, unsigned char* start, const unsigned char* const end)
{
if (fd < 0
|| !start
|| !end)
{
fde_push_context(fdu_context_safe);
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
while (start < end) //sic
{
const int i = read(fd, start, end - start);
if (i > 0) {
start += i;
}
else if (!i
|| (errno != EINTR
&& errno != EAGAIN))
{
fde_push_context(fdu_context_safe);
fde_push_stdlib_error("read", errno);
return false;
}
}
return true;
}
bool fdu_safe_write(int fd, const unsigned char* start, const unsigned char* const end)
{
if (fd < 0
|| !start
|| !end)
{
fde_push_context(fdu_context_safe);
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
while (start < end)
{
const int i = write(fd, start, end-start);
if (i > 0) {
start += i;
}
else if (errno != EINTR
&& errno != EAGAIN)
{
fde_push_context(fdu_context_safe);
fde_push_stdlib_error("write", errno);
return false;
}
}
return true;
}
bool fdu_safe_write_str(int fd, const unsigned char* buffer)
{
return fdu_safe_write(fd,
buffer,
buffer ? (buffer+strlen((const char*) buffer)) : 0);
}
bool fdu_safe_close(int fd)
{
if (fd < 0) {
fde_push_context(fdu_context_safe);
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
retry:
if (close(fd) == 0)
return true;
else if (errno == EINTR)
goto retry;
else {
fde_push_context(fdu_context_safe);
fde_push_stdlib_error("close", errno);
return false;
}
}
bool fdu_safe_chdir(const char* new_dir)
{
if (!new_dir
|| !*new_dir)
{
fde_push_context(fdu_context_safe);
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
if (chdir(new_dir) != 0) {
fde_push_context(fdu_context_safe);
fde_push_stdlib_error("chdir", errno);
return false;
}
return true;
}
bool fdu_copy_fd(int oldfd, int newfd)
{
if (oldfd < 0
|| newfd < 0)
{
fde_push_context(fdu_context_safe);
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
//
if (oldfd == newfd)
return true;
for (;;) {
if (dup2(oldfd, newfd) >= 0)
return true;
else if (errno != EINTR) {
fde_push_context(fdu_context_safe);
fde_push_stdlib_error("dup2", errno);
return false;
}
}
}
bool fdu_move_fd(int oldfd, int newfd)
{
return oldfd == newfd
|| (fdu_copy_fd(oldfd, newfd)
&& fdu_safe_close(oldfd));
}
bool fdu_pidfile(const char* filename, int options)
{
const fde_node_t* ectx;
if (!(ectx =fde_push_context(fdu_context_pidfile)))
return false;
//
if (!filename
|| !filename[0]
|| (options & ~(FDU_PIDFILE_ONLYCHECK)))
{
fde_push_consistency_failure_id(fde_consistency_invalid_arguments);
return false;
}
/* open file
*
* flags must not modify the file if it exists
* (advisory lock doesn't apply yet)
*/
const int fd = open(filename, O_RDWR|O_CREAT|O_CLOEXEC, 0600);
if (fd < 0) {
fde_push_stdlib_error("open", errno);
return false;
}
// lock the file
{
struct flock flock;
flock.l_type = F_WRLCK;
flock.l_whence = SEEK_SET;
flock.l_start = 0;
flock.l_len = 0;
if (fcntl(fd, F_SETLK, &flock) < 0) {
fde_push_stdlib_error("fcntl", errno);
fdu_safe_close(fd);
return false;
}
}
if (options & FDU_PIDFILE_ONLYCHECK) {
return fdu_safe_close(fd)
&& fde_safe_pop_context(fdu_context_pidfile, ectx);
}
// write pid and truncate
{
enum { pid_buffer_size = 20 };
unsigned char buf[pid_buffer_size];
struct stat st;
const int len = snprintf((char*) buf, pid_buffer_size, "%u\n", getpid());
if (len <= 1) {
fde_push_stdlib_error("snprintf", 0);
fdu_safe_close(fd);
return false;
}
if (!fdu_safe_write(fd, buf, buf+len)) {
fdu_safe_close(fd);
return false;
}
if (fstat(fd, &st) != 0) {
fde_push_stdlib_error("fstat", errno);
fdu_safe_close(fd);
return false;
}
if (st.st_size != len
&& ftruncate(fd, len) < 0)
{
fde_push_stdlib_error("ftruncate", errno);
fdu_safe_close(fd);
return false;
}
}
return fde_pop_context(fdu_context_pidfile, ectx); // don't close fd
}
|
hmcts/wa-monitor-unconfigured-tasks-service | src/integrationTest/java/uk/gov/hmcts/reform/wataskmonitor/controllers/MonitorTaskJobControllerForAdHocJobTest.java | <reponame>hmcts/wa-monitor-unconfigured-tasks-service
package uk.gov.hmcts.reform.wataskmonitor.controllers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator;
import uk.gov.hmcts.reform.wataskmonitor.TestUtility;
import uk.gov.hmcts.reform.wataskmonitor.clients.CamundaClient;
import uk.gov.hmcts.reform.wataskmonitor.domain.taskmonitor.request.JobDetails;
import uk.gov.hmcts.reform.wataskmonitor.domain.taskmonitor.request.MonitorTaskJobRequest;
import uk.gov.hmcts.reform.wataskmonitor.services.ResourceEnum;
import uk.gov.hmcts.reform.wataskmonitor.utils.ResourceUtility;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static uk.gov.hmcts.reform.wataskmonitor.controllers.MonitorTaskJobControllerUtility.expectedResponse;
import static uk.gov.hmcts.reform.wataskmonitor.domain.taskmonitor.JobName.AD_HOC_DELETE_PROCESS_INSTANCES;
class MonitorTaskJobControllerForAdHocJobTest extends SpringBootIntegrationBaseTest {
public static final String SERVICE_TOKEN = "some <PASSWORD> token";
@MockBean
private CamundaClient camundaClient;
@MockBean
private AuthTokenGenerator authTokenGenerator;
private String requestParameter;
@BeforeEach
void setUp() {
mockExternalDependencies();
}
@SuppressWarnings({"PMD.JUnitTestsShouldIncludeAssert", "PMD.LawOfDemeter"})
@Test
public void givenMonitorTaskJobRequestShouldReturnStatus200AndExpectedResponse() throws Exception {
MonitorTaskJobRequest monitorTaskJobReq = new MonitorTaskJobRequest(new JobDetails(
AD_HOC_DELETE_PROCESS_INSTANCES));
mockMvc.perform(
post("/monitor/tasks/jobs")
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("utf8")
.content(TestUtility.asJsonString(monitorTaskJobReq)))
.andExpect(status().isOk())
.andExpect(content().string(equalTo(expectedResponse.apply(AD_HOC_DELETE_PROCESS_INSTANCES.name()))));
verify(authTokenGenerator).generate();
verify(camundaClient).deleteProcessInstance(eq(SERVICE_TOKEN), eq(requestParameter));
}
private void mockExternalDependencies() {
when(authTokenGenerator.generate()).thenReturn(SERVICE_TOKEN);
requestParameter = ResourceUtility.getResource(ResourceEnum.DELETE_PROCESS_INSTANCES_JOB_SERVICE);
String someResponse = "{\"id\": \"78e1a849-d9b3-11eb-bb4f-d62f1f620fc5\",\"type\": \"instance-deletion\" }";
when(camundaClient.deleteProcessInstance(eq(SERVICE_TOKEN), eq(requestParameter)))
.thenReturn(someResponse);
}
}
|
davimuri/algorithms | src/main/java/algorithms/gcj2019/r1a/Pylons.java | <reponame>davimuri/algorithms<filename>src/main/java/algorithms/gcj2019/r1a/Pylons.java
package algorithms.gcj2019.r1a;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Pylons {
public static void main(String args[]) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int testCases = in.nextInt();
for (int t = 1; t <= testCases; t++) {
int rows = in.nextInt();
int cols = in.nextInt();
List<int[]> path = path(rows, cols);
if (path.isEmpty()) {
System.out.printf("Case #%d: IMPOSSIBLE%n", t);
} else {
System.out.printf("Case #%d: POSSIBLE%n", t);
path.stream().forEach(e -> {
System.out.println(e[0] + " " + e[1]);
});
}
}
}
public static List<int[]> path(int rows, int cols) {
if (rows * cols <= 9) {
return Collections.emptyList();
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
boolean[][] matrix = new boolean[rows][cols];
List<int[]> path = pathFromMatrix(i, j, matrix);
if (path.size() == rows * cols) {
return path;
}
}
}
return Collections.emptyList();
}
public static List<int[]> pathFromMatrix(int row, int col, boolean[][] matrix) {
List<int[]> path = new ArrayList<>(matrix.length * matrix[0].length);
int[] move = {row, col};
while (move != null) {
matrix[move[0]][move[1]] = true;
path.add(new int[] {move[0]+1, move[1]+1});
move = nextMoveFromPosition(move[0], move[1], matrix);
}
//assert path.size() == matrix.length * matrix[0].length : "Wrong path of size " + path.size()
// + " for matrix " + matrix.length + " x " + matrix[0].length;
return path;
}
private static int[] nextMoveFromPosition(int row, int col, boolean[][] matrix) {
List<int[]> candidates = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (!matrix[i][j] && row != i && col != j && row - col != i - j && row + col != i + j) {
candidates.add(new int[] {i, j});
}
}
}
return selectMoveFromCandidates(candidates, matrix);
}
private static int[] selectMoveFromCandidates(List<int[]> candidates, boolean[][] matrix) {
int maxFreeCells = -1;
int[] selected = null;
for (int[] candidate : candidates) {
int freeCells = countFreeNeighbors(candidate[0], candidate[1], matrix);
if (freeCells > maxFreeCells) {
maxFreeCells = freeCells;
selected = candidate;
}
}
return selected;
}
private static int countFreeNeighbors(int row, int col, boolean[][] matrix) {
int freeNeighbors = 0;
freeNeighbors += countFreeCellsInDirection(row, col, 1, 0, matrix);
freeNeighbors += countFreeCellsInDirection(row, col, 1, 1, matrix);
freeNeighbors += countFreeCellsInDirection(row, col, 0, 1, matrix);
freeNeighbors += countFreeCellsInDirection(row, col, -1, 1, matrix);
freeNeighbors += countFreeCellsInDirection(row, col, -1, 0, matrix);
freeNeighbors += countFreeCellsInDirection(row, col, -1, -1, matrix);
freeNeighbors += countFreeCellsInDirection(row, col, 0, -1, matrix);
freeNeighbors += countFreeCellsInDirection(row, col, 1, -1, matrix);
return freeNeighbors;
}
private static int countFreeCellsInDirection(int row, int col, int orientationX, int orientationY, boolean[][] matrix) {
int freeNeighbors = 0;
int r = row + orientationX;
int c = col + orientationY;
while (0 <= r && r < matrix.length && 0 <= c && c < matrix[row].length) {
if (!matrix[r][c]) {
freeNeighbors++;
}
r += orientationX;
c += orientationY;
}
return freeNeighbors;
}
}
|
ApacheJondy/ShortVideo | ShortVideoUIDemo/faceunity/src/main/java/com/faceunity/authpack.java | package com.faceunity;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class authpack {
public static int sha1_32(byte[] buf){int ret=0;try{byte[] digest=MessageDigest.getInstance("SHA1").digest(buf);return ((int)(digest[0]&0xff)<<24)+((int)(digest[1]&0xff)<<16)+((int)(digest[2]&0xff)<<8)+((int)(digest[3]&0xff)<<0);}catch(Exception e){}return ret;}
public static byte[] A(){
byte[] buf=new byte[1158];
int i=0;
for(i=23;i<38;i++){ buf[0]=(byte)i; if(sha1_32(buf)==-1358628657){break;} }
for(i=-77;i<-58;i++){ buf[1]=(byte)i; if(sha1_32(buf)==150011871){break;} }
for(i=-74;i<-55;i++){ buf[2]=(byte)i; if(sha1_32(buf)==2125618389){break;} }
for(i=108;i<126;i++){ buf[3]=(byte)i; if(sha1_32(buf)==601202827){break;} }
for(i=-70;i<-45;i++){ buf[4]=(byte)i; if(sha1_32(buf)==1637508673){break;} }
for(i=-38;i<-14;i++){ buf[5]=(byte)i; if(sha1_32(buf)==-580074447){break;} }
for(i=117;i<128;i++){ buf[6]=(byte)i; if(sha1_32(buf)==1958314589){break;} }
for(i=83;i<101;i++){ buf[7]=(byte)i; if(sha1_32(buf)==1639216142){break;} }
for(i=-110;i<-86;i++){ buf[8]=(byte)i; if(sha1_32(buf)==-155183514){break;} }
for(i=-9;i<-4;i++){ buf[9]=(byte)i; if(sha1_32(buf)==94774827){break;} }
for(i=4;i<15;i++){ buf[10]=(byte)i; if(sha1_32(buf)==1185586213){break;} }
for(i=71;i<73;i++){ buf[11]=(byte)i; if(sha1_32(buf)==-1498067242){break;} }
for(i=91;i<109;i++){ buf[12]=(byte)i; if(sha1_32(buf)==-209356046){break;} }
for(i=-96;i<-75;i++){ buf[13]=(byte)i; if(sha1_32(buf)==1254191735){break;} }
for(i=115;i<126;i++){ buf[14]=(byte)i; if(sha1_32(buf)==2024256772){break;} }
for(i=-1;i<14;i++){ buf[15]=(byte)i; if(sha1_32(buf)==-495155416){break;} }
for(i=-37;i<-16;i++){ buf[16]=(byte)i; if(sha1_32(buf)==1742105014){break;} }
for(i=-113;i<-105;i++){ buf[17]=(byte)i; if(sha1_32(buf)==678210155){break;} }
for(i=-97;i<-76;i++){ buf[18]=(byte)i; if(sha1_32(buf)==-424821799){break;} }
for(i=-106;i<-93;i++){ buf[19]=(byte)i; if(sha1_32(buf)==-896445092){break;} }
for(i=-71;i<-58;i++){ buf[20]=(byte)i; if(sha1_32(buf)==-992898528){break;} }
for(i=54;i<74;i++){ buf[21]=(byte)i; if(sha1_32(buf)==-2073878581){break;} }
for(i=48;i<60;i++){ buf[22]=(byte)i; if(sha1_32(buf)==941366331){break;} }
for(i=-35;i<-17;i++){ buf[23]=(byte)i; if(sha1_32(buf)==1872131657){break;} }
for(i=-78;i<-57;i++){ buf[24]=(byte)i; if(sha1_32(buf)==-1322539988){break;} }
for(i=27;i<41;i++){ buf[25]=(byte)i; if(sha1_32(buf)==887855869){break;} }
for(i=48;i<63;i++){ buf[26]=(byte)i; if(sha1_32(buf)==1959135231){break;} }
for(i=-4;i<5;i++){ buf[27]=(byte)i; if(sha1_32(buf)==-922426056){break;} }
for(i=-32;i<-17;i++){ buf[28]=(byte)i; if(sha1_32(buf)==-214916887){break;} }
for(i=-61;i<-55;i++){ buf[29]=(byte)i; if(sha1_32(buf)==225556604){break;} }
for(i=55;i<69;i++){ buf[30]=(byte)i; if(sha1_32(buf)==-299309188){break;} }
for(i=-22;i<-3;i++){ buf[31]=(byte)i; if(sha1_32(buf)==-1147658039){break;} }
for(i=-91;i<-74;i++){ buf[32]=(byte)i; if(sha1_32(buf)==1441555910){break;} }
for(i=66;i<89;i++){ buf[33]=(byte)i; if(sha1_32(buf)==-1968905449){break;} }
for(i=-57;i<-37;i++){ buf[34]=(byte)i; if(sha1_32(buf)==1682185487){break;} }
for(i=4;i<14;i++){ buf[35]=(byte)i; if(sha1_32(buf)==1708687329){break;} }
for(i=113;i<115;i++){ buf[36]=(byte)i; if(sha1_32(buf)==-576738486){break;} }
for(i=23;i<36;i++){ buf[37]=(byte)i; if(sha1_32(buf)==-7515735){break;} }
for(i=-5;i<11;i++){ buf[38]=(byte)i; if(sha1_32(buf)==1754461779){break;} }
for(i=-51;i<-41;i++){ buf[39]=(byte)i; if(sha1_32(buf)==-1468746695){break;} }
for(i=-35;i<-8;i++){ buf[40]=(byte)i; if(sha1_32(buf)==1214206357){break;} }
for(i=-6;i<0;i++){ buf[41]=(byte)i; if(sha1_32(buf)==-978328016){break;} }
for(i=79;i<86;i++){ buf[42]=(byte)i; if(sha1_32(buf)==898767138){break;} }
for(i=-128;i<-120;i++){ buf[43]=(byte)i; if(sha1_32(buf)==920567640){break;} }
for(i=-99;i<-78;i++){ buf[44]=(byte)i; if(sha1_32(buf)==1934565900){break;} }
for(i=102;i<124;i++){ buf[45]=(byte)i; if(sha1_32(buf)==-85894081){break;} }
for(i=-54;i<-32;i++){ buf[46]=(byte)i; if(sha1_32(buf)==-240829910){break;} }
for(i=20;i<34;i++){ buf[47]=(byte)i; if(sha1_32(buf)==-1917749228){break;} }
for(i=-56;i<-46;i++){ buf[48]=(byte)i; if(sha1_32(buf)==709008110){break;} }
for(i=1;i<11;i++){ buf[49]=(byte)i; if(sha1_32(buf)==1998249816){break;} }
for(i=112;i<118;i++){ buf[50]=(byte)i; if(sha1_32(buf)==970845185){break;} }
for(i=98;i<109;i++){ buf[51]=(byte)i; if(sha1_32(buf)==212392393){break;} }
for(i=-69;i<-60;i++){ buf[52]=(byte)i; if(sha1_32(buf)==-1907291957){break;} }
for(i=74;i<92;i++){ buf[53]=(byte)i; if(sha1_32(buf)==-972479457){break;} }
for(i=-31;i<-14;i++){ buf[54]=(byte)i; if(sha1_32(buf)==576823935){break;} }
for(i=0;i<9;i++){ buf[55]=(byte)i; if(sha1_32(buf)==313555175){break;} }
for(i=20;i<38;i++){ buf[56]=(byte)i; if(sha1_32(buf)==-1146058650){break;} }
for(i=-128;i<-119;i++){ buf[57]=(byte)i; if(sha1_32(buf)==1248389777){break;} }
for(i=49;i<61;i++){ buf[58]=(byte)i; if(sha1_32(buf)==-335756394){break;} }
for(i=-88;i<-75;i++){ buf[59]=(byte)i; if(sha1_32(buf)==-1674425000){break;} }
for(i=27;i<47;i++){ buf[60]=(byte)i; if(sha1_32(buf)==1231176298){break;} }
for(i=-42;i<-25;i++){ buf[61]=(byte)i; if(sha1_32(buf)==1837136045){break;} }
for(i=6;i<14;i++){ buf[62]=(byte)i; if(sha1_32(buf)==936378196){break;} }
for(i=112;i<128;i++){ buf[63]=(byte)i; if(sha1_32(buf)==-1612679621){break;} }
for(i=-71;i<-48;i++){ buf[64]=(byte)i; if(sha1_32(buf)==-1406924660){break;} }
for(i=-25;i<1;i++){ buf[65]=(byte)i; if(sha1_32(buf)==-1601577605){break;} }
for(i=107;i<128;i++){ buf[66]=(byte)i; if(sha1_32(buf)==792835455){break;} }
for(i=76;i<89;i++){ buf[67]=(byte)i; if(sha1_32(buf)==-798521907){break;} }
for(i=28;i<44;i++){ buf[68]=(byte)i; if(sha1_32(buf)==-310884795){break;} }
for(i=-10;i<6;i++){ buf[69]=(byte)i; if(sha1_32(buf)==-929312684){break;} }
for(i=73;i<89;i++){ buf[70]=(byte)i; if(sha1_32(buf)==-1504788452){break;} }
for(i=38;i<45;i++){ buf[71]=(byte)i; if(sha1_32(buf)==-649645483){break;} }
for(i=75;i<101;i++){ buf[72]=(byte)i; if(sha1_32(buf)==1822398359){break;} }
for(i=102;i<122;i++){ buf[73]=(byte)i; if(sha1_32(buf)==1413042175){break;} }
for(i=-128;i<-101;i++){ buf[74]=(byte)i; if(sha1_32(buf)==-197913195){break;} }
for(i=-73;i<-57;i++){ buf[75]=(byte)i; if(sha1_32(buf)==-256601229){break;} }
for(i=-42;i<-34;i++){ buf[76]=(byte)i; if(sha1_32(buf)==-1534299570){break;} }
for(i=117;i<128;i++){ buf[77]=(byte)i; if(sha1_32(buf)==731789525){break;} }
for(i=34;i<51;i++){ buf[78]=(byte)i; if(sha1_32(buf)==-1143185211){break;} }
for(i=-27;i<-10;i++){ buf[79]=(byte)i; if(sha1_32(buf)==827641870){break;} }
for(i=-49;i<-22;i++){ buf[80]=(byte)i; if(sha1_32(buf)==780366888){break;} }
for(i=27;i<38;i++){ buf[81]=(byte)i; if(sha1_32(buf)==956726212){break;} }
for(i=-113;i<-99;i++){ buf[82]=(byte)i; if(sha1_32(buf)==-2022927251){break;} }
for(i=-28;i<-12;i++){ buf[83]=(byte)i; if(sha1_32(buf)==-2044991082){break;} }
for(i=-92;i<-71;i++){ buf[84]=(byte)i; if(sha1_32(buf)==134290337){break;} }
for(i=-3;i<5;i++){ buf[85]=(byte)i; if(sha1_32(buf)==-170920869){break;} }
for(i=-34;i<-16;i++){ buf[86]=(byte)i; if(sha1_32(buf)==-1254335670){break;} }
for(i=-128;i<-115;i++){ buf[87]=(byte)i; if(sha1_32(buf)==-1984526056){break;} }
for(i=-114;i<-90;i++){ buf[88]=(byte)i; if(sha1_32(buf)==-1370041261){break;} }
for(i=-59;i<-44;i++){ buf[89]=(byte)i; if(sha1_32(buf)==726413309){break;} }
for(i=-54;i<-48;i++){ buf[90]=(byte)i; if(sha1_32(buf)==-1367820493){break;} }
for(i=-68;i<-65;i++){ buf[91]=(byte)i; if(sha1_32(buf)==1206923793){break;} }
for(i=75;i<95;i++){ buf[92]=(byte)i; if(sha1_32(buf)==-862036098){break;} }
for(i=45;i<64;i++){ buf[93]=(byte)i; if(sha1_32(buf)==154033847){break;} }
for(i=51;i<67;i++){ buf[94]=(byte)i; if(sha1_32(buf)==213358449){break;} }
for(i=30;i<50;i++){ buf[95]=(byte)i; if(sha1_32(buf)==885294017){break;} }
for(i=26;i<48;i++){ buf[96]=(byte)i; if(sha1_32(buf)==-939104078){break;} }
for(i=-32;i<-5;i++){ buf[97]=(byte)i; if(sha1_32(buf)==-374093691){break;} }
for(i=-57;i<-27;i++){ buf[98]=(byte)i; if(sha1_32(buf)==1076854937){break;} }
for(i=35;i<45;i++){ buf[99]=(byte)i; if(sha1_32(buf)==-184965729){break;} }
for(i=-57;i<-51;i++){ buf[100]=(byte)i; if(sha1_32(buf)==-1694400219){break;} }
for(i=91;i<108;i++){ buf[101]=(byte)i; if(sha1_32(buf)==64370136){break;} }
for(i=-107;i<-92;i++){ buf[102]=(byte)i; if(sha1_32(buf)==1960158338){break;} }
for(i=-102;i<-87;i++){ buf[103]=(byte)i; if(sha1_32(buf)==-117892337){break;} }
for(i=92;i<103;i++){ buf[104]=(byte)i; if(sha1_32(buf)==1729316629){break;} }
for(i=56;i<84;i++){ buf[105]=(byte)i; if(sha1_32(buf)==-504283332){break;} }
for(i=91;i<99;i++){ buf[106]=(byte)i; if(sha1_32(buf)==2078184928){break;} }
for(i=-45;i<-33;i++){ buf[107]=(byte)i; if(sha1_32(buf)==2126091036){break;} }
for(i=-22;i<-17;i++){ buf[108]=(byte)i; if(sha1_32(buf)==2031820001){break;} }
for(i=41;i<58;i++){ buf[109]=(byte)i; if(sha1_32(buf)==-1380811246){break;} }
for(i=5;i<24;i++){ buf[110]=(byte)i; if(sha1_32(buf)==-390484479){break;} }
for(i=7;i<33;i++){ buf[111]=(byte)i; if(sha1_32(buf)==-815683668){break;} }
for(i=-21;i<-7;i++){ buf[112]=(byte)i; if(sha1_32(buf)==913629853){break;} }
for(i=-50;i<-32;i++){ buf[113]=(byte)i; if(sha1_32(buf)==-2108408343){break;} }
for(i=-65;i<-49;i++){ buf[114]=(byte)i; if(sha1_32(buf)==1945540408){break;} }
for(i=-18;i<0;i++){ buf[115]=(byte)i; if(sha1_32(buf)==1211420364){break;} }
for(i=-37;i<-32;i++){ buf[116]=(byte)i; if(sha1_32(buf)==1321754800){break;} }
for(i=-54;i<-41;i++){ buf[117]=(byte)i; if(sha1_32(buf)==-796677015){break;} }
for(i=47;i<63;i++){ buf[118]=(byte)i; if(sha1_32(buf)==-1580268213){break;} }
for(i=-33;i<-27;i++){ buf[119]=(byte)i; if(sha1_32(buf)==1386836164){break;} }
for(i=64;i<88;i++){ buf[120]=(byte)i; if(sha1_32(buf)==2135829767){break;} }
for(i=-128;i<-123;i++){ buf[121]=(byte)i; if(sha1_32(buf)==-635418176){break;} }
for(i=107;i<125;i++){ buf[122]=(byte)i; if(sha1_32(buf)==1794709719){break;} }
for(i=102;i<128;i++){ buf[123]=(byte)i; if(sha1_32(buf)==-1106962074){break;} }
for(i=-77;i<-54;i++){ buf[124]=(byte)i; if(sha1_32(buf)==1787290465){break;} }
for(i=-82;i<-77;i++){ buf[125]=(byte)i; if(sha1_32(buf)==-1661101938){break;} }
for(i=106;i<117;i++){ buf[126]=(byte)i; if(sha1_32(buf)==-66508872){break;} }
for(i=-115;i<-96;i++){ buf[127]=(byte)i; if(sha1_32(buf)==-1529745974){break;} }
for(i=56;i<82;i++){ buf[128]=(byte)i; if(sha1_32(buf)==103543278){break;} }
for(i=37;i<48;i++){ buf[129]=(byte)i; if(sha1_32(buf)==-715413980){break;} }
for(i=-47;i<-37;i++){ buf[130]=(byte)i; if(sha1_32(buf)==-292605369){break;} }
for(i=121;i<128;i++){ buf[131]=(byte)i; if(sha1_32(buf)==-107804946){break;} }
for(i=43;i<56;i++){ buf[132]=(byte)i; if(sha1_32(buf)==1684550759){break;} }
for(i=-6;i<-2;i++){ buf[133]=(byte)i; if(sha1_32(buf)==-759640338){break;} }
for(i=-17;i<-11;i++){ buf[134]=(byte)i; if(sha1_32(buf)==442170830){break;} }
for(i=113;i<123;i++){ buf[135]=(byte)i; if(sha1_32(buf)==-1724056015){break;} }
for(i=-87;i<-61;i++){ buf[136]=(byte)i; if(sha1_32(buf)==1131830303){break;} }
for(i=-48;i<-18;i++){ buf[137]=(byte)i; if(sha1_32(buf)==1577814030){break;} }
for(i=-91;i<-61;i++){ buf[138]=(byte)i; if(sha1_32(buf)==-401809673){break;} }
for(i=-58;i<-51;i++){ buf[139]=(byte)i; if(sha1_32(buf)==-145741756){break;} }
for(i=118;i<128;i++){ buf[140]=(byte)i; if(sha1_32(buf)==-1787180805){break;} }
for(i=29;i<55;i++){ buf[141]=(byte)i; if(sha1_32(buf)==118455117){break;} }
for(i=81;i<94;i++){ buf[142]=(byte)i; if(sha1_32(buf)==856435228){break;} }
for(i=-47;i<-44;i++){ buf[143]=(byte)i; if(sha1_32(buf)==-1184210038){break;} }
for(i=49;i<62;i++){ buf[144]=(byte)i; if(sha1_32(buf)==-635056227){break;} }
for(i=34;i<50;i++){ buf[145]=(byte)i; if(sha1_32(buf)==-163995085){break;} }
for(i=-26;i<-12;i++){ buf[146]=(byte)i; if(sha1_32(buf)==1731380548){break;} }
for(i=-65;i<-49;i++){ buf[147]=(byte)i; if(sha1_32(buf)==-1250069924){break;} }
for(i=-65;i<-49;i++){ buf[148]=(byte)i; if(sha1_32(buf)==919994043){break;} }
for(i=56;i<68;i++){ buf[149]=(byte)i; if(sha1_32(buf)==2144262193){break;} }
for(i=-125;i<-106;i++){ buf[150]=(byte)i; if(sha1_32(buf)==-685387999){break;} }
for(i=-121;i<-113;i++){ buf[151]=(byte)i; if(sha1_32(buf)==1302035221){break;} }
for(i=-21;i<0;i++){ buf[152]=(byte)i; if(sha1_32(buf)==-1671377830){break;} }
for(i=-35;i<-21;i++){ buf[153]=(byte)i; if(sha1_32(buf)==-171647375){break;} }
for(i=19;i<47;i++){ buf[154]=(byte)i; if(sha1_32(buf)==1205945435){break;} }
for(i=-8;i<5;i++){ buf[155]=(byte)i; if(sha1_32(buf)==1722785651){break;} }
for(i=-99;i<-88;i++){ buf[156]=(byte)i; if(sha1_32(buf)==1576287215){break;} }
for(i=100;i<108;i++){ buf[157]=(byte)i; if(sha1_32(buf)==133946672){break;} }
for(i=-128;i<-119;i++){ buf[158]=(byte)i; if(sha1_32(buf)==-535039500){break;} }
for(i=-80;i<-60;i++){ buf[159]=(byte)i; if(sha1_32(buf)==-2134780099){break;} }
for(i=-102;i<-79;i++){ buf[160]=(byte)i; if(sha1_32(buf)==1611024577){break;} }
for(i=1;i<13;i++){ buf[161]=(byte)i; if(sha1_32(buf)==1353670737){break;} }
for(i=48;i<54;i++){ buf[162]=(byte)i; if(sha1_32(buf)==11815846){break;} }
for(i=53;i<75;i++){ buf[163]=(byte)i; if(sha1_32(buf)==-823341308){break;} }
for(i=28;i<52;i++){ buf[164]=(byte)i; if(sha1_32(buf)==62194335){break;} }
for(i=-104;i<-96;i++){ buf[165]=(byte)i; if(sha1_32(buf)==442160774){break;} }
for(i=-95;i<-64;i++){ buf[166]=(byte)i; if(sha1_32(buf)==-1568113077){break;} }
for(i=-78;i<-57;i++){ buf[167]=(byte)i; if(sha1_32(buf)==1670431331){break;} }
for(i=-128;i<-117;i++){ buf[168]=(byte)i; if(sha1_32(buf)==1591678196){break;} }
for(i=18;i<28;i++){ buf[169]=(byte)i; if(sha1_32(buf)==139089000){break;} }
for(i=-64;i<-42;i++){ buf[170]=(byte)i; if(sha1_32(buf)==-1513151491){break;} }
for(i=-115;i<-105;i++){ buf[171]=(byte)i; if(sha1_32(buf)==-146050048){break;} }
for(i=39;i<51;i++){ buf[172]=(byte)i; if(sha1_32(buf)==1327195692){break;} }
for(i=-16;i<-4;i++){ buf[173]=(byte)i; if(sha1_32(buf)==-564292373){break;} }
for(i=63;i<78;i++){ buf[174]=(byte)i; if(sha1_32(buf)==-847205909){break;} }
for(i=32;i<47;i++){ buf[175]=(byte)i; if(sha1_32(buf)==-383886651){break;} }
for(i=-99;i<-80;i++){ buf[176]=(byte)i; if(sha1_32(buf)==-2121414809){break;} }
for(i=0;i<19;i++){ buf[177]=(byte)i; if(sha1_32(buf)==96589333){break;} }
for(i=58;i<70;i++){ buf[178]=(byte)i; if(sha1_32(buf)==1137738919){break;} }
for(i=117;i<128;i++){ buf[179]=(byte)i; if(sha1_32(buf)==-755565880){break;} }
for(i=9;i<27;i++){ buf[180]=(byte)i; if(sha1_32(buf)==1985152359){break;} }
for(i=-115;i<-97;i++){ buf[181]=(byte)i; if(sha1_32(buf)==-1982771198){break;} }
for(i=-30;i<-26;i++){ buf[182]=(byte)i; if(sha1_32(buf)==-1175822337){break;} }
for(i=73;i<78;i++){ buf[183]=(byte)i; if(sha1_32(buf)==-1934312345){break;} }
for(i=31;i<43;i++){ buf[184]=(byte)i; if(sha1_32(buf)==834697620){break;} }
for(i=-108;i<-95;i++){ buf[185]=(byte)i; if(sha1_32(buf)==1635345989){break;} }
for(i=23;i<44;i++){ buf[186]=(byte)i; if(sha1_32(buf)==1101529652){break;} }
for(i=14;i<25;i++){ buf[187]=(byte)i; if(sha1_32(buf)==1671315803){break;} }
for(i=53;i<77;i++){ buf[188]=(byte)i; if(sha1_32(buf)==719970536){break;} }
for(i=21;i<38;i++){ buf[189]=(byte)i; if(sha1_32(buf)==1813500887){break;} }
for(i=56;i<76;i++){ buf[190]=(byte)i; if(sha1_32(buf)==-1609708650){break;} }
for(i=-54;i<-42;i++){ buf[191]=(byte)i; if(sha1_32(buf)==1866977823){break;} }
for(i=-10;i<4;i++){ buf[192]=(byte)i; if(sha1_32(buf)==-858229076){break;} }
for(i=-57;i<-39;i++){ buf[193]=(byte)i; if(sha1_32(buf)==-1500104829){break;} }
for(i=-76;i<-60;i++){ buf[194]=(byte)i; if(sha1_32(buf)==746669880){break;} }
for(i=-66;i<-37;i++){ buf[195]=(byte)i; if(sha1_32(buf)==-583861268){break;} }
for(i=31;i<56;i++){ buf[196]=(byte)i; if(sha1_32(buf)==-2147201712){break;} }
for(i=-55;i<-46;i++){ buf[197]=(byte)i; if(sha1_32(buf)==407708674){break;} }
for(i=-14;i<3;i++){ buf[198]=(byte)i; if(sha1_32(buf)==463321110){break;} }
for(i=-24;i<2;i++){ buf[199]=(byte)i; if(sha1_32(buf)==-1952448942){break;} }
for(i=81;i<98;i++){ buf[200]=(byte)i; if(sha1_32(buf)==-2052903390){break;} }
for(i=-84;i<-57;i++){ buf[201]=(byte)i; if(sha1_32(buf)==1179393564){break;} }
for(i=103;i<122;i++){ buf[202]=(byte)i; if(sha1_32(buf)==1806197476){break;} }
for(i=-42;i<-25;i++){ buf[203]=(byte)i; if(sha1_32(buf)==978477315){break;} }
for(i=74;i<89;i++){ buf[204]=(byte)i; if(sha1_32(buf)==-1791355162){break;} }
for(i=55;i<65;i++){ buf[205]=(byte)i; if(sha1_32(buf)==301705279){break;} }
for(i=-34;i<-21;i++){ buf[206]=(byte)i; if(sha1_32(buf)==1759696631){break;} }
for(i=-41;i<-28;i++){ buf[207]=(byte)i; if(sha1_32(buf)==1883115466){break;} }
for(i=116;i<128;i++){ buf[208]=(byte)i; if(sha1_32(buf)==-1326008889){break;} }
for(i=-5;i<8;i++){ buf[209]=(byte)i; if(sha1_32(buf)==-1733636942){break;} }
for(i=54;i<77;i++){ buf[210]=(byte)i; if(sha1_32(buf)==-871684064){break;} }
for(i=-13;i<0;i++){ buf[211]=(byte)i; if(sha1_32(buf)==837936488){break;} }
for(i=-25;i<1;i++){ buf[212]=(byte)i; if(sha1_32(buf)==-698452810){break;} }
for(i=94;i<100;i++){ buf[213]=(byte)i; if(sha1_32(buf)==-1481398027){break;} }
for(i=-30;i<-11;i++){ buf[214]=(byte)i; if(sha1_32(buf)==-1517211960){break;} }
for(i=49;i<64;i++){ buf[215]=(byte)i; if(sha1_32(buf)==1273940788){break;} }
for(i=-65;i<-40;i++){ buf[216]=(byte)i; if(sha1_32(buf)==1387399978){break;} }
for(i=-128;i<-118;i++){ buf[217]=(byte)i; if(sha1_32(buf)==-137098064){break;} }
for(i=97;i<110;i++){ buf[218]=(byte)i; if(sha1_32(buf)==-1871690340){break;} }
for(i=-16;i<11;i++){ buf[219]=(byte)i; if(sha1_32(buf)==1011492946){break;} }
for(i=106;i<128;i++){ buf[220]=(byte)i; if(sha1_32(buf)==-1288244512){break;} }
for(i=89;i<106;i++){ buf[221]=(byte)i; if(sha1_32(buf)==-748094880){break;} }
for(i=-52;i<-33;i++){ buf[222]=(byte)i; if(sha1_32(buf)==-387388703){break;} }
for(i=97;i<125;i++){ buf[223]=(byte)i; if(sha1_32(buf)==1032354867){break;} }
for(i=103;i<122;i++){ buf[224]=(byte)i; if(sha1_32(buf)==1827022671){break;} }
for(i=-125;i<-105;i++){ buf[225]=(byte)i; if(sha1_32(buf)==1352955481){break;} }
for(i=-84;i<-65;i++){ buf[226]=(byte)i; if(sha1_32(buf)==419807685){break;} }
for(i=4;i<26;i++){ buf[227]=(byte)i; if(sha1_32(buf)==1881070909){break;} }
for(i=94;i<103;i++){ buf[228]=(byte)i; if(sha1_32(buf)==1880664331){break;} }
for(i=64;i<70;i++){ buf[229]=(byte)i; if(sha1_32(buf)==-688667051){break;} }
for(i=66;i<90;i++){ buf[230]=(byte)i; if(sha1_32(buf)==-735493232){break;} }
for(i=35;i<55;i++){ buf[231]=(byte)i; if(sha1_32(buf)==1483529403){break;} }
for(i=-18;i<-16;i++){ buf[232]=(byte)i; if(sha1_32(buf)==-501200002){break;} }
for(i=11;i<14;i++){ buf[233]=(byte)i; if(sha1_32(buf)==71767808){break;} }
for(i=-77;i<-65;i++){ buf[234]=(byte)i; if(sha1_32(buf)==1705580166){break;} }
for(i=-113;i<-92;i++){ buf[235]=(byte)i; if(sha1_32(buf)==2126418739){break;} }
for(i=35;i<59;i++){ buf[236]=(byte)i; if(sha1_32(buf)==-342194691){break;} }
for(i=26;i<54;i++){ buf[237]=(byte)i; if(sha1_32(buf)==-1463255063){break;} }
for(i=-126;i<-118;i++){ buf[238]=(byte)i; if(sha1_32(buf)==-1319941903){break;} }
for(i=118;i<125;i++){ buf[239]=(byte)i; if(sha1_32(buf)==-277185989){break;} }
for(i=-38;i<-27;i++){ buf[240]=(byte)i; if(sha1_32(buf)==-1425426218){break;} }
for(i=113;i<123;i++){ buf[241]=(byte)i; if(sha1_32(buf)==-581998582){break;} }
for(i=109;i<126;i++){ buf[242]=(byte)i; if(sha1_32(buf)==-171243528){break;} }
for(i=16;i<23;i++){ buf[243]=(byte)i; if(sha1_32(buf)==559851773){break;} }
for(i=-88;i<-74;i++){ buf[244]=(byte)i; if(sha1_32(buf)==1754145065){break;} }
for(i=-121;i<-97;i++){ buf[245]=(byte)i; if(sha1_32(buf)==948553730){break;} }
for(i=10;i<21;i++){ buf[246]=(byte)i; if(sha1_32(buf)==-1197536605){break;} }
for(i=-49;i<-29;i++){ buf[247]=(byte)i; if(sha1_32(buf)==-1123486632){break;} }
for(i=-116;i<-104;i++){ buf[248]=(byte)i; if(sha1_32(buf)==1163445576){break;} }
for(i=2;i<16;i++){ buf[249]=(byte)i; if(sha1_32(buf)==-283429303){break;} }
for(i=31;i<50;i++){ buf[250]=(byte)i; if(sha1_32(buf)==-1659545726){break;} }
for(i=-116;i<-95;i++){ buf[251]=(byte)i; if(sha1_32(buf)==1792006438){break;} }
for(i=1;i<6;i++){ buf[252]=(byte)i; if(sha1_32(buf)==-1901457192){break;} }
for(i=-45;i<-18;i++){ buf[253]=(byte)i; if(sha1_32(buf)==1617334676){break;} }
for(i=64;i<67;i++){ buf[254]=(byte)i; if(sha1_32(buf)==-579322381){break;} }
for(i=-54;i<-43;i++){ buf[255]=(byte)i; if(sha1_32(buf)==506262059){break;} }
for(i=-78;i<-59;i++){ buf[256]=(byte)i; if(sha1_32(buf)==-475764595){break;} }
for(i=-41;i<-35;i++){ buf[257]=(byte)i; if(sha1_32(buf)==-1194863755){break;} }
for(i=-74;i<-59;i++){ buf[258]=(byte)i; if(sha1_32(buf)==1567357443){break;} }
for(i=-111;i<-105;i++){ buf[259]=(byte)i; if(sha1_32(buf)==-32404550){break;} }
for(i=-5;i<5;i++){ buf[260]=(byte)i; if(sha1_32(buf)==-32404550){break;} }
for(i=-7;i<7;i++){ buf[261]=(byte)i; if(sha1_32(buf)==-819071777){break;} }
for(i=-127;i<-114;i++){ buf[262]=(byte)i; if(sha1_32(buf)==-1221926192){break;} }
for(i=1;i<20;i++){ buf[263]=(byte)i; if(sha1_32(buf)==-105203300){break;} }
for(i=67;i<79;i++){ buf[264]=(byte)i; if(sha1_32(buf)==1887975884){break;} }
for(i=6;i<21;i++){ buf[265]=(byte)i; if(sha1_32(buf)==958462092){break;} }
for(i=10;i<29;i++){ buf[266]=(byte)i; if(sha1_32(buf)==835100532){break;} }
for(i=-66;i<-62;i++){ buf[267]=(byte)i; if(sha1_32(buf)==-488146537){break;} }
for(i=-128;i<-126;i++){ buf[268]=(byte)i; if(sha1_32(buf)==975116175){break;} }
for(i=102;i<115;i++){ buf[269]=(byte)i; if(sha1_32(buf)==-1482470387){break;} }
for(i=24;i<41;i++){ buf[270]=(byte)i; if(sha1_32(buf)==-921499580){break;} }
for(i=-2;i<21;i++){ buf[271]=(byte)i; if(sha1_32(buf)==2132049418){break;} }
for(i=105;i<125;i++){ buf[272]=(byte)i; if(sha1_32(buf)==688444873){break;} }
for(i=-17;i<-12;i++){ buf[273]=(byte)i; if(sha1_32(buf)==733339192){break;} }
for(i=63;i<66;i++){ buf[274]=(byte)i; if(sha1_32(buf)==371565019){break;} }
for(i=121;i<128;i++){ buf[275]=(byte)i; if(sha1_32(buf)==-2113121485){break;} }
for(i=-23;i<0;i++){ buf[276]=(byte)i; if(sha1_32(buf)==-838207011){break;} }
for(i=-51;i<-31;i++){ buf[277]=(byte)i; if(sha1_32(buf)==-28157081){break;} }
for(i=-5;i<20;i++){ buf[278]=(byte)i; if(sha1_32(buf)==-324859933){break;} }
for(i=122;i<128;i++){ buf[279]=(byte)i; if(sha1_32(buf)==-727928195){break;} }
for(i=-62;i<-50;i++){ buf[280]=(byte)i; if(sha1_32(buf)==-1715895776){break;} }
for(i=-128;i<-106;i++){ buf[281]=(byte)i; if(sha1_32(buf)==-557483798){break;} }
for(i=-83;i<-62;i++){ buf[282]=(byte)i; if(sha1_32(buf)==-979713083){break;} }
for(i=101;i<119;i++){ buf[283]=(byte)i; if(sha1_32(buf)==311737151){break;} }
for(i=-73;i<-65;i++){ buf[284]=(byte)i; if(sha1_32(buf)==-18908881){break;} }
for(i=52;i<64;i++){ buf[285]=(byte)i; if(sha1_32(buf)==-1917268494){break;} }
for(i=59;i<83;i++){ buf[286]=(byte)i; if(sha1_32(buf)==-1473098132){break;} }
for(i=78;i<96;i++){ buf[287]=(byte)i; if(sha1_32(buf)==-1646905509){break;} }
for(i=-68;i<-65;i++){ buf[288]=(byte)i; if(sha1_32(buf)==-642825419){break;} }
for(i=-40;i<-23;i++){ buf[289]=(byte)i; if(sha1_32(buf)==-1607918119){break;} }
for(i=58;i<84;i++){ buf[290]=(byte)i; if(sha1_32(buf)==-2093930291){break;} }
for(i=24;i<30;i++){ buf[291]=(byte)i; if(sha1_32(buf)==-1178455151){break;} }
for(i=110;i<128;i++){ buf[292]=(byte)i; if(sha1_32(buf)==-586998744){break;} }
for(i=-85;i<-63;i++){ buf[293]=(byte)i; if(sha1_32(buf)==330485042){break;} }
for(i=22;i<52;i++){ buf[294]=(byte)i; if(sha1_32(buf)==-1793573204){break;} }
for(i=-1;i<14;i++){ buf[295]=(byte)i; if(sha1_32(buf)==1640317832){break;} }
for(i=-105;i<-101;i++){ buf[296]=(byte)i; if(sha1_32(buf)==-1319198985){break;} }
for(i=24;i<33;i++){ buf[297]=(byte)i; if(sha1_32(buf)==-1118644936){break;} }
for(i=-47;i<-31;i++){ buf[298]=(byte)i; if(sha1_32(buf)==-1681847166){break;} }
for(i=-37;i<-36;i++){ buf[299]=(byte)i; if(sha1_32(buf)==211280299){break;} }
for(i=-86;i<-68;i++){ buf[300]=(byte)i; if(sha1_32(buf)==652707930){break;} }
for(i=89;i<110;i++){ buf[301]=(byte)i; if(sha1_32(buf)==-1851498410){break;} }
for(i=12;i<30;i++){ buf[302]=(byte)i; if(sha1_32(buf)==-1710571997){break;} }
for(i=-38;i<-14;i++){ buf[303]=(byte)i; if(sha1_32(buf)==2013301930){break;} }
for(i=34;i<48;i++){ buf[304]=(byte)i; if(sha1_32(buf)==-128270519){break;} }
for(i=-114;i<-107;i++){ buf[305]=(byte)i; if(sha1_32(buf)==-1842902812){break;} }
for(i=-109;i<-98;i++){ buf[306]=(byte)i; if(sha1_32(buf)==-1436494384){break;} }
for(i=38;i<56;i++){ buf[307]=(byte)i; if(sha1_32(buf)==1017938479){break;} }
for(i=101;i<122;i++){ buf[308]=(byte)i; if(sha1_32(buf)==1714329966){break;} }
for(i=-77;i<-56;i++){ buf[309]=(byte)i; if(sha1_32(buf)==459561429){break;} }
for(i=63;i<79;i++){ buf[310]=(byte)i; if(sha1_32(buf)==-1188469065){break;} }
for(i=-12;i<6;i++){ buf[311]=(byte)i; if(sha1_32(buf)==1944485683){break;} }
for(i=-104;i<-82;i++){ buf[312]=(byte)i; if(sha1_32(buf)==-745249699){break;} }
for(i=-49;i<-34;i++){ buf[313]=(byte)i; if(sha1_32(buf)==85998552){break;} }
for(i=-19;i<7;i++){ buf[314]=(byte)i; if(sha1_32(buf)==2074433678){break;} }
for(i=29;i<45;i++){ buf[315]=(byte)i; if(sha1_32(buf)==-202063425){break;} }
for(i=-118;i<-98;i++){ buf[316]=(byte)i; if(sha1_32(buf)==1688180993){break;} }
for(i=19;i<26;i++){ buf[317]=(byte)i; if(sha1_32(buf)==-64536316){break;} }
for(i=-128;i<-114;i++){ buf[318]=(byte)i; if(sha1_32(buf)==-968075741){break;} }
for(i=-24;i<-3;i++){ buf[319]=(byte)i; if(sha1_32(buf)==-2074060992){break;} }
for(i=-13;i<4;i++){ buf[320]=(byte)i; if(sha1_32(buf)==1830555506){break;} }
for(i=-74;i<-60;i++){ buf[321]=(byte)i; if(sha1_32(buf)==505977534){break;} }
for(i=36;i<44;i++){ buf[322]=(byte)i; if(sha1_32(buf)==1958652343){break;} }
for(i=92;i<110;i++){ buf[323]=(byte)i; if(sha1_32(buf)==-440772900){break;} }
for(i=91;i<101;i++){ buf[324]=(byte)i; if(sha1_32(buf)==-1243872517){break;} }
for(i=-64;i<-46;i++){ buf[325]=(byte)i; if(sha1_32(buf)==-1897720796){break;} }
for(i=6;i<18;i++){ buf[326]=(byte)i; if(sha1_32(buf)==-808810371){break;} }
for(i=35;i<53;i++){ buf[327]=(byte)i; if(sha1_32(buf)==-164977320){break;} }
for(i=59;i<69;i++){ buf[328]=(byte)i; if(sha1_32(buf)==-695314673){break;} }
for(i=78;i<97;i++){ buf[329]=(byte)i; if(sha1_32(buf)==-1084936546){break;} }
for(i=-107;i<-94;i++){ buf[330]=(byte)i; if(sha1_32(buf)==686865490){break;} }
for(i=-60;i<-44;i++){ buf[331]=(byte)i; if(sha1_32(buf)==152017389){break;} }
for(i=-79;i<-61;i++){ buf[332]=(byte)i; if(sha1_32(buf)==-1754693327){break;} }
for(i=54;i<70;i++){ buf[333]=(byte)i; if(sha1_32(buf)==-1337237320){break;} }
for(i=5;i<25;i++){ buf[334]=(byte)i; if(sha1_32(buf)==1234352964){break;} }
for(i=2;i<20;i++){ buf[335]=(byte)i; if(sha1_32(buf)==1727781049){break;} }
for(i=-55;i<-37;i++){ buf[336]=(byte)i; if(sha1_32(buf)==-1020585576){break;} }
for(i=51;i<67;i++){ buf[337]=(byte)i; if(sha1_32(buf)==1241352627){break;} }
for(i=-52;i<-44;i++){ buf[338]=(byte)i; if(sha1_32(buf)==-106179566){break;} }
for(i=-115;i<-106;i++){ buf[339]=(byte)i; if(sha1_32(buf)==-1204589915){break;} }
for(i=-78;i<-74;i++){ buf[340]=(byte)i; if(sha1_32(buf)==971295545){break;} }
for(i=1;i<24;i++){ buf[341]=(byte)i; if(sha1_32(buf)==-624293175){break;} }
for(i=-52;i<-43;i++){ buf[342]=(byte)i; if(sha1_32(buf)==-1013844197){break;} }
for(i=46;i<63;i++){ buf[343]=(byte)i; if(sha1_32(buf)==1036174629){break;} }
for(i=-109;i<-103;i++){ buf[344]=(byte)i; if(sha1_32(buf)==1362524760){break;} }
for(i=-92;i<-71;i++){ buf[345]=(byte)i; if(sha1_32(buf)==-896869152){break;} }
for(i=-23;i<-11;i++){ buf[346]=(byte)i; if(sha1_32(buf)==1094662120){break;} }
for(i=103;i<117;i++){ buf[347]=(byte)i; if(sha1_32(buf)==-996991372){break;} }
for(i=-12;i<5;i++){ buf[348]=(byte)i; if(sha1_32(buf)==484465929){break;} }
for(i=-108;i<-82;i++){ buf[349]=(byte)i; if(sha1_32(buf)==1412009958){break;} }
for(i=72;i<95;i++){ buf[350]=(byte)i; if(sha1_32(buf)==-1392976291){break;} }
for(i=80;i<94;i++){ buf[351]=(byte)i; if(sha1_32(buf)==1678754778){break;} }
for(i=60;i<77;i++){ buf[352]=(byte)i; if(sha1_32(buf)==-2087089173){break;} }
for(i=25;i<38;i++){ buf[353]=(byte)i; if(sha1_32(buf)==1660244473){break;} }
for(i=50;i<70;i++){ buf[354]=(byte)i; if(sha1_32(buf)==-546430093){break;} }
for(i=45;i<65;i++){ buf[355]=(byte)i; if(sha1_32(buf)==716639735){break;} }
for(i=-27;i<-4;i++){ buf[356]=(byte)i; if(sha1_32(buf)==372714944){break;} }
for(i=43;i<67;i++){ buf[357]=(byte)i; if(sha1_32(buf)==1438913073){break;} }
for(i=-98;i<-73;i++){ buf[358]=(byte)i; if(sha1_32(buf)==-1329479841){break;} }
for(i=-47;i<-36;i++){ buf[359]=(byte)i; if(sha1_32(buf)==1084827581){break;} }
for(i=99;i<126;i++){ buf[360]=(byte)i; if(sha1_32(buf)==-750784978){break;} }
for(i=-67;i<-53;i++){ buf[361]=(byte)i; if(sha1_32(buf)==-635563708){break;} }
for(i=-35;i<-21;i++){ buf[362]=(byte)i; if(sha1_32(buf)==1826149079){break;} }
for(i=88;i<94;i++){ buf[363]=(byte)i; if(sha1_32(buf)==-1323797295){break;} }
for(i=-84;i<-58;i++){ buf[364]=(byte)i; if(sha1_32(buf)==1052610078){break;} }
for(i=-113;i<-91;i++){ buf[365]=(byte)i; if(sha1_32(buf)==479009611){break;} }
for(i=110;i<127;i++){ buf[366]=(byte)i; if(sha1_32(buf)==-485621857){break;} }
for(i=72;i<88;i++){ buf[367]=(byte)i; if(sha1_32(buf)==-1284257070){break;} }
for(i=-59;i<-53;i++){ buf[368]=(byte)i; if(sha1_32(buf)==-767333101){break;} }
for(i=101;i<128;i++){ buf[369]=(byte)i; if(sha1_32(buf)==679537959){break;} }
for(i=-69;i<-58;i++){ buf[370]=(byte)i; if(sha1_32(buf)==-939316739){break;} }
for(i=-28;i<-4;i++){ buf[371]=(byte)i; if(sha1_32(buf)==-1500842620){break;} }
for(i=104;i<118;i++){ buf[372]=(byte)i; if(sha1_32(buf)==-390265346){break;} }
for(i=-108;i<-88;i++){ buf[373]=(byte)i; if(sha1_32(buf)==-1972223378){break;} }
for(i=-48;i<-40;i++){ buf[374]=(byte)i; if(sha1_32(buf)==1659561681){break;} }
for(i=-54;i<-34;i++){ buf[375]=(byte)i; if(sha1_32(buf)==402228163){break;} }
for(i=43;i<53;i++){ buf[376]=(byte)i; if(sha1_32(buf)==-124760645){break;} }
for(i=-116;i<-108;i++){ buf[377]=(byte)i; if(sha1_32(buf)==1730772631){break;} }
for(i=87;i<99;i++){ buf[378]=(byte)i; if(sha1_32(buf)==-1198626561){break;} }
for(i=98;i<106;i++){ buf[379]=(byte)i; if(sha1_32(buf)==2049841991){break;} }
for(i=60;i<72;i++){ buf[380]=(byte)i; if(sha1_32(buf)==-651928436){break;} }
for(i=100;i<119;i++){ buf[381]=(byte)i; if(sha1_32(buf)==-801440912){break;} }
for(i=10;i<32;i++){ buf[382]=(byte)i; if(sha1_32(buf)==-1616181206){break;} }
for(i=-121;i<-107;i++){ buf[383]=(byte)i; if(sha1_32(buf)==164486984){break;} }
for(i=81;i<86;i++){ buf[384]=(byte)i; if(sha1_32(buf)==-1888488659){break;} }
for(i=-5;i<22;i++){ buf[385]=(byte)i; if(sha1_32(buf)==1343622462){break;} }
for(i=-128;i<-110;i++){ buf[386]=(byte)i; if(sha1_32(buf)==-1861755014){break;} }
for(i=-16;i<8;i++){ buf[387]=(byte)i; if(sha1_32(buf)==1711034602){break;} }
for(i=114;i<128;i++){ buf[388]=(byte)i; if(sha1_32(buf)==135376430){break;} }
for(i=-53;i<-33;i++){ buf[389]=(byte)i; if(sha1_32(buf)==-334142025){break;} }
for(i=97;i<111;i++){ buf[390]=(byte)i; if(sha1_32(buf)==-273778807){break;} }
for(i=101;i<127;i++){ buf[391]=(byte)i; if(sha1_32(buf)==-1248959672){break;} }
for(i=103;i<128;i++){ buf[392]=(byte)i; if(sha1_32(buf)==-1112709479){break;} }
for(i=-69;i<-50;i++){ buf[393]=(byte)i; if(sha1_32(buf)==-155845047){break;} }
for(i=-123;i<-100;i++){ buf[394]=(byte)i; if(sha1_32(buf)==1628779446){break;} }
for(i=-108;i<-91;i++){ buf[395]=(byte)i; if(sha1_32(buf)==-1103815601){break;} }
for(i=42;i<62;i++){ buf[396]=(byte)i; if(sha1_32(buf)==-830023223){break;} }
for(i=-7;i<9;i++){ buf[397]=(byte)i; if(sha1_32(buf)==-1555456885){break;} }
for(i=104;i<128;i++){ buf[398]=(byte)i; if(sha1_32(buf)==24223231){break;} }
for(i=52;i<68;i++){ buf[399]=(byte)i; if(sha1_32(buf)==1605835319){break;} }
for(i=70;i<93;i++){ buf[400]=(byte)i; if(sha1_32(buf)==1625112749){break;} }
for(i=-124;i<-116;i++){ buf[401]=(byte)i; if(sha1_32(buf)==-1563449024){break;} }
for(i=69;i<95;i++){ buf[402]=(byte)i; if(sha1_32(buf)==1832675919){break;} }
for(i=-42;i<-29;i++){ buf[403]=(byte)i; if(sha1_32(buf)==1982290684){break;} }
for(i=-83;i<-56;i++){ buf[404]=(byte)i; if(sha1_32(buf)==985716655){break;} }
for(i=-39;i<-33;i++){ buf[405]=(byte)i; if(sha1_32(buf)==-1980494587){break;} }
for(i=-122;i<-106;i++){ buf[406]=(byte)i; if(sha1_32(buf)==-694159317){break;} }
for(i=-44;i<-17;i++){ buf[407]=(byte)i; if(sha1_32(buf)==1006868312){break;} }
for(i=-95;i<-85;i++){ buf[408]=(byte)i; if(sha1_32(buf)==-2062888994){break;} }
for(i=10;i<29;i++){ buf[409]=(byte)i; if(sha1_32(buf)==824564519){break;} }
for(i=82;i<98;i++){ buf[410]=(byte)i; if(sha1_32(buf)==-1329055767){break;} }
for(i=74;i<82;i++){ buf[411]=(byte)i; if(sha1_32(buf)==1415096769){break;} }
for(i=-84;i<-62;i++){ buf[412]=(byte)i; if(sha1_32(buf)==-1741864708){break;} }
for(i=74;i<98;i++){ buf[413]=(byte)i; if(sha1_32(buf)==526724544){break;} }
for(i=-5;i<4;i++){ buf[414]=(byte)i; if(sha1_32(buf)==1230200674){break;} }
for(i=72;i<82;i++){ buf[415]=(byte)i; if(sha1_32(buf)==1162526780){break;} }
for(i=-117;i<-105;i++){ buf[416]=(byte)i; if(sha1_32(buf)==-1963408248){break;} }
for(i=104;i<128;i++){ buf[417]=(byte)i; if(sha1_32(buf)==1845620758){break;} }
for(i=-41;i<-12;i++){ buf[418]=(byte)i; if(sha1_32(buf)==-989456661){break;} }
for(i=-62;i<-50;i++){ buf[419]=(byte)i; if(sha1_32(buf)==2099016882){break;} }
for(i=10;i<24;i++){ buf[420]=(byte)i; if(sha1_32(buf)==1616571809){break;} }
for(i=65;i<85;i++){ buf[421]=(byte)i; if(sha1_32(buf)==1211123624){break;} }
for(i=45;i<68;i++){ buf[422]=(byte)i; if(sha1_32(buf)==-824757887){break;} }
for(i=-110;i<-104;i++){ buf[423]=(byte)i; if(sha1_32(buf)==-700866270){break;} }
for(i=56;i<79;i++){ buf[424]=(byte)i; if(sha1_32(buf)==-1097674732){break;} }
for(i=-111;i<-95;i++){ buf[425]=(byte)i; if(sha1_32(buf)==-133956823){break;} }
for(i=26;i<37;i++){ buf[426]=(byte)i; if(sha1_32(buf)==1556644977){break;} }
for(i=-124;i<-110;i++){ buf[427]=(byte)i; if(sha1_32(buf)==-448810849){break;} }
for(i=19;i<33;i++){ buf[428]=(byte)i; if(sha1_32(buf)==-895095530){break;} }
for(i=-52;i<-38;i++){ buf[429]=(byte)i; if(sha1_32(buf)==-1813771351){break;} }
for(i=12;i<34;i++){ buf[430]=(byte)i; if(sha1_32(buf)==615422857){break;} }
for(i=-99;i<-76;i++){ buf[431]=(byte)i; if(sha1_32(buf)==632666688){break;} }
for(i=-105;i<-81;i++){ buf[432]=(byte)i; if(sha1_32(buf)==-1235811813){break;} }
for(i=-100;i<-85;i++){ buf[433]=(byte)i; if(sha1_32(buf)==484168271){break;} }
for(i=-73;i<-55;i++){ buf[434]=(byte)i; if(sha1_32(buf)==1931022491){break;} }
for(i=119;i<128;i++){ buf[435]=(byte)i; if(sha1_32(buf)==-1970229736){break;} }
for(i=-25;i<-10;i++){ buf[436]=(byte)i; if(sha1_32(buf)==1285557426){break;} }
for(i=14;i<28;i++){ buf[437]=(byte)i; if(sha1_32(buf)==752920229){break;} }
for(i=41;i<50;i++){ buf[438]=(byte)i; if(sha1_32(buf)==-205862422){break;} }
for(i=100;i<125;i++){ buf[439]=(byte)i; if(sha1_32(buf)==1617490858){break;} }
for(i=13;i<16;i++){ buf[440]=(byte)i; if(sha1_32(buf)==1087661347){break;} }
for(i=-35;i<-17;i++){ buf[441]=(byte)i; if(sha1_32(buf)==-1914184163){break;} }
for(i=-103;i<-85;i++){ buf[442]=(byte)i; if(sha1_32(buf)==-149228431){break;} }
for(i=23;i<32;i++){ buf[443]=(byte)i; if(sha1_32(buf)==709572000){break;} }
for(i=-103;i<-90;i++){ buf[444]=(byte)i; if(sha1_32(buf)==693543630){break;} }
for(i=110;i<120;i++){ buf[445]=(byte)i; if(sha1_32(buf)==-79913770){break;} }
for(i=55;i<62;i++){ buf[446]=(byte)i; if(sha1_32(buf)==-260379670){break;} }
for(i=48;i<68;i++){ buf[447]=(byte)i; if(sha1_32(buf)==693753270){break;} }
for(i=-61;i<-37;i++){ buf[448]=(byte)i; if(sha1_32(buf)==-352922415){break;} }
for(i=75;i<97;i++){ buf[449]=(byte)i; if(sha1_32(buf)==734462970){break;} }
for(i=-15;i<5;i++){ buf[450]=(byte)i; if(sha1_32(buf)==-646639591){break;} }
for(i=-112;i<-95;i++){ buf[451]=(byte)i; if(sha1_32(buf)==1560276580){break;} }
for(i=-103;i<-92;i++){ buf[452]=(byte)i; if(sha1_32(buf)==-1731521893){break;} }
for(i=109;i<113;i++){ buf[453]=(byte)i; if(sha1_32(buf)==2040613884){break;} }
for(i=-116;i<-104;i++){ buf[454]=(byte)i; if(sha1_32(buf)==968833531){break;} }
for(i=-37;i<-24;i++){ buf[455]=(byte)i; if(sha1_32(buf)==-40839742){break;} }
for(i=97;i<113;i++){ buf[456]=(byte)i; if(sha1_32(buf)==-1996372897){break;} }
for(i=-7;i<14;i++){ buf[457]=(byte)i; if(sha1_32(buf)==808739958){break;} }
for(i=-34;i<-29;i++){ buf[458]=(byte)i; if(sha1_32(buf)==-716453863){break;} }
for(i=-67;i<-50;i++){ buf[459]=(byte)i; if(sha1_32(buf)==1238668142){break;} }
for(i=82;i<107;i++){ buf[460]=(byte)i; if(sha1_32(buf)==858540697){break;} }
for(i=13;i<25;i++){ buf[461]=(byte)i; if(sha1_32(buf)==1577557927){break;} }
for(i=1;i<10;i++){ buf[462]=(byte)i; if(sha1_32(buf)==-1978713046){break;} }
for(i=69;i<84;i++){ buf[463]=(byte)i; if(sha1_32(buf)==1683291725){break;} }
for(i=-78;i<-76;i++){ buf[464]=(byte)i; if(sha1_32(buf)==-2144039416){break;} }
for(i=81;i<106;i++){ buf[465]=(byte)i; if(sha1_32(buf)==-1864590224){break;} }
for(i=-99;i<-94;i++){ buf[466]=(byte)i; if(sha1_32(buf)==-512406687){break;} }
for(i=-117;i<-96;i++){ buf[467]=(byte)i; if(sha1_32(buf)==501088050){break;} }
for(i=4;i<10;i++){ buf[468]=(byte)i; if(sha1_32(buf)==-1851722287){break;} }
for(i=-128;i<-118;i++){ buf[469]=(byte)i; if(sha1_32(buf)==-1796633139){break;} }
for(i=112;i<117;i++){ buf[470]=(byte)i; if(sha1_32(buf)==-1110456949){break;} }
for(i=26;i<44;i++){ buf[471]=(byte)i; if(sha1_32(buf)==1902713425){break;} }
for(i=53;i<76;i++){ buf[472]=(byte)i; if(sha1_32(buf)==-1934586731){break;} }
for(i=-36;i<-21;i++){ buf[473]=(byte)i; if(sha1_32(buf)==-1803551392){break;} }
for(i=92;i<101;i++){ buf[474]=(byte)i; if(sha1_32(buf)==-2070241435){break;} }
for(i=100;i<122;i++){ buf[475]=(byte)i; if(sha1_32(buf)==-1948570825){break;} }
for(i=61;i<87;i++){ buf[476]=(byte)i; if(sha1_32(buf)==925267592){break;} }
for(i=-60;i<-49;i++){ buf[477]=(byte)i; if(sha1_32(buf)==857399406){break;} }
for(i=-109;i<-94;i++){ buf[478]=(byte)i; if(sha1_32(buf)==-232471263){break;} }
for(i=-82;i<-69;i++){ buf[479]=(byte)i; if(sha1_32(buf)==664220266){break;} }
for(i=-70;i<-61;i++){ buf[480]=(byte)i; if(sha1_32(buf)==711938203){break;} }
for(i=-33;i<-9;i++){ buf[481]=(byte)i; if(sha1_32(buf)==-1879588321){break;} }
for(i=-126;i<-116;i++){ buf[482]=(byte)i; if(sha1_32(buf)==-1823601434){break;} }
for(i=-41;i<-30;i++){ buf[483]=(byte)i; if(sha1_32(buf)==-217593920){break;} }
for(i=88;i<91;i++){ buf[484]=(byte)i; if(sha1_32(buf)==-1142735081){break;} }
for(i=58;i<72;i++){ buf[485]=(byte)i; if(sha1_32(buf)==-1099677920){break;} }
for(i=101;i<125;i++){ buf[486]=(byte)i; if(sha1_32(buf)==2005559897){break;} }
for(i=78;i<86;i++){ buf[487]=(byte)i; if(sha1_32(buf)==1946621968){break;} }
for(i=9;i<29;i++){ buf[488]=(byte)i; if(sha1_32(buf)==418712554){break;} }
for(i=115;i<121;i++){ buf[489]=(byte)i; if(sha1_32(buf)==-475728962){break;} }
for(i=-128;i<-118;i++){ buf[490]=(byte)i; if(sha1_32(buf)==2058798393){break;} }
for(i=-124;i<-102;i++){ buf[491]=(byte)i; if(sha1_32(buf)==930080598){break;} }
for(i=81;i<97;i++){ buf[492]=(byte)i; if(sha1_32(buf)==1714569132){break;} }
for(i=0;i<19;i++){ buf[493]=(byte)i; if(sha1_32(buf)==-2100234425){break;} }
for(i=-120;i<-118;i++){ buf[494]=(byte)i; if(sha1_32(buf)==1554836500){break;} }
for(i=70;i<100;i++){ buf[495]=(byte)i; if(sha1_32(buf)==-538197906){break;} }
for(i=-62;i<-47;i++){ buf[496]=(byte)i; if(sha1_32(buf)==-517823642){break;} }
for(i=-10;i<20;i++){ buf[497]=(byte)i; if(sha1_32(buf)==-1673740629){break;} }
for(i=-8;i<21;i++){ buf[498]=(byte)i; if(sha1_32(buf)==2003888704){break;} }
for(i=79;i<102;i++){ buf[499]=(byte)i; if(sha1_32(buf)==1120303415){break;} }
for(i=-35;i<-34;i++){ buf[500]=(byte)i; if(sha1_32(buf)==-2119836693){break;} }
for(i=110;i<116;i++){ buf[501]=(byte)i; if(sha1_32(buf)==1900666502){break;} }
for(i=90;i<106;i++){ buf[502]=(byte)i; if(sha1_32(buf)==1509087397){break;} }
for(i=-85;i<-70;i++){ buf[503]=(byte)i; if(sha1_32(buf)==-876286535){break;} }
for(i=-17;i<-3;i++){ buf[504]=(byte)i; if(sha1_32(buf)==-1313807770){break;} }
for(i=79;i<99;i++){ buf[505]=(byte)i; if(sha1_32(buf)==-1752067405){break;} }
for(i=-81;i<-66;i++){ buf[506]=(byte)i; if(sha1_32(buf)==1315558258){break;} }
for(i=89;i<106;i++){ buf[507]=(byte)i; if(sha1_32(buf)==-659007507){break;} }
for(i=84;i<93;i++){ buf[508]=(byte)i; if(sha1_32(buf)==1816687728){break;} }
for(i=-95;i<-80;i++){ buf[509]=(byte)i; if(sha1_32(buf)==1190471492){break;} }
for(i=-108;i<-92;i++){ buf[510]=(byte)i; if(sha1_32(buf)==-422986764){break;} }
for(i=28;i<57;i++){ buf[511]=(byte)i; if(sha1_32(buf)==1457392458){break;} }
for(i=112;i<118;i++){ buf[512]=(byte)i; if(sha1_32(buf)==-1768925778){break;} }
for(i=34;i<49;i++){ buf[513]=(byte)i; if(sha1_32(buf)==280385272){break;} }
for(i=-100;i<-72;i++){ buf[514]=(byte)i; if(sha1_32(buf)==-1057734941){break;} }
for(i=-128;i<-125;i++){ buf[515]=(byte)i; if(sha1_32(buf)==-1280359161){break;} }
for(i=30;i<43;i++){ buf[516]=(byte)i; if(sha1_32(buf)==-1918509497){break;} }
for(i=86;i<88;i++){ buf[517]=(byte)i; if(sha1_32(buf)==-310117888){break;} }
for(i=92;i<116;i++){ buf[518]=(byte)i; if(sha1_32(buf)==-1961375195){break;} }
for(i=85;i<96;i++){ buf[519]=(byte)i; if(sha1_32(buf)==-1561729477){break;} }
for(i=108;i<117;i++){ buf[520]=(byte)i; if(sha1_32(buf)==-1504657700){break;} }
for(i=-81;i<-73;i++){ buf[521]=(byte)i; if(sha1_32(buf)==95131790){break;} }
for(i=-14;i<10;i++){ buf[522]=(byte)i; if(sha1_32(buf)==1982103763){break;} }
for(i=61;i<87;i++){ buf[523]=(byte)i; if(sha1_32(buf)==809982249){break;} }
for(i=-47;i<-27;i++){ buf[524]=(byte)i; if(sha1_32(buf)==863398427){break;} }
for(i=73;i<94;i++){ buf[525]=(byte)i; if(sha1_32(buf)==560798688){break;} }
for(i=4;i<18;i++){ buf[526]=(byte)i; if(sha1_32(buf)==-443436723){break;} }
for(i=-113;i<-97;i++){ buf[527]=(byte)i; if(sha1_32(buf)==1322803963){break;} }
for(i=-96;i<-86;i++){ buf[528]=(byte)i; if(sha1_32(buf)==-285701762){break;} }
for(i=92;i<106;i++){ buf[529]=(byte)i; if(sha1_32(buf)==1582201957){break;} }
for(i=14;i<31;i++){ buf[530]=(byte)i; if(sha1_32(buf)==238642774){break;} }
for(i=38;i<48;i++){ buf[531]=(byte)i; if(sha1_32(buf)==-833532378){break;} }
for(i=19;i<37;i++){ buf[532]=(byte)i; if(sha1_32(buf)==91845460){break;} }
for(i=-113;i<-94;i++){ buf[533]=(byte)i; if(sha1_32(buf)==2064239164){break;} }
for(i=-106;i<-87;i++){ buf[534]=(byte)i; if(sha1_32(buf)==-573665088){break;} }
for(i=-64;i<-55;i++){ buf[535]=(byte)i; if(sha1_32(buf)==364105236){break;} }
for(i=93;i<112;i++){ buf[536]=(byte)i; if(sha1_32(buf)==-903415443){break;} }
for(i=-82;i<-75;i++){ buf[537]=(byte)i; if(sha1_32(buf)==1557829454){break;} }
for(i=-3;i<2;i++){ buf[538]=(byte)i; if(sha1_32(buf)==1557829454){break;} }
for(i=-112;i<-103;i++){ buf[539]=(byte)i; if(sha1_32(buf)==1628267827){break;} }
for(i=-96;i<-89;i++){ buf[540]=(byte)i; if(sha1_32(buf)==1843506701){break;} }
for(i=84;i<97;i++){ buf[541]=(byte)i; if(sha1_32(buf)==1835383595){break;} }
for(i=-40;i<-28;i++){ buf[542]=(byte)i; if(sha1_32(buf)==-39708791){break;} }
for(i=115;i<128;i++){ buf[543]=(byte)i; if(sha1_32(buf)==-1584635469){break;} }
for(i=114;i<122;i++){ buf[544]=(byte)i; if(sha1_32(buf)==1865427793){break;} }
for(i=-79;i<-67;i++){ buf[545]=(byte)i; if(sha1_32(buf)==-1059617945){break;} }
for(i=11;i<19;i++){ buf[546]=(byte)i; if(sha1_32(buf)==-51178513){break;} }
for(i=-62;i<-41;i++){ buf[547]=(byte)i; if(sha1_32(buf)==-383624739){break;} }
for(i=100;i<112;i++){ buf[548]=(byte)i; if(sha1_32(buf)==1130601932){break;} }
for(i=-70;i<-61;i++){ buf[549]=(byte)i; if(sha1_32(buf)==597072033){break;} }
for(i=-73;i<-55;i++){ buf[550]=(byte)i; if(sha1_32(buf)==-1597661964){break;} }
for(i=3;i<33;i++){ buf[551]=(byte)i; if(sha1_32(buf)==-1490561211){break;} }
for(i=99;i<125;i++){ buf[552]=(byte)i; if(sha1_32(buf)==-955748857){break;} }
for(i=108;i<128;i++){ buf[553]=(byte)i; if(sha1_32(buf)==1797572359){break;} }
for(i=-96;i<-78;i++){ buf[554]=(byte)i; if(sha1_32(buf)==-175819837){break;} }
for(i=43;i<48;i++){ buf[555]=(byte)i; if(sha1_32(buf)==-1786527524){break;} }
for(i=7;i<27;i++){ buf[556]=(byte)i; if(sha1_32(buf)==338363619){break;} }
for(i=80;i<108;i++){ buf[557]=(byte)i; if(sha1_32(buf)==-1644692677){break;} }
for(i=-22;i<-7;i++){ buf[558]=(byte)i; if(sha1_32(buf)==587221521){break;} }
for(i=-66;i<-54;i++){ buf[559]=(byte)i; if(sha1_32(buf)==-161424293){break;} }
for(i=-118;i<-106;i++){ buf[560]=(byte)i; if(sha1_32(buf)==-1406601389){break;} }
for(i=57;i<81;i++){ buf[561]=(byte)i; if(sha1_32(buf)==-1482783010){break;} }
for(i=-128;i<-122;i++){ buf[562]=(byte)i; if(sha1_32(buf)==1061910096){break;} }
for(i=-46;i<-30;i++){ buf[563]=(byte)i; if(sha1_32(buf)==-110156601){break;} }
for(i=-50;i<-39;i++){ buf[564]=(byte)i; if(sha1_32(buf)==1023568112){break;} }
for(i=-31;i<-23;i++){ buf[565]=(byte)i; if(sha1_32(buf)==1971231528){break;} }
for(i=60;i<78;i++){ buf[566]=(byte)i; if(sha1_32(buf)==-152110360){break;} }
for(i=85;i<103;i++){ buf[567]=(byte)i; if(sha1_32(buf)==-1017611291){break;} }
for(i=-41;i<-31;i++){ buf[568]=(byte)i; if(sha1_32(buf)==1595059211){break;} }
for(i=-39;i<-27;i++){ buf[569]=(byte)i; if(sha1_32(buf)==807980856){break;} }
for(i=-117;i<-94;i++){ buf[570]=(byte)i; if(sha1_32(buf)==1268808966){break;} }
for(i=44;i<60;i++){ buf[571]=(byte)i; if(sha1_32(buf)==-685910373){break;} }
for(i=3;i<17;i++){ buf[572]=(byte)i; if(sha1_32(buf)==-1153385123){break;} }
for(i=-10;i<7;i++){ buf[573]=(byte)i; if(sha1_32(buf)==-433981040){break;} }
for(i=82;i<100;i++){ buf[574]=(byte)i; if(sha1_32(buf)==1770545730){break;} }
for(i=-43;i<-20;i++){ buf[575]=(byte)i; if(sha1_32(buf)==-1282181558){break;} }
for(i=105;i<128;i++){ buf[576]=(byte)i; if(sha1_32(buf)==-2071728719){break;} }
for(i=32;i<40;i++){ buf[577]=(byte)i; if(sha1_32(buf)==-1616239364){break;} }
for(i=48;i<70;i++){ buf[578]=(byte)i; if(sha1_32(buf)==207592318){break;} }
for(i=-69;i<-58;i++){ buf[579]=(byte)i; if(sha1_32(buf)==384615389){break;} }
for(i=44;i<59;i++){ buf[580]=(byte)i; if(sha1_32(buf)==142515695){break;} }
for(i=-107;i<-88;i++){ buf[581]=(byte)i; if(sha1_32(buf)==566429716){break;} }
for(i=-15;i<-1;i++){ buf[582]=(byte)i; if(sha1_32(buf)==1229642561){break;} }
for(i=87;i<94;i++){ buf[583]=(byte)i; if(sha1_32(buf)==-282155995){break;} }
for(i=53;i<67;i++){ buf[584]=(byte)i; if(sha1_32(buf)==-183633319){break;} }
for(i=-128;i<-112;i++){ buf[585]=(byte)i; if(sha1_32(buf)==762562685){break;} }
for(i=-106;i<-97;i++){ buf[586]=(byte)i; if(sha1_32(buf)==1122077627){break;} }
for(i=120;i<122;i++){ buf[587]=(byte)i; if(sha1_32(buf)==-1027328696){break;} }
for(i=37;i<43;i++){ buf[588]=(byte)i; if(sha1_32(buf)==1711180226){break;} }
for(i=32;i<47;i++){ buf[589]=(byte)i; if(sha1_32(buf)==-2106002105){break;} }
for(i=-26;i<-7;i++){ buf[590]=(byte)i; if(sha1_32(buf)==761356895){break;} }
for(i=-54;i<-38;i++){ buf[591]=(byte)i; if(sha1_32(buf)==-1518578937){break;} }
for(i=27;i<53;i++){ buf[592]=(byte)i; if(sha1_32(buf)==-172703001){break;} }
for(i=28;i<53;i++){ buf[593]=(byte)i; if(sha1_32(buf)==978355164){break;} }
for(i=58;i<74;i++){ buf[594]=(byte)i; if(sha1_32(buf)==612189169){break;} }
for(i=-106;i<-101;i++){ buf[595]=(byte)i; if(sha1_32(buf)==-549547930){break;} }
for(i=91;i<105;i++){ buf[596]=(byte)i; if(sha1_32(buf)==907333874){break;} }
for(i=-28;i<-13;i++){ buf[597]=(byte)i; if(sha1_32(buf)==601286964){break;} }
for(i=68;i<88;i++){ buf[598]=(byte)i; if(sha1_32(buf)==-1039492430){break;} }
for(i=-128;i<-120;i++){ buf[599]=(byte)i; if(sha1_32(buf)==1693422985){break;} }
for(i=-34;i<-21;i++){ buf[600]=(byte)i; if(sha1_32(buf)==1061029381){break;} }
for(i=79;i<90;i++){ buf[601]=(byte)i; if(sha1_32(buf)==1780079668){break;} }
for(i=119;i<126;i++){ buf[602]=(byte)i; if(sha1_32(buf)==-338170){break;} }
for(i=-46;i<-20;i++){ buf[603]=(byte)i; if(sha1_32(buf)==-295410030){break;} }
for(i=37;i<67;i++){ buf[604]=(byte)i; if(sha1_32(buf)==493165360){break;} }
for(i=-11;i<13;i++){ buf[605]=(byte)i; if(sha1_32(buf)==-47861366){break;} }
for(i=-98;i<-87;i++){ buf[606]=(byte)i; if(sha1_32(buf)==-1708134779){break;} }
for(i=-93;i<-67;i++){ buf[607]=(byte)i; if(sha1_32(buf)==-119888952){break;} }
for(i=-128;i<-108;i++){ buf[608]=(byte)i; if(sha1_32(buf)==-1180055743){break;} }
for(i=96;i<108;i++){ buf[609]=(byte)i; if(sha1_32(buf)==1892637669){break;} }
for(i=-49;i<-40;i++){ buf[610]=(byte)i; if(sha1_32(buf)==1387777936){break;} }
for(i=6;i<16;i++){ buf[611]=(byte)i; if(sha1_32(buf)==1326267247){break;} }
for(i=105;i<119;i++){ buf[612]=(byte)i; if(sha1_32(buf)==1218202255){break;} }
for(i=1;i<10;i++){ buf[613]=(byte)i; if(sha1_32(buf)==-989547152){break;} }
for(i=-52;i<-47;i++){ buf[614]=(byte)i; if(sha1_32(buf)==8785006){break;} }
for(i=54;i<74;i++){ buf[615]=(byte)i; if(sha1_32(buf)==-2013972205){break;} }
for(i=-64;i<-56;i++){ buf[616]=(byte)i; if(sha1_32(buf)==-1443026951){break;} }
for(i=-71;i<-43;i++){ buf[617]=(byte)i; if(sha1_32(buf)==380187626){break;} }
for(i=-123;i<-93;i++){ buf[618]=(byte)i; if(sha1_32(buf)==-1722757195){break;} }
for(i=-49;i<-34;i++){ buf[619]=(byte)i; if(sha1_32(buf)==-614706955){break;} }
for(i=-128;i<-118;i++){ buf[620]=(byte)i; if(sha1_32(buf)==755574329){break;} }
for(i=100;i<122;i++){ buf[621]=(byte)i; if(sha1_32(buf)==649619469){break;} }
for(i=-128;i<-110;i++){ buf[622]=(byte)i; if(sha1_32(buf)==-925607820){break;} }
for(i=-70;i<-47;i++){ buf[623]=(byte)i; if(sha1_32(buf)==1216234815){break;} }
for(i=-128;i<-120;i++){ buf[624]=(byte)i; if(sha1_32(buf)==1151750831){break;} }
for(i=121;i<128;i++){ buf[625]=(byte)i; if(sha1_32(buf)==-569790309){break;} }
for(i=46;i<65;i++){ buf[626]=(byte)i; if(sha1_32(buf)==369375737){break;} }
for(i=-92;i<-80;i++){ buf[627]=(byte)i; if(sha1_32(buf)==1497187025){break;} }
for(i=103;i<111;i++){ buf[628]=(byte)i; if(sha1_32(buf)==-264362998){break;} }
for(i=58;i<67;i++){ buf[629]=(byte)i; if(sha1_32(buf)==-1895129002){break;} }
for(i=86;i<90;i++){ buf[630]=(byte)i; if(sha1_32(buf)==-1578877234){break;} }
for(i=26;i<38;i++){ buf[631]=(byte)i; if(sha1_32(buf)==-922135801){break;} }
for(i=-126;i<-106;i++){ buf[632]=(byte)i; if(sha1_32(buf)==1157136770){break;} }
for(i=33;i<58;i++){ buf[633]=(byte)i; if(sha1_32(buf)==1005068418){break;} }
for(i=-119;i<-103;i++){ buf[634]=(byte)i; if(sha1_32(buf)==-1060471641){break;} }
for(i=-20;i<3;i++){ buf[635]=(byte)i; if(sha1_32(buf)==191217117){break;} }
for(i=44;i<55;i++){ buf[636]=(byte)i; if(sha1_32(buf)==-401870091){break;} }
for(i=-102;i<-94;i++){ buf[637]=(byte)i; if(sha1_32(buf)==-1560626520){break;} }
for(i=95;i<122;i++){ buf[638]=(byte)i; if(sha1_32(buf)==-806516615){break;} }
for(i=27;i<44;i++){ buf[639]=(byte)i; if(sha1_32(buf)==-29264667){break;} }
for(i=-98;i<-77;i++){ buf[640]=(byte)i; if(sha1_32(buf)==-1616513708){break;} }
for(i=-61;i<-38;i++){ buf[641]=(byte)i; if(sha1_32(buf)==-2041935096){break;} }
for(i=64;i<80;i++){ buf[642]=(byte)i; if(sha1_32(buf)==-338529575){break;} }
for(i=110;i<128;i++){ buf[643]=(byte)i; if(sha1_32(buf)==1553337191){break;} }
for(i=-3;i<0;i++){ buf[644]=(byte)i; if(sha1_32(buf)==1268581838){break;} }
for(i=-128;i<-106;i++){ buf[645]=(byte)i; if(sha1_32(buf)==100952631){break;} }
for(i=26;i<40;i++){ buf[646]=(byte)i; if(sha1_32(buf)==71792284){break;} }
for(i=-48;i<-27;i++){ buf[647]=(byte)i; if(sha1_32(buf)==1111264493){break;} }
for(i=-80;i<-71;i++){ buf[648]=(byte)i; if(sha1_32(buf)==-1323851165){break;} }
for(i=-34;i<-9;i++){ buf[649]=(byte)i; if(sha1_32(buf)==-2052417606){break;} }
for(i=-78;i<-52;i++){ buf[650]=(byte)i; if(sha1_32(buf)==-1177437871){break;} }
for(i=89;i<97;i++){ buf[651]=(byte)i; if(sha1_32(buf)==1577195969){break;} }
for(i=26;i<37;i++){ buf[652]=(byte)i; if(sha1_32(buf)==-269629187){break;} }
for(i=76;i<95;i++){ buf[653]=(byte)i; if(sha1_32(buf)==-1838594212){break;} }
for(i=-83;i<-65;i++){ buf[654]=(byte)i; if(sha1_32(buf)==-2138401693){break;} }
for(i=75;i<90;i++){ buf[655]=(byte)i; if(sha1_32(buf)==-2126850343){break;} }
for(i=-121;i<-111;i++){ buf[656]=(byte)i; if(sha1_32(buf)==2056475312){break;} }
for(i=-28;i<-8;i++){ buf[657]=(byte)i; if(sha1_32(buf)==-955719505){break;} }
for(i=-90;i<-75;i++){ buf[658]=(byte)i; if(sha1_32(buf)==-1682219956){break;} }
for(i=-55;i<-39;i++){ buf[659]=(byte)i; if(sha1_32(buf)==-389133170){break;} }
for(i=-61;i<-46;i++){ buf[660]=(byte)i; if(sha1_32(buf)==1532351868){break;} }
for(i=-15;i<4;i++){ buf[661]=(byte)i; if(sha1_32(buf)==-2073460241){break;} }
for(i=-125;i<-120;i++){ buf[662]=(byte)i; if(sha1_32(buf)==1498074811){break;} }
for(i=114;i<128;i++){ buf[663]=(byte)i; if(sha1_32(buf)==441625773){break;} }
for(i=-100;i<-87;i++){ buf[664]=(byte)i; if(sha1_32(buf)==1483646052){break;} }
for(i=-128;i<-112;i++){ buf[665]=(byte)i; if(sha1_32(buf)==320241101){break;} }
for(i=123;i<125;i++){ buf[666]=(byte)i; if(sha1_32(buf)==-324194149){break;} }
for(i=-38;i<-26;i++){ buf[667]=(byte)i; if(sha1_32(buf)==620081206){break;} }
for(i=-116;i<-86;i++){ buf[668]=(byte)i; if(sha1_32(buf)==-1102202327){break;} }
for(i=70;i<85;i++){ buf[669]=(byte)i; if(sha1_32(buf)==916254078){break;} }
for(i=-118;i<-102;i++){ buf[670]=(byte)i; if(sha1_32(buf)==-934670656){break;} }
for(i=2;i<16;i++){ buf[671]=(byte)i; if(sha1_32(buf)==-822735882){break;} }
for(i=-33;i<-21;i++){ buf[672]=(byte)i; if(sha1_32(buf)==-611816320){break;} }
for(i=31;i<57;i++){ buf[673]=(byte)i; if(sha1_32(buf)==-937299915){break;} }
for(i=35;i<41;i++){ buf[674]=(byte)i; if(sha1_32(buf)==-1435404042){break;} }
for(i=-127;i<-117;i++){ buf[675]=(byte)i; if(sha1_32(buf)==-1670829461){break;} }
for(i=77;i<101;i++){ buf[676]=(byte)i; if(sha1_32(buf)==677362997){break;} }
for(i=-14;i<1;i++){ buf[677]=(byte)i; if(sha1_32(buf)==677362997){break;} }
for(i=2;i<24;i++){ buf[678]=(byte)i; if(sha1_32(buf)==36264425){break;} }
for(i=91;i<111;i++){ buf[679]=(byte)i; if(sha1_32(buf)==-1563716530){break;} }
for(i=-94;i<-86;i++){ buf[680]=(byte)i; if(sha1_32(buf)==-164867468){break;} }
for(i=-34;i<-11;i++){ buf[681]=(byte)i; if(sha1_32(buf)==690011026){break;} }
for(i=38;i<51;i++){ buf[682]=(byte)i; if(sha1_32(buf)==-1336113568){break;} }
for(i=-16;i<-9;i++){ buf[683]=(byte)i; if(sha1_32(buf)==1624136172){break;} }
for(i=29;i<49;i++){ buf[684]=(byte)i; if(sha1_32(buf)==-1291090393){break;} }
for(i=82;i<103;i++){ buf[685]=(byte)i; if(sha1_32(buf)==-913154626){break;} }
for(i=-104;i<-83;i++){ buf[686]=(byte)i; if(sha1_32(buf)==1664639153){break;} }
for(i=-21;i<-10;i++){ buf[687]=(byte)i; if(sha1_32(buf)==-1494669012){break;} }
for(i=-116;i<-106;i++){ buf[688]=(byte)i; if(sha1_32(buf)==2082462176){break;} }
for(i=91;i<102;i++){ buf[689]=(byte)i; if(sha1_32(buf)==-1386435621){break;} }
for(i=56;i<69;i++){ buf[690]=(byte)i; if(sha1_32(buf)==1800710036){break;} }
for(i=66;i<80;i++){ buf[691]=(byte)i; if(sha1_32(buf)==925475375){break;} }
for(i=3;i<16;i++){ buf[692]=(byte)i; if(sha1_32(buf)==-294525819){break;} }
for(i=114;i<128;i++){ buf[693]=(byte)i; if(sha1_32(buf)==2063012106){break;} }
for(i=27;i<45;i++){ buf[694]=(byte)i; if(sha1_32(buf)==-417256472){break;} }
for(i=1;i<19;i++){ buf[695]=(byte)i; if(sha1_32(buf)==1725637744){break;} }
for(i=97;i<121;i++){ buf[696]=(byte)i; if(sha1_32(buf)==-1729778332){break;} }
for(i=8;i<26;i++){ buf[697]=(byte)i; if(sha1_32(buf)==-1191462037){break;} }
for(i=-82;i<-56;i++){ buf[698]=(byte)i; if(sha1_32(buf)==85502333){break;} }
for(i=110;i<118;i++){ buf[699]=(byte)i; if(sha1_32(buf)==-562909455){break;} }
for(i=100;i<121;i++){ buf[700]=(byte)i; if(sha1_32(buf)==-1438746314){break;} }
for(i=42;i<67;i++){ buf[701]=(byte)i; if(sha1_32(buf)==-1725653913){break;} }
for(i=64;i<89;i++){ buf[702]=(byte)i; if(sha1_32(buf)==1538717991){break;} }
for(i=63;i<81;i++){ buf[703]=(byte)i; if(sha1_32(buf)==-979420986){break;} }
for(i=-109;i<-80;i++){ buf[704]=(byte)i; if(sha1_32(buf)==-1818023360){break;} }
for(i=12;i<36;i++){ buf[705]=(byte)i; if(sha1_32(buf)==1889107546){break;} }
for(i=-117;i<-94;i++){ buf[706]=(byte)i; if(sha1_32(buf)==-688265294){break;} }
for(i=-74;i<-72;i++){ buf[707]=(byte)i; if(sha1_32(buf)==1807967314){break;} }
for(i=-128;i<-103;i++){ buf[708]=(byte)i; if(sha1_32(buf)==-909333878){break;} }
for(i=33;i<45;i++){ buf[709]=(byte)i; if(sha1_32(buf)==-833917112){break;} }
for(i=-27;i<-6;i++){ buf[710]=(byte)i; if(sha1_32(buf)==1419757866){break;} }
for(i=35;i<40;i++){ buf[711]=(byte)i; if(sha1_32(buf)==1840778377){break;} }
for(i=-68;i<-57;i++){ buf[712]=(byte)i; if(sha1_32(buf)==682490682){break;} }
for(i=17;i<33;i++){ buf[713]=(byte)i; if(sha1_32(buf)==45182953){break;} }
for(i=66;i<78;i++){ buf[714]=(byte)i; if(sha1_32(buf)==1289487478){break;} }
for(i=46;i<54;i++){ buf[715]=(byte)i; if(sha1_32(buf)==813128622){break;} }
for(i=-105;i<-91;i++){ buf[716]=(byte)i; if(sha1_32(buf)==-1820805504){break;} }
for(i=103;i<113;i++){ buf[717]=(byte)i; if(sha1_32(buf)==17593546){break;} }
for(i=-73;i<-64;i++){ buf[718]=(byte)i; if(sha1_32(buf)==-2093251178){break;} }
for(i=-77;i<-56;i++){ buf[719]=(byte)i; if(sha1_32(buf)==854932860){break;} }
for(i=112;i<116;i++){ buf[720]=(byte)i; if(sha1_32(buf)==-1874394022){break;} }
for(i=-102;i<-72;i++){ buf[721]=(byte)i; if(sha1_32(buf)==646994106){break;} }
for(i=-16;i<-12;i++){ buf[722]=(byte)i; if(sha1_32(buf)==-442038616){break;} }
for(i=96;i<118;i++){ buf[723]=(byte)i; if(sha1_32(buf)==533061814){break;} }
for(i=87;i<111;i++){ buf[724]=(byte)i; if(sha1_32(buf)==-1672613062){break;} }
for(i=-68;i<-39;i++){ buf[725]=(byte)i; if(sha1_32(buf)==1825885070){break;} }
for(i=-83;i<-60;i++){ buf[726]=(byte)i; if(sha1_32(buf)==-396952105){break;} }
for(i=-117;i<-90;i++){ buf[727]=(byte)i; if(sha1_32(buf)==1197905297){break;} }
for(i=6;i<31;i++){ buf[728]=(byte)i; if(sha1_32(buf)==-918247204){break;} }
for(i=-122;i<-107;i++){ buf[729]=(byte)i; if(sha1_32(buf)==-789029112){break;} }
for(i=-64;i<-50;i++){ buf[730]=(byte)i; if(sha1_32(buf)==2054318526){break;} }
for(i=84;i<86;i++){ buf[731]=(byte)i; if(sha1_32(buf)==915291628){break;} }
for(i=120;i<128;i++){ buf[732]=(byte)i; if(sha1_32(buf)==454982690){break;} }
for(i=-19;i<3;i++){ buf[733]=(byte)i; if(sha1_32(buf)==-1302609820){break;} }
for(i=10;i<17;i++){ buf[734]=(byte)i; if(sha1_32(buf)==2063952692){break;} }
for(i=-85;i<-70;i++){ buf[735]=(byte)i; if(sha1_32(buf)==-895592912){break;} }
for(i=112;i<128;i++){ buf[736]=(byte)i; if(sha1_32(buf)==-1371577084){break;} }
for(i=34;i<58;i++){ buf[737]=(byte)i; if(sha1_32(buf)==1506924143){break;} }
for(i=-79;i<-54;i++){ buf[738]=(byte)i; if(sha1_32(buf)==1510125273){break;} }
for(i=-97;i<-83;i++){ buf[739]=(byte)i; if(sha1_32(buf)==2005844676){break;} }
for(i=59;i<75;i++){ buf[740]=(byte)i; if(sha1_32(buf)==-78382256){break;} }
for(i=100;i<116;i++){ buf[741]=(byte)i; if(sha1_32(buf)==-122238508){break;} }
for(i=-91;i<-76;i++){ buf[742]=(byte)i; if(sha1_32(buf)==2024103529){break;} }
for(i=-117;i<-116;i++){ buf[743]=(byte)i; if(sha1_32(buf)==-1217373545){break;} }
for(i=-100;i<-69;i++){ buf[744]=(byte)i; if(sha1_32(buf)==-81762748){break;} }
for(i=-34;i<-15;i++){ buf[745]=(byte)i; if(sha1_32(buf)==-467792525){break;} }
for(i=-40;i<-25;i++){ buf[746]=(byte)i; if(sha1_32(buf)==-867828647){break;} }
for(i=15;i<32;i++){ buf[747]=(byte)i; if(sha1_32(buf)==-1807512389){break;} }
for(i=-36;i<-16;i++){ buf[748]=(byte)i; if(sha1_32(buf)==-1805418654){break;} }
for(i=-65;i<-55;i++){ buf[749]=(byte)i; if(sha1_32(buf)==-1752532072){break;} }
for(i=4;i<19;i++){ buf[750]=(byte)i; if(sha1_32(buf)==1272193840){break;} }
for(i=-15;i<-2;i++){ buf[751]=(byte)i; if(sha1_32(buf)==-80553109){break;} }
for(i=107;i<128;i++){ buf[752]=(byte)i; if(sha1_32(buf)==-1577178669){break;} }
for(i=-104;i<-97;i++){ buf[753]=(byte)i; if(sha1_32(buf)==338304122){break;} }
for(i=-108;i<-97;i++){ buf[754]=(byte)i; if(sha1_32(buf)==-1183854621){break;} }
for(i=70;i<86;i++){ buf[755]=(byte)i; if(sha1_32(buf)==-1701781734){break;} }
for(i=-39;i<-28;i++){ buf[756]=(byte)i; if(sha1_32(buf)==-358960858){break;} }
for(i=122;i<128;i++){ buf[757]=(byte)i; if(sha1_32(buf)==1116285300){break;} }
for(i=47;i<69;i++){ buf[758]=(byte)i; if(sha1_32(buf)==1715114729){break;} }
for(i=-62;i<-55;i++){ buf[759]=(byte)i; if(sha1_32(buf)==-1050011137){break;} }
for(i=-83;i<-59;i++){ buf[760]=(byte)i; if(sha1_32(buf)==218810212){break;} }
for(i=-42;i<-30;i++){ buf[761]=(byte)i; if(sha1_32(buf)==-1733092871){break;} }
for(i=9;i<27;i++){ buf[762]=(byte)i; if(sha1_32(buf)==7650798){break;} }
for(i=74;i<100;i++){ buf[763]=(byte)i; if(sha1_32(buf)==-39275181){break;} }
for(i=-8;i<10;i++){ buf[764]=(byte)i; if(sha1_32(buf)==195991939){break;} }
for(i=-83;i<-64;i++){ buf[765]=(byte)i; if(sha1_32(buf)==302387670){break;} }
for(i=-105;i<-92;i++){ buf[766]=(byte)i; if(sha1_32(buf)==-1601128494){break;} }
for(i=115;i<127;i++){ buf[767]=(byte)i; if(sha1_32(buf)==1758170321){break;} }
for(i=-64;i<-47;i++){ buf[768]=(byte)i; if(sha1_32(buf)==1349905706){break;} }
for(i=-90;i<-83;i++){ buf[769]=(byte)i; if(sha1_32(buf)==-762589365){break;} }
for(i=-95;i<-82;i++){ buf[770]=(byte)i; if(sha1_32(buf)==1524820416){break;} }
for(i=39;i<62;i++){ buf[771]=(byte)i; if(sha1_32(buf)==1514444234){break;} }
for(i=-99;i<-76;i++){ buf[772]=(byte)i; if(sha1_32(buf)==-1587974584){break;} }
for(i=-29;i<-11;i++){ buf[773]=(byte)i; if(sha1_32(buf)==149828451){break;} }
for(i=27;i<49;i++){ buf[774]=(byte)i; if(sha1_32(buf)==-1378487456){break;} }
for(i=27;i<52;i++){ buf[775]=(byte)i; if(sha1_32(buf)==-1020629236){break;} }
for(i=-91;i<-70;i++){ buf[776]=(byte)i; if(sha1_32(buf)==-2042945985){break;} }
for(i=-88;i<-74;i++){ buf[777]=(byte)i; if(sha1_32(buf)==2028633411){break;} }
for(i=92;i<120;i++){ buf[778]=(byte)i; if(sha1_32(buf)==-1727197513){break;} }
for(i=46;i<74;i++){ buf[779]=(byte)i; if(sha1_32(buf)==1002745950){break;} }
for(i=-51;i<-40;i++){ buf[780]=(byte)i; if(sha1_32(buf)==993585617){break;} }
for(i=-80;i<-62;i++){ buf[781]=(byte)i; if(sha1_32(buf)==-206388808){break;} }
for(i=39;i<56;i++){ buf[782]=(byte)i; if(sha1_32(buf)==1646147171){break;} }
for(i=-128;i<-109;i++){ buf[783]=(byte)i; if(sha1_32(buf)==1637251184){break;} }
for(i=4;i<32;i++){ buf[784]=(byte)i; if(sha1_32(buf)==-1385138602){break;} }
for(i=67;i<69;i++){ buf[785]=(byte)i; if(sha1_32(buf)==773167810){break;} }
for(i=-128;i<-107;i++){ buf[786]=(byte)i; if(sha1_32(buf)==-1514468240){break;} }
for(i=53;i<70;i++){ buf[787]=(byte)i; if(sha1_32(buf)==-1854018463){break;} }
for(i=-41;i<-29;i++){ buf[788]=(byte)i; if(sha1_32(buf)==1118123493){break;} }
for(i=-102;i<-85;i++){ buf[789]=(byte)i; if(sha1_32(buf)==-563420322){break;} }
for(i=57;i<68;i++){ buf[790]=(byte)i; if(sha1_32(buf)==-2124326879){break;} }
for(i=84;i<97;i++){ buf[791]=(byte)i; if(sha1_32(buf)==1387119808){break;} }
for(i=-94;i<-79;i++){ buf[792]=(byte)i; if(sha1_32(buf)==-2024771945){break;} }
for(i=-95;i<-79;i++){ buf[793]=(byte)i; if(sha1_32(buf)==2131260530){break;} }
for(i=0;i<23;i++){ buf[794]=(byte)i; if(sha1_32(buf)==168489931){break;} }
for(i=-76;i<-65;i++){ buf[795]=(byte)i; if(sha1_32(buf)==-1884700212){break;} }
for(i=-107;i<-86;i++){ buf[796]=(byte)i; if(sha1_32(buf)==-629126220){break;} }
for(i=68;i<84;i++){ buf[797]=(byte)i; if(sha1_32(buf)==224974700){break;} }
for(i=-39;i<-14;i++){ buf[798]=(byte)i; if(sha1_32(buf)==-1339021226){break;} }
for(i=-61;i<-51;i++){ buf[799]=(byte)i; if(sha1_32(buf)==85488678){break;} }
for(i=-60;i<-43;i++){ buf[800]=(byte)i; if(sha1_32(buf)==1963118539){break;} }
for(i=-49;i<-25;i++){ buf[801]=(byte)i; if(sha1_32(buf)==-2044799044){break;} }
for(i=107;i<119;i++){ buf[802]=(byte)i; if(sha1_32(buf)==-64471098){break;} }
for(i=-53;i<-41;i++){ buf[803]=(byte)i; if(sha1_32(buf)==1437945543){break;} }
for(i=-86;i<-62;i++){ buf[804]=(byte)i; if(sha1_32(buf)==1451063960){break;} }
for(i=8;i<16;i++){ buf[805]=(byte)i; if(sha1_32(buf)==-1140117381){break;} }
for(i=112;i<126;i++){ buf[806]=(byte)i; if(sha1_32(buf)==2129081488){break;} }
for(i=-52;i<-40;i++){ buf[807]=(byte)i; if(sha1_32(buf)==491582840){break;} }
for(i=56;i<66;i++){ buf[808]=(byte)i; if(sha1_32(buf)==-1564630904){break;} }
for(i=100;i<115;i++){ buf[809]=(byte)i; if(sha1_32(buf)==1093368621){break;} }
for(i=-119;i<-115;i++){ buf[810]=(byte)i; if(sha1_32(buf)==1498762409){break;} }
for(i=-12;i<4;i++){ buf[811]=(byte)i; if(sha1_32(buf)==1498762409){break;} }
for(i=-29;i<-20;i++){ buf[812]=(byte)i; if(sha1_32(buf)==-1500810312){break;} }
for(i=-104;i<-86;i++){ buf[813]=(byte)i; if(sha1_32(buf)==-933316243){break;} }
for(i=73;i<95;i++){ buf[814]=(byte)i; if(sha1_32(buf)==-807554590){break;} }
for(i=2;i<25;i++){ buf[815]=(byte)i; if(sha1_32(buf)==-2006703030){break;} }
for(i=82;i<84;i++){ buf[816]=(byte)i; if(sha1_32(buf)==-1678692296){break;} }
for(i=84;i<95;i++){ buf[817]=(byte)i; if(sha1_32(buf)==-1974818200){break;} }
for(i=2;i<16;i++){ buf[818]=(byte)i; if(sha1_32(buf)==-189321962){break;} }
for(i=-81;i<-59;i++){ buf[819]=(byte)i; if(sha1_32(buf)==1763067823){break;} }
for(i=121;i<128;i++){ buf[820]=(byte)i; if(sha1_32(buf)==-877472259){break;} }
for(i=68;i<71;i++){ buf[821]=(byte)i; if(sha1_32(buf)==1299130276){break;} }
for(i=-69;i<-46;i++){ buf[822]=(byte)i; if(sha1_32(buf)==-1823340105){break;} }
for(i=-127;i<-112;i++){ buf[823]=(byte)i; if(sha1_32(buf)==79701674){break;} }
for(i=18;i<38;i++){ buf[824]=(byte)i; if(sha1_32(buf)==-1702139909){break;} }
for(i=-51;i<-23;i++){ buf[825]=(byte)i; if(sha1_32(buf)==691674669){break;} }
for(i=-96;i<-71;i++){ buf[826]=(byte)i; if(sha1_32(buf)==238478800){break;} }
for(i=72;i<90;i++){ buf[827]=(byte)i; if(sha1_32(buf)==-899290964){break;} }
for(i=-93;i<-70;i++){ buf[828]=(byte)i; if(sha1_32(buf)==1152543546){break;} }
for(i=12;i<34;i++){ buf[829]=(byte)i; if(sha1_32(buf)==-280576430){break;} }
for(i=-72;i<-62;i++){ buf[830]=(byte)i; if(sha1_32(buf)==-77601187){break;} }
for(i=-65;i<-55;i++){ buf[831]=(byte)i; if(sha1_32(buf)==-1099898630){break;} }
for(i=104;i<125;i++){ buf[832]=(byte)i; if(sha1_32(buf)==-10258667){break;} }
for(i=-6;i<15;i++){ buf[833]=(byte)i; if(sha1_32(buf)==462508238){break;} }
for(i=-21;i<-2;i++){ buf[834]=(byte)i; if(sha1_32(buf)==42561612){break;} }
for(i=85;i<107;i++){ buf[835]=(byte)i; if(sha1_32(buf)==-1446124213){break;} }
for(i=19;i<34;i++){ buf[836]=(byte)i; if(sha1_32(buf)==-1114829467){break;} }
for(i=-128;i<-109;i++){ buf[837]=(byte)i; if(sha1_32(buf)==-1554122356){break;} }
for(i=-1;i<17;i++){ buf[838]=(byte)i; if(sha1_32(buf)==1700990178){break;} }
for(i=-24;i<-3;i++){ buf[839]=(byte)i; if(sha1_32(buf)==-2129203639){break;} }
for(i=-63;i<-61;i++){ buf[840]=(byte)i; if(sha1_32(buf)==822832394){break;} }
for(i=-10;i<7;i++){ buf[841]=(byte)i; if(sha1_32(buf)==1498437385){break;} }
for(i=-68;i<-56;i++){ buf[842]=(byte)i; if(sha1_32(buf)==764458943){break;} }
for(i=-122;i<-105;i++){ buf[843]=(byte)i; if(sha1_32(buf)==-1428484920){break;} }
for(i=16;i<35;i++){ buf[844]=(byte)i; if(sha1_32(buf)==-2088972474){break;} }
for(i=106;i<124;i++){ buf[845]=(byte)i; if(sha1_32(buf)==1057106681){break;} }
for(i=110;i<128;i++){ buf[846]=(byte)i; if(sha1_32(buf)==1192979070){break;} }
for(i=64;i<86;i++){ buf[847]=(byte)i; if(sha1_32(buf)==-1450658051){break;} }
for(i=-83;i<-73;i++){ buf[848]=(byte)i; if(sha1_32(buf)==1164338345){break;} }
for(i=48;i<64;i++){ buf[849]=(byte)i; if(sha1_32(buf)==-1830539053){break;} }
for(i=43;i<62;i++){ buf[850]=(byte)i; if(sha1_32(buf)==1396682349){break;} }
for(i=57;i<70;i++){ buf[851]=(byte)i; if(sha1_32(buf)==-1015462442){break;} }
for(i=-108;i<-94;i++){ buf[852]=(byte)i; if(sha1_32(buf)==-511264660){break;} }
for(i=-124;i<-113;i++){ buf[853]=(byte)i; if(sha1_32(buf)==-2025693442){break;} }
for(i=10;i<16;i++){ buf[854]=(byte)i; if(sha1_32(buf)==-2051987174){break;} }
for(i=-65;i<-48;i++){ buf[855]=(byte)i; if(sha1_32(buf)==-299164388){break;} }
for(i=-128;i<-116;i++){ buf[856]=(byte)i; if(sha1_32(buf)==840846418){break;} }
for(i=-94;i<-83;i++){ buf[857]=(byte)i; if(sha1_32(buf)==2129463079){break;} }
for(i=111;i<127;i++){ buf[858]=(byte)i; if(sha1_32(buf)==375998593){break;} }
for(i=78;i<98;i++){ buf[859]=(byte)i; if(sha1_32(buf)==-389269146){break;} }
for(i=53;i<61;i++){ buf[860]=(byte)i; if(sha1_32(buf)==-1773011846){break;} }
for(i=-50;i<-28;i++){ buf[861]=(byte)i; if(sha1_32(buf)==1360979827){break;} }
for(i=-35;i<-21;i++){ buf[862]=(byte)i; if(sha1_32(buf)==-1046607476){break;} }
for(i=103;i<120;i++){ buf[863]=(byte)i; if(sha1_32(buf)==549574095){break;} }
for(i=-25;i<-3;i++){ buf[864]=(byte)i; if(sha1_32(buf)==1492911388){break;} }
for(i=-53;i<-27;i++){ buf[865]=(byte)i; if(sha1_32(buf)==-1283064242){break;} }
for(i=-74;i<-59;i++){ buf[866]=(byte)i; if(sha1_32(buf)==-1114180464){break;} }
for(i=-89;i<-76;i++){ buf[867]=(byte)i; if(sha1_32(buf)==1534088266){break;} }
for(i=63;i<82;i++){ buf[868]=(byte)i; if(sha1_32(buf)==-282042228){break;} }
for(i=-54;i<-39;i++){ buf[869]=(byte)i; if(sha1_32(buf)==160031996){break;} }
for(i=-95;i<-79;i++){ buf[870]=(byte)i; if(sha1_32(buf)==1361785552){break;} }
for(i=-110;i<-94;i++){ buf[871]=(byte)i; if(sha1_32(buf)==1943453866){break;} }
for(i=-94;i<-82;i++){ buf[872]=(byte)i; if(sha1_32(buf)==1590912905){break;} }
for(i=12;i<33;i++){ buf[873]=(byte)i; if(sha1_32(buf)==1144388572){break;} }
for(i=-51;i<-28;i++){ buf[874]=(byte)i; if(sha1_32(buf)==-23097481){break;} }
for(i=3;i<20;i++){ buf[875]=(byte)i; if(sha1_32(buf)==1873977542){break;} }
for(i=-104;i<-80;i++){ buf[876]=(byte)i; if(sha1_32(buf)==-604341289){break;} }
for(i=-57;i<-29;i++){ buf[877]=(byte)i; if(sha1_32(buf)==-100094999){break;} }
for(i=101;i<115;i++){ buf[878]=(byte)i; if(sha1_32(buf)==-1202705935){break;} }
for(i=38;i<57;i++){ buf[879]=(byte)i; if(sha1_32(buf)==1629600420){break;} }
for(i=-115;i<-107;i++){ buf[880]=(byte)i; if(sha1_32(buf)==-1388940846){break;} }
for(i=79;i<93;i++){ buf[881]=(byte)i; if(sha1_32(buf)==248688599){break;} }
for(i=70;i<81;i++){ buf[882]=(byte)i; if(sha1_32(buf)==-342521666){break;} }
for(i=-104;i<-87;i++){ buf[883]=(byte)i; if(sha1_32(buf)==241380084){break;} }
for(i=-70;i<-52;i++){ buf[884]=(byte)i; if(sha1_32(buf)==-1603513729){break;} }
for(i=-34;i<-25;i++){ buf[885]=(byte)i; if(sha1_32(buf)==-1979841637){break;} }
for(i=89;i<96;i++){ buf[886]=(byte)i; if(sha1_32(buf)==1502277436){break;} }
for(i=84;i<102;i++){ buf[887]=(byte)i; if(sha1_32(buf)==-1082247723){break;} }
for(i=-64;i<-45;i++){ buf[888]=(byte)i; if(sha1_32(buf)==306615885){break;} }
for(i=24;i<34;i++){ buf[889]=(byte)i; if(sha1_32(buf)==-1898412950){break;} }
for(i=8;i<24;i++){ buf[890]=(byte)i; if(sha1_32(buf)==320881333){break;} }
for(i=-120;i<-114;i++){ buf[891]=(byte)i; if(sha1_32(buf)==-844531405){break;} }
for(i=-108;i<-90;i++){ buf[892]=(byte)i; if(sha1_32(buf)==-778561392){break;} }
for(i=-122;i<-105;i++){ buf[893]=(byte)i; if(sha1_32(buf)==1290546306){break;} }
for(i=-39;i<-19;i++){ buf[894]=(byte)i; if(sha1_32(buf)==-1555951631){break;} }
for(i=-10;i<2;i++){ buf[895]=(byte)i; if(sha1_32(buf)==852129991){break;} }
for(i=-29;i<0;i++){ buf[896]=(byte)i; if(sha1_32(buf)==-384234057){break;} }
for(i=-104;i<-92;i++){ buf[897]=(byte)i; if(sha1_32(buf)==-493916394){break;} }
for(i=-76;i<-59;i++){ buf[898]=(byte)i; if(sha1_32(buf)==-924293204){break;} }
for(i=-55;i<-45;i++){ buf[899]=(byte)i; if(sha1_32(buf)==-1241674290){break;} }
for(i=66;i<71;i++){ buf[900]=(byte)i; if(sha1_32(buf)==-1046109390){break;} }
for(i=-67;i<-53;i++){ buf[901]=(byte)i; if(sha1_32(buf)==1459002080){break;} }
for(i=-60;i<-50;i++){ buf[902]=(byte)i; if(sha1_32(buf)==982680207){break;} }
for(i=-33;i<-10;i++){ buf[903]=(byte)i; if(sha1_32(buf)==1487374768){break;} }
for(i=63;i<89;i++){ buf[904]=(byte)i; if(sha1_32(buf)==1075513208){break;} }
for(i=17;i<39;i++){ buf[905]=(byte)i; if(sha1_32(buf)==-467005197){break;} }
for(i=27;i<39;i++){ buf[906]=(byte)i; if(sha1_32(buf)==735814082){break;} }
for(i=-50;i<-37;i++){ buf[907]=(byte)i; if(sha1_32(buf)==1276941038){break;} }
for(i=-69;i<-54;i++){ buf[908]=(byte)i; if(sha1_32(buf)==358573369){break;} }
for(i=-73;i<-50;i++){ buf[909]=(byte)i; if(sha1_32(buf)==-997924859){break;} }
for(i=-111;i<-97;i++){ buf[910]=(byte)i; if(sha1_32(buf)==1851576505){break;} }
for(i=36;i<54;i++){ buf[911]=(byte)i; if(sha1_32(buf)==-1158239392){break;} }
for(i=76;i<90;i++){ buf[912]=(byte)i; if(sha1_32(buf)==1490340140){break;} }
for(i=-66;i<-43;i++){ buf[913]=(byte)i; if(sha1_32(buf)==1296332573){break;} }
for(i=37;i<54;i++){ buf[914]=(byte)i; if(sha1_32(buf)==774823636){break;} }
for(i=-35;i<-27;i++){ buf[915]=(byte)i; if(sha1_32(buf)==-1046915320){break;} }
for(i=105;i<124;i++){ buf[916]=(byte)i; if(sha1_32(buf)==-1386518214){break;} }
for(i=45;i<64;i++){ buf[917]=(byte)i; if(sha1_32(buf)==248700538){break;} }
for(i=-57;i<-55;i++){ buf[918]=(byte)i; if(sha1_32(buf)==-875595847){break;} }
for(i=102;i<126;i++){ buf[919]=(byte)i; if(sha1_32(buf)==-318220555){break;} }
for(i=95;i<113;i++){ buf[920]=(byte)i; if(sha1_32(buf)==1739492991){break;} }
for(i=19;i<36;i++){ buf[921]=(byte)i; if(sha1_32(buf)==-1615191447){break;} }
for(i=-5;i<12;i++){ buf[922]=(byte)i; if(sha1_32(buf)==97223495){break;} }
for(i=-9;i<19;i++){ buf[923]=(byte)i; if(sha1_32(buf)==-761790487){break;} }
for(i=-12;i<-6;i++){ buf[924]=(byte)i; if(sha1_32(buf)==-234524695){break;} }
for(i=21;i<37;i++){ buf[925]=(byte)i; if(sha1_32(buf)==-161833398){break;} }
for(i=-34;i<-12;i++){ buf[926]=(byte)i; if(sha1_32(buf)==-1541671395){break;} }
for(i=67;i<90;i++){ buf[927]=(byte)i; if(sha1_32(buf)==-751943402){break;} }
for(i=110;i<124;i++){ buf[928]=(byte)i; if(sha1_32(buf)==981387674){break;} }
for(i=116;i<128;i++){ buf[929]=(byte)i; if(sha1_32(buf)==-1961621572){break;} }
for(i=-37;i<-12;i++){ buf[930]=(byte)i; if(sha1_32(buf)==1359178259){break;} }
for(i=19;i<37;i++){ buf[931]=(byte)i; if(sha1_32(buf)==-821216218){break;} }
for(i=76;i<82;i++){ buf[932]=(byte)i; if(sha1_32(buf)==-918005577){break;} }
for(i=64;i<82;i++){ buf[933]=(byte)i; if(sha1_32(buf)==320599467){break;} }
for(i=105;i<119;i++){ buf[934]=(byte)i; if(sha1_32(buf)==1186019903){break;} }
for(i=-128;i<-113;i++){ buf[935]=(byte)i; if(sha1_32(buf)==307363402){break;} }
for(i=84;i<86;i++){ buf[936]=(byte)i; if(sha1_32(buf)==1446850967){break;} }
for(i=106;i<128;i++){ buf[937]=(byte)i; if(sha1_32(buf)==-1989208016){break;} }
for(i=-96;i<-76;i++){ buf[938]=(byte)i; if(sha1_32(buf)==-656905687){break;} }
for(i=99;i<123;i++){ buf[939]=(byte)i; if(sha1_32(buf)==-1261809862){break;} }
for(i=90;i<107;i++){ buf[940]=(byte)i; if(sha1_32(buf)==-165655371){break;} }
for(i=27;i<48;i++){ buf[941]=(byte)i; if(sha1_32(buf)==-383503691){break;} }
for(i=75;i<93;i++){ buf[942]=(byte)i; if(sha1_32(buf)==-1513953178){break;} }
for(i=87;i<117;i++){ buf[943]=(byte)i; if(sha1_32(buf)==-2018596118){break;} }
for(i=-32;i<-19;i++){ buf[944]=(byte)i; if(sha1_32(buf)==1193492057){break;} }
for(i=32;i<41;i++){ buf[945]=(byte)i; if(sha1_32(buf)==1953027839){break;} }
for(i=-28;i<-23;i++){ buf[946]=(byte)i; if(sha1_32(buf)==2047028226){break;} }
for(i=105;i<118;i++){ buf[947]=(byte)i; if(sha1_32(buf)==-516369465){break;} }
for(i=-92;i<-79;i++){ buf[948]=(byte)i; if(sha1_32(buf)==-1550196458){break;} }
for(i=-95;i<-67;i++){ buf[949]=(byte)i; if(sha1_32(buf)==-44900694){break;} }
for(i=-118;i<-88;i++){ buf[950]=(byte)i; if(sha1_32(buf)==2066872012){break;} }
for(i=-123;i<-106;i++){ buf[951]=(byte)i; if(sha1_32(buf)==-452225466){break;} }
for(i=59;i<82;i++){ buf[952]=(byte)i; if(sha1_32(buf)==1056918255){break;} }
for(i=91;i<119;i++){ buf[953]=(byte)i; if(sha1_32(buf)==-1143176782){break;} }
for(i=110;i<128;i++){ buf[954]=(byte)i; if(sha1_32(buf)==2124328802){break;} }
for(i=81;i<97;i++){ buf[955]=(byte)i; if(sha1_32(buf)==1188653234){break;} }
for(i=25;i<44;i++){ buf[956]=(byte)i; if(sha1_32(buf)==-1913568312){break;} }
for(i=14;i<27;i++){ buf[957]=(byte)i; if(sha1_32(buf)==848183263){break;} }
for(i=-9;i<21;i++){ buf[958]=(byte)i; if(sha1_32(buf)==1777354223){break;} }
for(i=-27;i<-14;i++){ buf[959]=(byte)i; if(sha1_32(buf)==1115798659){break;} }
for(i=9;i<30;i++){ buf[960]=(byte)i; if(sha1_32(buf)==-1875678462){break;} }
for(i=-67;i<-48;i++){ buf[961]=(byte)i; if(sha1_32(buf)==906017043){break;} }
for(i=-113;i<-90;i++){ buf[962]=(byte)i; if(sha1_32(buf)==-834468664){break;} }
for(i=71;i<89;i++){ buf[963]=(byte)i; if(sha1_32(buf)==262611064){break;} }
for(i=2;i<17;i++){ buf[964]=(byte)i; if(sha1_32(buf)==-492744027){break;} }
for(i=-15;i<4;i++){ buf[965]=(byte)i; if(sha1_32(buf)==1414241541){break;} }
for(i=-65;i<-59;i++){ buf[966]=(byte)i; if(sha1_32(buf)==773293741){break;} }
for(i=-12;i<9;i++){ buf[967]=(byte)i; if(sha1_32(buf)==-992919704){break;} }
for(i=-44;i<-23;i++){ buf[968]=(byte)i; if(sha1_32(buf)==1716115756){break;} }
for(i=-128;i<-115;i++){ buf[969]=(byte)i; if(sha1_32(buf)==-716707560){break;} }
for(i=-115;i<-94;i++){ buf[970]=(byte)i; if(sha1_32(buf)==1372961574){break;} }
for(i=-24;i<-14;i++){ buf[971]=(byte)i; if(sha1_32(buf)==742534534){break;} }
for(i=4;i<20;i++){ buf[972]=(byte)i; if(sha1_32(buf)==2004129999){break;} }
for(i=-108;i<-93;i++){ buf[973]=(byte)i; if(sha1_32(buf)==877174527){break;} }
for(i=73;i<81;i++){ buf[974]=(byte)i; if(sha1_32(buf)==1322952214){break;} }
for(i=34;i<45;i++){ buf[975]=(byte)i; if(sha1_32(buf)==1766518555){break;} }
for(i=-93;i<-73;i++){ buf[976]=(byte)i; if(sha1_32(buf)==-237276488){break;} }
for(i=-115;i<-101;i++){ buf[977]=(byte)i; if(sha1_32(buf)==-1516859372){break;} }
for(i=-87;i<-76;i++){ buf[978]=(byte)i; if(sha1_32(buf)==459739408){break;} }
for(i=41;i<52;i++){ buf[979]=(byte)i; if(sha1_32(buf)==-1454030461){break;} }
for(i=-63;i<-41;i++){ buf[980]=(byte)i; if(sha1_32(buf)==559467964){break;} }
for(i=105;i<120;i++){ buf[981]=(byte)i; if(sha1_32(buf)==-1242941105){break;} }
for(i=-6;i<21;i++){ buf[982]=(byte)i; if(sha1_32(buf)==221599753){break;} }
for(i=-113;i<-94;i++){ buf[983]=(byte)i; if(sha1_32(buf)==-1449470264){break;} }
for(i=-93;i<-77;i++){ buf[984]=(byte)i; if(sha1_32(buf)==930972586){break;} }
for(i=82;i<101;i++){ buf[985]=(byte)i; if(sha1_32(buf)==1698272601){break;} }
for(i=-46;i<-29;i++){ buf[986]=(byte)i; if(sha1_32(buf)==1422413259){break;} }
for(i=1;i<21;i++){ buf[987]=(byte)i; if(sha1_32(buf)==-1443511892){break;} }
for(i=-83;i<-67;i++){ buf[988]=(byte)i; if(sha1_32(buf)==-1700350663){break;} }
for(i=-87;i<-65;i++){ buf[989]=(byte)i; if(sha1_32(buf)==1153143491){break;} }
for(i=90;i<114;i++){ buf[990]=(byte)i; if(sha1_32(buf)==1636780856){break;} }
for(i=93;i<105;i++){ buf[991]=(byte)i; if(sha1_32(buf)==-1269432350){break;} }
for(i=53;i<60;i++){ buf[992]=(byte)i; if(sha1_32(buf)==1036744305){break;} }
for(i=-5;i<7;i++){ buf[993]=(byte)i; if(sha1_32(buf)==575531645){break;} }
for(i=-32;i<-23;i++){ buf[994]=(byte)i; if(sha1_32(buf)==-1886308494){break;} }
for(i=93;i<102;i++){ buf[995]=(byte)i; if(sha1_32(buf)==2110681539){break;} }
for(i=35;i<42;i++){ buf[996]=(byte)i; if(sha1_32(buf)==-1949353261){break;} }
for(i=-118;i<-106;i++){ buf[997]=(byte)i; if(sha1_32(buf)==-263831306){break;} }
for(i=-119;i<-93;i++){ buf[998]=(byte)i; if(sha1_32(buf)==-1099360581){break;} }
for(i=-2;i<13;i++){ buf[999]=(byte)i; if(sha1_32(buf)==-1362504430){break;} }
for(i=100;i<103;i++){ buf[1000]=(byte)i; if(sha1_32(buf)==-1257691832){break;} }
for(i=-42;i<-31;i++){ buf[1001]=(byte)i; if(sha1_32(buf)==-2002029958){break;} }
for(i=69;i<71;i++){ buf[1002]=(byte)i; if(sha1_32(buf)==-1286241597){break;} }
for(i=122;i<128;i++){ buf[1003]=(byte)i; if(sha1_32(buf)==2103217191){break;} }
for(i=40;i<51;i++){ buf[1004]=(byte)i; if(sha1_32(buf)==1065320944){break;} }
for(i=-128;i<-120;i++){ buf[1005]=(byte)i; if(sha1_32(buf)==-821522776){break;} }
for(i=-25;i<-9;i++){ buf[1006]=(byte)i; if(sha1_32(buf)==-417993319){break;} }
for(i=-111;i<-108;i++){ buf[1007]=(byte)i; if(sha1_32(buf)==-1298036252){break;} }
for(i=-35;i<-23;i++){ buf[1008]=(byte)i; if(sha1_32(buf)==1774996689){break;} }
for(i=-1;i<15;i++){ buf[1009]=(byte)i; if(sha1_32(buf)==1201478341){break;} }
for(i=64;i<82;i++){ buf[1010]=(byte)i; if(sha1_32(buf)==821258089){break;} }
for(i=-7;i<5;i++){ buf[1011]=(byte)i; if(sha1_32(buf)==821258089){break;} }
for(i=3;i<21;i++){ buf[1012]=(byte)i; if(sha1_32(buf)==-202308924){break;} }
for(i=-100;i<-80;i++){ buf[1013]=(byte)i; if(sha1_32(buf)==-594496430){break;} }
for(i=10;i<37;i++){ buf[1014]=(byte)i; if(sha1_32(buf)==-885022447){break;} }
for(i=-18;i<5;i++){ buf[1015]=(byte)i; if(sha1_32(buf)==-151956883){break;} }
for(i=-48;i<-31;i++){ buf[1016]=(byte)i; if(sha1_32(buf)==1357924214){break;} }
for(i=15;i<23;i++){ buf[1017]=(byte)i; if(sha1_32(buf)==-1598640548){break;} }
for(i=40;i<60;i++){ buf[1018]=(byte)i; if(sha1_32(buf)==1636996827){break;} }
for(i=78;i<97;i++){ buf[1019]=(byte)i; if(sha1_32(buf)==-681343121){break;} }
for(i=22;i<41;i++){ buf[1020]=(byte)i; if(sha1_32(buf)==-249538630){break;} }
for(i=42;i<52;i++){ buf[1021]=(byte)i; if(sha1_32(buf)==1265057560){break;} }
for(i=9;i<31;i++){ buf[1022]=(byte)i; if(sha1_32(buf)==-1905770904){break;} }
for(i=-73;i<-68;i++){ buf[1023]=(byte)i; if(sha1_32(buf)==2042794182){break;} }
for(i=20;i<45;i++){ buf[1024]=(byte)i; if(sha1_32(buf)==-140836972){break;} }
for(i=-4;i<10;i++){ buf[1025]=(byte)i; if(sha1_32(buf)==548709754){break;} }
for(i=81;i<90;i++){ buf[1026]=(byte)i; if(sha1_32(buf)==843328795){break;} }
for(i=119;i<121;i++){ buf[1027]=(byte)i; if(sha1_32(buf)==-830558953){break;} }
for(i=-125;i<-118;i++){ buf[1028]=(byte)i; if(sha1_32(buf)==1883825255){break;} }
for(i=41;i<63;i++){ buf[1029]=(byte)i; if(sha1_32(buf)==-1854044825){break;} }
for(i=106;i<115;i++){ buf[1030]=(byte)i; if(sha1_32(buf)==577198552){break;} }
for(i=92;i<97;i++){ buf[1031]=(byte)i; if(sha1_32(buf)==-1031445519){break;} }
for(i=-43;i<-30;i++){ buf[1032]=(byte)i; if(sha1_32(buf)==-1522769751){break;} }
for(i=-24;i<-12;i++){ buf[1033]=(byte)i; if(sha1_32(buf)==2114592705){break;} }
for(i=99;i<108;i++){ buf[1034]=(byte)i; if(sha1_32(buf)==-89748567){break;} }
for(i=54;i<78;i++){ buf[1035]=(byte)i; if(sha1_32(buf)==-1566644466){break;} }
for(i=81;i<94;i++){ buf[1036]=(byte)i; if(sha1_32(buf)==1258925208){break;} }
for(i=-24;i<-16;i++){ buf[1037]=(byte)i; if(sha1_32(buf)==-1786505716){break;} }
for(i=-31;i<-30;i++){ buf[1038]=(byte)i; if(sha1_32(buf)==-653163048){break;} }
for(i=-128;i<-120;i++){ buf[1039]=(byte)i; if(sha1_32(buf)==-1581345541){break;} }
for(i=125;i<128;i++){ buf[1040]=(byte)i; if(sha1_32(buf)==597193248){break;} }
for(i=-60;i<-31;i++){ buf[1041]=(byte)i; if(sha1_32(buf)==614975119){break;} }
for(i=80;i<96;i++){ buf[1042]=(byte)i; if(sha1_32(buf)==-2142960585){break;} }
for(i=-110;i<-96;i++){ buf[1043]=(byte)i; if(sha1_32(buf)==1308456481){break;} }
for(i=116;i<128;i++){ buf[1044]=(byte)i; if(sha1_32(buf)==-731224412){break;} }
for(i=-113;i<-108;i++){ buf[1045]=(byte)i; if(sha1_32(buf)==2019213489){break;} }
for(i=37;i<46;i++){ buf[1046]=(byte)i; if(sha1_32(buf)==1363257339){break;} }
for(i=-41;i<-30;i++){ buf[1047]=(byte)i; if(sha1_32(buf)==663011465){break;} }
for(i=-63;i<-61;i++){ buf[1048]=(byte)i; if(sha1_32(buf)==577182518){break;} }
for(i=-125;i<-113;i++){ buf[1049]=(byte)i; if(sha1_32(buf)==-1532921600){break;} }
for(i=71;i<78;i++){ buf[1050]=(byte)i; if(sha1_32(buf)==-591701488){break;} }
for(i=89;i<105;i++){ buf[1051]=(byte)i; if(sha1_32(buf)==835671068){break;} }
for(i=-79;i<-74;i++){ buf[1052]=(byte)i; if(sha1_32(buf)==1792144516){break;} }
for(i=-122;i<-103;i++){ buf[1053]=(byte)i; if(sha1_32(buf)==-1813644621){break;} }
for(i=108;i<128;i++){ buf[1054]=(byte)i; if(sha1_32(buf)==1546877554){break;} }
for(i=-102;i<-78;i++){ buf[1055]=(byte)i; if(sha1_32(buf)==-1196496685){break;} }
for(i=-80;i<-65;i++){ buf[1056]=(byte)i; if(sha1_32(buf)==1077956670){break;} }
for(i=-53;i<-38;i++){ buf[1057]=(byte)i; if(sha1_32(buf)==26090437){break;} }
for(i=97;i<107;i++){ buf[1058]=(byte)i; if(sha1_32(buf)==-1077854056){break;} }
for(i=-2;i<5;i++){ buf[1059]=(byte)i; if(sha1_32(buf)==969075253){break;} }
for(i=48;i<55;i++){ buf[1060]=(byte)i; if(sha1_32(buf)==1679336485){break;} }
for(i=109;i<113;i++){ buf[1061]=(byte)i; if(sha1_32(buf)==607349655){break;} }
for(i=23;i<51;i++){ buf[1062]=(byte)i; if(sha1_32(buf)==-485439258){break;} }
for(i=39;i<55;i++){ buf[1063]=(byte)i; if(sha1_32(buf)==-1343430795){break;} }
for(i=32;i<50;i++){ buf[1064]=(byte)i; if(sha1_32(buf)==225856432){break;} }
for(i=10;i<28;i++){ buf[1065]=(byte)i; if(sha1_32(buf)==1208661350){break;} }
for(i=-54;i<-28;i++){ buf[1066]=(byte)i; if(sha1_32(buf)==968901244){break;} }
for(i=53;i<65;i++){ buf[1067]=(byte)i; if(sha1_32(buf)==-697955559){break;} }
for(i=-95;i<-82;i++){ buf[1068]=(byte)i; if(sha1_32(buf)==-1974630861){break;} }
for(i=21;i<41;i++){ buf[1069]=(byte)i; if(sha1_32(buf)==898533417){break;} }
for(i=74;i<89;i++){ buf[1070]=(byte)i; if(sha1_32(buf)==295037278){break;} }
for(i=65;i<91;i++){ buf[1071]=(byte)i; if(sha1_32(buf)==278687653){break;} }
for(i=5;i<21;i++){ buf[1072]=(byte)i; if(sha1_32(buf)==-1272541154){break;} }
for(i=101;i<125;i++){ buf[1073]=(byte)i; if(sha1_32(buf)==1324109431){break;} }
for(i=-25;i<-5;i++){ buf[1074]=(byte)i; if(sha1_32(buf)==-1361495218){break;} }
for(i=-100;i<-84;i++){ buf[1075]=(byte)i; if(sha1_32(buf)==-2024684934){break;} }
for(i=-76;i<-59;i++){ buf[1076]=(byte)i; if(sha1_32(buf)==944912955){break;} }
for(i=45;i<50;i++){ buf[1077]=(byte)i; if(sha1_32(buf)==1005433486){break;} }
for(i=-52;i<-32;i++){ buf[1078]=(byte)i; if(sha1_32(buf)==-458047093){break;} }
for(i=-84;i<-68;i++){ buf[1079]=(byte)i; if(sha1_32(buf)==490986449){break;} }
for(i=19;i<28;i++){ buf[1080]=(byte)i; if(sha1_32(buf)==-1022548088){break;} }
for(i=35;i<52;i++){ buf[1081]=(byte)i; if(sha1_32(buf)==-369130635){break;} }
for(i=-100;i<-90;i++){ buf[1082]=(byte)i; if(sha1_32(buf)==1934617642){break;} }
for(i=95;i<103;i++){ buf[1083]=(byte)i; if(sha1_32(buf)==-1213791714){break;} }
for(i=54;i<59;i++){ buf[1084]=(byte)i; if(sha1_32(buf)==625340672){break;} }
for(i=17;i<40;i++){ buf[1085]=(byte)i; if(sha1_32(buf)==1555461739){break;} }
for(i=53;i<71;i++){ buf[1086]=(byte)i; if(sha1_32(buf)==-1886344022){break;} }
for(i=26;i<35;i++){ buf[1087]=(byte)i; if(sha1_32(buf)==1358628428){break;} }
for(i=-36;i<-18;i++){ buf[1088]=(byte)i; if(sha1_32(buf)==1972639341){break;} }
for(i=-23;i<-5;i++){ buf[1089]=(byte)i; if(sha1_32(buf)==334862035){break;} }
for(i=-104;i<-81;i++){ buf[1090]=(byte)i; if(sha1_32(buf)==-473872236){break;} }
for(i=-127;i<-100;i++){ buf[1091]=(byte)i; if(sha1_32(buf)==-23319558){break;} }
for(i=74;i<94;i++){ buf[1092]=(byte)i; if(sha1_32(buf)==-64398834){break;} }
for(i=14;i<33;i++){ buf[1093]=(byte)i; if(sha1_32(buf)==906115816){break;} }
for(i=-25;i<-9;i++){ buf[1094]=(byte)i; if(sha1_32(buf)==1805063901){break;} }
for(i=-50;i<-45;i++){ buf[1095]=(byte)i; if(sha1_32(buf)==1017361141){break;} }
for(i=-4;i<10;i++){ buf[1096]=(byte)i; if(sha1_32(buf)==908217016){break;} }
for(i=-23;i<0;i++){ buf[1097]=(byte)i; if(sha1_32(buf)==874218066){break;} }
for(i=-38;i<-19;i++){ buf[1098]=(byte)i; if(sha1_32(buf)==-131550062){break;} }
for(i=101;i<120;i++){ buf[1099]=(byte)i; if(sha1_32(buf)==1781819003){break;} }
for(i=68;i<85;i++){ buf[1100]=(byte)i; if(sha1_32(buf)==313762538){break;} }
for(i=35;i<50;i++){ buf[1101]=(byte)i; if(sha1_32(buf)==-800801991){break;} }
for(i=-40;i<-30;i++){ buf[1102]=(byte)i; if(sha1_32(buf)==-1278599340){break;} }
for(i=72;i<83;i++){ buf[1103]=(byte)i; if(sha1_32(buf)==-4878209){break;} }
for(i=85;i<109;i++){ buf[1104]=(byte)i; if(sha1_32(buf)==1853519571){break;} }
for(i=78;i<103;i++){ buf[1105]=(byte)i; if(sha1_32(buf)==-1196149222){break;} }
for(i=29;i<32;i++){ buf[1106]=(byte)i; if(sha1_32(buf)==-379896512){break;} }
for(i=86;i<102;i++){ buf[1107]=(byte)i; if(sha1_32(buf)==-832014274){break;} }
for(i=-64;i<-60;i++){ buf[1108]=(byte)i; if(sha1_32(buf)==-431146182){break;} }
for(i=-37;i<-16;i++){ buf[1109]=(byte)i; if(sha1_32(buf)==-1337981186){break;} }
for(i=102;i<118;i++){ buf[1110]=(byte)i; if(sha1_32(buf)==-2069303324){break;} }
for(i=-36;i<-12;i++){ buf[1111]=(byte)i; if(sha1_32(buf)==1954296779){break;} }
for(i=29;i<34;i++){ buf[1112]=(byte)i; if(sha1_32(buf)==1086532361){break;} }
for(i=44;i<60;i++){ buf[1113]=(byte)i; if(sha1_32(buf)==-1202627653){break;} }
for(i=118;i<128;i++){ buf[1114]=(byte)i; if(sha1_32(buf)==-139693675){break;} }
for(i=53;i<71;i++){ buf[1115]=(byte)i; if(sha1_32(buf)==-204924087){break;} }
for(i=-71;i<-62;i++){ buf[1116]=(byte)i; if(sha1_32(buf)==1060822301){break;} }
for(i=-15;i<0;i++){ buf[1117]=(byte)i; if(sha1_32(buf)==-704466841){break;} }
for(i=94;i<110;i++){ buf[1118]=(byte)i; if(sha1_32(buf)==727524952){break;} }
for(i=-42;i<-17;i++){ buf[1119]=(byte)i; if(sha1_32(buf)==-199352270){break;} }
for(i=98;i<110;i++){ buf[1120]=(byte)i; if(sha1_32(buf)==-349188712){break;} }
for(i=101;i<113;i++){ buf[1121]=(byte)i; if(sha1_32(buf)==63772797){break;} }
for(i=66;i<86;i++){ buf[1122]=(byte)i; if(sha1_32(buf)==-2055479209){break;} }
for(i=-100;i<-83;i++){ buf[1123]=(byte)i; if(sha1_32(buf)==221768916){break;} }
for(i=47;i<60;i++){ buf[1124]=(byte)i; if(sha1_32(buf)==-1582663946){break;} }
for(i=9;i<18;i++){ buf[1125]=(byte)i; if(sha1_32(buf)==61408104){break;} }
for(i=-73;i<-65;i++){ buf[1126]=(byte)i; if(sha1_32(buf)==1725241599){break;} }
for(i=-56;i<-38;i++){ buf[1127]=(byte)i; if(sha1_32(buf)==-1220109877){break;} }
for(i=-100;i<-83;i++){ buf[1128]=(byte)i; if(sha1_32(buf)==-236264979){break;} }
for(i=87;i<104;i++){ buf[1129]=(byte)i; if(sha1_32(buf)==-2054909783){break;} }
for(i=20;i<31;i++){ buf[1130]=(byte)i; if(sha1_32(buf)==-42923554){break;} }
for(i=34;i<52;i++){ buf[1131]=(byte)i; if(sha1_32(buf)==92290212){break;} }
for(i=0;i<16;i++){ buf[1132]=(byte)i; if(sha1_32(buf)==670075057){break;} }
for(i=17;i<28;i++){ buf[1133]=(byte)i; if(sha1_32(buf)==1959628169){break;} }
for(i=-16;i<2;i++){ buf[1134]=(byte)i; if(sha1_32(buf)==458377618){break;} }
for(i=106;i<123;i++){ buf[1135]=(byte)i; if(sha1_32(buf)==2062634645){break;} }
for(i=-128;i<-112;i++){ buf[1136]=(byte)i; if(sha1_32(buf)==-2108473398){break;} }
for(i=68;i<89;i++){ buf[1137]=(byte)i; if(sha1_32(buf)==-100282352){break;} }
for(i=-84;i<-66;i++){ buf[1138]=(byte)i; if(sha1_32(buf)==1818675631){break;} }
for(i=96;i<107;i++){ buf[1139]=(byte)i; if(sha1_32(buf)==2020691441){break;} }
for(i=4;i<21;i++){ buf[1140]=(byte)i; if(sha1_32(buf)==-2111841858){break;} }
for(i=121;i<128;i++){ buf[1141]=(byte)i; if(sha1_32(buf)==-701785220){break;} }
for(i=14;i<29;i++){ buf[1142]=(byte)i; if(sha1_32(buf)==-755904574){break;} }
for(i=66;i<80;i++){ buf[1143]=(byte)i; if(sha1_32(buf)==1588506176){break;} }
for(i=-11;i<-1;i++){ buf[1144]=(byte)i; if(sha1_32(buf)==1035634929){break;} }
for(i=26;i<43;i++){ buf[1145]=(byte)i; if(sha1_32(buf)==-608563770){break;} }
for(i=109;i<128;i++){ buf[1146]=(byte)i; if(sha1_32(buf)==575667257){break;} }
for(i=101;i<115;i++){ buf[1147]=(byte)i; if(sha1_32(buf)==1428637178){break;} }
for(i=-85;i<-78;i++){ buf[1148]=(byte)i; if(sha1_32(buf)==1831647207){break;} }
for(i=-17;i<11;i++){ buf[1149]=(byte)i; if(sha1_32(buf)==-568966982){break;} }
for(i=53;i<62;i++){ buf[1150]=(byte)i; if(sha1_32(buf)==-107779253){break;} }
for(i=-83;i<-74;i++){ buf[1151]=(byte)i; if(sha1_32(buf)==-1730259211){break;} }
for(i=-107;i<-83;i++){ buf[1152]=(byte)i; if(sha1_32(buf)==-406954439){break;} }
for(i=20;i<22;i++){ buf[1153]=(byte)i; if(sha1_32(buf)==-825121001){break;} }
for(i=24;i<45;i++){ buf[1154]=(byte)i; if(sha1_32(buf)==-90478088){break;} }
for(i=35;i<59;i++){ buf[1155]=(byte)i; if(sha1_32(buf)==-1901228050){break;} }
for(i=-100;i<-90;i++){ buf[1156]=(byte)i; if(sha1_32(buf)==109563348){break;} }
for(i=110;i<126;i++){ buf[1157]=(byte)i; if(sha1_32(buf)==1557366062){break;} }
return buf;
}
}
|
domdomegg/tabula | web/src/main/scala/uk/ac/warwick/tabula/web/controllers/mitcircs/MitCircsViewController.scala | package uk.ac.warwick.tabula.web.controllers.mitcircs
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{ModelAttribute, PathVariable, RequestMapping}
import uk.ac.warwick.tabula.commands.mitcircs.StudentViewMitCircsSubmissionCommand
import uk.ac.warwick.tabula.data.model.StudentMember
import uk.ac.warwick.tabula.data.model.mitcircs.MitigatingCircumstancesSubmission
import uk.ac.warwick.tabula.web.Mav
import uk.ac.warwick.tabula.web.controllers.profiles.ProfileBreadcrumbs
import uk.ac.warwick.tabula.web.controllers.profiles.profile.AbstractViewProfileController
@Controller
@RequestMapping(Array("/profiles/view/{student}/personalcircs/mitcircs/view/{submission}"))
class MitCircsViewController extends AbstractViewProfileController {
@ModelAttribute("command")
def getCommand(
@PathVariable student: StudentMember,
@PathVariable submission: MitigatingCircumstancesSubmission
): StudentViewMitCircsSubmissionCommand.Command = {
mustBeLinked(submission, student)
StudentViewMitCircsSubmissionCommand(submission)
}
@RequestMapping
def render(@ModelAttribute("command") cmd: StudentViewMitCircsSubmissionCommand.Command, @PathVariable submission: MitigatingCircumstancesSubmission): Mav = {
Mav("mitcircs/view",
"submission" -> cmd.apply(),
"isSelf" -> user.universityId.maybeText.contains(submission.student.universityId)
).crumbs(breadcrumbsStudent(activeAcademicYear, submission.student.mostSignificantCourse, ProfileBreadcrumbs.Profile.PersonalCircumstances): _*)
}
}
|
ggilchrist-ledger/ledger-live-desktop | src/renderer/screens/exchange/swap/Form/AnimatedArrows.js | // @flow
import React, { useState } from "react";
import Animation from "~/renderer/animations";
import type { ThemedComponent } from "~/renderer/styles/StyleProvider";
import swapAnim from "~/renderer/animations/swap.json";
import styled from "styled-components";
const Container: ThemedComponent<{}> = styled.div`
width: ${p => p.size + 12}px;
height: ${p => p.size + 12}px;
padding: 4px;
& path {
stroke: ${p =>
!p.disabled ? p.theme.colors.palette.primary.main : p.theme.colors.palette.text.shade30};
fill: ${p =>
!p.disabled ? p.theme.colors.palette.primary.main : p.theme.colors.palette.text.shade30};
}
`;
const AnimatedArrows = ({ size = 16, disabled = false }: { size: number, disabled: boolean }) => {
const [nonce, setNonce] = useState(0);
return (
<Container
disabled={disabled}
onClick={() => {
if (!disabled) setNonce(nonce + 1);
}}
size={size}
>
<Animation
key={`swap-arrows-${nonce}`}
isStopped={!nonce}
animation={swapAnim}
loop={false}
size={size}
/>
</Container>
);
};
export default AnimatedArrows;
|
best08618/asylo | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/tree-ssa/pr22026.c | /* PR tree-optimization/22026
VRP used think that ~[0,0] + ~[0,0] = ~[0,0], which is wrong. The
same applies to subtraction and unsigned multiplication. */
/* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-vrp1" } */
int
plus (int x, int y)
{
if (x != 0)
if (y != 0)
{
int z = x + y;
if (z != 0)
return 1;
}
return 0;
}
int
minus (int x, int y)
{
if (x != 0)
if (y != 0)
{
int z = x - y;
if (z != 0)
return 1;
}
return 0;
}
int
mult (unsigned x, unsigned y)
{
if (x != 0)
if (y != 0)
{
unsigned z = x * y;
if (z != 0)
return 1;
}
return 0;
}
/* None of the predicates can be folded in these functions. */
/* { dg-final { scan-tree-dump-times "Folding predicate" 0 "vrp1" } } */
|
ivenpoker/Python-Projects | Projects/Online Workouts/w3resource/Basic - Part-I/program-138.py | <filename>Projects/Online Workouts/w3resource/Basic - Part-I/program-138.py
#!/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Program to convert true to 1 and false to 0. #
# Program Author : <NAME> <<EMAIL>> #
# Creation Date : September 3, 2019 #
# #
#######################################################################################
if __name__ == '__main__':
x = 'true'
x = int(x == 'true')
print(f"Value of x: {x}")
x = 'abcd'
x = int(x == 'true')
print(f"Value of x: {x}")
|
segmentio/netx | ip.go | <reponame>segmentio/netx<filename>ip.go
package netx
import "net"
// IsIP checks if s is a valid representation of an IPv4 or IPv6 address.
func IsIP(s string) bool {
return net.ParseIP(s) != nil
}
// IsIPv4 checks if s is a valid representation of an IPv4 address.
func IsIPv4(s string) bool {
ip := net.ParseIP(s)
return ip != nil && ip.To4() != nil
}
// IsIPv6 checks if s is a valid representation of an IPv6 address.
func IsIPv6(s string) bool {
ip := net.ParseIP(s)
return ip != nil && ip.To4() == nil
}
|
smhc/openapi4j | openapi-operation-validator/src/test/java/org/openapi4j/operation/validator/validation/RequestValidatorTest.java | package org.openapi4j.operation.validator.validation;
import org.junit.Test;
import org.openapi4j.core.exception.ResolutionException;
import org.openapi4j.core.validation.ValidationException;
import org.openapi4j.operation.validator.model.Request;
import org.openapi4j.operation.validator.model.impl.DefaultRequest;
import org.openapi4j.parser.OpenApi3Parser;
import org.openapi4j.parser.model.v3.OpenApi3;
import java.net.URL;
import static org.junit.Assert.fail;
import static org.openapi4j.operation.validator.model.Request.Method.GET;
import static org.openapi4j.operation.validator.model.Request.Method.POST;
public class RequestValidatorTest {
@Test
public void withoutServerPathFindOperationCheck() throws ResolutionException, ValidationException {
URL specPath = RequestValidatorTest.class.getResource("/request/requestValidator.yaml");
OpenApi3 api = new OpenApi3Parser().parse(specPath, false);
RequestValidator requestValidator = new RequestValidator(api);
check(
requestValidator,
new DefaultRequest.Builder("https://api.com/fixed/1/fixed/2/fixed/", GET).build(),
true);
check(
requestValidator,
new DefaultRequest.Builder("https://api.com/fixed/string/fixed/2/fixed/", GET).build(),
false);
// wrong path, parameters are not bound
check(
requestValidator,
new DefaultRequest.Builder("https://api.com/fixed/fixed/2/fixed/", GET).build(),
false);
// Empty string is still valid
check(
requestValidator,
new DefaultRequest.Builder("https://api.com/fixed/1/fixed//fixed/", GET).build(),
true);
}
@Test
public void withServerPathFindOperationCheck() throws ResolutionException, ValidationException {
URL specPath = RequestValidatorTest.class.getResource("/request/requestValidator-with-servers.yaml");
OpenApi3 api = new OpenApi3Parser().parse(specPath, false);
RequestValidator requestValidator = new RequestValidator(api);
// absolute url
check(
requestValidator,
new DefaultRequest.Builder("https://api.com/fixed/1/fixed/2/fixed/", GET).build(),
true);
check(
requestValidator,
new DefaultRequest.Builder("https://api.com/v1/fixed/1/fixed/2/fixed/", GET).build(),
true);
// relative (value = file:/2, so we serve from file:/.../openapi4j/openapi-operation-validator/build/resources/test/request/requestValidator-with-servers.yaml)
check(
requestValidator,
new DefaultRequest.Builder("file:/v2/fixed/1/fixed/2/fixed/", GET).build(),
true);
check(
requestValidator,
new DefaultRequest.Builder("file:/v2/bar/fixed/1/fixed/2/fixed/", GET).build(),
true);
// with path parameter
check(
requestValidator,
new DefaultRequest.Builder("https://foo.api.com/bar/fixed/1/fixed/2/fixed/", GET).build(),
true);
check(
requestValidator,
new DefaultRequest.Builder("https://foo.api.com/bar/fixed/", POST).header("Content-Type", "application/json").build(),
true);
}
private void check(RequestValidator requestValidator, Request rq, boolean shouldBeValid) {
try {
requestValidator.validate(rq);
} catch (ValidationException e) {
System.out.println(e.toString());
if (shouldBeValid) {
fail();
}
}
}
}
|
opetstudio/mypos | src/Containers/Gallery/api.js | <filename>src/Containers/Gallery/api.js
// a library to wrap and simplify api calls
import AppConfig from '../../Config/AppConfig'
export const create = (api) => ({
postGallery: (data, opt) => {
api.setHeader(AppConfig.authHeader, opt.session.token_type + ' ' + opt.session.access_token)
return api.post('/gallerys', data)
},
getGallery: (data, opt) => {
api.setHeader(AppConfig.authHeader, opt.session.token_type + ' ' + opt.session.access_token)
return api.get('/gallerys/' + data.id)
},
getGallerys: (data, opt) => {
// console.log('gallery.api.getGallerys===>>>>')
let { apiName, baseUrl, newerModifiedon } = data
// if (!opt.session.token) return {}
if (baseUrl) api.setBaseURL(baseUrl)
api.setHeader(AppConfig.authHeader, opt.session.token_type + ' ' + opt.session.access_token)
return api.get(apiName || '/gallerys', { newerModifiedon }, data)
},
updateGallery: (data, id, opt) => {
console.log('hit api updateGallery', data)
api.setHeader(AppConfig.authHeader, opt.session.token_type + ' ' + opt.session.access_token)
return api.patch('/gallerys/' + id, data)
},
updateGalleryBatch: (data, opt) => {
console.log('hit api updateGalleryBatch', data)
api.setHeader(AppConfig.authHeader, opt.session.token_type + ' ' + opt.session.access_token)
return api.post('/gallerys-update-batch', data)
},
removeGallery: (data, id, opt) => {
api.setHeader(AppConfig.authHeader, opt.session.token_type + ' ' + opt.session.access_token)
return api.delete('/gallerys/' + id, data)
}
})
|
TravisCannon/panamax-api | spec/serializers/job_lite_serializer_spec.rb | require 'spec_helper'
describe JobLiteSerializer do
fixtures :jobs, :job_templates
it 'exposes the attributes to be jsonified' do
serialized = described_class.new(jobs(:cluster_job)).as_json
expected_keys = [:name, :environment, :steps]
expect(serialized.keys).to match_array expected_keys
end
it 'retreives the name from the job template serialized' do
serialized = described_class.new(jobs(:cluster_job))
expect(serialized.name).to eq jobs(:cluster_job).job_template.name
end
context 'when serializing job environment variables' do
let(:new_env_var) { { 'variable' => 'foo', 'value' => 8080 } }
it 'stringifies the job environment variable values' do
some_job = jobs(:cluster_job)
some_job.environment << new_env_var
serialized = described_class.new(some_job)
expect(serialized.environment.first['value']).to eq '8080'
end
end
end
|
lol768/tabula | common/src/main/scala/uk/ac/warwick/tabula/web/controllers/BaseController.scala | package uk.ac.warwick.tabula.web.controllers
import java.net.URI
import javax.annotation.Resource
import org.springframework.beans.factory.annotation.{Autowired, Required}
import org.springframework.context.MessageSource
import org.springframework.stereotype.Controller
import org.springframework.validation.Validator
import org.springframework.web.bind.WebDataBinder
import org.springframework.web.bind.annotation.InitBinder
import uk.ac.warwick.sso.client.SSOConfiguration
import uk.ac.warwick.sso.client.tags.SSOLoginLinkGenerator
import uk.ac.warwick.tabula.data.Daoisms
import uk.ac.warwick.tabula.events.EventHandling
import uk.ac.warwick.tabula.helpers.{Logging, StringUtils}
import uk.ac.warwick.tabula.helpers.StringUtils._
import uk.ac.warwick.tabula.services.SecurityService
import uk.ac.warwick.tabula.system.permissions.{PermissionsChecking, PermissionsCheckingMethods}
import uk.ac.warwick.tabula.validators.CompositeValidator
import uk.ac.warwick.tabula.web.Mav
import uk.ac.warwick.tabula.{CurrentUser, ItemNotFoundException, PermissionDeniedException, RequestInfo}
import scala.util.Try
trait ControllerMethods extends PermissionsCheckingMethods with Logging {
def user: CurrentUser
var securityService: SecurityService
def restricted[A <: PermissionsChecking](something: => A): Option[A] =
try {
permittedByChecks(securityService, user, something)
Some(something)
} catch {
case _ @ (_ : ItemNotFoundException | _ : PermissionDeniedException)=> None
}
def restrictedBy[A <: PermissionsChecking](fn: => Boolean)(something: => A): Option[A] =
if (fn) restricted(something)
else Some(something)
}
trait ControllerViews extends Logging {
val Mav = uk.ac.warwick.tabula.web.Mav
def getReturnTo(defaultUrl: String): String = {
Try {
val uri = new URI(getReturnToUnescaped(defaultUrl))
implicit def nonEmpty(s: String): Option[String] = Option(s).filterNot(_ == "").filterNot(_ == null)
val qs: Option[String] = uri.getQuery
val path: Option[String] = uri.getRawPath
path.map(_ + qs.map("?" + _).getOrElse(""))
}.toOption.flatten.getOrElse("")
}
def getReturnToUnescaped(defaultUrl: String): String =
requestInfo.flatMap {
_.requestParameters.get("returnTo")
}.flatMap {
_.headOption
}.filter {
_.hasText
}.fold({
if (defaultUrl.isEmpty)
logger.warn("Empty defaultUrl when using returnTo")
defaultUrl
})(url =>
// Prevent returnTo rabbit hole by stripping other returnTos from the URL
url.replaceAll("[&?]returnTo=[^&]*", "")
)
def Redirect(path: String, objects: (String, _)*): Mav = Redirect(path, Map(objects: _*))
def Redirect(path: String, objects: Map[String, _]): Mav = Mav("redirect:" + validRedirectDestination(getReturnToUnescaped(path)), objects)
// Force the redirect regardless of returnTo
def RedirectForce(path: String, objects: (String, _)*): Mav = RedirectForce(path, Map(objects: _*))
def RedirectForce(path: String, objects: Map[String, _]): Mav = Mav("redirect:" + validRedirectDestination(path), objects)
private def validRedirectDestination(dest: String): String = Option(dest).filter(d => d.startsWith("/") || d.startsWith(s"${currentUri.getScheme}://${currentUri.getAuthority}/") || d == loginUrl).getOrElse("/")
def RedirectToSignin(target: String = loginUrl): Mav = Redirect(target)
private def currentUri = requestInfo.get.requestedUri
private def currentPath: String = currentUri.getPath
def loginUrl: String = {
val generator = new SSOLoginLinkGenerator
generator.setConfig(SSOConfiguration.getConfig)
generator.setTarget(currentUri.toString)
generator.getLoginUrl
}
def requestInfo: Option[RequestInfo]
}
trait ControllerImports {
import org.springframework.web.bind.annotation.RequestMethod
final val GET = RequestMethod.GET
final val PUT = RequestMethod.PUT
final val HEAD = RequestMethod.HEAD
final val POST = RequestMethod.POST
final val DELETE = RequestMethod.DELETE
type RequestMapping = org.springframework.web.bind.annotation.RequestMapping
}
trait PreRequestHandler {
def preRequest
}
trait MessageResolver {
/**
* Resolve a message from messages.properties. This is the same way that
* validation error codes are resolved.
*/
def getMessage(key: String, args: Object*): String
}
/**
* Useful traits for all controllers to have.
*/
@Controller
abstract class BaseController extends ControllerMethods
with ControllerViews
with ValidatesCommand
with Logging
with EventHandling
with Daoisms
with StringUtils
with ControllerImports
with PreRequestHandler
with MessageResolver {
@Required @Resource(name = "validator") var globalValidator: Validator = _
@Autowired
var securityService: SecurityService = _
@Autowired private var messageSource: MessageSource = _
/**
* Resolve a message from messages.properties. This is the same way that
* validation error codes are resolved.
*/
def getMessage(key: String, args: Object*): String = messageSource.getMessage(key, args.toArray, null)
var disallowedFields: List[String] = Nil
def requestInfo: Option[RequestInfo] = RequestInfo.fromThread
def user: CurrentUser = requestInfo.get.user
def ajax: Boolean = requestInfo.exists(_.ajax)
/**
* Enables the Hibernate filter for this session to exclude
* entities marked as deleted.
*/
private var _hideDeletedItems = false
def hideDeletedItems: Unit = { _hideDeletedItems = true }
def showDeletedItems: Unit = { _hideDeletedItems = false }
final def preRequest {
// if hideDeletedItems has been called, exclude all "deleted=1" items from Hib queries.
if (_hideDeletedItems) {
session.enableFilter("notDeleted")
}
onPreRequest
}
// Stub implementation that can be overridden for logic that goes before a request
def onPreRequest {}
/**
* Sets up @Valid validation.
* If "validator" has been set, it will be used. If "keepOriginalValidator" is true,
* it will be joined up with the default global validator (the one that does annotation based
* validation like @NotEmpty). Otherwise it's replaced.
*
* Sets up disallowedFields.
*/
@InitBinder final def _binding(binder: WebDataBinder): Unit = {
if (validator != null) {
if (keepOriginalValidator) {
val original = binder.getValidator
binder.setValidator(new CompositeValidator(validator, original))
} else {
binder.setValidator(validator)
}
}
binder.setDisallowedFields(disallowedFields: _*)
binding(binder, binder.getTarget)
}
/**
* Do any custom binding init by overriding this method.
*/
def binding[A](binder: WebDataBinder, target: A) {}
} |
mohistH/nanogui_from_dalerank | src/python/misc.cpp | #ifdef NANOGUI_PYTHON
#include "python.h"
DECLARE_WIDGET(ColorWheel);
DECLARE_WIDGET(ColorPicker);
DECLARE_WIDGET(Graph);
DECLARE_WIDGET(ImageView);
DECLARE_WIDGET(ImagePanel);
void register_misc(py::module &m) {
py::class_<ColorWheel, Widget, ref<ColorWheel>, PyColorWheel>(m, "ColorWheel", D(ColorWheel))
.def(py::init<Widget *>(), py::arg("parent"), D(ColorWheel, ColorWheel))
.def(py::init<Widget *, const Color &>(), py::arg("parent"), py::arg("Color"))
.def("color", &ColorWheel::color, D(ColorWheel, color))
.def("setColor", &ColorWheel::setColor, D(ColorWheel, setColor))
.def("callback", &ColorWheel::callback, D(ColorWheel, callback))
.def("setCallback", &ColorWheel::setCallback, D(ColorWheel, setCallback));
py::class_<ColorPicker, PopupButton, ref<ColorPicker>, PyColorPicker>(m, "ColorPicker", D(ColorPicker))
.def(py::init<Widget *>(), py::arg("parent"), D(ColorPicker, ColorPicker))
.def(py::init<Widget *, const Color &>(), py::arg("parent"), py::arg("Color"))
.def("color", &ColorPicker::color, D(ColorPicker, color))
.def("setColor", &ColorPicker::setColor, D(ColorPicker, setColor))
.def("callback", &ColorPicker::callback, D(ColorPicker, callback))
.def("setCallback", &ColorPicker::setCallback, D(ColorPicker, setCallback))
.def("finalCallback", &ColorPicker::finalCallback, D(ColorPicker, finalCallback))
.def("setFinalCallback", &ColorPicker::setFinalCallback, D(ColorPicker, setFinalCallback));
py::class_<Graph, Widget, ref<Graph>, PyGraph>(m, "Graph", D(Graph))
.def(py::init<Widget *, const std::string &>(), py::arg("parent"),
py::arg("caption") = std::string("Untitled"), D(Graph, Graph))
.def("caption", &Graph::caption, D(Graph, caption))
.def("setCaption", &Graph::setCaption, D(Graph, setCaption))
.def("header", &Graph::header, D(Graph, header))
.def("setHeader", &Graph::setHeader, D(Graph, setHeader))
.def("footer", &Graph::footer, D(Graph, footer))
.def("setFooter", &Graph::setFooter, D(Graph, setFooter))
.def("backgroundColor", &Graph::backgroundColor, D(Graph, backgroundColor))
.def("setBackgroundColor", &Graph::setBackgroundColor, D(Graph, setBackgroundColor))
.def("foregroundColor", &Graph::foregroundColor, D(Graph, foregroundColor))
.def("setForegroundColor", &Graph::setForegroundColor, D(Graph, setForegroundColor))
.def("textColor", &Graph::textColor, D(Graph, textColor))
.def("setTextColor", &Graph::setTextColor, D(Graph, setTextColor))
.def("values", (VectorXf &(Graph::*)(void)) &Graph::values, D(Graph, values))
.def("setValues", &Graph::setValues, D(Graph, setValues));
py::class_<ImageView, Widget, ref<ImageView>, PyImageView>(m, "ImageView", D(ImageView))
.def(py::init<Widget *, uint32_t>(), D(ImageView, ImageView))
.def("bindImage", &ImageView::bindImage, D(ImageView, bindImage))
//.def("imageShader", &ImageView::imageShader, D(ImageView, imageShader))
.def("scaledImageSize", &ImageView::scaledImageSize, D(ImageView, scaledImageSize))
.def("offset", &ImageView::offset, D(ImageView, offset))
.def("setOffset", &ImageView::setOffset, D(ImageView, setOffset))
.def("scale", &ImageView::scale, D(ImageView, scale))
.def("fixedOffset", &ImageView::fixedOffset, D(ImageView, fixedOffset))
.def("setFixedOffset", &ImageView::setFixedOffset, D(ImageView, setFixedOffset))
.def("fixedScale", &ImageView::fixedScale, D(ImageView, fixedScale))
.def("setFixedScale", &ImageView::setFixedScale, D(ImageView, setFixedScale))
.def("zoomSensitivity", &ImageView::zoomSensitivity, D(ImageView, zoomSensitivity))
.def("setZoomSensitivity", &ImageView::setZoomSensitivity, D(ImageView, setZoomSensitivity))
.def("gridThreshold", &ImageView::gridThreshold, D(ImageView, gridThreshold))
.def("setGridThreshold", &ImageView::setGridThreshold, D(ImageView, setGridThreshold))
.def("pixelInfoThreshold", &ImageView::pixelInfoThreshold, D(ImageView, pixelInfoThreshold))
.def("setPixelInfoThreshold", &ImageView::setPixelInfoThreshold, D(ImageView, setPixelInfoThreshold))
.def("setPixelInfoCallback", &ImageView::setPixelInfoCallback, D(ImageView, setPixelInfoCallback))
.def("pixelInfoCallback", &ImageView::pixelInfoCallback, D(ImageView, pixelInfoCallback))
.def("setFontScaleFactor", &ImageView::setFontScaleFactor, D(ImageView, setFontScaleFactor))
.def("fontScaleFactor", &ImageView::fontScaleFactor, D(ImageView, fontScaleFactor))
.def("imageCoordinateAt", &ImageView::imageCoordinateAt, D(ImageView, imageCoordinateAt))
.def("clampedImageCoordinateAt", &ImageView::clampedImageCoordinateAt, D(ImageView, clampedImageCoordinateAt))
.def("positionForCoordinate", &ImageView::positionForCoordinate, D(ImageView, positionForCoordinate))
.def("setImageCoordinateAt", &ImageView::setImageCoordinateAt, D(ImageView, setImageCoordinateAt))
.def("center",&ImageView::center, D(ImageView, center))
.def("fit", &ImageView::fit, D(ImageView, fit))
.def("setScaleCentered", &ImageView::setScaleCentered, D(ImageView, setScaleCentered))
.def("moveOffset", &ImageView::moveOffset, D(ImageView, moveOffset))
.def("zoom", &ImageView::zoom, D(ImageView, zoom))
.def("gridVisible", &ImageView::gridVisible, D(ImageView, gridVisible))
.def("pixelInfoVisible", &ImageView::pixelInfoVisible, D(ImageView, pixelInfoVisible))
.def("helpersVisible", &ImageView::helpersVisible, D(ImageView, helpersVisible));
py::class_<ImagePanel, Widget, ref<ImagePanel>, PyImagePanel>(m, "ImagePanel", D(ImagePanel))
.def(py::init<Widget *>(), py::arg("parent"), D(ImagePanel, ImagePanel))
.def("images", &ImagePanel::images, D(ImagePanel, images))
.def("setImages", &ImagePanel::setImages, D(ImagePanel, setImages))
.def("callback", &ImagePanel::callback, D(ImagePanel, callback))
.def("setCallback", &ImagePanel::setCallback, D(ImagePanel, setCallback));
}
#endif
|
ViktorIvanoff/SoftUni-Courses | JavaScript/Programming Basics/04. For Loop/Lab/06. Sum of Numbers.js | function sumOfDigits(num) {
let sum = 0;
for (let i = 0; i < num.length; i++) {
sum+= Number(num[i]);
}
console.log(`The sum of the digits is:${sum}`);
} |
dyzmapl/BumpTop | trunk/win/Source/Includes/QtIncludes/src/declarative/util/qdeclarativestate_p.h | <filename>trunk/win/Source/Includes/QtIncludes/src/declarative/util/qdeclarativestate_p.h
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (<EMAIL>)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QDECLARATIVESTATE_H
#define QDECLARATIVESTATE_H
#include <qdeclarative.h>
#include <qdeclarativeproperty.h>
#include <QtCore/qobject.h>
#include <QtCore/qsharedpointer.h>
#include <private/qdeclarativeglobal_p.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Declarative)
class QDeclarativeActionEvent;
class QDeclarativeAbstractBinding;
class QDeclarativeBinding;
class QDeclarativeExpression;
class Q_DECLARATIVE_PRIVATE_EXPORT QDeclarativeAction
{
public:
QDeclarativeAction();
QDeclarativeAction(QObject *, const QString &, const QVariant &);
QDeclarativeAction(QObject *, const QString &,
QDeclarativeContext *, const QVariant &);
bool restore:1;
bool actionDone:1;
bool reverseEvent:1;
bool deletableToBinding:1;
QDeclarativeProperty property;
QVariant fromValue;
QVariant toValue;
QDeclarativeAbstractBinding *fromBinding;
QWeakPointer<QDeclarativeAbstractBinding> toBinding;
QDeclarativeActionEvent *event;
//strictly for matching
QObject *specifiedObject;
QString specifiedProperty;
void deleteFromBinding();
};
class Q_AUTOTEST_EXPORT QDeclarativeActionEvent
{
public:
virtual ~QDeclarativeActionEvent();
virtual QString typeName() const;
enum Reason { ActualChange, FastForward };
virtual void execute(Reason reason = ActualChange);
virtual bool isReversable();
virtual void reverse(Reason reason = ActualChange);
virtual void saveOriginals() {}
virtual bool needsCopy() { return false; }
virtual void copyOriginals(QDeclarativeActionEvent *) {}
virtual bool isRewindable() { return isReversable(); }
virtual void rewind() {}
virtual void saveCurrentValues() {}
virtual void saveTargetValues() {}
virtual bool changesBindings();
virtual void clearBindings();
virtual bool override(QDeclarativeActionEvent*other);
};
//### rename to QDeclarativeStateChange?
class QDeclarativeStateGroup;
class QDeclarativeState;
class QDeclarativeStateOperationPrivate;
class Q_DECLARATIVE_EXPORT QDeclarativeStateOperation : public QObject
{
Q_OBJECT
public:
QDeclarativeStateOperation(QObject *parent = 0)
: QObject(parent) {}
typedef QList<QDeclarativeAction> ActionList;
virtual ActionList actions();
QDeclarativeState *state() const;
void setState(QDeclarativeState *state);
protected:
QDeclarativeStateOperation(QObjectPrivate &dd, QObject *parent = 0);
private:
Q_DECLARE_PRIVATE(QDeclarativeStateOperation)
Q_DISABLE_COPY(QDeclarativeStateOperation)
};
typedef QDeclarativeStateOperation::ActionList QDeclarativeStateActions;
class QDeclarativeTransition;
class QDeclarativeStatePrivate;
class Q_DECLARATIVE_EXPORT QDeclarativeState : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(QDeclarativeBinding *when READ when WRITE setWhen)
Q_PROPERTY(QString extend READ extends WRITE setExtends)
Q_PROPERTY(QDeclarativeListProperty<QDeclarativeStateOperation> changes READ changes)
Q_CLASSINFO("DefaultProperty", "changes")
Q_CLASSINFO("DeferredPropertyNames", "changes")
public:
QDeclarativeState(QObject *parent=0);
virtual ~QDeclarativeState();
QString name() const;
void setName(const QString &);
bool isNamed() const;
/*'when' is a QDeclarativeBinding to limit state changes oscillation
due to the unpredictable order of evaluation of bound expressions*/
bool isWhenKnown() const;
QDeclarativeBinding *when() const;
void setWhen(QDeclarativeBinding *);
QString extends() const;
void setExtends(const QString &);
QDeclarativeListProperty<QDeclarativeStateOperation> changes();
int operationCount() const;
QDeclarativeStateOperation *operationAt(int) const;
QDeclarativeState &operator<<(QDeclarativeStateOperation *);
void apply(QDeclarativeStateGroup *, QDeclarativeTransition *, QDeclarativeState *revert);
void cancel();
QDeclarativeStateGroup *stateGroup() const;
void setStateGroup(QDeclarativeStateGroup *);
bool containsPropertyInRevertList(QObject *target, const QString &name) const;
bool changeValueInRevertList(QObject *target, const QString &name, const QVariant &revertValue);
bool changeBindingInRevertList(QObject *target, const QString &name, QDeclarativeAbstractBinding *binding);
bool removeEntryFromRevertList(QObject *target, const QString &name);
void addEntryToRevertList(const QDeclarativeAction &action);
void removeAllEntriesFromRevertList(QObject *target);
void addEntriesToRevertList(const QList<QDeclarativeAction> &actions);
QVariant valueInRevertList(QObject *target, const QString &name) const;
QDeclarativeAbstractBinding *bindingInRevertList(QObject *target, const QString &name) const;
bool isStateActive() const;
Q_SIGNALS:
void completed();
private:
Q_DECLARE_PRIVATE(QDeclarativeState)
Q_DISABLE_COPY(QDeclarativeState)
};
QT_END_NAMESPACE
QML_DECLARE_TYPE(QDeclarativeStateOperation)
QML_DECLARE_TYPE(QDeclarativeState)
QT_END_HEADER
#endif // QDECLARATIVESTATE_H
|
nowkoai/test | ee/spec/frontend/analytics/merge_request_analytics/components/app_spec.js | import { shallowMount } from '@vue/test-utils';
import MergeRequestAnalyticsApp from 'ee/analytics/merge_request_analytics/components/app.vue';
import FilterBar from 'ee/analytics/merge_request_analytics/components/filter_bar.vue';
import ThroughputChart from 'ee/analytics/merge_request_analytics/components/throughput_chart.vue';
import ThroughputTable from 'ee/analytics/merge_request_analytics/components/throughput_table.vue';
import DateRange from '~/analytics/shared/components/daterange.vue';
import UrlSync from '~/vue_shared/components/url_sync.vue';
describe('MergeRequestAnalyticsApp', () => {
let wrapper;
function createComponent() {
wrapper = shallowMount(MergeRequestAnalyticsApp, {
propsData: {
startDate: new Date('2020-05-01'),
endDate: new Date('2020-10-01'),
},
});
}
beforeEach(() => {
createComponent();
});
afterEach(() => {
wrapper.destroy();
wrapper = null;
});
it('displays the page title', () => {
const pageTitle = wrapper.find('[data-testid="pageTitle"').text();
expect(pageTitle).toBe('Merge Request Analytics');
});
it('displays the filter bar component', () => {
expect(wrapper.findComponent(FilterBar).exists()).toBe(true);
});
it('displays the date range component', () => {
expect(wrapper.findComponent(DateRange).exists()).toBe(true);
});
it('displays the throughput chart component', () => {
expect(wrapper.findComponent(ThroughputChart).exists()).toBe(true);
});
it('displays the throughput table component', () => {
expect(wrapper.findComponent(ThroughputTable).exists()).toBe(true);
});
describe('url sync', () => {
it('includes the url sync component', () => {
expect(wrapper.findComponent(UrlSync).exists()).toBe(true);
});
it('has the start and end date params', () => {
const urlSync = wrapper.findComponent(UrlSync);
expect(urlSync.props('query')).toMatchObject({
start_date: '2020-05-01',
end_date: '2020-10-01',
});
});
});
});
|
Junhua9981/WebProjectFinal | database/database_helper.py | <reponame>Junhua9981/WebProjectFinal
def student_helper(student) -> dict:
return {
"id": str(student['_id']),
"fullname": student['fullname'],
"email": student['email'],
"course_of_study": student['course_of_study'],
"year": student['year'],
"GPA": student['gpa']
}
def admin_helper(admin) -> dict:
return {
"name": admin['name'],
}
def user_helper(user) -> dict:
return {
"email": user['email'],
}
def teacher_helper(teacher) -> dict:
return {
"name": teacher['name'],
"department": teacher['department'],
"teaching_subject": teacher['teaching_subject'],
"learned_grade": teacher['learned_grade'],
"learned_graded_user_number": teacher['learned_graded_user_number'],
"stress_grade": teacher['stress_grade'],
"stress_graded_user_number": teacher['stress_graded_user_number'],
"sweet_score": teacher['sweet_score'],
"sweet_graded_user_number": teacher['sweet_graded_user_number'],
}
def teacher_name_helper(teacher) -> dict:
return {
"name": teacher['name'],
}
def teacher_comment_helper(teacher) -> list:
ret = []
for comment in teacher:
ret.append({"comment": comment['comment'], "timestamp": comment['timestamp']})
return ret
def comment_helper(comment) -> dict:
return {
"comment": comment['comment'],
"timestamp": comment['timestamp'],
"teacher": comment['teacher'],
} |
rishson/dojoEnterpriseApp | src/js/rishson/widget/_Widget.js | <reponame>rishson/dojoEnterpriseApp<gh_stars>1-10
define([
"dojo/_base/declare", // declare
"dijit/_Widget", //mixin
"rishson/Base", //mixin
"dojo/_base/lang", // hitch
"dojo/topic", // publish/subscribe
"rishson/Globals"
], function (declare, _Widget, Base, lang, topic, Globals) {
/**
* @class
* @name rishson.widget._Widget
* @description This is the base class for all widgets.<p>
* We mixin Phil Higgin's memory leak mitigation solution that is implemented in Base.<p>
* This base class also adds very generic event pub/sub abilities so that widgets can be completely self-contained and
* not have to know about their runtime invocation container or understand context concerns such as Ajax request.
*/
return declare("rishson.widget._Widget", [_Widget, Base], {
/**
* @constructor
*/
constructor: function () {
/*create a unique id for every instance of a widget. This is needed for when we publish our events and want to
publish who we are. If id is blank then we assume there is only 1 instance of the implementing widget.*/
this._id = this.declaredClass + this.id;
this.subList = {
WIDGET_DISABLE: Globals.TOPIC_NAMESPACE + '/disable',
WIDGET_ENABLE: Globals.TOPIC_NAMESPACE + '/enable',
ERROR_CME: Globals.TOPIC_NAMESPACE + '/error/cme',
ERROR_INVALID: Globals.TOPIC_NAMESPACE + '/error/invalid'
};
},
/**
* @function
* @name rishson.widget._Widget.postCreate
* @override dijit._Widget
*/
postCreate: function () {
//subscribe to topics that EVERY widget needs to potentially know about
topic.subscribe(this.subList.WIDGET_DISABLE, lang.hitch(this, "_disable"));
topic.subscribe(this.subList.WIDGET_ENABLE, lang.hitch(this, "_enable"));
topic.subscribe(this.subList.ERROR_CME, lang.hitch(this, "_cmeHandler"));
topic.subscribe(this.subList.ERROR_INVALID, lang.hitch(this, "_invalidHandler"));
this.inherited(arguments);
},
/**
* @function
* @private
* @description Disable this widget
*/
_disable: function () {
console.error(this.declaredClass + " : _disable has to be implemented by derived widgets.");
},
/**
* @function
* @private
* @description Enable this widget
*/
_enable: function () {
console.error(this.declaredClass + " : _enable has to be implemented by derived widgets.");
},
/**
* @function
* @private
* @param {Object} latestVersionOfObject the latest version of an object that this widget knows how to render.
* @description Handle a ConcurrentModificationException
*/
_cmeHandler: function (latestVersionOfObject) {
console.error(this.declaredClass + " : _cmeHandler has to be implemented by derived widgets.");
},
/**
* @function
* @private
* @param {Object} validationFailures the validation failures to act on.
* @description Handle validation errors when performing some mutating action.
*/
_invalidHandler: function (validationFailures) {
console.error(this.declaredClass + " : _invalidHandler has to be implemented by derived widgets.");
}
});
});
|
samslow/react-native-tutorial | Examples/StateManagement/SetStateBasicTutorial/containers/CounterContainer.js | <reponame>samslow/react-native-tutorial
import React from 'react';
import Counter from '../components/Counter';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
class CounterContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: [
{
counterNum: 0,
},
],
};
}
// Add counter
handleAddCounter = () => {
const {counter} = this.state;
this.setState({
counter: counter.concat({counterNum: 0}),
});
};
// Remove counter
handleRemoveCounter = () => {
const {counter} = this.state;
this.setState({
counter: counter.slice(0, this.state.counter.length - 1),
});
};
// Increment counterNum
handleIncrement = ({index}) => {
const {counter} = this.state;
this.setState({
counter: [
...counter.slice(0, index),
{
counterNum: counter[index].counterNum + 1,
},
...counter.slice(index + 1, counter.length),
],
});
};
// Decrement counterNum
handleDecrement = ({index}) => {
const {counter} = this.state;
this.setState({
counter: [
...counter.slice(0, index),
{
counterNum: counter[index].counterNum - 1,
},
...counter.slice(index + 1, counter.length),
],
});
};
render() {
const {counter} = this.state;
return (
<View>
<View style={styles.counterAddRemoveContainer}>
<TouchableOpacity
style={styles.counterAddRemoveButton}
onPress={this.handleAddCounter}>
<Text
style={{textAlign: 'center', color: 'white', fontWeight: '700'}}>
Add Counter
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.counterAddRemoveButton}
onPress={this.handleRemoveCounter}>
<Text
style={{textAlign: 'center', color: 'white', fontWeight: '700'}}>
Remove Counter
</Text>
</TouchableOpacity>
</View>
<View style={styles.counterFrame}>
{counter.map((item, index) => (
<Counter
key={index}
index={index}
value={item}
handleIncrement={this.handleIncrement}
handleDecrement={this.handleDecrement}
/>
))}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
counterFrame: {
padding: 10,
},
counterAddRemoveContainer: {
width: '100%',
display: 'flex',
flexDirection: 'row',
},
counterAddRemoveButton: {
margin: 10,
padding: 10,
flex: 1,
backgroundColor: '#8041D9',
},
});
export default CounterContainer;
|
arnozhang/LuaMobileSdk | sources/Android/sdk/src/main/java/com/lua/mobile/sdk/engine/bridge/ReflectPlainDataBridge.java | <reponame>arnozhang/LuaMobileSdk<gh_stars>0
/**
* Android LuaMobileSdk for Android framework project.
*
* Copyright 2016 <NAME> <<EMAIL>>
*
* 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.lua.mobile.sdk.engine.bridge;
import android.support.annotation.NonNull;
import android.util.Log;
import com.lua.mobile.sdk.engine.LuaScriptEngine;
import com.lua.mobile.sdk.engine.args.LuaBridgeArgs;
import java.lang.reflect.Field;
public class ReflectPlainDataBridge<T> extends LuaPlainDataBridge<T> {
private static final String TAG = "BridgeReflectPlainData";
private Class<T> mDataClass;
public ReflectPlainDataBridge(Class<T> clazz) {
mDataClass = clazz;
}
@Override
public Class<T> getDataClass() {
return mDataClass;
}
@NonNull
@Override
public T createInstance(@NonNull LuaScriptEngine scriptEngine, @NonNull LuaBridgeArgs args) {
try {
return mDataClass.newInstance();
} catch (Exception e) {
Log.e(TAG, String.format("Cannot new instance for: %s.",
mDataClass.getSimpleName()), e);
}
return null;
}
@Override
public Object getData(T object, String name) {
try {
Field field = mDataClass.getField(name);
field.setAccessible(true);
return field.get(object);
} catch (Exception e) {
Log.e(TAG, String.format("Cannot get field: %s.%s. ",
mDataClass.getSimpleName(), name), e);
}
return null;
}
@Override
public void setData(T object, String name, Object data) {
try {
Field field = mDataClass.getField(name);
field.setAccessible(true);
field.set(object, name);
} catch (Exception e) {
Log.e(TAG, String.format("Cannot set field: %s.%s = %s. ",
mDataClass.getSimpleName(), name, String.valueOf(data)), e);
}
}
}
|
JLXIA/esp | tools/src/google/api/backend.pb.go | // Code generated by protoc-gen-go.
// source: google/api/backend.proto
// DO NOT EDIT!
package api
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// `Backend` defines the backend configuration for a service.
type Backend struct {
// A list of backend rules providing configuration for individual API
// elements.
Rules []*BackendRule `protobuf:"bytes,1,rep,name=rules" json:"rules,omitempty"`
}
func (m *Backend) Reset() { *m = Backend{} }
func (m *Backend) String() string { return proto.CompactTextString(m) }
func (*Backend) ProtoMessage() {}
func (*Backend) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{0} }
func (m *Backend) GetRules() []*BackendRule {
if m != nil {
return m.Rules
}
return nil
}
// A backend rule provides configuration for an individual API element.
type BackendRule struct {
// Selects the methods to which this rule applies.
//
// Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
Selector string `protobuf:"bytes,1,opt,name=selector" json:"selector,omitempty"`
// The address of the API backend.
//
Address string `protobuf:"bytes,2,opt,name=address" json:"address,omitempty"`
// The number of seconds to wait for a response from a request. The
// default depends on the deployment context.
Deadline float64 `protobuf:"fixed64,3,opt,name=deadline" json:"deadline,omitempty"`
}
func (m *BackendRule) Reset() { *m = BackendRule{} }
func (m *BackendRule) String() string { return proto.CompactTextString(m) }
func (*BackendRule) ProtoMessage() {}
func (*BackendRule) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{1} }
func init() {
proto.RegisterType((*Backend)(nil), "google.api.Backend")
proto.RegisterType((*BackendRule)(nil), "google.api.BackendRule")
}
func init() { proto.RegisterFile("google/api/backend.proto", fileDescriptor2) }
var fileDescriptor2 = []byte{
// 180 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x4c, 0x8f, 0xc1, 0xae, 0x82, 0x30,
0x10, 0x45, 0xd3, 0x47, 0x9e, 0xe8, 0x60, 0x5c, 0x74, 0x63, 0xe3, 0xaa, 0x61, 0xc5, 0xc6, 0x92,
0xe8, 0xc6, 0x35, 0x5f, 0x40, 0xfa, 0x03, 0xa6, 0xd0, 0x09, 0x21, 0x56, 0x4a, 0x5a, 0xf8, 0x7f,
0x03, 0x45, 0x64, 0x79, 0xe7, 0x9c, 0xc9, 0xcc, 0x05, 0xd6, 0x58, 0xdb, 0x18, 0xcc, 0x55, 0xdf,
0xe6, 0x95, 0xaa, 0x5f, 0xd8, 0x69, 0xd1, 0x3b, 0x3b, 0x58, 0x0a, 0x81, 0x08, 0xd5, 0xb7, 0xe9,
0x03, 0xe2, 0x22, 0x40, 0x7a, 0x85, 0x7f, 0x37, 0x1a, 0xf4, 0x8c, 0xf0, 0x28, 0x4b, 0x6e, 0x67,
0xf1, 0xd3, 0xc4, 0xe2, 0xc8, 0xd1, 0xa0, 0x0c, 0x56, 0xfa, 0x84, 0x64, 0x33, 0xa5, 0x17, 0xd8,
0x7b, 0x34, 0x58, 0x0f, 0xd6, 0x31, 0xc2, 0x49, 0x76, 0x90, 0x6b, 0xa6, 0x0c, 0x62, 0xa5, 0xb5,
0x43, 0xef, 0xd9, 0xdf, 0x8c, 0xbe, 0x71, 0xda, 0xd2, 0xa8, 0xb4, 0x69, 0x3b, 0x64, 0x11, 0x27,
0x19, 0x91, 0x6b, 0x2e, 0x38, 0x9c, 0x6a, 0xfb, 0xde, 0x7c, 0x51, 0x1c, 0x97, 0x83, 0xe5, 0x54,
0xa3, 0x24, 0xd5, 0x6e, 0xee, 0x73, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, 0x02, 0xf8, 0x16, 0xb6,
0xeb, 0x00, 0x00, 0x00,
}
|
databeast/apicore | apiv2-network/gossip/proto/state/state_not_in_quorum.go | package state
import (
"pkg.autotunego.com/pkg/network/gossip/msgtypes"
)
type notInQuorum struct {
nodeStatus msgtypes.NodeStatus
stateEvent chan msgtypes.StateEvent
quorumProvider Quorum
}
var instanceNotInQuorum *notInQuorum
func GetNotInQuorum(
stateEvent chan msgtypes.StateEvent,
quorumProvider Quorum,
) State {
return ¬InQuorum{
nodeStatus: msgtypes.NODE_STATUS_NOT_IN_QUORUM,
stateEvent: stateEvent,
quorumProvider: quorumProvider,
}
}
func (niq *notInQuorum) String() string {
return "NODE_STATUS_NOT_IN_QUORUM"
}
func (niq *notInQuorum) NodeStatus() msgtypes.NodeStatus {
return niq.nodeStatus
}
func (niq *notInQuorum) SelfAlive(localNodeInfoMap msgtypes.NodeInfoMap) (State, error) {
if !niq.quorumProvider.IsNodeInQuorum(localNodeInfoMap) {
return niq, nil
} else {
return GetUp(niq.stateEvent, niq.quorumProvider), nil
}
}
func (niq *notInQuorum) NodeAlive(localNodeInfoMap msgtypes.NodeInfoMap) (State, error) {
if !niq.quorumProvider.IsNodeInQuorum(localNodeInfoMap) {
return niq, nil
} else {
return GetUp(niq.stateEvent, niq.quorumProvider), nil
}
}
func (niq *notInQuorum) SelfLeave() (State, error) {
return GetDown(niq.stateEvent, niq.quorumProvider), nil
}
func (niq *notInQuorum) NodeLeave(
localNodeInfoMap msgtypes.NodeInfoMap,
) (State, error) {
return niq, nil
}
func (niq *notInQuorum) UpdateClusterSize(
localNodeInfoMap msgtypes.NodeInfoMap,
) (State, error) {
if !niq.quorumProvider.IsNodeInQuorum(localNodeInfoMap) {
return niq, nil
} else {
return GetUp(niq.stateEvent, niq.quorumProvider), nil
}
}
func (niq *notInQuorum) UpdateClusterDomainsActiveMap(
localNodeInfoMap msgtypes.NodeInfoMap,
) (State, error) {
if !niq.quorumProvider.IsNodeInQuorum(localNodeInfoMap) {
return niq, nil
} else {
return GetUp(niq.stateEvent, niq.quorumProvider), nil
}
}
func (niq *notInQuorum) Timeout(
localNodeInfoMap msgtypes.NodeInfoMap,
) (State, error) {
return niq, nil
}
|
karllgiovany/Aion-Lightning-4.9-SRC | AL-Tools/PacketSamurai_4.9/src/com/aionemu/packetsamurai/logreaders/AbstractLogReader.java | <reponame>karllgiovany/Aion-Lightning-4.9-SRC<gh_stars>1-10
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.packetsamurai.logreaders;
import java.io.IOException;
import java.util.Set;
import com.aionemu.packetsamurai.PacketSamurai;
import com.aionemu.packetsamurai.protocol.Protocol;
import com.aionemu.packetsamurai.protocol.ProtocolManager;
import com.aionemu.packetsamurai.session.Session;
import javolution.util.FastSet;
/**
*
* @author <NAME>
* @author <NAME>
*
*/
public abstract class AbstractLogReader
{
protected Set<Session> _sessions;
protected String _fileName;
protected AbstractLogReader(String filename) throws IOException
{
_fileName = filename;
_sessions = new FastSet<Session>();
}
public void parse() throws IOException
{
long time = System.currentTimeMillis();
this.parseHeader();
this.parsePackets(false);
closeFile();
if(PacketSamurai.VERBOSITY.ordinal() >= PacketSamurai.VerboseLevel.VERBOSE.ordinal())
System.out.println("Log parsed in "+(System.currentTimeMillis() - time)+"ms");
}
public void reloadParse() throws IOException
{
long time = System.currentTimeMillis();
this.parseHeader();
this.parsePackets(true);
closeFile();
if(PacketSamurai.VERBOSITY.ordinal() >= PacketSamurai.VerboseLevel.VERBOSE.ordinal())
System.out.println("Log parsed in "+(System.currentTimeMillis() - time)+"ms");
}
public Set<Session> getSessions()
{
return _sessions;
}
/**
* if this is true, then you can get a partial Session just after loading the headers and getSessions will return a set containing only 1 session
* @return
*/
public abstract boolean supportsHeaderReading();
public abstract boolean parsePackets(boolean isReload) throws IOException;
public abstract boolean parseHeader() throws IOException;
protected abstract void closeFile() throws IOException;
protected abstract String getAditionalName();
protected abstract String getFileExtension();
public boolean hasContinuation()
{
return false;
}
/**
* Attempts to retrieve the protocol by the specified port, using the following methodology:<BR>
* <li>If there no protocol loaded for the specified port the user is prompted to choose one from all the loaded ones.</li>
* <li>If there only one protocol loaded for the specified port its intantly returned.</li>
* <li>If there more then one protocol loaded for the specified port the user is prompted to choose between them.</li>
* @param port
* @return The protocol as specified above
*/
public static Protocol getLogProtocolByPort(int port)
{
Protocol p = null;
Set<Protocol> protos = ProtocolManager.getInstance().getProtocolForPort(port);
if (protos == null || protos.isEmpty())
{
p = ProtocolManager.promptUserToChoose("Choose the protocol for this log (err?).");
}
else if (protos.size() == 1)
{
p = protos.iterator().next();
}
else
{
p = ProtocolManager.promptUserToChoose(protos, "Choose the protocol for this log.");
}
return p;
}
public static AbstractLogReader getLogReaderForFile(String filename)
{
//maybe we'd better register the readers and select wth the getExtension
AbstractLogReader reader = null;
try
{
if (filename.endsWith("pcap") || filename.endsWith("cap"))
{
reader = new PCapReader(filename);
}
else if(filename.endsWith("psl")){
reader = new PSLReader(filename);
}
else
{
PacketSamurai.getUserInterface().log("ERROR: Failed to open file, unsupported extension.");
return null;
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return reader;
}
public String getFileName() {
return this._fileName;
}
}
|
nanomashinX/hsweb-framework | hsweb-authorization/hsweb-authorization-jwt/src/main/java/org/hswebframework/web/authorization/jwt/JwtTokenParser.java | package org.hswebframework.web.authorization.jwt;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.hswebframework.web.authorization.basic.web.ParsedToken;
import org.hswebframework.web.authorization.basic.web.UserTokenParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
/**
* @see UserTokenParser
* @since 3.0
*/
public class JwtTokenParser implements UserTokenParser {
private static final Logger logger = LoggerFactory.getLogger(JwtTokenParser.class);
private JwtConfig jwtConfig;
public JwtTokenParser(JwtConfig jwtConfig) {
this.jwtConfig = jwtConfig;
}
@Override
public ParsedToken parseToken(HttpServletRequest request) {
String headerToken = request.getHeader("jwt-token");
if (StringUtils.isEmpty(headerToken)) {
headerToken = request.getHeader("Authorization");
if (!StringUtils.isEmpty(headerToken)) {
if (headerToken.contains(" ")) {
String[] auth = headerToken.split("[ ]");
if (auth[0].equalsIgnoreCase("jwt") || auth[0].equalsIgnoreCase("Bearer")) {
headerToken = auth[1];
}else{
return null;
}
}
}
}
if (headerToken != null) {
try {
Claims claims = parseJWT(headerToken);
if (claims.getExpiration().getTime() <= System.currentTimeMillis()) {
return null;
}
return JSON.parseObject(claims.getSubject(), JwtAuthorizedToken.class);
} catch (ExpiredJwtException e) {
return null;
} catch (Exception e) {
logger.debug("parse token [{}] error", headerToken, e);
return null;
}
}
return null;
}
public Claims parseJWT(String jwt) {
SecretKey key = jwtConfig.generalKey();
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt).getBody();
}
}
|
hymer-up/streamlink | tests/streams/test_dash.py | import unittest
from streamlink import PluginError
from streamlink.stream import DASHStream
from streamlink.stream.dash import DASHStreamWorker
from streamlink.stream.dash_manifest import MPD
from tests.mock import MagicMock, patch, ANY, Mock, call
from tests.resources import text, xml
class TestDASHStream(unittest.TestCase):
def setUp(self):
self.session = MagicMock()
self.test_url = "http://test.bar/foo.mpd"
self.session.http.get.return_value = Mock(url=self.test_url)
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_video_only(self, mpdClass):
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080)
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["720p", "1080p"])
)
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_audio_only(self, mpdClass):
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="audio/mp4", bandwidth=128.0, lang='en'),
Mock(id=2, mimeType="audio/mp4", bandwidth=256.0, lang='en')
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["a128k", "a256k"])
)
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_audio_single(self, mpdClass):
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en')
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["720p", "1080p"])
)
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_audio_multi(self, mpdClass):
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'),
Mock(id=4, mimeType="audio/aac", bandwidth=256.0, lang='en')
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["720p+a128k", "1080p+a128k", "720p+a256k", "1080p+a256k"])
)
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_audio_multi_lang(self, mpdClass):
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'),
Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='es')
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["720p", "1080p"])
)
self.assertEqual(streams["720p"].audio_representation.lang, "en")
self.assertEqual(streams["1080p"].audio_representation.lang, "en")
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_audio_multi_lang_alpha3(self, mpdClass):
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='eng'),
Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='spa')
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["720p", "1080p"])
)
self.assertEqual(streams["720p"].audio_representation.lang, "eng")
self.assertEqual(streams["1080p"].audio_representation.lang, "eng")
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_audio_invalid_lang(self, mpdClass):
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en_no_voice'),
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["720p", "1080p"])
)
self.assertEqual(streams["720p"].audio_representation.lang, "en_no_voice")
self.assertEqual(streams["1080p"].audio_representation.lang, "en_no_voice")
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_audio_multi_lang_locale(self, mpdClass):
self.session.localization.language.alpha2 = "es"
self.session.localization.explicit = True
mpdClass.return_value = Mock(periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
Mock(id=1, mimeType="video/mp4", height=720),
Mock(id=2, mimeType="video/mp4", height=1080),
Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'),
Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='es')
])
])
])
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(
sorted(list(streams.keys())),
sorted(["720p", "1080p"])
)
self.assertEqual(streams["720p"].audio_representation.lang, "es")
self.assertEqual(streams["1080p"].audio_representation.lang, "es")
@patch('streamlink.stream.dash.MPD')
def test_parse_manifest_drm(self, mpdClass):
mpdClass.return_value = Mock(periods=[Mock(adaptationSets=[Mock(contentProtection="DRM")])])
self.assertRaises(PluginError,
DASHStream.parse_manifest,
self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
def test_parse_manifest_string(self):
with text("dash/test_9.mpd") as mpd_txt:
test_manifest = mpd_txt.read()
streams = DASHStream.parse_manifest(self.session, test_manifest)
self.assertSequenceEqual(list(streams.keys()), ['2500k'])
@patch('streamlink.stream.dash.DASHStreamReader')
@patch('streamlink.stream.dash.FFMPEGMuxer')
def test_stream_open_video_only(self, muxer, reader):
stream = DASHStream(self.session, Mock(), Mock(id=1, mimeType="video/mp4"))
open_reader = reader.return_value = Mock()
stream.open()
reader.assert_called_with(stream, 1, "video/mp4")
open_reader.open.assert_called_with()
muxer.assert_not_called()
@patch('streamlink.stream.dash.DASHStreamReader')
@patch('streamlink.stream.dash.FFMPEGMuxer')
def test_stream_open_video_audio(self, muxer, reader):
stream = DASHStream(self.session, Mock(), Mock(id=1, mimeType="video/mp4"), Mock(id=2, mimeType="audio/mp3", lang='en'))
open_reader = reader.return_value = Mock()
stream.open()
self.assertSequenceEqual(reader.mock_calls, [call(stream, 1, "video/mp4"),
call().open(),
call(stream, 2, "audio/mp3"),
call().open()])
self.assertSequenceEqual(muxer.mock_calls, [call(self.session, open_reader, open_reader, copyts=True),
call().open()])
@patch('streamlink.stream.dash.MPD')
def test_segments_number_time(self, mpdClass):
with xml("dash/test_9.mpd") as mpd_xml:
mpdClass.return_value = MPD(mpd_xml, base_url="http://test.bar", url="http://test.bar/foo.mpd")
streams = DASHStream.parse_manifest(self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
self.assertSequenceEqual(list(streams.keys()), ['2500k'])
class TestDASHStreamWorker(unittest.TestCase):
@patch("streamlink.stream.dash_manifest.time.sleep")
@patch('streamlink.stream.dash.MPD')
def test_dynamic_reload(self, mpdClass, sleep):
reader = MagicMock()
worker = DASHStreamWorker(reader)
reader.representation_id = 1
reader.mime_type = "video/mp4"
representation = Mock(id=1, mimeType="video/mp4", height=720)
segments = [Mock(url="init_segment"), Mock(url="first_segment"), Mock(url="second_segment")]
representation.segments.return_value = [segments[0]]
mpdClass.return_value = worker.mpd = Mock(dynamic=True,
publishTime=1,
periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
representation
])
])
])
worker.mpd.type = "dynamic"
worker.mpd.minimumUpdatePeriod.total_seconds.return_value = 0
worker.mpd.periods[0].duration.total_seconds.return_value = 0
segment_iter = worker.iter_segments()
representation.segments.return_value = segments[:1]
self.assertEqual(next(segment_iter), segments[0])
representation.segments.assert_called_with(init=True)
representation.segments.return_value = segments[1:]
self.assertSequenceEqual([next(segment_iter), next(segment_iter)], segments[1:])
representation.segments.assert_called_with(init=False)
@patch("streamlink.stream.dash_manifest.time.sleep")
def test_static(self, sleep):
reader = MagicMock()
worker = DASHStreamWorker(reader)
reader.representation_id = 1
reader.mime_type = "video/mp4"
representation = Mock(id=1, mimeType="video/mp4", height=720)
segments = [Mock(url="init_segment"), Mock(url="first_segment"), Mock(url="second_segment")]
representation.segments.return_value = [segments[0]]
worker.mpd = Mock(dynamic=False,
publishTime=1,
periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
representation
])
])
])
worker.mpd.type = "static"
worker.mpd.minimumUpdatePeriod.total_seconds.return_value = 0
worker.mpd.periods[0].duration.total_seconds.return_value = 0
representation.segments.return_value = segments
self.assertSequenceEqual(list(worker.iter_segments()), segments)
representation.segments.assert_called_with(init=True)
@patch("streamlink.stream.dash_manifest.time.sleep")
def test_duplicate_rep_id(self, sleep):
representation_vid = Mock(id=1, mimeType="video/mp4", height=720)
representation_aud = Mock(id=1, mimeType="audio/aac", lang='en')
mpd = Mock(dynamic=False,
publishTime=1,
periods=[
Mock(adaptationSets=[
Mock(contentProtection=None,
representations=[
representation_vid
]),
Mock(contentProtection=None,
representations=[
representation_aud
])
])
])
self.assertEqual(representation_vid, DASHStreamWorker.get_representation(mpd, 1, "video/mp4"))
self.assertEqual(representation_aud, DASHStreamWorker.get_representation(mpd, 1, "audio/aac"))
|
abrahamfdzg/TibiaAuto12 | Core/GetMapPosition.py | def GetMapPosition(HOOK_OPTION):
MapPositions = [0, 0, 0, 0]
if HOOK_OPTION == 0:
import pyautogui
top_right = pyautogui.locateOnScreen("images/MapSettings/MapSettings.png", confidence=0.8)
map_size = 110 # 110px square
MapPositions[0], MapPositions[1] = top_right[0] - map_size + 4, top_right[1] + 1
MapPositions[2], MapPositions[3] = top_right[0] - 1, top_right[1] + map_size- 1
if top_right[0] != -1:
print(f"MiniMap Start [X: {MapPositions[0]}, Y: {MapPositions[1]}]")
print(f"MiniMap End [X: {MapPositions[2]}, Y: {MapPositions[3]}]")
print("")
print(f"Size of MiniMap [X: {MapPositions[2] - MapPositions[0]}, Y: {MapPositions[3] - MapPositions[1]}]")
return MapPositions[0], MapPositions[1], MapPositions[2], MapPositions[3]
else:
print("Error To Get Map Positions")
return -1, -1, -1, -1
elif HOOK_OPTION == 1:
from Engine.HookWindow import LocateImage
top_right = LocateImage("images/MapSettings/MapSettings.png", Precision=0.8)
map_size = 110 # 110px square
MapPositions[0], MapPositions[1] = top_right[0] - map_size + 4, top_right[1] + 1
MapPositions[2], MapPositions[3] = top_right[0] - 1, top_right[1] + map_size - 1
if top_right[0] != -1:
print(f"MiniMap Start [X: {MapPositions[0]}, Y: {MapPositions[1]}]")
print(f"MiniMap End [X: {MapPositions[2]}, Y: {MapPositions[3]}]")
print("")
print(f"Size of MiniMap [X: {MapPositions[2] - MapPositions[0]}, Y: {MapPositions[3] - MapPositions[1]}]")
return MapPositions[0], MapPositions[1], MapPositions[2], MapPositions[3]
else:
print("Error To Get Map Positions")
return -1, -1, -1, -1
|
xzrunner/model3 | source/CompTransform.cpp | <reponame>xzrunner/model3<filename>source/CompTransform.cpp
#include "node3/CompTransform.h"
namespace n3
{
const char* const CompTransform::TYPE_NAME = "n3_transform";
CompTransform::CompTransform()
: m_scale(1, 1, 1)
{
}
std::unique_ptr<n0::NodeComp> CompTransform::Clone(const n0::SceneNode& node) const
{
auto comp = std::make_unique<CompTransform>();
comp->m_position = m_position;
comp->m_angle = m_angle;
comp->m_scale = m_scale;
return comp;
}
sm::mat4 CompTransform::GetTransformMat() const
{
auto mt_scale = sm::mat4::Scaled(m_scale.x, m_scale.y, m_scale.z);
auto mt_rot = sm::mat4(m_angle);
auto mt_trans = sm::mat4::Translated(m_position.x, m_position.y, m_position.z);
return mt_trans * mt_rot * mt_scale;
}
} |
truthiswill/intellij-community | java/java-tests/testData/psi/resolve/var/Qualified3.java | <gh_stars>1-10
public class Test{
static int a = 0;
public int foo(){
return new Test().<ref>a;
}
}
|
nikitabelotelov/coffee | node_modules/sbis3-ws/WS.Core/core/helpers/Object/isEqual.js | define('Core/helpers/Object/isEqual', ['Types/object', 'Env/Env'], function(object, Env) {
/**
*
* Модуль, в котором описана функция <b>isEqual(obj1, obj2)</b>,
*
* Функция рекурсивно сравнивает два объекта или массива.
* Объекты считаются равными тогда, когда они равны по оператору ===, или когда они являются plain Object и у них одинаковые наборы внутренних ключей, и по каждому ключу значения равны, причём, если эти значения - объекты или массивы, то они сравниваются рекурсивно.
* Функция возвращает true, когда оба объекта/массива идентичны.
*
* <h2>Параметры функции</h2>
*
* <ul>
* <li><b>obj1</b> {Object|Array}.</li>
* <li><b>obj2</b> {Object|Array}.</li>
* </ul>
*
* <h2>Пример использования</h2>
* <pre>
* require(['Core/helpers/Object/isEqual'], function(isEqual) {
*
* // true
* console.log(isEqual({foo: 'bar'}, {foo: 'bar'}));
*
* // false
* console.log(isEqual([0], ['0']));
* });
* </pre>
*
* @class Core/helpers/Object/isEqual
* @public
* @deprecated
* @author <NAME>.
*/
if (typeof window !== 'undefined' && Env.IoC.has('ILogger')) {
Env.IoC.resolve('ILogger').warn('Core/helpers/Object/isEqual', 'Модуль устарел и будет удален используйте Types/object:isEqual');
}
return object.isEqual;
});
|
vsawchuk/CPDBv2_frontend | test/components/cr-page/involvement/involvement.js | import React from 'react';
import { shallow } from 'enzyme';
import Involvement from 'components/cr-page/involvement';
import InvolvementItem from 'components/cr-page/involvement/involvement-item';
describe('Involvement component', function () {
const involvements = {
'investigator': [{ id: 1 }],
'police_witness': [{ id: 2 }],
};
it('should render list of involvement items', function () {
const wrapper = shallow(<Involvement involvements={ involvements }/>);
wrapper.find(InvolvementItem).should.have.length(2);
});
});
|
MartinWeise/probe-engine | internal/orchestra/update/update.go | // Package update contains code to update the probe state with orchestra
package update
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/ooni/probe-engine/internal/jsonapi"
"github.com/ooni/probe-engine/internal/orchestra/login"
"github.com/ooni/probe-engine/internal/orchestra/metadata"
"github.com/ooni/probe-engine/model"
)
// Config contains configs for calling the update API.
type Config struct {
Auth *login.Auth
BaseURL string
ClientID string
HTTPClient *http.Client
Logger model.Logger
Metadata metadata.Metadata
UserAgent string
}
type request struct {
metadata.Metadata
}
// Do registers this probe with OONI orchestra
func Do(ctx context.Context, config Config) error {
if config.Auth == nil {
return errors.New("config.Auth is nil")
}
authorization := fmt.Sprintf("Bearer %s", config.Auth.Token)
req := &request{Metadata: config.Metadata}
var resp struct{}
urlpath := fmt.Sprintf("/api/v1/update/%s", config.ClientID)
return (&jsonapi.Client{
Authorization: authorization,
BaseURL: config.BaseURL,
HTTPClient: config.HTTPClient,
Logger: config.Logger,
UserAgent: config.UserAgent,
}).Update(ctx, urlpath, req, &resp)
}
|
ojmakhura/andromda | cartridges/andromda-jsf2/src/main/java/org/andromda/cartridges/jsf2/metafacades/JSFManageableEntityLogicImpl.java | <gh_stars>1-10
package org.andromda.cartridges.jsf2.metafacades;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import org.andromda.cartridges.jsf2.JSFGlobals;
import org.andromda.cartridges.jsf2.JSFProfile;
import org.andromda.cartridges.jsf2.JSFUtils;
import org.andromda.metafacades.uml.UMLProfile;
import org.andromda.metafacades.uml.DependencyFacade;
import org.andromda.metafacades.uml.ManageableEntityAssociationEnd;
import org.andromda.metafacades.uml.ManageableEntityAttribute;
import org.andromda.metafacades.uml.Role;
import org.andromda.metafacades.uml.UMLMetafacadeProperties;
import org.andromda.utils.StringUtilsHelper;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
/**
* MetafacadeLogic implementation for org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity.
*
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity
*/
public class JSFManageableEntityLogicImpl
extends JSFManageableEntityLogic
{
private static final long serialVersionUID = 34L;
/**
* The logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(JSFManageableEntityLogicImpl.class);
/**
* @param metaObject
* @param context
*/
public JSFManageableEntityLogicImpl(Object metaObject, String context)
{
super(metaObject, context);
}
/**
* @return getName().toLowerCase() + "-crud"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getViewName()
*/
protected String handleGetViewName()
{
return this.getName().toLowerCase() + "-crud";
}
/**
* @return toResourceMessageKey(this.getName()) + ".view.title"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getViewTitleKey()
*/
protected String handleGetViewTitleKey()
{
return StringUtilsHelper.toResourceMessageKey(this.getName()) + ".view.title";
}
/**
* @return StringUtilsHelper.toPhrase(getName())
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getViewTitleValue()
*/
protected String handleGetViewTitleValue()
{
return StringUtilsHelper.toPhrase(getName());
}
/**
* @return "manageableList"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getListName()
*/
protected String handleGetListName()
{
return "manageableList";
}
/**
* @return getManageablePackageName() + getNamespaceProperty() + this.getFormBeanClassName()
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getFormBeanType()
*/
protected String handleGetFormBeanType()
{
return this.getManageablePackageName() + this.getNamespaceProperty() + this.getFormBeanClassName();
}
/**
* @return formBeanName
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getFormBeanName()
*/
protected String handleGetFormBeanName()
{
final String pattern = ObjectUtils.toString(this.getConfiguredProperty(JSFGlobals.FORM_BEAN_PATTERN));
final String formBeanName = pattern.replaceFirst("\\{0\\}", "manage");
return formBeanName.replaceFirst("\\{1\\}", this.getName());
}
/**
* @return StringUtilsHelper.toResourceMessageKey(this.getName()) + ".exception"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getExceptionKey()
*/
protected String handleGetExceptionKey()
{
return StringUtilsHelper.toResourceMessageKey(this.getName()) + ".exception";
}
/**
* @return getManageablePackageName() + getNamespaceProperty() + getActionClassName()
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getActionType()
*/
protected String handleGetActionType()
{
return this.getManageablePackageName() + this.getNamespaceProperty() + this.getActionClassName();
}
/**
* @return '/' + StringUtils.replace(this.getActionType(), getNamespaceProperty(), "/")
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getActionFullPath()
*/
protected String handleGetActionFullPath()
{
return '/' + StringUtils.replace(this.getActionType(), this.getNamespaceProperty(), "/");
}
/**
* @return '/' + getName() + "/Manage"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getActionPath()
*/
protected String handleGetActionPath()
{
return super.getActionFullPath();
}
/**
* @return "Manage" + getName()
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getActionClassName()
*/
protected String handleGetActionClassName()
{
return getName();
}
/**
* @return getViewFullPath()
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getExceptionPath()
*/
protected String handleGetExceptionPath()
{
return this.getViewFullPath();
}
/**
* @return false
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isPreload()
*/
protected boolean handleIsPreload()
{
return false; //TODO think about...
// return this.isCreate() || this.isRead() || this.isUpdate() || this.isDelete();
}
/**
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntityLogic#getManageableIdentifier()
*/
@Override
public org.andromda.metafacades.uml.ManageableEntityAttribute getManageableIdentifier()
{
return super.getManageableIdentifier();
}
/**
* @return StringUtils.capitalize(this.getFormBeanName())
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getFormBeanClassName()
*/
protected String handleGetFormBeanClassName()
{
return StringUtils.capitalize(this.getFormBeanName());
}
/**
* @return StringUtils.replace(getFormBeanType(), getNamespaceProperty(), "/")
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getFormBeanFullPath()
*/
protected String handleGetFormBeanFullPath()
{
return StringUtils.replace(this.getFormBeanType(), this.getNamespaceProperty(), "/");
}
/**
* @return "getManageableList"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getListGetterName()
*/
protected String handleGetListGetterName()
{
return "getManageableList";
}
/**
* @return "setManageableList"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getListSetterName()
*/
protected String handleGetListSetterName()
{
return "setManageableList";
}
/**
* @return StringUtilsHelper.toResourceMessageKey(this.getName())
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getMessageKey()
*/
protected String handleGetMessageKey()
{
return StringUtilsHelper.toResourceMessageKey(this.getName());
}
/**
* @return StringUtilsHelper.toPhrase(this.getName())
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getMessageValue()
*/
protected String handleGetMessageValue()
{
return StringUtilsHelper.toPhrase(this.getName());
}
/**
* @return getMessageKey() + ".online.help"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getOnlineHelpKey()
*/
protected String handleGetOnlineHelpKey()
{
return this.getMessageKey() + ".online.help";
}
/**
* @return onlineHelpValue
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getOnlineHelpValue()
*/
protected String handleGetOnlineHelpValue()
{
final String value = StringUtilsHelper.toResourceMessage(this.getDocumentation("", 64, false));
return (value == null) ? "No entity documentation has been specified" : value;
}
/**
* @return getActionPath() + "Help"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getOnlineHelpActionPath()
*/
protected String handleGetOnlineHelpActionPath()
{
return this.getActionPath() + "Help";
}
/**
* @return '/' + getManageablePackagePath() + '/' + getName().toLowerCase() + "_help"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getOnlineHelpPagePath()
*/
protected String handleGetOnlineHelpPagePath()
{
return '/' + this.getManageablePackagePath() + '/' + this.getName().toLowerCase() + "_help";
}
/**
* @return getTableExportTypes().indexOf("none") == -1
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isTableExportable()
*/
protected boolean handleIsTableExportable()
{
return this.getTableExportTypes().indexOf("none") == -1;
}
/**
* @return null
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getTableExportTypes()
*/
protected String handleGetTableExportTypes()
{
return null;
//TODO a resolver
// return JSFUtils.getDisplayTagExportTypes(
// this.findTaggedValues(JSFProfile.TAGGEDVALUE_TABLE_EXPORT),
// (String)getConfiguredProperty(JSFGlobals.PROPERTY_DEFAULT_TABLE_EXPORT_TYPES) );
}
/**
* @return tableMaxRows
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getTableMaxRows()
*/
protected int handleGetTableMaxRows()
{
final Object taggedValue = this.findTaggedValue(JSFProfile.TAGGEDVALUE_TABLE_MAXROWS);
int pageSize;
try
{
pageSize = Integer.parseInt(String.valueOf(taggedValue));
}
catch (Exception e)
{
pageSize = JSFProfile.TAGGEDVALUE_TABLE_MAXROWS_DEFAULT_COUNT;
}
return pageSize;
}
/**
* @return tableSortable
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isTableSortable()
*/
protected boolean handleIsTableSortable()
{
final Object taggedValue = this.findTaggedValue(JSFProfile.TAGGEDVALUE_TABLE_SORTABLE);
return (taggedValue == null)
? JSFProfile.TAGGEDVALUE_TABLE_SORTABLE_DEFAULT_VALUE
: Boolean.valueOf(String.valueOf(taggedValue)).booleanValue();
}
/**
* @return controllerType
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getControllerType()
*/
protected String handleGetControllerType()
{
return this.getManageablePackageName() + this.getNamespaceProperty() + this.getControllerName();
}
/**
* @return StringUtils.uncapitalize(this.getName()) + "Controller"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getControllerBeanName()
*/
protected String handleGetControllerBeanName()
{
return StringUtils.uncapitalize(this.getName()) + "Controller";
}
/**
* @return '/' + StringUtils.replace(getControllerType(), getNamespaceProperty(), "/")
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getControllerFullPath()
*/
protected String handleGetControllerFullPath()
{
return '/' + StringUtils.replace(this.getControllerType(), this.getNamespaceProperty(), "/");
}
/**
* @return getName() + "Controller"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getControllerName()
*/
protected String handleGetControllerName()
{
return this.getName() + "Controller";
}
/**
* @return getName() + this.getConfiguredProperty(JSFGlobals.CRUD_VALUE_OBJECT_SUFFIX)
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getValueObjectClassName()
*/
protected String handleGetValueObjectClassName()
{
return getName() + this.getConfiguredProperty(JSFGlobals.CRUD_VALUE_OBJECT_SUFFIX);
}
/**
* @return formSerialVersionUID
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getFormSerialVersionUID()
*/
protected String handleGetFormSerialVersionUID()
{
final StringBuilder buffer = new StringBuilder();
buffer.append(this.getFormBeanType());
addSerialUIDData(buffer);
return JSFUtils.calcSerialVersionUID(buffer);
}
/**
* @return actionSerialVersionUID
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getActionSerialVersionUID()
*/
protected String handleGetActionSerialVersionUID()
{
final StringBuilder buffer = new StringBuilder();
buffer.append(this.getActionFullPath());
addSerialUIDData(buffer);
return JSFUtils.calcSerialVersionUID(buffer);
}
/**
* @return populatorName
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getPopulatorName()
*/
protected String handleGetPopulatorName()
{
return ObjectUtils.toString(this.getConfiguredProperty(JSFGlobals.VIEW_POPULATOR_PATTERN)).replaceAll(
"\\{0\\}",
StringUtilsHelper.upperCamelCaseName(this.getFormBeanClassName()));
}
/**
* @return '/' + StringUtils.replace(getPopulatorType(), getNamespaceProperty(), "/")
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getPopulatorFullPath()
*/
protected String handleGetPopulatorFullPath()
{
return '/' + StringUtils.replace(this.getPopulatorType(), this.getNamespaceProperty(), "/");
}
/**
* @return getManageablePackageName() + getNamespaceProperty() + getPopulatorName()
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getPopulatorType()
*/
protected String handleGetPopulatorType()
{
return this.getManageablePackageName() + this.getNamespaceProperty() + this.getPopulatorName();
}
/**
* @return '/' + getManageablePackagePath() + '/' + getViewName()
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getViewFullPath()
*/
protected String handleGetViewFullPath()
{
return '/' + this.getManageablePackagePath() + '/' + this.getViewName();
}
/**
* @return '/' + getManageablePackagePath() + '/' + getName().toLowerCase() + "-ods-export"
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getViewFullPath()
*/
protected String handleGetOdsExportFullPath()
{
return '/' + this.getManageablePackagePath() + '/' + this.getName().toLowerCase()+".ods-export";
}
/**
* @return isValidationRequired
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isValidationRequired()
*/
protected boolean handleIsValidationRequired()
{
for (final ManageableEntityAttribute attribute : this.getManageableAttributes())
{
if(attribute instanceof JSFManageableEntityAttribute)
{
final JSFManageableEntityAttribute jsfAttribute = (JSFManageableEntityAttribute)attribute;
if (jsfAttribute.isValidationRequired())
{
return true;
}
}
}
return false;
}
/**
* @return searchFormBeanName
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getSearchFormBeanName()
*/
protected String handleGetSearchFormBeanName()
{
final String pattern = ObjectUtils.toString(this.getConfiguredProperty(JSFGlobals.FORM_BEAN_PATTERN));
final String formBeanName = pattern.replaceFirst("\\{0\\}", "manage");
return formBeanName.replaceFirst("\\{1\\}",this.getName() + "Search");
}
/**
* @return searchFormBeanType
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getSearchFormBeanType()
*/
protected String handleGetSearchFormBeanType()
{
return this.getManageablePackageName() + this.getNamespaceProperty() + this.getSearchFormBeanClassName();
}
/**
* @return searchFormBeanFullPath
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getSearchFormBeanFullPath()
*/
protected String handleGetSearchFormBeanFullPath()
{
return StringUtils.replace(this.getSearchFormBeanType(), this.getNamespaceProperty(), "/");
}
/**
* @return StringUtils.capitalize(this.getSearchFormBeanName())
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getSearchFormBeanClassName()
*/
protected String handleGetSearchFormBeanClassName()
{
return StringUtils.capitalize(this.getSearchFormBeanName());
}
private Boolean usingManageableSearchable=null;
private boolean isUsingManageableSearchable()
{
if(usingManageableSearchable == null)
{
for(final ManageableEntityAttribute attr: getManageableAttributes())
{
if(BooleanUtils.toBoolean(ObjectUtils.toString(attr.findTaggedValue(JSFProfile.ANDROMDA_MANAGEABLE_ATTRIBUTE_SEARCHABLE))))
{
usingManageableSearchable=true;
break;
}
}
if(usingManageableSearchable == null)
{
for(final ManageableEntityAssociationEnd end: getManageableAssociationEnds())
{
//TODO constant should go to JSFProfile of UMLPROFILE
if(BooleanUtils.toBoolean(ObjectUtils.toString(end.findTaggedValue(JSFProfile.ANDROMDA_MANAGEABLE_ATTRIBUTE_SEARCHABLE))))
{
usingManageableSearchable=true;
break;
}
}
}
if(usingManageableSearchable == null)
{
usingManageableSearchable = false;
}
}
return usingManageableSearchable;
}
/**
* @return manageableSearchAttributes
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getManageableSearchAttributes()
*/
protected Collection<JSFManageableEntityAttribute> handleGetManageableSearchAttributes()
{
final Collection<JSFManageableEntityAttribute> searchAttributes=new ArrayList<JSFManageableEntityAttribute>();
if(isUsingManageableSearchable())
{
for(final ManageableEntityAttribute attr: getManageableAttributes())
{
if(BooleanUtils.toBoolean(ObjectUtils.toString(attr.findTaggedValue(JSFProfile.ANDROMDA_MANAGEABLE_ATTRIBUTE_SEARCHABLE))))
{
searchAttributes.add((JSFManageableEntityAttribute)attr);
}
}
}
else
{
for(ManageableEntityAttribute attr: getManageableAttributes())
{
if(attr.isDisplay() && !attr.getType().isBlobType() && !attr.getType().isClobType())
{
searchAttributes.add((JSFManageableEntityAttribute)attr);
}
}
}
return searchAttributes;
}
/**
* @return getManageableAssociationEnds()
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getManageableSearchAssociationEnds()
*/
protected Collection<ManageableEntityAssociationEnd> handleGetManageableSearchAssociationEnds()
{
final Collection<ManageableEntityAssociationEnd> searchAssociationEnds=new ArrayList<ManageableEntityAssociationEnd>();
if(isUsingManageableSearchable())
{
for(final ManageableEntityAssociationEnd end: getManageableAssociationEnds())
{
if(BooleanUtils.toBoolean(ObjectUtils.toString(end.findTaggedValue(JSFProfile.ANDROMDA_MANAGEABLE_ATTRIBUTE_SEARCHABLE)))
|| end.isComposition())
{
searchAssociationEnds.add(end);
}
}
}
else
{
for(final ManageableEntityAssociationEnd end: getManageableAssociationEnds())
{
if(end.isDisplay() || end.isComposition())
{
searchAssociationEnds.add(end);
}
}
}
return searchAssociationEnds;
}
/**
* @param element
* @return isSearchable
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isSearchable(Object)
*/
protected boolean handleIsSearchable(Object element)
{
return getManageableSearchAttributes().contains(element) || getManageableSearchAssociationEnds().contains(element);
}
/**
* @return the configured property denoting the character sequence to use for the separation of namespaces
*/
private String getNamespaceProperty()
{
return (String)this.getConfiguredProperty(UMLMetafacadeProperties.NAMESPACE_SEPARATOR);
}
private void addSerialUIDData(StringBuilder buffer)
{
for (final ManageableEntityAttribute attribute : this.getManageableAttributes())
{
buffer.append(attribute.getName());
}
for (final ManageableEntityAssociationEnd end : this.getManageableAssociationEnds())
{
buffer.append(end.getName());
}
}
/**
* @return allRoles
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getRoles()
*/
@SuppressWarnings("rawtypes")
protected Collection handleGetRoles()
{
//copied form the Service <<Metafacade>>
final Collection<DependencyFacade> roles = new ArrayList<DependencyFacade>(this.getTargetDependencies());
CollectionUtils.filter(roles, new Predicate()
{
public boolean evaluate(final Object object)
{
DependencyFacade dependency = (DependencyFacade)object;
return dependency != null && dependency.getSourceElement() instanceof Role;
}
});
CollectionUtils.transform(roles, new Transformer()
{
public Object transform(final Object object)
{
return ((DependencyFacade)object).getSourceElement();
}
});
@SuppressWarnings({ "unchecked" })
final Collection allRoles = new LinkedHashSet(roles);
// add all roles which are generalizations of this one
CollectionUtils.forAllDo(roles, new Closure()
{
@SuppressWarnings("unchecked")
public void execute(final Object object)
{
allRoles.addAll(((Role)object).getAllSpecializations());
}
});
return allRoles;
}
/**
* @return actionRoles
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getActionRoles()
*/
protected String handleGetActionRoles()
{
//copied from JSFUseCaseLogicImpl
final StringBuilder rolesBuffer = new StringBuilder();
boolean first = true;
for (final Role role : this.getRoles())
{
if (first)
{
first = false;
}
else
{
rolesBuffer.append(',');
}
rolesBuffer.append(role.getName());
}
return rolesBuffer.toString();
}
/**
* @return needsFileUpload
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isNeedsFileUpload()
*/
protected boolean handleIsNeedsFileUpload()
{
for (final ManageableEntityAttribute attribute : this.getManageableAttributes())
{
if(attribute instanceof JSFManageableEntityAttribute)
{
final JSFManageableEntityAttribute jsfAttribute = (JSFManageableEntityAttribute)attribute;
if(jsfAttribute.isNeedsFileUpload())
{
return true;
}
}
}
return false;
}
/**
* @return needsUserInterface
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isNeedsUserInterface()
*/
protected boolean handleIsNeedsUserInterface()
{
if(isAbstract())
{
return false;
}
for (final ManageableEntityAttribute attribute : this.getManageableAttributes())
{
if(attribute instanceof JSFManageableEntityAttribute)
{
final JSFManageableEntityAttribute jsfAttribute = (JSFManageableEntityAttribute)attribute;
if(!jsfAttribute.isHidden())
{
return true;
}
}
}
for (final ManageableEntityAssociationEnd associationEnd : this.getManageableAssociationEnds())
{
if(associationEnd instanceof JSFManageableEntityAssociationEnd)
{
final JSFManageableEntityAssociationEnd jsfAssociationEnd = (JSFManageableEntityAssociationEnd)associationEnd;
if(!jsfAssociationEnd.isDisplay())
{
return true;
}
}
}
return false;
}
/**
* @return converterClassName
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getConverterClassName
*/
public String handleGetConverterClassName()
{
return StringUtils.replace(
ObjectUtils.toString(this.getConfiguredProperty(JSFGlobals.CONVERTER_PATTERN)),
"{0}",
this.getName());
}
/**
* @return converterType
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getConverterType
*/
public String handleGetConverterType()
{
return this.getManageablePackageName() + this.getNamespaceProperty() + this.getConverterClassName();
}
/**
* @return converterFullPath
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getConverterFullPath
*/
public String handleGetConverterFullPath()
{
return StringUtils.replace(this.getConverterType(), this.getNamespaceProperty(), "/");
}
//TODO review
@Override
public ManageableEntityAttribute getDisplayAttribute() {
for(final ManageableEntityAttribute attribute: getManageableAttributes())
{
if(BooleanUtils.toBoolean(ObjectUtils.toString(attribute.findTaggedValue(JSFProfile.ANDROMDA_MANAGEABLE_ATTRIBUTE_DISPLAY))))
{
return attribute;
}
}
//associations ???
// for(final ManageableEntityAssociationEnd associationEnd: getManageableAssociationEnds())
// {
// if(BooleanUtils.toBoolean(ObjectUtils.toString(associationEnd.findTaggedValue("andromda_manageable_display"))))
// {
// return associationEnd;
// }
// }
return super.getDisplayAttribute();
}
/**
* @return needsImplementation
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#isNeedsImplementation
*/
@Override
protected boolean handleIsNeedsImplementation() {
final Object generateCrudImpls=this.getConfiguredProperty(JSFGlobals.GENERATE_CRUD_IMPLS);
if(generateCrudImpls != null && Boolean.parseBoolean(generateCrudImpls.toString()))
{
return true;
}
else
{
final Object taggedValue = this.findTaggedValue(JSFProfile.ANDROMDA_MANAGEABLE_IMPLEMENTATION);
return (taggedValue == null)
? JSFProfile.TAGGEDVALUE_MANAGEABLE_IMPLEMENTATION_DEFAULT_VALUE
: Boolean.valueOf(String.valueOf(taggedValue)).booleanValue();
}
}
@Override
protected String handleGetSearchFilterFullPath() {
return '/' + StringUtils.replace(this.getManageablePackageName(), this.getNamespaceProperty(), "/") + '/' + getSearchFilterName();
}
@Override
protected String handleGetSearchFilterName() {
return this.getName() + "SearchFilter";
}
@Override
protected String handleGetSearchFilterSerialVersionUID() {
String serialVersionUID = String.valueOf(0L);
try
{
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] hashBytes = md.digest(getSearchFilterFullPath().getBytes());
long hash = 0;
for (int ctr = Math.min(
hashBytes.length,
8) - 1; ctr >= 0; ctr--)
{
hash = (hash << 8) | (hashBytes[ctr] & 0xFF);
}
serialVersionUID = String.valueOf(hash);
}
catch (final NoSuchAlgorithmException exception)
{
final String message = "Error performing ManageableEntity.getSearchFilterSerialVersionUID";
LOGGER.error(
message,
exception);
}
return serialVersionUID;
}
/**
* @return manageableEditAttributes
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getManageableEditAttributes()
*/
@Override
protected Collection<JSFManageableEntityAttribute> handleGetManageableEditAttributes() {
final Collection<JSFManageableEntityAttribute> editAttributes=new ArrayList<JSFManageableEntityAttribute>();
for(final ManageableEntityAttribute attr: getManageableAttributes())
{
final JSFManageableEntityAttribute jsfAttr=(JSFManageableEntityAttribute)attr;
if(jsfAttr.isEditable())
{
editAttributes.add(jsfAttr);
}
}
return editAttributes;
}
/**
* @return manageableDetailsAssociations
* @see org.andromda.cartridges.jsf2.metafacades.JSFManageableEntity#getManageableDetailsAssociations()
*/
@Override
protected Collection<ManageableEntityAssociationEnd> handleGetManageableDetailsAssociationsEnds()
{
final Collection<ManageableEntityAssociationEnd> manageableDetailsAssociationsEnds = new ArrayList<ManageableEntityAssociationEnd>();
for(ManageableEntityAssociationEnd associationEnd: (Collection<ManageableEntityAssociationEnd>)this.getManageableAssociationEnds())
{
if(associationEnd.isMany() && associationEnd.getType().hasStereotype(UMLProfile.STEREOTYPE_MANAGEABLE) &&
associationEnd.getOtherEnd().isNavigable() && associationEnd.getOtherEnd().isComposition())
{
manageableDetailsAssociationsEnds.add(associationEnd);
}
}
return manageableDetailsAssociationsEnds;
}
}
|
ideacrew/intellimesh | spec/intellimesh/messages/message_spec.rb | <gh_stars>0
# frozen_string_literal: true
require "spec_helper"
require 'intellimesh'
class MessageIncluded
include Intellimesh::Messages::Message
# This declaration keeps developer honest about initilizing code in the module
def initialize
end
def load_header_property_set
message(local_header_properties)
end
def load_meta_property_set
message(local_meta_properties)
end
def load_context_property_set
message(local_context_properties)
end
def load_all_property_sets
header_hash = hash_merge([
local_header_properties,
{ meta: local_meta_properties},
{ context: local_context_properties}
])
# binding.pry
message(header_hash)
end
def local_header_properties
{
to: 'amqp://exchange_name',
type: :object,
}
end
def local_context_properties
{
priority: :now,
expires: 300,
reply_to: 'amqp://exchange_name/reply_to_queue',
}
end
def local_meta_properties
{
locale: 'en',
encrypted: false,
ack_requested: true,
}
end
class EventJob
include Intellimesh::Messages::Message
end
class TrackedEventJob
include Intellimesh::Messages::Message
end
class CommandJob
include Intellimesh::Messages::Message
end
class CommandServiceJob
include Intellimesh::Messages::Message
def received_message
end
end
RSpec.describe Intellimesh::Messages::Message do
let(:header_defaults) do {
from: nil,
to: nil,
subject: nil,
submitted_at: nil,
type: :object,
errors: {},
context: context_defaults,
meta: {},
}
end
let(:context_defaults) do {
enqueued_at: nil,
priority: :now,
expires: 0,
reply_to: nil,
routing_slip: {},
}
end
context "A class instance with an initialized Message" do
# subject { MessageIncluded.new().message(message_options) }
subject { MessageIncluded.new() }
before { subject.message(message_options) }
let(:id_key) { :id }
let(:message_options) { {type: :object} }
it "the Message Header should initialize with default values" do
expect(subject.message_header.except(:id)).to include(header_defaults)
expect(subject.message_context).to include(context_defaults)
expect(subject.message_meta).to eq({})
end
it "and the Message Header should include an :id key" do
expect(subject.message_header).to have_key(id_key)
expect(subject.message_header[:id]).to_not be_nil
end
it "and the Message Meta keys should be nil" do
expect(subject.message_header[:meta]).to eq({})
end
it "and the Message Body should be empty" do
expect(subject.message_body).to eq({})
end
context "and Message Header properties are individually updated" do
context "an update to the readlonly :id property is attempted" do
let(:id) { "123abc" }
it("should raise an Argument error") do
expect{subject.update_message_header(:id => id)}.to raise_error(ArgumentError)
end
end
context "an update to the :submitted_at property is attempted with valid value" do
let(:timestamp) { Time.now.utc }
before { subject.update_message_header(submitted_at: timestamp) }
it "should update the submitted_at property" do
expect(subject.message_header[:submitted_at]).to eq timestamp
end
end
end
context "and Message Header properties are updated as a set" do
before { subject.load_header_property_set }
it "should update the header properties hash" do
expect(subject.message_header).to include(subject.local_header_properties)
end
end
context "and a Message Meta property is individually added" do
let(:new_meta_property_name) { "favorite_color" }
let(:new_meta_value) { "green" }
let(:new_meta_property) { { new_meta_property_name.to_sym => new_meta_value } }
before { subject.update_message_header(new_meta_property) }
it "should add the new property" do
expect(subject.message_header[:meta].keys).to include new_meta_property_name.to_sym
expect(subject.message_meta[new_meta_property_name.to_sym]).to eq new_meta_value
expect(subject.message_header[:meta][new_meta_property_name.to_sym]).to eq new_meta_value
end
end
context "and Message Meta propertes are loaded as a set" do
before { subject.load_meta_property_set }
it "should initialize the meta properties hash" do
expect(subject.message_meta).to eq subject.local_meta_properties
end
it "should update the meta hash in the parent Header properties" do
expect(subject.message_header[:meta]).to eq subject.local_meta_properties
end
context "and a Message Meta property is individually updated" do
let(:updated_meta_property) { { encrypted: true } }
before { subject.update_message_header(updated_meta_property) }
it "should update the existing value" do
expect(subject.message_header[:meta][updated_meta_property.keys.first]).to eq updated_meta_property.values.first
end
end
end
context "and a Message Context property is individually updated" do
context "an update to the :priority property is attempted with a valid value" do
let(:hourly_priority) { :hourly }
before { subject.update_message_header({priority: hourly_priority }) }
it("should update the :priority property") do
expect(subject.message_context[:priority]).to eq hourly_priority
end
end
end
context "and Message Context propertes are loaded as a set" do
before { subject.load_context_property_set }
it "should initialize the context properties hash" do
expect(subject.message_context).to include subject.local_context_properties
end
it "should update the context hash in the parent Header properties" do
expect(subject.message_header[:context]).to include subject.local_context_properties
end
context "and a Message context property is individually updated" do
let(:updated_context_property) { { expires: 42 } }
before { subject.update_message_header(updated_context_property) }
it "should update the existing value" do
expect(subject.message_header[:context][updated_context_property.keys.first]).to eq updated_context_property.values.first
end
end
end
context "and Message is created all at once from nested hashes" do
before { subject.load_all_property_sets }
it "should update the meta hash in the parent Header properties" do
expect(subject.message_header[:meta]).to eq subject.local_meta_properties
end
it "should initialize the meta properties hash" do
expect(subject.message_meta).to include subject.local_meta_properties
end
it "should initialize the context properties hash" do
expect(subject.message_context).to include subject.local_context_properties
end
end
context "and a Message body is added" do
end
end
end
end
|
Chaf-Libraries/Ilum | Source/Ilum/Geometry/Mesh/Process/IMeshProcess.cpp | #include "IMeshProcess.hpp"
namespace Ilum::geometry
{
const std::vector<glm::vec3> IMeshProcess::preprocess(const std::vector<Vertex> &vertices)
{
std::vector<glm::vec3> result(vertices.size());
for (size_t i = 0; i < vertices.size(); i++)
{
result[i] = vertices[i].position;
}
return result;
}
const std::vector<Vertex> IMeshProcess::postprocess(const std::vector<glm::vec3> &vertices, const std::vector<uint32_t> &indices, const std::vector<glm::vec2> &texcoords)
{
std::vector<Vertex> result(vertices.size());
for (size_t i = 0; i < indices.size(); i += 3)
{
glm::vec3 e2 = vertices[indices[i + 1]] - vertices[indices[i]];
glm::vec3 e1 = vertices[indices[i + 2]] - vertices[indices[i]];
glm::vec3 normal = glm::normalize(glm::cross(e1, e2));
result[indices[i]].normal += normal;
result[indices[i + 1]].normal += normal;
result[indices[i + 2]].normal += normal;
}
for (size_t i = 0; i < vertices.size(); i++)
{
result[i].position = vertices[i];
result[i].normal = glm::normalize(result[i].normal);
if (!texcoords.empty())
{
result[i].texcoord = texcoords[i];
}
}
return result;
}
} // namespace Ilum::geometry |
akifoezkan/Halide-HLS | src/IRMatch.cpp | #include <iostream>
#include <map>
#include "IRVisitor.h"
#include "IRMatch.h"
#include "IREquality.h"
#include "IROperator.h"
namespace Halide {
namespace Internal {
using std::vector;
using std::map;
using std::string;
void expr_match_test() {
vector<Expr> matches;
Expr w = Variable::make(Int(32), "*");
Expr fw = Variable::make(Float(32), "*");
Expr x = Variable::make(Int(32), "x");
Expr y = Variable::make(Int(32), "y");
Expr fx = Variable::make(Float(32), "fx");
Expr fy = Variable::make(Float(32), "fy");
Expr vec_wild = Variable::make(Int(32, 4), "*");
internal_assert(expr_match(w, 3, matches) &&
equal(matches[0], 3));
internal_assert(expr_match(w + 3, (y*2) + 3, matches) &&
equal(matches[0], y*2));
internal_assert(expr_match(fw * 17 + cast<float>(w + cast<int>(fw)),
(81.0f * fy) * 17 + cast<float>(x/2 + cast<int>(x + 4.5f)), matches) &&
matches.size() == 3 &&
equal(matches[0], 81.0f * fy) &&
equal(matches[1], x/2) &&
equal(matches[2], x + 4.5f));
internal_assert(!expr_match(fw + 17, fx + 18, matches) &&
matches.empty());
internal_assert(!expr_match((w*2) + 17, fx + 17, matches) &&
matches.empty());
internal_assert(!expr_match(w * 3, 3 * x, matches) &&
matches.empty());
internal_assert(expr_match(vec_wild * 3, Ramp::make(x, y, 4) * 3, matches));
std::cout << "expr_match test passed" << std::endl;
}
class IRMatch : public IRVisitor {
public:
bool result;
vector<Expr> *matches;
map<string, Expr> *var_matches;
Expr expr;
IRMatch(Expr e, vector<Expr> &m) : result(true), matches(&m), var_matches(nullptr), expr(e) {
}
IRMatch(Expr e, map<string, Expr> &m) : result(true), matches(nullptr), var_matches(&m), expr(e) {
}
using IRVisitor::visit;
bool types_match(Type pattern_type, Type expr_type) {
bool bits_matches = (pattern_type.bits() == 0) || (pattern_type.bits() == expr_type.bits());
bool lanes_matches = (pattern_type.lanes() == 0) || (pattern_type.lanes() == expr_type.lanes());
bool code_matches = (pattern_type.code() == expr_type.code());
return bits_matches && lanes_matches && code_matches;
}
void visit(const IntImm *op) {
const IntImm *e = expr.as<IntImm>();
if (!e ||
e->value != op->value ||
!types_match(op->type, e->type)) {
result = false;
}
}
void visit(const UIntImm *op) {
const UIntImm *e = expr.as<UIntImm>();
if (!e ||
e->value != op->value ||
!types_match(op->type, e->type)) {
result = false;
}
}
void visit(const FloatImm *op) {
const FloatImm *e = expr.as<FloatImm>();
// Note we use uint64_t equality instead of double equality to
// catch NaNs. We're checking for the same bits.
if (!e ||
reinterpret_bits<uint64_t>(e->value) !=
reinterpret_bits<uint64_t>(op->value) ||
!types_match(op->type, e->type)) {
result = false;
}
}
void visit(const Cast *op) {
const Cast *e = expr.as<Cast>();
if (result && e && types_match(op->type, e->type)) {
expr = e->value;
op->value.accept(this);
} else {
result = false;
}
}
void visit(const Variable *op) {
if (!result) {
return;
}
if (!types_match(op->type, expr.type())) {
result = false;
} else if (matches) {
if (op->name == "*") {
matches->push_back(expr);
} else {
const Variable *e = expr.as<Variable>();
result = e && (e->name == op->name);
}
} else if (var_matches) {
Expr &match = (*var_matches)[op->name];
if (match.defined()) {
result = equal(match, expr);
} else {
match = expr;
}
}
}
template<typename T>
void visit_binary_operator(const T *op) {
const T *e = expr.as<T>();
if (result && e) {
expr = e->a;
op->a.accept(this);
expr = e->b;
op->b.accept(this);
} else {
result = false;
}
}
void visit(const Add *op) {visit_binary_operator(op);}
void visit(const Sub *op) {visit_binary_operator(op);}
void visit(const Mul *op) {visit_binary_operator(op);}
void visit(const Div *op) {visit_binary_operator(op);}
void visit(const Mod *op) {visit_binary_operator(op);}
void visit(const Min *op) {visit_binary_operator(op);}
void visit(const Max *op) {visit_binary_operator(op);}
void visit(const EQ *op) {visit_binary_operator(op);}
void visit(const NE *op) {visit_binary_operator(op);}
void visit(const LT *op) {visit_binary_operator(op);}
void visit(const LE *op) {visit_binary_operator(op);}
void visit(const GT *op) {visit_binary_operator(op);}
void visit(const GE *op) {visit_binary_operator(op);}
void visit(const And *op) {visit_binary_operator(op);}
void visit(const Or *op) {visit_binary_operator(op);}
void visit(const Not *op) {
const Not *e = expr.as<Not>();
if (result && e) {
expr = e->a;
op->a.accept(this);
} else {
result = false;
}
}
void visit(const Select *op) {
const Select *e = expr.as<Select>();
if (result && e) {
expr = e->condition;
op->condition.accept(this);
expr = e->true_value;
op->true_value.accept(this);
expr = e->false_value;
op->false_value.accept(this);
} else {
result = false;
}
}
void visit(const Load *op) {
const Load *e = expr.as<Load>();
if (result && e && types_match(op->type, e->type) && e->name == op->name) {
expr = e->predicate;
op->predicate.accept(this);
expr = e->index;
op->index.accept(this);
} else {
result = false;
}
}
void visit(const Ramp *op) {
const Ramp *e = expr.as<Ramp>();
if (result && e && e->lanes == op->lanes) {
expr = e->base;
op->base.accept(this);
expr = e->stride;
op->stride.accept(this);
} else {
result = false;
}
}
void visit(const Broadcast *op) {
const Broadcast *e = expr.as<Broadcast>();
if (result && e && types_match(op->type, e->type)) {
expr = e->value;
op->value.accept(this);
} else {
result = false;
}
}
void visit(const Call *op) {
const Call *e = expr.as<Call>();
if (result && e &&
types_match(op->type, e->type) &&
e->name == op->name &&
e->value_index == op->value_index &&
e->call_type == op->call_type &&
e->args.size() == op->args.size()) {
for (size_t i = 0; result && (i < e->args.size()); i++) {
expr = e->args[i];
op->args[i].accept(this);
}
} else {
result = false;
}
}
void visit(const Let *op) {
const Let *e = expr.as<Let>();
if (result && e && e->name == op->name) {
expr = e->value;
op->value.accept(this);
expr = e->body;
op->body.accept(this);
} else {
result = false;
}
}
};
bool expr_match(Expr pattern, Expr expr, vector<Expr> &matches) {
matches.clear();
if (!pattern.defined() && !expr.defined()) return true;
if (!pattern.defined() || !expr.defined()) return false;
IRMatch eq(expr, matches);
pattern.accept(&eq);
if (eq.result) {
return true;
} else {
matches.clear();
return false;
}
}
bool expr_match(Expr pattern, Expr expr, map<string, Expr> &matches) {
// Explicitly don't clear matches. This allows usages to pre-match
// some variables.
if (!pattern.defined() && !expr.defined()) return true;
if (!pattern.defined() || !expr.defined()) return false;
IRMatch eq(expr, matches);
pattern.accept(&eq);
if (eq.result) {
return true;
} else {
matches.clear();
return false;
}
}
}}
|
KRE02/magic-search-engine | indexer/lib/patches/patch_reconcile_on_set_priority.rb | <gh_stars>10-100
class PatchReconcileOnSetPriority < Patch
# If something is missing, it will fail validation later on,
# only pass what you'd like to see reconciled automatically
def fields_to_reconcile
[
"name",
"manaCost",
"text",
"types",
"subtypes",
"supertypes",
"rulings",
]
end
def call
each_card do |name, printings|
fields_to_reconcile.each do |field_name|
# All versions are same, or all different versions are low priority
variants = max_priority_variants(printings, field_name)
if variants.size == 1
canonical = variants.keys[0]
printings.each do |printing|
printing[field_name] = canonical
end
else
conflicting_sets = variants.values.map{|scs| scs.join(",") }
warn "Can't reconcile #{name} on #{field_name}, need to prioritize between #{ conflicting_sets.join(" vs ") }"
end
end
end
end
def max_priority_variants(printings, field_name)
by_priority = {}
printings.each do |printing|
set_code = printing["set_code"]
set_priority = printing["set"]["priority"]
variant = printing[field_name]
by_priority[set_priority] ||= {}
by_priority[set_priority][variant] ||= []
by_priority[set_priority][variant] << set_code
end
by_priority[by_priority.keys.max]
end
end
|
kevinpeterson/titanium-json-ld | src/main/java/com/apicatalog/jsonld/framing/ValuePatternMatcher.java | package com.apicatalog.jsonld.framing;
import java.util.Arrays;
import javax.json.JsonObject;
import javax.json.JsonString;
import javax.json.JsonValue;
import com.apicatalog.jsonld.json.JsonUtils;
import com.apicatalog.jsonld.lang.Keywords;
/**
*
* @see <a href="https://w3c.github.io/json-ld-framing/#value-matching">Value Pattern Matching Algorithm</a>
*
*/
public final class ValuePatternMatcher {
// required
private JsonObject pattern;
private JsonObject value;
private ValuePatternMatcher(final JsonObject pattern, final JsonObject value) {
this.pattern = pattern;
this.value = value;
}
public static final ValuePatternMatcher with(final JsonObject pattern, final JsonObject value) {
return new ValuePatternMatcher(pattern, value);
}
public boolean match() {
final JsonValue value2 = pattern.containsKey(Keywords.VALUE)
? pattern.get(Keywords.VALUE)
: null;
final JsonValue type2 = pattern.containsKey(Keywords.TYPE)
? pattern.get(Keywords.TYPE)
: null;
final JsonValue lang2 = pattern.containsKey(Keywords.LANGUAGE)
? pattern.get(Keywords.LANGUAGE)
: null;
if (value2 == null && type2 == null && lang2 == null) {
return true;
}
return matchValue(value2) && matchType(type2) && matchLanguage(lang2);
}
private boolean matchValue(JsonValue value2) {
final JsonValue value1 = value.containsKey(Keywords.VALUE)
? value.get(Keywords.VALUE)
: null;
return (JsonUtils.isNotNull(value1) && isWildcard(value2))
|| (JsonUtils.isNotNull(value2) && JsonUtils.toJsonArray(value2).contains(value1))
;
}
private boolean matchType(JsonValue type2) {
final JsonValue type1 = value.containsKey(Keywords.TYPE)
? value.get(Keywords.TYPE)
: null;
return (JsonUtils.isNotNull(type1) && isWildcard(type2))
|| (JsonUtils.isNull(type1) && isNone(type2))
|| (JsonUtils.isNotNull(type2) && JsonUtils.toJsonArray(type2).contains(type1))
;
}
private boolean matchLanguage(JsonValue lang2) {
final String lang1 = value.containsKey(Keywords.LANGUAGE)
? value.getString(Keywords.LANGUAGE).toLowerCase()
: null;
if ((lang1 != null && isWildcard(lang2))
|| (lang1 == null && isNone(lang2))
) {
return true;
}
if (lang1 == null || lang2 == null) {
return false;
}
return JsonUtils.isNotNull(lang2)
&& JsonUtils.toJsonArray(lang2)
.stream()
.map(JsonString.class::cast)
.map(JsonString::getString)
.anyMatch(x -> x.equalsIgnoreCase(lang1));
}
protected static final boolean isWildcard(JsonValue value, String...except) {
if (JsonUtils.isEmptyObject(value)) {
return true;
}
JsonObject frame = null;
if (JsonUtils.isObject(value)) {
frame = (JsonObject)value;
} else if (JsonUtils.isArray(value)
&& value.asJsonArray().size() == 1
&& JsonUtils.isObject(value.asJsonArray().get(0))) {
frame = value.asJsonArray().getJsonObject(0);
}
if (frame == null) {
return false;
}
return frame.isEmpty() || frame.keySet()
.stream()
.allMatch(Arrays.asList(
Keywords.DEFAULT,
Keywords.OMIT_DEFAULT,
Keywords.EMBED,
Keywords.EXPLICIT,
Keywords.REQUIRE_ALL,
except
)::contains);
}
protected static final boolean isNone(JsonValue value) {
return JsonUtils.isNull(value) || JsonUtils.isEmptyArray(value);
}
}
|
a0953245782/pig-vue | backend/src/main/java/com/chenym/pig/service/RedisService.java | <reponame>a0953245782/pig-vue<gh_stars>1-10
package com.chenym.pig.service;
import com.chenym.pig.common.exception.RedisConnectException;
import com.chenym.pig.vo.RedisInfoVo;
import java.util.List;
import java.util.Map;
public interface RedisService {
/**
* 获取 redis 的详细信息
*
* @return List
*/
List<RedisInfoVo> getRedisInfo() throws RedisConnectException;
/**
* 获取 redis key 数量
*
* @return Map
*/
Map<String, Object> getKeysSize() throws RedisConnectException;
/**
* 获取 redis 内存信息
*
* @return Map
*/
Map<String, Object> getMemoryInfo() throws RedisConnectException;
}
|
MichalCervenansky/sandbox | integration-tests/src/test/java/com/redhat/service/bridge/integration/tests/resources/ResourceUtils.java | <filename>integration-tests/src/test/java/com/redhat/service/bridge/integration/tests/resources/ResourceUtils.java
package com.redhat.service.bridge.integration.tests.resources;
import java.util.Optional;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import static io.restassured.RestAssured.given;
public class ResourceUtils {
public static RequestSpecification jsonRequest(String token) {
return jsonRequest(Optional.ofNullable(token));
}
public static RequestSpecification jsonRequest(Optional<String> token) {
RequestSpecification requestSpec = given().contentType(ContentType.JSON).when();
if (token.isPresent()) {
return requestSpec.auth().oauth2(token.get());
} else {
return requestSpec;
}
}
}
|
pranavsadavarte221b/xv6 | doxygen/html/search/all_15.js | var searchData=
[
['v2p_697',['V2P',['../d8/da9/memlayout_8h.html#a5021188bc7da1304f27e913aee183407',1,'memlayout.h']]],
['v2p_5fwo_698',['V2P_WO',['../d8/da9/memlayout_8h.html#a07c445cd5425fc1d69188d1e6d511e4b',1,'memlayout.h']]],
['vaddr_699',['vaddr',['../de/d4f/structproghdr.html#a6fa1051e19935bbedc5eaf086f5330b4',1,'proghdr']]],
['valid_700',['valid',['../d0/df8/structinode.html#aad324382ba30eb83daa5304fce7dca08',1,'inode']]],
['vectors_701',['vectors',['../dc/d6f/trap_8c.html#a3e6e0e8b5ba8014e09de2d9aa3740486',1,'trap.c']]],
['ver_702',['VER',['../dc/df6/lapic_8c.html#a98ed931f97fef7e06e3ea441d0326c67',1,'lapic.c']]],
['version_703',['version',['../d7/da8/structelfhdr.html#abb1c8274f47cfdbbcefe44af2d5c723d',1,'elfhdr::version()'],['../d8/d01/structmpconf.html#ade1055584605c76f4e1134d6631e0afa',1,'mpconf::version()'],['../d4/d22/structmpproc.html#a6d7948bc046404527c0eec71e3e93209',1,'mpproc::version()'],['../d6/d9b/structmpioapic.html#a7c6f3d950f89e2b982fd53f7c59681e7',1,'mpioapic::version()']]],
['vm_2ec_704',['vm.c',['../de/de9/vm_8c.html',1,'']]],
['vm_2ed_705',['vm.d',['../d2/dea/vm_8d.html',1,'']]]
];
|
jalynxing/choerodon-starters | choerodon-liquibase/src/main/java/io/choerodon/liquibase/excel/DbAdaptor.java | <gh_stars>0
package io.choerodon.liquibase.excel;
import io.choerodon.liquibase.addition.AdditionDataSource;
import io.choerodon.liquibase.helper.LiquibaseHelper;
import liquibase.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import static io.choerodon.liquibase.excel.TableData.TableCellValue;
/**
* DbAdaptor,包含数据库连接信息及基本的操作语句
*
* @author <EMAIL>
*/
public class DbAdaptor {
static final Map<String, Integer> SQL_TYPE_MAP = new HashMap<>();
private static final String ZH_CN = "zh_CN";
private static final String SQL_UPDATE = "update ";
private static final String SQL_WHERE = " where ";
private static final String SQL_SET =" set ";
static {
SQL_TYPE_MAP.put("VARCHAR", Types.VARCHAR);
SQL_TYPE_MAP.put("DATE", Types.DATE);
SQL_TYPE_MAP.put("CLOB", Types.CLOB);
SQL_TYPE_MAP.put("BLOB", Types.BLOB);
SQL_TYPE_MAP.put("DECIMAL", Types.DECIMAL);
SQL_TYPE_MAP.put("BIGINT", Types.BIGINT);
SQL_TYPE_MAP.put("INT", Types.BIGINT);
}
Map<String, String> tableInsertSqlMap = new HashMap<>();
Map<String, String> tableUpdateSqlMap = new HashMap<>();
Map<String, String> tableUpdateTlSqlMap = new HashMap<>();
private SimpleDateFormat sdfL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private SimpleDateFormat sdfS = new SimpleDateFormat("yyyy-MM-dd");
private Logger logger = LoggerFactory.getLogger(getClass());
private DataSource dataSource;
private Connection connection;
private ExcelDataLoader dataProcessor;
private boolean useSeq = false;
private boolean override = true;
private LiquibaseHelper helper;
public DbAdaptor(ExcelDataLoader dataProcessor, AdditionDataSource ad) {
this.dataProcessor = dataProcessor;
this.helper = ad.getLiquibaseHelper();
this.useSeq = helper.isSupportSequence();
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
public void initConnection() throws SQLException {
connection = dataSource.getConnection();
connection.setAutoCommit(false);
}
/**
* 关闭连接.
*
* @param commit 是否commit
*/
public void closeConnection(boolean commit) {
if (connection != null) {
try (Connection c = connection) {
if (commit) {
c.commit();
} else {
c.rollback();
}
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
}
protected Connection getConnection() {
return connection;
}
/**
* 处理表行.
*
* @param tableRow 表行
* @return 新插入, 或检测存在 则返回 1,否则0
* @throws SQLException SQL异常
*/
public int processTableRow(TableData.TableRow tableRow) throws SQLException {
if (tableRow.isProcessFlag()) {
return 0;
}
Long cu = checkExists(tableRow);
if (cu == null && tableRow.canInsert()) {
doInsert(tableRow);
doInsertTl(tableRow);
return 1;
} else if (cu != null && cu >= 0) {
tableRow.setProcessFlag(true);
doInsertTl(tableRow);
return 1;
}
return 0;
}
/**
* 检查行是否存在.
*
* @param tableRow 表行
* @return 反回 -1: 不能检查唯一性(唯一性字段值不确定),返回 0:存在,但没有自动生成的主键, 返回 null:不存在, 返回 大于0:存在,现有主键
* @throws SQLException SQL异常
*/
protected Long checkExists(TableData.TableRow tableRow) throws SQLException {
boolean uniquePresent = true;
TableCellValue genTableCellValue = null;
for (TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.getColumn().isGen()) {
genTableCellValue = tableCellValue;
}
if (tableCellValue.isFormula() && !tableCellValue.isValuePresent()) {
dataProcessor.tryUpdateCell(tableCellValue);
}
if (tableCellValue.getColumn().isUnique()) {
uniquePresent = uniquePresent && tableCellValue.isValuePresent();
}
}
if (!uniquePresent) {
logger.info("[{}] check exists: ?? row:{} ,result :(-1)not ready",
tableRow.getTable().getName(), tableRow);
return -1L;
}
StringBuilder sb = new StringBuilder();
sb.append("select ").append(genTableCellValue == null ? "0" : genTableCellValue.getColumn().getName())
.append(" from ").append(tableRow.getTable().getName());
sb.append(" where ");
List<String> list = new ArrayList<>();
List<TableCellValue> params = new ArrayList<>();
for (TableData.TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.getColumn().isUnique()) {
list.add(tableCellValue.getColumn().getName() + "=?");
params.add(tableCellValue);
}
}
sb.append(StringUtils.join(list, " AND "));
try (PreparedStatement ps = connection.prepareStatement(sb.toString())) {
int index = 1;
for (TableCellValue tableCellValue : params) {
setParam(ps, tableCellValue, index++);
}
try (ResultSet rs = ps.executeQuery()) {
if (rs == null || !rs.next()) {
logger.info("[{}] check exists: <> row:{} ,result :not exists",
tableRow.getTable().getName(), tableRow);
return null;
}
Long pk = rs.getLong(1);
if (rs.next()) {
throw new IllegalStateException("check unique found more than one,row:"
+ tableRow);
}
logger.info("[{}] check exists: == row:{} ,result :{}", tableRow.getTable().getName(), tableRow, pk);
if (genTableCellValue != null) {
genTableCellValue.updateValue("" + pk);
}
tableRow.setExistsFlag(true);
return pk;
} catch (SQLException e) {
logger.error("[{}]error check unique, row:{}, sql:{}",
tableRow.getTable().getName(), tableRow, sb);
throw e;
}
}
}
/**
* 更新TableRow.
* 调用此方法之前,需要确保所有值已就绪。
*
* @param tableRow 要更新的TableRow
* @return update count
* @throws SQLException SQL异常
*/
protected int doUpdate(TableData.TableRow tableRow, Set<String> excludedColumns, Set<String> logInfo) throws SQLException {
int updateCount = 0;
TableCellValue genTableCellValue = null;
List<TableCellValue> uniques = new ArrayList<>();
List<TableCellValue> normals = new ArrayList<>();
for (TableData.TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.isFormula() && !tableCellValue.isValuePresent()) {
dataProcessor.tryUpdateCell(tableCellValue);
}
if (tableCellValue.getColumn().isGen()) {
genTableCellValue = tableCellValue;
} else if (tableCellValue.getColumn().isUnique()) {
if (!excluded(tableCellValue.getColumn().getName(), excludedColumns)) {
uniques.add(tableCellValue);
} else {
logInfo.add(processLog(tableRow, tableCellValue));
}
} else {
if (!excluded(tableCellValue.getColumn().getName(), excludedColumns)) {
normals.add(tableCellValue);
} else {
logInfo.add(processLog(tableRow, tableCellValue));
}
}
}
if (genTableCellValue != null) {
uniques.clear();
uniques.add(genTableCellValue);
}
if (normals.isEmpty()) {
return updateCount;
}
//更新表的sql
String sql = prepareTableUpdateSql(tableRow, uniques, normals);
try (PreparedStatement ps = connection.prepareStatement(sql)) {
int index = 1;
for (TableCellValue tableCellValue : normals) {
if (tableCellValue.getColumn().getLang() == null
|| ZH_CN.equalsIgnoreCase(tableCellValue.getColumn().getLang())) {
setParam(ps, tableCellValue, index++);
}
}
for (TableCellValue tableCellValue : uniques) {
setParam(ps, tableCellValue, index++);
}
updateCount += ps.executeUpdate();
tableRow.setUpdateFlag(true);
} catch (SQLException e) {
logger.error("[{}]update error, row:{} ,sql:{}",
tableRow.getTable().getName(), tableRow, sql);
throw e;
}
if (genTableCellValue == null || tableRow.getTable().getLangs().isEmpty()) {
return updateCount;
}
//更新多语言表的sql
sql = prepareTableUpdateTlSql(tableRow, genTableCellValue, normals);
for (String lang : tableRow.getTable().getLangs()) {
try (PreparedStatement ps = connection.prepareStatement(sql)) {
int index = 1;
for (TableData.TableCellValue tableCellValue : normals) {
if (lang.equals(tableCellValue.getColumn().getLang())) {
setParam(ps, tableCellValue, index++);
}
}
setParam(ps, genTableCellValue, index++);
ps.setString(index, lang);
updateCount += ps.executeUpdate();
} catch (SQLException e) {
logger.error("[{}]error update tl ,row:{},sql:{}",
tableRow.getTable().getName(), tableRow, sql);
throw e;
}
}
return updateCount;
}
private String processLog(TableData.TableRow tableRow, TableCellValue tableCellValue) {
StringBuilder sb = new StringBuilder();
sb.append("skip update table : ");
sb.append(tableRow.getTable().getName());
sb.append(" column: ");
sb.append(tableCellValue.getColumn().getName());
return sb.toString();
}
private boolean excluded(String column, Set<String> excludedColumns) {
if (excludedColumns != null) {
for (String excludedColumn : excludedColumns) {
if (excludedColumn != null && excludedColumn.equalsIgnoreCase(column)) {
return true;
}
}
}
return false;
}
private String prepareTableUpdateSql(TableData.TableRow tableRow,
List<TableCellValue> uniques,
List<TableCellValue> normals) {
String sql = tableUpdateSqlMap.get(tableRow.getTable().getName());
if (sql == null) {
StringBuilder sb = new StringBuilder();
sb.append(SQL_UPDATE).append(tableRow.getTable().getName()).append(SQL_SET);
for (TableCellValue tableCellValue : normals) {
if (tableCellValue.getColumn().getLang() == null
|| ZH_CN.equalsIgnoreCase(tableCellValue.getColumn().getLang())) {
sb.append(tableCellValue.getColumn().getName());
sb.append("=?,");
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append(SQL_WHERE);
for (TableCellValue tableCellValue : uniques) {
sb.append(tableCellValue.getColumn().getName());
sb.append("=? AND ");
}
sb.delete(sb.length() - 4, sb.length());
sql = sb.toString();
tableUpdateSqlMap.put(tableRow.getTable().getName(), sql);
}
return sql;
}
private String prepareTableUpdateTlSql(TableData.TableRow tableRow,
TableCellValue genTableCellValue,
List<TableCellValue> normals) {
String sql = tableUpdateTlSqlMap.get(tableRow.getTable().getName());
if (sql == null) {
StringBuilder sb = new StringBuilder();
sb.append(SQL_UPDATE).append(tlTableName(tableRow.getTable().getName())).append(SQL_SET);
for (TableData.TableCellValue tableCellValue : normals) {
if (ZH_CN.equalsIgnoreCase(tableCellValue.getColumn().getLang())) {
sb.append(tableCellValue.getColumn().getName()).append("=?,");
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append(SQL_WHERE).append(genTableCellValue.getColumn().getName()).append("=? and lang=?");
sql = sb.toString();
tableUpdateTlSqlMap.put(tableRow.getTable().getName(), sql);
}
return sql;
}
/**
* 在调用本方法之前,需确保 该行记录具备插入条件.
*
* @param tableRow tableRow
* @return 返回结果码
* @throws SQLException 异常
*/
protected Long doInsert(TableData.TableRow tableRow) throws SQLException {
String sql = prepareInsertSql(tableRow);
Long genVal = null;
TableData.TableCellValue genTableCellValue = null;
try (PreparedStatement ps = connection.prepareStatement(sql,
PreparedStatement.RETURN_GENERATED_KEYS)) {
int nn = 1;
for (TableData.TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.getColumn().isGen()) {
genTableCellValue = tableCellValue;
if (sequencePk()) {
genVal = getSeqNextVal(tableRow.getTable().getName());
ps.setLong(nn++, genVal);
}
continue;
}
if (tableCellValue.getColumn().getLang() == null
|| ZH_CN.equals(tableCellValue.getColumn().getLang())) {
if (!tableCellValue.isValuePresent() && tableCellValue.isFormula()) {
ps.setLong(nn++, -1L);
} else {
setParam(ps, tableCellValue, nn++);
}
}
}
try {
ps.executeUpdate();
tableRow.setInsertFlag(true);
} catch (SQLException sqle) {
logger.error("[{}]error insert row:{} sql:{}",
tableRow.getTable().getName(), tableRow, sql);
throw sqle;
}
logger.info("insert row:{}", tableRow);
tableRow.getTable().setInsert(tableRow.getTable().getInsert() + 1);
if (!sequencePk() && genTableCellValue != null) {
try (ResultSet rs = ps.getGeneratedKeys()) {
if (rs != null && rs.next()) {
genVal = rs.getLong(1);
} else {
logger.warn("no gen pk,row:{}", tableRow);
}
}
}
}
if (genTableCellValue != null) {
genTableCellValue.updateValue("" + genVal);
}
tableRow.setProcessFlag(true);
return genVal;
}
private List<TableData.TableCellValue> getUnpresentFormulaTds(TableData.TableRow tableRow) {
List<TableData.TableCellValue> formulaTableCellValues = new ArrayList<>();
for (TableData.TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.isFormula() && !tableCellValue.isValuePresent()) {
formulaTableCellValues.add(tableCellValue);
}
}
return formulaTableCellValues;
}
/**
* 插入不存在的行,暂时不理会不能确定的值.
*
* @param tables getTable()
* @throws SQLException 异常
*/
public int weakInsert(List<TableData> tables) throws SQLException {
List<TableData.TableRow> tempList = new ArrayList<>();
for (TableData tableData : tables) {
for (TableData.TableRow tableRow : tableData.getTableRows()) {
if (tableRow.isProcessFlag()) {
continue;
}
Long cu = checkExists(tableRow);
if (cu == null) {
doInsert(tableRow);
tableRow.setProcessFlag(false);
logger.info("weak insert row:{}", tableRow);
doInsertTl(tableRow);
tempList.add(tableRow);
} else if (cu > 0) {
doInsertTl(tableRow);
tempList.add(tableRow);
}
}
}
int count = 0;
do {
count = 0;
for (TableData.TableRow tableRow : tempList) {
if (tableRow.isProcessFlag()) {
continue;
}
List<TableData.TableCellValue> formulaTableCellValues =
getUnpresentFormulaTds(tableRow);
int cc = 0;
for (TableData.TableCellValue tableCellValue : formulaTableCellValues) {
if (dataProcessor.tryUpdateCell(tableCellValue)) {
cc++;
doPostUpdate(tableRow, tableCellValue, Long.parseLong(""
+ tableCellValue.getValue()));
count++;
}
}
if (cc == formulaTableCellValues.size()) {
tableRow.setProcessFlag(true);
tableRow.setInsertFlag(true);
}
}
} while (count > 0);
for (TableData.TableRow tableRow : tempList) {
if (!tableRow.isProcessFlag()) {
throw new RuntimeException("can not insert :" + tableRow);
}
}
return tempList.size();
}
/**
* 当执行 weakInsert 后,使用该方法修复数据.
*
* @param tableRow tableRow
* @param tableCellValue tableCellValue
* @param value value
* @throws SQLException SQLException
*/
protected void doPostUpdate(TableData.TableRow tableRow,
TableCellValue tableCellValue,
Long value) throws SQLException {
TableData.TableCellValue genTableCellValue = null;
for (TableCellValue d : tableRow.getTableCellValues()) {
if (d.getColumn().isGen()) {
genTableCellValue = d;
break;
}
}
StringBuilder sb = new StringBuilder();
sb.append(SQL_UPDATE).append(tableRow.getTable().getName()).append(SQL_SET)
.append(tableCellValue.getColumn().getName()).append("=? where ");
if (genTableCellValue != null) {
sb.append(genTableCellValue.getColumn().getName()).append("=?");
}
try (PreparedStatement ps = connection.prepareStatement(sb.toString())) {
ps.setLong(1, value);
if (genTableCellValue != null) {
setParam(ps, genTableCellValue, 2);
}
ps.executeUpdate();
logger.debug("update getColumn():{} value:{} row:{}",
tableCellValue.getColumn().getName(), value, tableRow);
} catch (SQLException ee) {
logger.error("[{}]error post update getColumn():{},row:{} ,sql:{}",
tableRow.getTable().getName(), tableCellValue.getColumn().getName(), tableRow, sb);
throw ee;
}
}
private void setParam(PreparedStatement ps,
TableData.TableCellValue tableCellValue,
int nn) throws SQLException {
Object vv = convertDataType(tableCellValue.getValue(), tableCellValue.getColumn().getType());
if (vv == null) {
ps.setNull(nn, SQL_TYPE_MAP.get(tableCellValue.getColumn().getType()));
} else if (vv instanceof String) {
ps.setString(nn, (String) vv);
} else if (vv instanceof Long) {
ps.setLong(nn, (Long) vv);
} else if (vv instanceof Date) {
ps.setDate(nn, new java.sql.Date(((Date) vv).getTime()));
} else if (vv instanceof Double) {
ps.setDouble(nn, (Double) vv);
} else {
ps.setObject(nn, vv);
}
}
protected boolean checkTlExists(TableData.TableRow tableRow,
String lang) throws SQLException {
StringBuilder sb = new StringBuilder();
TableCellValue genTableCellValue = null;
for (TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.getColumn().isGen() || tableCellValue.getColumn().isUnique()) {
genTableCellValue = tableCellValue;
break;
}
}
if (genTableCellValue == null) {
return true;
}
sb.append("select 1 from ").append(tlTableName(tableRow.getTable().getName()));
sb.append(" where ").append(genTableCellValue.getColumn().getName()).append("=?");
sb.append(" AND LANG=?");
String sql = sb.toString();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setObject(1, genTableCellValue.getValue());
ps.setObject(2, lang);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
} catch (SQLException e) {
logger.error("[{}]error check tl exists, row:{} ,sql:{}",
tableRow.getTable().getName(), tableRow, sql);
throw e;
}
}
}
private String tlTableName(String tableName) {
String s = tableName.replaceAll("_", "");
boolean allIsUpperCase = true;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isLowerCase(c)) {
allIsUpperCase = false;
break;
}
}
if (allIsUpperCase) {
return tableName + "_TL";
} else {
return tableName + "_tl";
}
}
/**
* 为支持的语言插入多语言数据.
* <br>
* 不支持多语言的表,没有任何副作用<br>
* 插入之前,会检查等价数据是否存在
*
* @param tableRow tableRow
* @return 操作结果
* @throws SQLException 异常
*/
protected int doInsertTl(TableData.TableRow tableRow) throws SQLException {
int cc = 0;
for (String lang : tableRow.getTable().getLangs()) {
// 没有多语言支持的话,这个循环不会执行
// 当基表插入成功以后,tl 表肯定可以插入成功(如果不存在)
cc += doInsertTl(tableRow, lang);
}
return cc;
}
protected int doInsertTl(TableData.TableRow tableRow, String lang) throws SQLException {
if (checkTlExists(tableRow, lang)) {
return 0;
}
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(tlTableName(tableRow.getTable().getName())).append("(");
List<String> keys = new LinkedList<>();
List<TableData.TableCellValue> values = new LinkedList<>();
TableData.TableCellValue unique = null;
boolean isGen = false;
for (TableData.TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.getColumn().isUnique()) {
unique = tableCellValue;
}
if (tableCellValue.getColumn().isGen()) {
isGen = true;
keys.add(tableCellValue.getColumn().getName());
values.add(tableCellValue);
} else if (lang.equals(tableCellValue.getColumn().getLang())) {
keys.add(tableCellValue.getColumn().getName());
values.add(tableCellValue);
}
}
if (!isGen && unique != null) {
keys.add(unique.getColumn().getName());
values.add(unique);
}
keys.add("lang");
sb.append(StringUtils.join(keys, ","));
sb.append(")VALUES(");
for (int i = 0; i < values.size(); i++) {
sb.append("?").append(",");
}
sb.append("?)");
String sql = sb.toString();
try (PreparedStatement ps = connection.prepareStatement(sql)) {
int nn = 1;
for (TableData.TableCellValue tableCellValue : values) {
setParam(ps, tableCellValue, nn++);
}
ps.setString(nn, lang);
try {
ps.executeUpdate();
} catch (SQLException sqle) {
logger.error("[{}]error insert tl row:{} sql:{}",
tableRow.getTable().getName(), tableRow, sql);
throw sqle;
}
}
logger.info("insert tl for row : {} lang:{}", tableRow, lang);
return 1;
}
protected Object convertDataType(String value, String type) {
if (StringUtils.isEmpty(value)) {
return null;
}
if ("DATE".equalsIgnoreCase(type)) {
try {
if (value.length() <= 10) {
return sdfS.parse(value);
}
return sdfL.parse(value);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
if ("DECIMAL".equalsIgnoreCase(type) || "NUMBER".equalsIgnoreCase(type)
|| "BIGINT".equalsIgnoreCase(type)) {
if (value.length() == 0) {
return null;
}
if (value.contains(".")) {
return Double.parseDouble(value);
}
return Long.parseLong(value);
}
return value;
}
protected String prepareInsertSql(TableData.TableRow tableRow) {
String sql = tableInsertSqlMap.get(tableRow.getTable().getName());
if (sql == null) {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(tableRow.getTable().getName()).append("(");
int cc = 0;
for (TableData.TableCellValue tableCellValue : tableRow.getTableCellValues()) {
if (tableCellValue.getColumn().isGen() && !sequencePk()) {
continue;
}
if (tableCellValue.getColumn().getLang() == null
|| ZH_CN.equals(tableCellValue.getColumn().getLang())) {
cc++;
sb.append(tableCellValue.getColumn().getName());
sb.append(",");
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append(") VALUES (");
for (int i = 0; i < cc; i++) {
sb.append("?,");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(")");
sql = sb.toString();
tableInsertSqlMap.put(tableRow.getTable().getName(), sql);
}
return sql;
}
protected Long getSeqNextVal(String tableName) throws SQLException {
try (PreparedStatement ps = connection.prepareStatement("select "
+ tableName + "_s.nextval from dual")) {
try (ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getLong(1);
} catch (SQLException e) {
logger.error("error get sequence nextVal, tableName:{}", tableName);
throw e;
}
}
}
protected boolean sequencePk() {
return useSeq;
}
}
|
alligatormon/alligator | src/metric/metrictree.h | #pragma once
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <stdlib.h>
#include <ctype.h>
#include "metric/labels.h"
#include "metric/percentile_heap.h"
#include "common/selector.h"
#define RED 1
#define BLACK 0
#define RIGHT 1
#define LEFT 0
typedef struct sort_order_node {
char *name;
tommy_node node;
uint32_t hash;
} sort_order_node;
typedef struct sortplan
{
char *plan[65535];
size_t size;
} sortplan;
typedef struct labels_t
{
char *name;
size_t name_len;
char *key;
size_t key_len;
sortplan *sort_plan;
uint8_t allocatedname;
uint8_t allocatedkey;
struct labels_t *next;
} labels_t;
typedef struct labels_container
{
char *name;
char *key;
uint8_t allocatedname;
uint8_t allocatedkey;
tommy_node node;
} labels_container;
typedef struct labels_words_cache
{
char *w;
size_t l;
size_t count;
tommy_node node;
} labels_words_cache;
typedef struct metric_list {
union
{
double d;
uint64_t u;
int64_t i;
char *s; // string
};
uint64_t timestamp;
uint64_t serial;
} metric_list;
struct expire_node;
struct expire_tree;
typedef struct metric_node
{
union
{
double d;
uint64_t u;
int64_t i;
char *s; // string
char *index; // index file
metric_list *list;
};
int16_t index_element_list;
int8_t type;
percentile_buffer *pb;
int8_t en;
struct metric_node *steam[2];
//struct metric_tree *stree;
labels_t *labels;
int color;
struct expire_node *expire_node;
} metric_node;
typedef struct expire_node
{
int color;
int64_t key;
metric_node *metric;
struct expire_node *steam[2];
} expire_node;
typedef struct metric_tree
{
struct metric_node *root;
int64_t count;
size_t str_size;
sortplan *sort_plan;
tommy_hashdyn* labels_words_hash;
} metric_tree;
typedef struct mapping_label
{
char *name;
char *key;
struct mapping_label *next;
} mapping_label;
typedef struct mapping_metric
{
char *metric_name;
char *template;
size_t template_len;
struct mapping_metric *next;
uint64_t match;
size_t glob_size;
char **glob;
int64_t *percentile;
int64_t percentile_size;
int64_t *bucket;
int64_t bucket_size;
int64_t *le;
int64_t le_size;
size_t wildcard;
mapping_label *label_head;
mapping_label *label_tail;
} mapping_metric;
typedef struct query_struct {
char *metric_name;
char *key;
double val;
double min;
double max;
tommy_hashdyn *lbl;
uint64_t count;
tommy_node node;
} query_struct;
//void metric_add_labels5(char *name, void* value, int8_t type, char *namespace, char *name1, char *key1, char *name2, char *key2, char *name3, char *key3, char *name4, char *key4, char *name5, char *key5);
void metric_delete (metric_tree *tree, labels_t *labels, struct expire_tree *expiretree);
metric_node* metric_find(metric_tree *tree, labels_t* labels);
void metrictree_get(metric_node *x, labels_t* labels, string *str);
void labels_gen_string(labels_t *labels, int l, string *str, metric_node *x);
|
vdvorak83/Job4j | SQL_JDBC/6.TestTask/vacancyParser/src/test/java/ru/matevosyan/dataBase/package-info.java | <gh_stars>1-10
/**
* ConnectionDBTest class for testing database connection.
* created on 26.01.2018
* @author <NAME>.
* @version 1.0
*/
package ru.matevosyan.dataBase; |
CNResoy/Spicy | src/minecraft/spicy/gui/click/component/components/sub/Keybind.java | package spicy.gui.click.component.components.sub;
import net.minecraft.client.renderer.GlStateManager;
import org.lwjgl.input.Keyboard;
import spicy.gui.click.component.Component;
import spicy.gui.click.component.components.Button;
import spicy.main.Spicy;
public class Keybind extends Component
{
private boolean hovered;
private boolean binding;
private Button parent;
private int offset;
private int x;
private int y;
public Keybind(final Button button, final int offset) {
this.parent = button;
this.x = button.parent.getX() + button.parent.getWidth();
this.y = button.parent.getY() + button.offset;
this.offset = offset;
}
@Override
public void setOff(final int newOff) {
this.offset = newOff;
}
@Override
public void renderComponent() {
Spicy.INSTANCE.fontManager.getFont("FONT 15").drawStringWithShadow(this.binding ? "Press a key..." : ("Key: " + Keyboard.getKeyName(this.parent.mod.getModuleKey())), (float)(this.parent.parent.getX() + 6), (float)(this.parent.parent.getY() + this.offset + 3), -1);
GlStateManager.color(1,1,1);
}
@Override
public void updateComponent(final int mouseX, final int mouseY) {
this.hovered = this.isMouseOnButton(mouseX, mouseY);
this.y = this.parent.parent.getY() + this.offset;
this.x = this.parent.parent.getX();
}
@Override
public void mouseClicked(final int mouseX, final int mouseY, final int button) {
if (this.isMouseOnButton(mouseX, mouseY) && button == 0 && this.parent.open) {
this.binding = !this.binding;
}
}
@Override
public void keyTyped(final char typedChar, final int key) {
if (this.binding) {
if (key == 211 || key == 57) {
this.parent.mod.setModuleKey(0);
this.binding = false;
return;
}
this.parent.mod.setModuleKey(key);
this.binding = false;
}
}
public boolean isMouseOnButton(final int x, final int y) {
return x > this.x && x < this.x + this.parent.parent.getWidth() && y > this.y - 1 && y < this.y + 14;
}
@Override
public int getHeight() {
return 16;
}
}
|
adam-rocska/closure-templates-php | java/tests/com/google/template/soy/soytree/AbstractSoyCommandNodeTest.java | <gh_stars>1-10
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.soytree;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.basetree.CopyState;
import com.google.template.soy.soytree.SoyNode.Kind;
import junit.framework.TestCase;
/**
* Unit tests for AbstractCommandNode.
*
*/
public final class AbstractSoyCommandNodeTest extends TestCase {
public void testGetTagString() {
DummyNode dn = new DummyNode(8, "blah blah");
assertEquals("{dummy blah blah}", dn.getTagString());
assertEquals("{dummy blah blah}", dn.toSourceString());
dn = new DummyNode(8, "{blah} blah");
assertEquals("{{dummy {blah} blah}}", dn.getTagString());
assertEquals("{{dummy {blah} blah}}", dn.toSourceString());
dn = new DummyNode(8, "blah {blah}");
assertEquals("{{dummy blah {blah} }}", dn.getTagString());
assertEquals("{{dummy blah {blah} }}", dn.toSourceString());
}
private static class DummyNode extends AbstractCommandNode {
public DummyNode(int id, String commandText) {
super(id, SourceLocation.UNKNOWN, "dummy", commandText);
}
@Override public Kind getKind() {
throw new UnsupportedOperationException();
}
@Override public DummyNode copy(CopyState copyState) {
throw new UnsupportedOperationException();
}
}
}
|
rapidstack/RESTEasyCLI | resteasycli/cmd/main.py | import sys
from cliff.app import App
from cliff.help import HelpCommand
from cliff.commandmanager import CommandManager
from resteasycli.config import Config
from resteasycli.lib.workspace import Workspace
from resteasycli.exceptions import FileNotFoundException
class CLIApp(App):
'''The main CLI app'''
def __init__(self):
super(CLIApp, self).__init__(
description=Config.DESCRIPTION,
version=Config.VERSION,
command_manager=CommandManager('cliff.recli.pre_init'),
deferred_help=True,
)
# TODO: Add auto completion the best way
# self.command_manager.add_command(
# 'complete', CompleteCommand)
self.workspace = None
def initialize_app(self, argv):
self.LOG.debug('initializing app')
try:
self.workspace = Workspace(logger=self.LOG)
self.command_manager.namespace = 'cliff.recli.post_init'
self.command_manager.load_commands(self.command_manager.namespace)
except FileNotFoundException:
pass
def prepare_to_run_command(self, cmd):
self.LOG.debug('preparing to run command {}'.format(
cmd.__class__.__name__))
def clean_up(self, cmd, result, err):
self.LOG.debug('cleaning up {}'.format(cmd.__class__.__name__))
if err:
self.LOG.debug('got an error: {}'.format(err))
def main(argv=sys.argv[1:]):
app = CLIApp()
try:
return app.run(argv)
except Exception as e:
sys.stderr.write('error: {}\n'.format(e))
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
kphed/soshen-oss | node-api-server/src/util/constants.js | module.exports = {
errorMessages: {
MISSING_PROPS: 'Missing required properties',
UNNECESSARY_PROPS: 'Contains unnecessary properties',
INVALID_PROP_TYPES: 'Invalid property types',
ACCESS_DENIED: 'Access denied',
INVALID_CREDENTIALS: 'Invalid credentials',
},
};
|
cdalvaro/project-euler | challenges/c0013/challenge.cpp | //
// challenge.cpp
// Challenges
//
// Created by <NAME> on 25/07/2020.
// Copyright © 2020 cdalvaro. All rights reserved.
//
#include <charconv>
#include <sstream>
#include <string>
#include "challenges/c0013/challenge.hpp"
using namespace challenges;
const std::vector<tools::types::BigInt> Challenge13::bigints{
"37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690"};
Challenge13::Challenge13() {
}
std::any Challenge13::solve() {
Type_t result;
tools::types::BigInt bigint;
for (const auto &number : bigints) {
bigint += number;
}
std::string_view sv_bigint{bigint.str()};
std::from_chars(sv_bigint.begin(), std::next(sv_bigint.begin(), 10), result);
return result;
}
|
dthung1602/MangaBookmark | frontend/src/components/EditManga/BasicFields.js | import Proptypes from "prop-types";
import FilterDropdown from "../Filters/FilterDropdown";
import LoopButton from "../Filters/LoopButton";
import { SHELVES } from "../../utils/constants";
import "./BasicFields.less";
const BasicFields = ({ manga, editManga, layout }) => {
const block = layout === "column";
return (
<div className={`basic-fields ${layout}`}>
<FilterDropdown
displayName={"Shelf"}
options={SHELVES}
showAnyOption={false}
selected={manga.shelf}
onSelect={editManga("shelf")}
block={block}
/>
<LoopButton
displayName={"Completed"}
options={["true", "false"]}
showAnyOption={false}
selected={String(manga.isCompleted)}
onSelect={editManga("isCompleted")}
block={block}
/>
<LoopButton
displayName={"Hidden"}
options={["true", "false"]}
showAnyOption={false}
selected={String(manga.hidden)}
onSelect={editManga("hidden")}
block={block}
/>
</div>
);
};
BasicFields.propTypes = {
manga: Proptypes.object.isRequired,
editManga: Proptypes.func.isRequired,
layout: Proptypes.oneOf(["column", "row"]).isRequired,
};
export default BasicFields;
|
RefactoringBotUser/clarity | src/main/java/skadistats/clarity/decoder/unpacker/factory/s1/LongUnpackerFactory.java | package skadistats.clarity.decoder.unpacker.factory.s1;
import skadistats.clarity.decoder.s1.SendProp;
import skadistats.clarity.decoder.unpacker.*;
import skadistats.clarity.model.s1.PropFlag;
public class LongUnpackerFactory implements UnpackerFactory<Long> {
public static Unpacker<Long> createUnpackerStatic(SendProp prop) {
int flags = prop.getFlags();
if ((flags & PropFlag.ENCODED_AS_VARINT) != 0) {
if ((flags & PropFlag.UNSIGNED) != 0) {
return new LongVarUnsignedUnpacker();
} else {
return new LongVarSignedUnpacker();
}
} else {
if ((flags & PropFlag.UNSIGNED) != 0) {
return new LongUnsignedUnpacker(prop.getNumBits());
} else {
return new LongSignedUnpacker(prop.getNumBits());
}
}
}
@Override
public Unpacker<Long> createUnpacker(SendProp prop) {
return createUnpackerStatic(prop);
}
}
|
papahigh/r2dbc-mysql | src/main/java/dev/miku/r2dbc/mysql/codec/ParametrizedCodec.java | /*
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.miku.r2dbc.mysql.codec;
import io.netty.buffer.ByteBuf;
import reactor.util.annotation.Nullable;
import java.lang.reflect.ParameterizedType;
/**
* Special codec for decode values with parameterized types.
* <p>
* It also can encode and decode values without parameter.
*
* @param <T> the type without parameter that is handled by this codec.
*/
public interface ParametrizedCodec<T> extends Codec<T> {
@Nullable
Object decode(ByteBuf value, FieldInformation info, ParameterizedType target, boolean binary, CodecContext context);
boolean canDecode(FieldInformation info, ParameterizedType target);
}
|
vschiavoni/unine-twine | benchmarks/sqlite/instrumentation-callbacks/src/timing_callbacks.c | <reponame>vschiavoni/unine-twine
#include <stdio.h>
#include "instrumentation_callbacks.h"
void on_initialization_finished() {}
void on_records_inserted(int database_type, int number_of_write,
int number_of_read, long int time)
{
printf("i,%d,%d,%d,%ld\n", database_type, number_of_write, number_of_read, time);
}
void on_sequential_queries_finished(int database_type, int number_of_write,
int number_of_read, long int time)
{
printf("qs,%d,%d,%d,%ld\n", database_type, number_of_write, number_of_read, time);
}
void on_random_queries_finished(int database_type, int number_of_write,
int number_of_read, long int time)
{
printf("qr,%d,%d,%d,%ld\n", database_type, number_of_write, number_of_read, time);
} |
codefollower/Open-Source-Research | HotSpot1.7-JVM-Linux-x86/src/share/vm/memory/compactingPermGenGen.cpp | <filename>HotSpot1.7-JVM-Linux-x86/src/share/vm/memory/compactingPermGenGen.cpp<gh_stars>100-1000
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "memory/compactingPermGenGen.hpp"
#include "memory/filemap.hpp"
#include "memory/genOopClosures.inline.hpp"
#include "memory/generation.inline.hpp"
#include "memory/generationSpec.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/java.hpp"
#ifndef SERIALGC
#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp"
#endif
// An ObjectClosure helper: Recursively adjust all pointers in an object
// and all objects by referenced it. Clear marks on objects in order to
// prevent visiting any object twice. This helper is used when the
// RedefineClasses() API has been called.
class AdjustSharedObjectClosure : public ObjectClosure {
public:
void do_object(oop obj) {
if (obj->is_shared_readwrite()) {
if (obj->mark()->is_marked()) {
obj->init_mark(); // Don't revisit this object.
obj->adjust_pointers(); // Adjust this object's references.
}
}
}
};
// An OopClosure helper: Recursively adjust all pointers in an object
// and all objects by referenced it. Clear marks on objects in order
// to prevent visiting any object twice.
class RecursiveAdjustSharedObjectClosure : public OopClosure {
protected:
template <class T> inline void do_oop_work(T* p) {
oop obj = oopDesc::load_decode_heap_oop_not_null(p);
if (obj->is_shared_readwrite()) {
if (obj->mark()->is_marked()) {
obj->init_mark(); // Don't revisit this object.
obj->oop_iterate(this); // Recurse - adjust objects referenced.
obj->adjust_pointers(); // Adjust this object's references.
// Special case: if a class has a read-only constant pool,
// then the read-write objects referenced by the pool must
// have their marks reset.
if (obj->klass() == Universe::instanceKlassKlassObj()) {
instanceKlass* ik = instanceKlass::cast((klassOop)obj);
constantPoolOop cp = ik->constants();
if (cp->is_shared_readonly()) {
cp->oop_iterate(this);
}
}
}
}
}
public:
virtual void do_oop(oop* p) { RecursiveAdjustSharedObjectClosure::do_oop_work(p); }
virtual void do_oop(narrowOop* p) { RecursiveAdjustSharedObjectClosure::do_oop_work(p); }
};
// We need to go through all placeholders in the system dictionary and
// try to resolve them into shared classes. Other threads might be in
// the process of loading a shared class and have strong roots on
// their stack to the class without having added the class to the
// dictionary yet. This means the class will be marked during phase 1
// but will not be unmarked during the application of the
// RecursiveAdjustSharedObjectClosure to the SystemDictionary.
class TraversePlaceholdersClosure {
public:
static void placeholders_do(Symbol* sym, oop loader) {
if (CompactingPermGenGen::is_shared(sym)) {
oop k = SystemDictionary::find_shared_class(sym);
if (k != NULL) {
RecursiveAdjustSharedObjectClosure clo;
clo.do_oop(&k);
}
}
}
};
void CompactingPermGenGen::initialize_performance_counters() {
const char* gen_name = "perm";
// Generation Counters - generation 2, 1 subspace
_gen_counters = new GenerationCounters(gen_name, 2, 1, &_virtual_space);
_space_counters = new CSpaceCounters(gen_name, 0,
_virtual_space.reserved_size(),
_the_space, _gen_counters);
}
void CompactingPermGenGen::update_counters() {
if (UsePerfData) {
_space_counters->update_all();
_gen_counters->update_all();
}
}
CompactingPermGenGen::CompactingPermGenGen(ReservedSpace rs,
ReservedSpace shared_rs,
size_t initial_byte_size,
int level, GenRemSet* remset,
ContiguousSpace* space,
PermanentGenerationSpec* spec_) :
OneContigSpaceCardGeneration(rs, initial_byte_size, MinPermHeapExpansion,
level, remset, space) {
set_spec(spec_);
if (!UseSharedSpaces && !DumpSharedSpaces) {
spec()->disable_sharing();
}
// Break virtual space into address ranges for all spaces.
if (spec()->enable_shared_spaces()) {
shared_end = (HeapWord*)(shared_rs.base() + shared_rs.size());
misccode_end = shared_end;
misccode_bottom = misccode_end - heap_word_size(spec()->misc_code_size());
miscdata_end = misccode_bottom;
miscdata_bottom = miscdata_end - heap_word_size(spec()->misc_data_size());
readwrite_end = miscdata_bottom;
readwrite_bottom =
readwrite_end - heap_word_size(spec()->read_write_size());
readonly_end = readwrite_bottom;
readonly_bottom =
readonly_end - heap_word_size(spec()->read_only_size());
shared_bottom = readonly_bottom;
unshared_end = shared_bottom;
assert((char*)shared_bottom == shared_rs.base(), "shared space mismatch");
} else {
shared_end = (HeapWord*)(rs.base() + rs.size());
misccode_end = shared_end;
misccode_bottom = shared_end;
miscdata_end = shared_end;
miscdata_bottom = shared_end;
readwrite_end = shared_end;
readwrite_bottom = shared_end;
readonly_end = shared_end;
readonly_bottom = shared_end;
shared_bottom = shared_end;
unshared_end = shared_bottom;
}
unshared_bottom = (HeapWord*) rs.base();
// Verify shared and unshared spaces adjacent.
assert((char*)shared_bottom == rs.base()+rs.size(), "shared space mismatch");
assert(unshared_end > unshared_bottom, "shared space mismatch");
// Split reserved memory into pieces.
ReservedSpace ro_rs = shared_rs.first_part(spec()->read_only_size(),
UseSharedSpaces);
ReservedSpace tmp_rs1 = shared_rs.last_part(spec()->read_only_size());
ReservedSpace rw_rs = tmp_rs1.first_part(spec()->read_write_size(),
UseSharedSpaces);
ReservedSpace tmp_rs2 = tmp_rs1.last_part(spec()->read_write_size());
ReservedSpace md_rs = tmp_rs2.first_part(spec()->misc_data_size(),
UseSharedSpaces);
ReservedSpace mc_rs = tmp_rs2.last_part(spec()->misc_data_size());
_shared_space_size = spec()->read_only_size()
+ spec()->read_write_size()
+ spec()->misc_data_size()
+ spec()->misc_code_size();
// Allocate the unshared (default) space.
_the_space = new ContigPermSpace(_bts,
MemRegion(unshared_bottom, heap_word_size(initial_byte_size)));
if (_the_space == NULL)
vm_exit_during_initialization("Could not allocate an unshared"
" CompactingPermGen Space");
// Allocate shared spaces
if (spec()->enable_shared_spaces()) {
// If mapping a shared file, the space is not committed, don't
// mangle.
NOT_PRODUCT(bool old_ZapUnusedHeapArea = ZapUnusedHeapArea;)
NOT_PRODUCT(if (UseSharedSpaces) ZapUnusedHeapArea = false;)
// Commit the memory behind the shared spaces if dumping (not
// mapping).
if (DumpSharedSpaces) {
_ro_vs.initialize(ro_rs, spec()->read_only_size());
_rw_vs.initialize(rw_rs, spec()->read_write_size());
_md_vs.initialize(md_rs, spec()->misc_data_size());
_mc_vs.initialize(mc_rs, spec()->misc_code_size());
}
// Allocate the shared spaces.
_ro_bts = new BlockOffsetSharedArray(
MemRegion(readonly_bottom,
heap_word_size(spec()->read_only_size())),
heap_word_size(spec()->read_only_size()));
_ro_space = new OffsetTableContigSpace(_ro_bts,
MemRegion(readonly_bottom, readonly_end));
_rw_bts = new BlockOffsetSharedArray(
MemRegion(readwrite_bottom,
heap_word_size(spec()->read_write_size())),
heap_word_size(spec()->read_write_size()));
_rw_space = new OffsetTableContigSpace(_rw_bts,
MemRegion(readwrite_bottom, readwrite_end));
// Restore mangling flag.
NOT_PRODUCT(ZapUnusedHeapArea = old_ZapUnusedHeapArea;)
if (_ro_space == NULL || _rw_space == NULL)
vm_exit_during_initialization("Could not allocate a shared space");
if (UseSharedSpaces) {
// Map in the regions in the shared file.
FileMapInfo* mapinfo = FileMapInfo::current_info();
size_t image_alignment = mapinfo->alignment();
CollectedHeap* ch = Universe::heap();
if ((!mapinfo->map_space(ro, ro_rs, _ro_space)) ||
(!mapinfo->map_space(rw, rw_rs, _rw_space)) ||
(!mapinfo->map_space(md, md_rs, NULL)) ||
(!mapinfo->map_space(mc, mc_rs, NULL)) ||
// check the alignment constraints
(ch == NULL || ch->kind() != CollectedHeap::GenCollectedHeap ||
image_alignment !=
((GenCollectedHeap*)ch)->gen_policy()->max_alignment())) {
// Base addresses didn't match; skip sharing, but continue
shared_rs.release();
spec()->disable_sharing();
// If -Xshare:on is specified, print out the error message and exit VM,
// otherwise, set UseSharedSpaces to false and continue.
if (RequireSharedSpaces) {
vm_exit_during_initialization("Unable to use shared archive.", NULL);
} else {
FLAG_SET_DEFAULT(UseSharedSpaces, false);
}
// Note: freeing the block offset array objects does not
// currently free up the underlying storage.
delete _ro_bts;
_ro_bts = NULL;
delete _ro_space;
_ro_space = NULL;
delete _rw_bts;
_rw_bts = NULL;
delete _rw_space;
_rw_space = NULL;
shared_end = (HeapWord*)(rs.base() + rs.size());
}
}
if (spec()->enable_shared_spaces()) {
// Cover both shared spaces entirely with cards.
_rs->resize_covered_region(MemRegion(readonly_bottom, readwrite_end));
}
// Reserved region includes shared spaces for oop.is_in_reserved().
_reserved.set_end(shared_end);
} else {
_ro_space = NULL;
_rw_space = NULL;
}
}
// Do a complete scan of the shared read write space to catch all
// objects which contain references to any younger generation. Forward
// the pointers. Avoid space_iterate, as actually visiting all the
// objects in the space will page in more objects than we need.
// Instead, use the system dictionary as strong roots into the read
// write space.
//
// If a RedefineClasses() call has been made, then we have to iterate
// over the entire shared read-write space in order to find all the
// objects that need to be forwarded. For example, it is possible for
// an nmethod to be found and marked in GC phase-1 only for the nmethod
// to be freed by the time we reach GC phase-3. The underlying method
// is still marked, but we can't (easily) find it in GC phase-3 so we
// blow up in GC phase-4. With RedefineClasses() we want replaced code
// (EMCP or obsolete) to go away (i.e., be collectible) once it is no
// longer being executed by any thread so we keep minimal attachments
// to the replaced code. However, we can't guarantee when those EMCP
// or obsolete methods will be collected so they may still be out there
// even after we've severed our minimal attachments.
void CompactingPermGenGen::pre_adjust_pointers() {
if (spec()->enable_shared_spaces()) {
if (JvmtiExport::has_redefined_a_class()) {
// RedefineClasses() requires a brute force approach
AdjustSharedObjectClosure blk;
rw_space()->object_iterate(&blk);
} else {
RecursiveAdjustSharedObjectClosure blk;
Universe::oops_do(&blk);
StringTable::oops_do(&blk);
SystemDictionary::always_strong_classes_do(&blk);
SystemDictionary::placeholders_do(TraversePlaceholdersClosure::placeholders_do);
}
}
}
#ifdef ASSERT
class VerifyMarksClearedClosure : public ObjectClosure {
public:
void do_object(oop obj) {
assert(SharedSkipVerify || !obj->mark()->is_marked(),
"Shared oop still marked?");
}
};
#endif
void CompactingPermGenGen::post_compact() {
#ifdef ASSERT
if (!SharedSkipVerify && spec()->enable_shared_spaces()) {
VerifyMarksClearedClosure blk;
rw_space()->object_iterate(&blk);
}
#endif
}
// Do not use in time-critical operations due to the possibility of paging
// in otherwise untouched or previously unread portions of the perm gen,
// for instance, the shared spaces. NOTE: Because CompactingPermGenGen
// derives from OneContigSpaceCardGeneration which is supposed to have a
// single space, and does not override its object_iterate() method,
// object iteration via that interface does not look at the objects in
// the shared spaces when using CDS. This should be fixed; see CR 6897798.
void CompactingPermGenGen::space_iterate(SpaceClosure* blk, bool usedOnly) {
OneContigSpaceCardGeneration::space_iterate(blk, usedOnly);
if (spec()->enable_shared_spaces()) {
// Making the rw_space walkable will page in the entire space, and
// is to be avoided in the case of time-critical operations.
// However, this is required for Verify and heap dump operations.
blk->do_space(ro_space());
blk->do_space(rw_space());
}
}
void CompactingPermGenGen::print_on(outputStream* st) const {
OneContigSpaceCardGeneration::print_on(st);
if (spec()->enable_shared_spaces()) {
st->print(" ro");
ro_space()->print_on(st);
st->print(" rw");
rw_space()->print_on(st);
} else {
st->print_cr("No shared spaces configured.");
}
}
// References from the perm gen to the younger generation objects may
// occur in static fields in Java classes or in constant pool references
// to String objects.
void CompactingPermGenGen::younger_refs_iterate(OopsInGenClosure* blk) {
OneContigSpaceCardGeneration::younger_refs_iterate(blk);
if (spec()->enable_shared_spaces()) {
blk->set_generation(this);
// ro_space has no younger gen refs.
_rs->younger_refs_in_space_iterate(rw_space(), blk);
blk->reset_generation();
}
}
// Shared spaces are addressed in pre_adjust_pointers.
void CompactingPermGenGen::adjust_pointers() {
the_space()->adjust_pointers();
}
void CompactingPermGenGen::compact() {
the_space()->compact();
}
size_t CompactingPermGenGen::contiguous_available() const {
// Don't include shared spaces.
return OneContigSpaceCardGeneration::contiguous_available()
- _shared_space_size;
}
size_t CompactingPermGenGen::max_capacity() const {
// Don't include shared spaces.
assert(UseSharedSpaces || (_shared_space_size == 0),
"If not used, the size of shared spaces should be 0");
return OneContigSpaceCardGeneration::max_capacity()
- _shared_space_size;
}
// No young generation references, clear this generation's main space's
// card table entries. Do NOT clear the card table entries for the
// read-only space (always clear) or the read-write space (valuable
// information).
void CompactingPermGenGen::clear_remembered_set() {
_rs->clear(MemRegion(the_space()->bottom(), the_space()->end()));
}
// Objects in this generation's main space may have moved, invalidate
// that space's cards. Do NOT invalidate the card table entries for the
// read-only or read-write spaces, as those objects never move.
void CompactingPermGenGen::invalidate_remembered_set() {
_rs->invalidate(used_region());
}
void CompactingPermGenGen::verify() {
the_space()->verify();
if (!SharedSkipVerify && spec()->enable_shared_spaces()) {
ro_space()->verify();
rw_space()->verify();
}
}
HeapWord* CompactingPermGenGen::unshared_bottom;
HeapWord* CompactingPermGenGen::unshared_end;
HeapWord* CompactingPermGenGen::shared_bottom;
HeapWord* CompactingPermGenGen::shared_end;
HeapWord* CompactingPermGenGen::readonly_bottom;
HeapWord* CompactingPermGenGen::readonly_end;
HeapWord* CompactingPermGenGen::readwrite_bottom;
HeapWord* CompactingPermGenGen::readwrite_end;
HeapWord* CompactingPermGenGen::miscdata_bottom;
HeapWord* CompactingPermGenGen::miscdata_end;
HeapWord* CompactingPermGenGen::misccode_bottom;
HeapWord* CompactingPermGenGen::misccode_end;
// JVM/TI RedefineClasses() support:
bool CompactingPermGenGen::remap_shared_readonly_as_readwrite() {
assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
if (UseSharedSpaces) {
// remap the shared readonly space to shared readwrite, private
FileMapInfo* mapinfo = FileMapInfo::current_info();
if (!mapinfo->remap_shared_readonly_as_readwrite()) {
return false;
}
}
return true;
}
|
jacob-izr/drake | util/MexWrapper.cpp | #include "MexWrapper.h"
#if defined(WIN32) || defined(WIN64)
#else
#include <dlfcn.h>
#endif
MexWrapper::MexWrapper(std::string const & filename) : m_mex_file(filename)
{
m_good = false;
#if defined(WIN32) || defined(WIN64)
#else
//load the mexfile
m_handle = dlopen(m_mex_file.c_str(), RTLD_NOW);
if (!m_handle) {
fprintf(stderr,"%s\n",dlerror());
return;
}
//locate and store the entry point in a function pointer
char* error;
*(void**) &(m_mexFunc) = dlsym(m_handle, "mexFunction");
if ((error = dlerror()) != NULL) {
fprintf(stderr,"%s\n", error);
dlclose(m_handle);
return;
}
m_good = true;
#endif
}
MexWrapper::~MexWrapper()
{
#if defined(WIN32) || defined(WIN64)
#else
if (m_good) {
dlclose(m_handle);
}
#endif
}
//the caller is responsible for allocating all of the mxArray* memory and freeing it when
//
void MexWrapper::mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) const
{
if (m_good) {
m_mexFunc(nlhs, plhs, nrhs, const_cast<const mxArray**>(prhs));
}
}
std::string MexWrapper::getMexFile() const
{
return m_mex_file;
} |
lananh265/social-network | node_modules/react-icons-kit/ikons/location.js | <reponame>lananh265/social-network<gh_stars>1-10
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.location = void 0;
var location = {
"viewBox": "0 0 64 64",
"children": [{
"name": "g",
"attribs": {
"id": "LOCATION"
},
"children": [{
"name": "g",
"attribs": {},
"children": [{
"name": "g",
"attribs": {},
"children": [{
"name": "path",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"d": "M64,3c0-1.657-1.343-3-3-3c-0.375,0-0.73,0.077-1.061,0.202l-0.003-0.007l-58,22\r\n\t\t\tl0.003,0.008C0.808,22.632,0,23.718,0,25c0,1.414,0.981,2.592,2.298,2.909l-0.002,0.007l27.218,6.57l6.57,27.218l0.007-0.002\r\n\t\t\tC36.409,63.019,37.586,64,39,64c1.282,0,2.368-0.808,2.797-1.939l0.008,0.003l22-58l-0.019-0.007C63.913,3.726,64,3.376,64,3z\r\n\t\t\t M39.638,50.859l-4.722-19.562l-0.007,0.002c-0.263-1.09-1.119-1.941-2.207-2.205l0.002-0.01l-19.562-4.722L55.831,8.169\r\n\t\t\tL39.638,50.859z"
},
"children": [{
"name": "path",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"d": "M64,3c0-1.657-1.343-3-3-3c-0.375,0-0.73,0.077-1.061,0.202l-0.003-0.007l-58,22\r\n\t\t\tl0.003,0.008C0.808,22.632,0,23.718,0,25c0,1.414,0.981,2.592,2.298,2.909l-0.002,0.007l27.218,6.57l6.57,27.218l0.007-0.002\r\n\t\t\tC36.409,63.019,37.586,64,39,64c1.282,0,2.368-0.808,2.797-1.939l0.008,0.003l22-58l-0.019-0.007C63.913,3.726,64,3.376,64,3z\r\n\t\t\t M39.638,50.859l-4.722-19.562l-0.007,0.002c-0.263-1.09-1.119-1.941-2.207-2.205l0.002-0.01l-19.562-4.722L55.831,8.169\r\n\t\t\tL39.638,50.859z"
},
"children": []
}]
}]
}]
}]
}]
};
exports.location = location; |
showa-yojyo/The-Modern-Cpp-Challenge | Chapter11/problem_89/main.cpp | <filename>Chapter11/problem_89/main.cpp
// #89 ヴィジュネル暗号
//
// C++ 新機能の学習には不向き
#include <iostream>
#include <string>
#include <string_view>
#include <cassert>
// 前項参照
std::string caesar_encrypt(std::string_view text, int shift)
{
std::string str;
str.reserve(text.length());
for (auto const & c : text)
{
if (isalpha(c) && isupper(c))
str += 'A' + (c - 'A' + shift) % 26;
else
str += c;
}
return str;
}
// 前項参照
std::string caesar_decrypt(std::string_view text, int shift)
{
std::string str;
str.reserve(text.length());
for (auto const & c : text)
{
if (isalpha(c) && isupper(c))
str += 'A' + (26 + c - 'A' - shift) % 26;
else
str += c;
}
return str;
}
// 本書 p. 237 の表
std::string build_vigenere_table()
{
std::string table;
table.reserve(26*26);
for (int i = 0; i < 26; ++i)
// 前項のアルゴリズムを利用
table += caesar_encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ", i);
return table;
}
std::string vigenere_encrypt(std::string_view text, std::string_view key)
{
std::string result;
result.reserve(text.length());
static auto table = build_vigenere_table();
for (size_t i = 0; i < text.length(); ++i)
{
auto row = key[i%key.length()] - 'A';
auto col = text[i] - 'A';
result += table[row * 26 + col];
}
return result;
}
std::string vigenere_decrypt(std::string_view text, std::string_view key)
{
std::string result;
result.reserve(text.length());
static auto table = build_vigenere_table();
for (size_t i = 0; i < text.length(); ++i)
{
auto row = key[i%key.length()] - 'A';
for (size_t col = 0; col < 26; col++)
{
if (table[row * 26 + col] == text[i])
{
result += 'A' + col;
break;
}
}
}
return result;
}
int main()
{
auto text = "THECPPCHALLENGER";
auto enc = vigenere_encrypt(text, "SAMPLE");
auto dec = vigenere_decrypt(enc, "SAMPLE");
assert(text == dec);
}
|
yanakievv/OS | GCC/IO_T1.c | #include <unistd.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <err.h>
#include <errno.h>
int main(int argc, char* argv[])
{
if (argc != 3)
{
err(1, "Arguments must be 3: cfile file1 file2\n");
}
int fd_cpyfrom = open(argv[1], O_RDONLY);
int fd_cpyto = open(argv[2], O_RDWR, O_TRUNC, O_CREAT, 00777);
if (fd_cpyfrom == -1 || fd_cpyto == -1)
{
err(2, "error");
}
struct stat st;
if (stat(argv[1], &st) == -1)
{
err(3, "error");
}
void *buff = malloc(st.st_size);
if (read(fd_cpyfrom, &buff, st.st_size) != st.st_size)
{
err(4, "error");
}
if (write(fd_cpyto, &buff, st.st_size) != st.st_size)
{
err(5, "error");
}
close(fd_cpyfrom);
close(fd_cpyto);
free(buff);
exit(0);
}
|
NNKit/NNCore | NNCore/Classes/Category/NS/NSDate+NNExtension.h | //
// NSDate+NNExtension.h
// NNCore
//
// Created by XMFraker on 2017/11/10.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
FOUNDATION_EXTERN NSString *const kNNDefaultDateFormat;
FOUNDATION_EXTERN NSString *const kNNShortDateFormat;
FOUNDATION_EXTERN NSString *const kNNShortTimeFormat;
@interface NSDate (NNExtension)
/** Year component */
@property (nonatomic, readonly) NSInteger year;
/** Month component (1~12) */
@property (nonatomic, readonly) NSInteger month;
/** Day component (1~31) */
@property (nonatomic, readonly) NSInteger day;
/** Hour component (0~23) */
@property (nonatomic, readonly) NSInteger hour;
/** Minute component (0~59) */
@property (nonatomic, readonly) NSInteger minute;
/** Second component (0~59) */
@property (nonatomic, readonly) NSInteger second;
/** Nanosecond component */
@property (nonatomic, readonly) NSInteger nanosecond;
/** Weekday component (1~7, first day is based on user setting) */
@property (nonatomic, readonly) NSInteger weekday;
/** WeekdayOrdinal component */
@property (nonatomic, readonly) NSInteger weekdayOrdinal;
/** WeekOfMonth component (1~5) */
@property (nonatomic, readonly) NSInteger weekOfMonth;
/** WeekOfYear component (1~53) */
@property (nonatomic, readonly) NSInteger weekOfYear;
/** YearForWeekOfYear component */
@property (nonatomic, readonly) NSInteger yearForWeekOfYear;
/** Quarter component */
@property (nonatomic, readonly) NSInteger quarter;
/** whether the month is leap month */
@property (nonatomic, readonly) BOOL isLeapMonth;
/** whether the year is leap year */
@property (nonatomic, readonly) BOOL isLeapYear;
/** whether date is today (based on current locale) */
@property (nonatomic, readonly) BOOL isToday;
/** whether date is yesterday (based on current locale) */
@property (nonatomic, readonly) BOOL isYesterday;
/** the date after today */
@property (copy, nonatomic, readonly) NSDate *tomorrow;
/** the date before today */
@property (copy, nonatomic, readonly) NSDate *yesterday;
#pragma mark - Public Methods
/**
Returns a date representing the receiver date shifted later by the provided number of years.
@param years Number of years to add.
@return Date modified by the number of desired years.
*/
- (nullable NSDate *)dateByAddingYears:(NSInteger)years;
/**
Returns a date representing the receiver date shifted later by the provided number of months.
@param months Number of months to add.
@return Date modified by the number of desired months.
*/
- (nullable NSDate *)dateByAddingMonths:(NSInteger)months;
/**
Returns a date representing the receiver date shifted later by the provided number of weeks.
@param weeks Number of weeks to add.
@return Date modified by the number of desired weeks.
*/
- (nullable NSDate *)dateByAddingWeeks:(NSInteger)weeks;
/**
Returns a date representing the receiver date shifted later by the provided number of days.
@param days Number of days to add.
@return Date modified by the number of desired days.
*/
- (nullable NSDate *)dateByAddingDays:(NSInteger)days;
/**
Returns a date representing the receiver date shifted later by the provided number of hours.
@param hours Number of hours to add.
@return Date modified by the number of desired hours.
*/
- (nullable NSDate *)dateByAddingHours:(NSInteger)hours;
/**
Returns a date representing the receiver date shifted later by the provided number of minutes.
@param minutes Number of minutes to add.
@return Date modified by the number of desired minutes.
*/
- (nullable NSDate *)dateByAddingMinutes:(NSInteger)minutes;
/**
Returns a date representing the receiver date shifted later by the provided number of seconds.
@param seconds Number of seconds to add.
@return Date modified by the number of desired seconds.
*/
- (nullable NSDate *)dateByAddingSeconds:(NSInteger)seconds;
@end
@interface NSDate (NNFormatExtension)
/**
将时间日期生成指定ISOFormat格式字符串
'yyyy-MM-dd'T'HH:mm:ssZ'
@return NSString or nil
*/
- (nullable NSString *)stringWithISOFormat;
/**
获取当前日期对应的时间字符串
@param format 指定的格式
@return NSString or nil
*/
- (nullable NSString *)stringWithFormat:(NSString *)format;
/**
获取当前日期对应的时间字符串
@param format 指定的格式
@param timeZone 指定时区
@param local 指定本地化
@return NSString or nil
*/
- (nullable NSString *)stringWithFormat:(NSString *)format
timeZone:(nullable NSTimeZone *)timeZone
local:(nullable NSLocale *)local;
#pragma mark - Class Methods
/**
获取一个单例模式的NSDateFormatter 对象
@return NSDateFormatter 对象
*/
+ (NSDateFormatter *)dateFromatter;
/**
从指定的ISOFormat格式解析时间
'yyyy-MM-dd'T'HH:mm:ssZ'
@param dateString 时间的字符串
@return NSDate or nil
*/
+ (nullable NSDate *)dateWithISOFormatString:(NSString *)dateString;
/**
从字符串中 获取NSDate
@param string date的字符串
@return NSDate or nil
*/
+ (nullable NSDate *)dateFromString:(NSString *)string;
/**
从字符串中 获取NSDate
@param string date的字符串
@param format 字符串日期格式 默认 yyyy-MM-dd HH:mm:ss
@return NSDate or nil
*/
+ (nullable NSDate *)dateFromString:(NSString *)string format:(NSString *)format;
/**
从字符串中获取NSDate
@param string 日期字符串
@param format 指定的格式
@param timeZone 指定时区
@param local 指定本地化
@return NSDate or nil
*/
+ (nullable NSDate *)dateFromString:(NSString *)string
format:(NSString *)format
timeZone:(nullable NSTimeZone *)timeZone
local:(nullable NSLocale *)local;
@end
NS_ASSUME_NONNULL_END
|
consulo/consulo-dotnet | msil-psi-impl/src/main/java/consulo/msil/lang/psi/impl/MsilGenericParameterImpl.java | /*
* Copyright 2013-2014 must-be.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.msil.lang.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import consulo.annotation.access.RequiredReadAction;
import consulo.annotation.access.RequiredWriteAction;
import consulo.dotnet.psi.*;
import consulo.dotnet.resolve.DotNetPsiSearcher;
import consulo.dotnet.resolve.DotNetTypeRef;
import consulo.msil.lang.psi.*;
import consulo.msil.lang.psi.impl.elementType.stub.MsilGenericParameterStub;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* @author VISTALL
* @since 23.05.14
*/
public class MsilGenericParameterImpl extends MsilStubElementImpl<MsilGenericParameterStub> implements MsilGenericParameter
{
public MsilGenericParameterImpl(@Nonnull ASTNode node)
{
super(node);
}
public MsilGenericParameterImpl(@Nonnull MsilGenericParameterStub stub, @Nonnull IStubElementType nodeType)
{
super(stub, nodeType);
}
@Override
public void accept(MsilVisitor visitor)
{
}
@RequiredReadAction
@Override
public boolean hasModifier(@Nonnull DotNetModifier modifier)
{
MsilGenericParameterStub stub = getGreenStub();
if(stub != null)
{
return stub.hasModifier(modifier);
}
if(modifier == DotNetModifier.CONTRAVARIANT)
{
return findChildByType(MsilTokens.MINUS) != null;
}
else if(modifier == DotNetModifier.COVARIANT)
{
return findChildByType(MsilTokens.PLUS) != null;
}
return false;
}
@RequiredReadAction
@Nullable
@Override
public DotNetModifierList getModifierList()
{
return null;
}
@RequiredReadAction
@Nullable
@Override
public PsiElement getNameIdentifier()
{
return findChildByType(MsilTokenSets.IDENTIFIERS);
}
@RequiredReadAction
@Override
public String getName()
{
MsilGenericParameterStub stub = getGreenStub();
if(stub != null)
{
return stub.getName();
}
PsiElement nameIdentifier = getNameIdentifier();
return nameIdentifier == null ? null : nameIdentifier.getText();
}
@RequiredWriteAction
@Override
public PsiElement setName(@NonNls @Nonnull String s) throws IncorrectOperationException
{
return null;
}
@RequiredReadAction
@Nonnull
@Override
public DotNetTypeRef[] getExtendTypeRefs()
{
DotNetTypeList typeList = getStubOrPsiChild(MsilStubElements.GENERIC_PARAM_EXTENDS_LIST);
if(typeList == null)
{
return DotNetTypeRef.EMPTY_ARRAY;
}
return typeList.getTypeRefs();
}
@RequiredReadAction
@Nullable
@Override
public MsilUserType.Target getTarget()
{
MsilGenericParameterStub stub = getGreenStub();
if(stub != null)
{
return stub.getTarget();
}
PsiElement constraintElement = findChildByType(MsilTokenSets.GENERIC_CONSTRAINT_KEYWORDS);
if(constraintElement == null)
{
return null;
}
IElementType elementType = constraintElement.getNode().getElementType();
if(elementType == MsilTokens.CLASS_KEYWORD)
{
return MsilUserType.Target.CLASS;
}
else if(elementType == MsilTokens.VALUETYPE_KEYWORD)
{
return MsilUserType.Target.STRUCT;
}
return null;
}
@RequiredReadAction
@Nonnull
@Override
public DotNetPsiSearcher.TypeResoleKind getTypeKind()
{
MsilUserType.Target target = getTarget();
if(target == null)
{
return DotNetPsiSearcher.TypeResoleKind.UNKNOWN;
}
switch(target)
{
case CLASS:
return DotNetPsiSearcher.TypeResoleKind.CLASS;
case STRUCT:
return DotNetPsiSearcher.TypeResoleKind.STRUCT;
default:
throw new IllegalArgumentException();
}
}
@RequiredReadAction
@Override
public boolean hasDefaultConstructor()
{
MsilGenericParameterStub stub = getGreenStub();
if(stub != null)
{
return stub.hasDefaultConstructor();
}
return findChildByType(MsilTokens._CTOR_KEYWORD) != null;
}
@Override
public int getIndex()
{
PsiElement parentByStub = getParentByStub();
if(parentByStub instanceof DotNetGenericParameterList)
{
return ArrayUtil.find(((DotNetGenericParameterList) parentByStub).getParameters(), this);
}
return -1;
}
@RequiredReadAction
@Nonnull
@Override
public DotNetAttribute[] getAttributes()
{
PsiElement parentByStub = getStubOrPsiParentOfType(MsilClassEntry.class);
if(parentByStub != null)
{
String name = getName();
if(name == null)
{
return DotNetAttribute.EMPTY_ARRAY;
}
return ((MsilClassEntry) parentByStub).getGenericParameterAttributes(name);
}
parentByStub = getStubOrPsiParentOfType(MsilMethodEntry.class);
if(parentByStub != null)
{
String name = getName();
if(name == null)
{
return DotNetAttribute.EMPTY_ARRAY;
}
return ((MsilMethodEntry) parentByStub).getGenericParameterAttributes(name);
}
return MsilCustomAttribute.EMPTY_ARRAY;
}
}
|
openforis/rxjs | dist/spec/operators/index-spec.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var index = require("rxjs/operators");
var chai_1 = require("chai");
describe('operators/index', function () {
it('should export operators', function () {
chai_1.expect(index.audit).to.exist;
chai_1.expect(index.auditTime).to.exist;
chai_1.expect(index.buffer).to.exist;
chai_1.expect(index.bufferCount).to.exist;
chai_1.expect(index.bufferTime).to.exist;
chai_1.expect(index.bufferToggle).to.exist;
chai_1.expect(index.bufferWhen).to.exist;
chai_1.expect(index.catchError).to.exist;
chai_1.expect(index.combineAll).to.exist;
chai_1.expect(index.concatAll).to.exist;
chai_1.expect(index.concatMap).to.exist;
chai_1.expect(index.concatMapTo).to.exist;
chai_1.expect(index.count).to.exist;
chai_1.expect(index.debounce).to.exist;
chai_1.expect(index.debounceTime).to.exist;
chai_1.expect(index.defaultIfEmpty).to.exist;
chai_1.expect(index.delay).to.exist;
chai_1.expect(index.delayWhen).to.exist;
chai_1.expect(index.dematerialize).to.exist;
chai_1.expect(index.distinct).to.exist;
chai_1.expect(index.distinctUntilChanged).to.exist;
chai_1.expect(index.distinctUntilKeyChanged).to.exist;
chai_1.expect(index.elementAt).to.exist;
chai_1.expect(index.every).to.exist;
chai_1.expect(index.exhaust).to.exist;
chai_1.expect(index.exhaustMap).to.exist;
chai_1.expect(index.expand).to.exist;
chai_1.expect(index.filter).to.exist;
chai_1.expect(index.finalize).to.exist;
chai_1.expect(index.find).to.exist;
chai_1.expect(index.findIndex).to.exist;
chai_1.expect(index.first).to.exist;
chai_1.expect(index.groupBy).to.exist;
chai_1.expect(index.ignoreElements).to.exist;
chai_1.expect(index.isEmpty).to.exist;
chai_1.expect(index.last).to.exist;
chai_1.expect(index.map).to.exist;
chai_1.expect(index.mapTo).to.exist;
chai_1.expect(index.materialize).to.exist;
chai_1.expect(index.max).to.exist;
chai_1.expect(index.mergeAll).to.exist;
chai_1.expect(index.mergeMap).to.exist;
chai_1.expect(index.mergeMap).to.exist;
chai_1.expect(index.mergeMapTo).to.exist;
chai_1.expect(index.mergeScan).to.exist;
chai_1.expect(index.min).to.exist;
chai_1.expect(index.multicast).to.exist;
chai_1.expect(index.observeOn).to.exist;
chai_1.expect(index.pairwise).to.exist;
chai_1.expect(index.partition).to.exist;
chai_1.expect(index.pluck).to.exist;
chai_1.expect(index.publish).to.exist;
chai_1.expect(index.publishBehavior).to.exist;
chai_1.expect(index.publishLast).to.exist;
chai_1.expect(index.publishReplay).to.exist;
chai_1.expect(index.reduce).to.exist;
chai_1.expect(index.repeat).to.exist;
chai_1.expect(index.repeatWhen).to.exist;
chai_1.expect(index.retry).to.exist;
chai_1.expect(index.retryWhen).to.exist;
chai_1.expect(index.refCount).to.exist;
chai_1.expect(index.sample).to.exist;
chai_1.expect(index.sampleTime).to.exist;
chai_1.expect(index.scan).to.exist;
chai_1.expect(index.sequenceEqual).to.exist;
chai_1.expect(index.share).to.exist;
chai_1.expect(index.shareReplay).to.exist;
chai_1.expect(index.single).to.exist;
chai_1.expect(index.skip).to.exist;
chai_1.expect(index.skipLast).to.exist;
chai_1.expect(index.skipUntil).to.exist;
chai_1.expect(index.skipWhile).to.exist;
chai_1.expect(index.startWith).to.exist;
chai_1.expect(index.switchAll).to.exist;
chai_1.expect(index.switchMap).to.exist;
chai_1.expect(index.switchMapTo).to.exist;
chai_1.expect(index.take).to.exist;
chai_1.expect(index.takeLast).to.exist;
chai_1.expect(index.takeUntil).to.exist;
chai_1.expect(index.takeWhile).to.exist;
chai_1.expect(index.tap).to.exist;
chai_1.expect(index.throttle).to.exist;
chai_1.expect(index.throttleTime).to.exist;
chai_1.expect(index.timeInterval).to.exist;
chai_1.expect(index.timeout).to.exist;
chai_1.expect(index.timeoutWith).to.exist;
chai_1.expect(index.timestamp).to.exist;
chai_1.expect(index.toArray).to.exist;
chai_1.expect(index.window).to.exist;
chai_1.expect(index.windowCount).to.exist;
chai_1.expect(index.windowTime).to.exist;
chai_1.expect(index.windowToggle).to.exist;
chai_1.expect(index.windowWhen).to.exist;
chai_1.expect(index.withLatestFrom).to.exist;
chai_1.expect(index.zipAll).to.exist;
});
});
//# sourceMappingURL=index-spec.js.map |
Alekssasho/sge_source | libs/sge_engine/src/sge_engine/TexturedPlaneDraw.h | #pragma once
#include "sge_core/AssetLibrary.h"
#include "sge_engine_api.h"
#include "sge_renderer/renderer/renderer.h"
#include "sge_utils/math/mat4.h"
namespace sge {
struct SGE_ENGINE_API TexturedPlaneDraw {
void draw(const RenderDestination& rdest,
const mat4f& projViewWorld,
Texture* texture,
const vec4f& tint,
const vec4f uvRegion = vec4f(0.f, 0.f, 1.f, 1.f));
Geometry getGeometry(SGEDevice* sgedev);
Material getMaterial(Texture* texture) const;
private:
struct Vertex {
vec3f p;
vec3f n;
vec2f uv;
};
void initialize(SGEDevice* sgedev);
bool m_isInitialized = false;
BindLocation m_projViewWorld_bindLoc;
BindLocation m_texDiffuse_bindLoc;
#ifdef SGE_RENDERER_D3D11
BindLocation m_texDiffuseSampler_bindLoc;
#endif
BindLocation m_tint_bindLoc;
BindLocation m_uvRegion_bindLoc;
VertexDeclIndex m_vertexDecl = VertexDeclIndex_Null;
GpuHandle<ShadingProgram> m_shadingProgram;
GpuHandle<Buffer> m_vertexBuffer;
StateGroup m_stateGroup;
CBufferFiller uniforms;
};
} // namespace sge
|
OpenXIP/xip-libraries | src/database/coregl/SoXipLogGLState.h | /*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef SOXIPLOGGLSTATE_H
#define SOXIPLOGGLSTATE_H
#include <Inventor/nodes/SoSubNode.h>
#include <Inventor/fields/SoSFString.h>
#include <Inventor/fields/SoSFBool.h>
class SoXipLogGLState : public SoNode
{
SO_NODE_HEADER(SoXipLogGLState);
public:
SoSFBool log;
SoSFString filename;
static void initClass();
SoXipLogGLState();
protected:
~SoXipLogGLState();
virtual void GLRender(SoGLRenderAction * action);
int mCount;
};
#endif
|
keitaronaruse/AtCoderTraining | ABC/ABC221/A/abc221-a.cpp | <gh_stars>0
/**
* @file abc221-a.cpp
* @brief ABC221 Problem A - Seismic magnitude scales
* @author <NAME>
* @date 2022-04-11
* @copyright MIT License
* @details https://atcoder.jp/contests/abc221/tasks/abc221_a
*/
// # Solution
#include <iostream>
int main()
{
// Read A = [ B, 9 ], B = [ 3, A ]
int A, B;
std::cin >> A >> B;
// Main
// Find solution
int scale = 1;
for( int i = 0; i < A - B; i ++ ) {
scale *= 32;
}
std::cout << scale << std::endl;
// Finalize
return( 0 );
}
|
matevans/third-party-application | it/uk/gov/hmrc/apiplatform/modules/questionnaires/repositories/SubmissionsDAOSpec.scala | package uk.gov.hmrc.apiplatform.modules.submissions.repositories
import uk.gov.hmrc.thirdpartyapplication.util.AsyncHmrcSpec
import uk.gov.hmrc.mongo.MongoSpecSupport
import org.scalatest.BeforeAndAfterEach
import org.scalatest.BeforeAndAfterAll
import uk.gov.hmrc.thirdpartyapplication.repository.IndexVerification
import uk.gov.hmrc.thirdpartyapplication.util.MetricsHelper
import akka.actor.ActorSystem
import akka.stream.Materializer
import play.modules.reactivemongo.ReactiveMongoComponent
import uk.gov.hmrc.mongo.MongoConnector
import scala.concurrent.ExecutionContext.Implicits.global
import uk.gov.hmrc.thirdpartyapplication.util.SubmissionsTestData
import scala.concurrent.ExecutionContext
import reactivemongo.core.errors.DatabaseException
import uk.gov.hmrc.apiplatform.modules.submissions.domain.models._
class SubmissionsDAOSpec
extends AsyncHmrcSpec
with MongoSpecSupport
with BeforeAndAfterEach with BeforeAndAfterAll
with IndexVerification
with MetricsHelper
with SubmissionsTestData {
implicit var s : ActorSystem = ActorSystem("test")
implicit var m : Materializer = Materializer(s)
private val reactiveMongoComponent = new ReactiveMongoComponent {
override def mongoConnector: MongoConnector = mongoConnectorForTest
}
private val repo = new SubmissionsRepository(reactiveMongoComponent)
private val dao = new SubmissionsDAO(repo)
override def beforeEach() {
List(repo).foreach { db =>
await(db.drop)
await(db.ensureIndexes)
}
}
override protected def afterAll() {
List(repo).foreach { db =>
await(db.drop)
await(s.terminate)
}
}
"save and retrieved" should {
"not find a record that is not there" in {
await(dao.fetch(Submission.Id.random)) shouldBe None
}
"store a record and retrieve it" in {
await(dao.save(aSubmission)) shouldBe aSubmission
await(dao.fetch(aSubmission.id)).value shouldBe aSubmission
}
"not store multiple records of the same submission id" in {
await(dao.save(aSubmission)) shouldBe aSubmission
intercept[DatabaseException] {
await(dao.save(aSubmission))
}
await(repo.count(implicitly[ExecutionContext])) shouldBe 1
}
}
"fetchLastest" should {
"find the only one" in {
await(dao.save(aSubmission))
await(dao.fetchLatest(applicationId)).value shouldBe aSubmission
}
"find the latest one" in {
await(dao.save(aSubmission))
await(dao.save(altSubmission))
await(dao.fetchLatest(applicationId)).value shouldBe altSubmission
}
}
"update" should {
"replace the existing record" in {
await(dao.save(aSubmission))
val oldAnswers = aSubmission.latestInstance.answersToQuestions
val newAnswers = oldAnswers + (questionId -> SingleChoiceAnswer("Yes"))
val updatedSubmission = aSubmission.setLatestAnswers(newAnswers)
await(dao.update(updatedSubmission)) shouldBe updatedSubmission
await(dao.fetchLatest(applicationId)).value shouldBe updatedSubmission
}
}
}
|
krattai/AEBL | blades/jabberd2/util/misc.h | <reponame>krattai/AEBL<gh_stars>1-10
/*
* jabberd - Jabber Open Source Server
* Copyright (c) 2002-2004 <NAME>, <NAME>,
* <NAME>, <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307USA
*/
/** @file util/misc.h
* @brief Miscellaneous utilities
* @author <NAME>
* $Revision: 1.1 $
* $Date: 2004/05/01 00:51:10 $
*/
#ifndef INCL_UTIL_MISC_H
#define INCL_UTIL_MISC_H 1
/* jabberd2 Windows DLL */
#ifndef JABBERD2_API
# ifdef _WIN32
# ifdef JABBERD2_EXPORTS
# define JABBERD2_API __declspec(dllexport)
# else /* JABBERD2_EXPORTS */
# define JABBERD2_API __declspec(dllimport)
# endif /* JABBERD2_EXPORTS */
# else /* _WIN32 */
# define JABBERD2_API extern
# endif /* _WIN32 */
#endif /* JABBERD2_API */
JABBERD2_API int misc_realloc(void **blocks, int len);
#define misc_alloc(blocks, size, len) if((size) > len) len = misc_realloc((void **) &(blocks), (size))
#endif
|
FinalProject-Team4/Server_DaangnMarket | app/notification/migrations/0004_notification_type.py | <filename>app/notification/migrations/0004_notification_type.py<gh_stars>1-10
# Generated by Django 3.0.4 on 2020-04-23 07:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notification', '0003_auto_20200416_1609'),
]
operations = [
migrations.AddField(
model_name='notification',
name='type',
field=models.CharField(default='notice', max_length=10),
),
]
|
Testiduk/gitlabhq | lib/gitlab/database/postgresql_adapter/type_map_cache.rb | <reponame>Testiduk/gitlabhq
# frozen_string_literal: true
# Caches loading of additional types from the DB
# https://github.com/rails/rails/blob/v6.0.3.2/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L521-L589
# rubocop:disable Gitlab/ModuleWithInstanceVariables
module Gitlab
module Database
module PostgresqlAdapter
module TypeMapCache
extend ActiveSupport::Concern
TYPE_MAP_CACHE_MONITOR = ::Monitor.new
class_methods do
def type_map_cache
TYPE_MAP_CACHE_MONITOR.synchronize do
@type_map_cache ||= {}
end
end
end
def initialize_type_map(map = type_map)
TYPE_MAP_CACHE_MONITOR.synchronize do
cached_type_map = self.class.type_map_cache[@connection_parameters.hash]
break @type_map = cached_type_map if cached_type_map
super
self.class.type_map_cache[@connection_parameters.hash] = map
end
end
def reload_type_map
TYPE_MAP_CACHE_MONITOR.synchronize do
self.class.type_map_cache[@connection_parameters.hash] = nil
end
super
end
end
end
end
end
|
kyapp69/streamlink-twitch-gui | src/app/services/streaming/player/substitutions.js | import Substitution from "utils/parameters/Substitution";
import t from "translation-key";
/** @type {Substitution[]} */
export default [
new Substitution(
[ "name", "channel", "channelname" ],
"stream.channel.display_name",
t`settings.player.args.substitutions.channel`
),
new Substitution(
[ "status", "title" ],
"stream.channel.status",
t`settings.player.args.substitutions.status`
),
new Substitution(
[ "game", "gamename" ],
"stream.stream.game",
t`settings.player.args.substitutions.game`
),
new Substitution(
"delay",
"stream.stream.delay",
t`settings.player.args.substitutions.delay`
),
new Substitution(
[ "online", "since", "created" ],
"stream.stream.created_at",
t`settings.player.args.substitutions.created`
),
new Substitution(
[ "viewers", "current" ],
"stream.stream.viewers",
t`settings.player.args.substitutions.viewers`
),
new Substitution(
[ "views", "overall" ],
"stream.channel.views",
t`settings.player.args.substitutions.views`
)
];
|
tienduy-nguyen/the-hacking-project | week6/day5/bot_discord/lib/error.rb | <reponame>tienduy-nguyen/the-hacking-project<filename>week6/day5/bot_discord/lib/error.rb
class RutherError
def unknown_command(command)
return "Sorry... I didn't understand that command argument: **#{ command }**\n"
end
end |
inka-pallycon/pallycon-drm-token-sample-python | pallycon/config/playready/digital_video_protection.py | DIGITAL_VIDEO_PROTECTION_LEVEL = (100, 250, 270, 300, 301)
LEVEL_100 = DIGITAL_VIDEO_PROTECTION_LEVEL[0] # 'LEVEL_100'
LEVEL_250 = DIGITAL_VIDEO_PROTECTION_LEVEL[1] # 'LEVEL_250'
LEVEL_270 = DIGITAL_VIDEO_PROTECTION_LEVEL[2] # 'LEVEL_270'
LEVEL_300 = DIGITAL_VIDEO_PROTECTION_LEVEL[3] # 'LEVEL_300'
LEVEL_301 = DIGITAL_VIDEO_PROTECTION_LEVEL[4] # 'LEVEL_301'
def check(digital_video_protection) -> bool:
return digital_video_protection in DIGITAL_VIDEO_PROTECTION_LEVEL
|
nmldiegues/jvm-stm | classpath-0.98/gnu/javax/sound/sampled/gstreamer/lines/GstSourceDataLine.java | /* GstSourceDataLine.java -- SourceDataLine implementation.
Copyright (C) 2007 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.sound.sampled.gstreamer.lines;
import gnu.javax.sound.AudioSecurityManager;
import gnu.javax.sound.sampled.gstreamer.lines.GstPipeline.State;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import static gnu.javax.sound.AudioSecurityManager.Permission;
public class GstSourceDataLine
extends GstDataLine implements SourceDataLine
{
private GstPipeline pipeline = null;
private boolean open = false;
public GstSourceDataLine(AudioFormat format)
{
super(format);
}
public void open() throws LineUnavailableException
{
AudioSecurityManager.checkPermissions(Permission.PLAY);
if (open)
throw new IllegalStateException("Line already opened");
// create the pipeline
pipeline = GstNativeDataLine.createSourcePipeline(getBufferSize());
this.open = true;
}
public void open(AudioFormat fmt) throws LineUnavailableException
{
AudioSecurityManager.checkPermissions(Permission.PLAY);
setFormat(fmt);
this.open();
}
public void open(AudioFormat fmt, int size) throws LineUnavailableException
{
AudioSecurityManager.checkPermissions(Permission.PLAY);
setBufferSize(size);
this.open(fmt);
}
public int write(byte[] buf, int offset, int length)
{
return this.pipeline.write(buf, offset, length);
}
public int available()
{
return this.pipeline.available();
}
public void drain()
{
this.pipeline.drain();
}
public void flush()
{
this.pipeline.flush();
}
public int getFramePosition()
{
System.out.println("getFramePosition -: IMPLEMENT ME!!");
return 0;
}
public long getLongFramePosition()
{
System.out.println("getLongFramePosition -: IMPLEMENT ME!!");
return 0;
}
public long getMicrosecondPosition()
{
System.out.println("getMicrosecondPosition -: IMPLEMENT ME!!");
return 0;
}
public boolean isActive()
{
State state = pipeline.getState();
return (state == State.PLAY || state == State.PAUSE);
}
public void start()
{
pipeline.setState(State.PLAY);
}
public void stop()
{
pipeline.setState(State.PAUSE);
}
public void close()
{
pipeline.close();
this.open = false;
}
public boolean isRunning()
{
return (pipeline.getState() == State.PLAY);
}
}
|
codeforamerica/clientcomm-rails | spec/features/user_sends_images_to_client_spec.rb | <filename>spec/features/user_sends_images_to_client_spec.rb
require 'rails_helper'
feature 'user sends images', active_job: true do
let(:message_body) { 'You have an appointment tomorrow at 10am' }
let(:rr) { create :reporting_relationship }
let(:user) { rr.user }
let(:client) { rr.client }
before do
login_as(user, scope: :user)
end
scenario 'user sends images to client', :js, active_job: true do
step 'when user goes to messages page' do
visit reporting_relationship_path(rr)
expect(page).not_to have_css('#file-name-preview')
end
step 'uploads csv file' do
attach_file('message[attachments][][media]', Rails.root + 'spec/fixtures/court_dates.csv', make_visible: true)
results = page.evaluate_script('$("#message_attachments_0_media").val()==""')
expect(page.evaluate_script(results)).to equal true
expect(page).to have_css '#file-name-preview span.image-help-text', text: 'You can only send .gif, .png, and .jpg files'
expect(page).to have_css('#send_message:disabled')
end
step 'uploads large image file' do
attach_file('message[attachments][][media]', Rails.root + 'spec/fixtures/large_image.jpg', make_visible: true)
results = page.evaluate_script('$("#message_attachments_0_media").val()==""')
expect(page.evaluate_script(results)).to equal true
expect(page).to have_css '#file-name-preview span.image-help-text', text: 'You can only send files <5MB in size'
expect(page).to have_css('#send_message:disabled')
end
step 'uploads image' do
attach_file('message[attachments][][media]', Rails.root + 'spec/fixtures/fluffy_cat.jpg', make_visible: true)
expect(page).to have_button('Send later', disabled: true)
expect(page).to have_css '#file-name-preview span.image-help-text', text: 'fluffy_cat.jpg'
end
step 'user clears image' do
perform_enqueued_jobs do
find('#image-cancel').click
results = page.evaluate_script('$("#message_attachments_0_media").val()==""')
expect(page.evaluate_script(results)).to equal true
expect(page).to_not have_css '#file-name-preview span.image-help-text', text: 'fluffy_cat.jpg'
expect(page).to have_css('#send_message:disabled')
end
end
step 'user sends image' do
attach_file('message[attachments][][media]', Rails.root + 'spec/fixtures/fluffy_cat.jpg', make_visible: true)
expect(page).to have_button('Send later', disabled: true)
expect(page).to have_css '#file-name-preview span.image-help-text', text: 'fluffy_cat.jpg'
perform_enqueued_jobs do
click_on 'send_message'
expect(page).to have_css '.message--outbound img'
expect(page).to_not have_css '#file-name-preview span.image-help-text', text: 'fluffy_cat.jpg'
results = page.evaluate_script('$("#message_attachments_0_media").val()==""')
expect(page.evaluate_script(results)).to equal true
end
end
end
end
|
nageshwarrao19/BUILD | BUILD_Projects/client/tests/history.controller.spec.js | <reponame>nageshwarrao19/BUILD
'use strict';
var expect = chai.expect;
describe('Unit Test: TeamCtrl', function () {
var scope;
var httpBackend;
var mockedActiveProjectService;
var mockedHistoryService;
var mockedUiError, mockedHttpError;
var PROJECT_ID = '548634330dad778c2dcbd9fb';
var errorSpy, httpErrorSpy;
var historyObj = {project_id: PROJECT_ID, resource_version: 1, description: 'Test Desc'};
beforeEach(module('ui.router'));
beforeEach(module('project.history'));
beforeEach(module('ngResource'));
beforeEach(module('project.services'));
beforeEach(module('project.services'));
beforeEach(module('common.ui.elements'));
beforeEach(inject(function ($injector, $rootScope, $httpBackend, $q, uiError, httpError) {
httpBackend = $httpBackend;
// The $controller service is used to create instances of controllers
var $controller = $injector.get('$controller');
scope = $rootScope.$new();
mockedActiveProjectService = {id: PROJECT_ID, name: 'Test Project'};
mockedUiError = uiError;
mockedHttpError = httpError;
errorSpy = sinon.spy(mockedUiError, 'create');
httpErrorSpy = sinon.spy(mockedHttpError, 'create');
mockedHistoryService = {
getHistory: function () {
var deferred = $q.defer();
deferred.$promise = deferred.promise;
deferred.resolve(
[historyObj]
);
return deferred;
}
};
$controller('ProjectHistoryCtrl', {
'$scope': scope,
'HistoryService': mockedHistoryService,
'ActiveProjectService': mockedActiveProjectService,
'uiError': mockedUiError,
'httpError': mockedHttpError
});
}));
afterEach(function () {
errorSpy.reset();
httpErrorSpy.reset();
});
it('Nothing loaded, so events are empty', function () {
// Before $apply is called the promise hasn't resolved the historyFactory yet
expect(scope.events).to.be.undefined;
});
it('Ctrl is loaded, so events is loaded', function () {
// Call $apply so events is populated
scope.$apply();
expect(scope.events.length).to.equal(1);
expect(scope.events[0].project_id).to.equal(PROJECT_ID);
expect(errorSpy.called).to.eql(false);
expect(httpErrorSpy.called).to.eql(false);
});
});
|
APrioriInvestments/typed_python | typed_python/compiler/type_wrappers/const_dict_wrapper.py | # Copyright 2017-2020 typed_python Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typed_python.compiler.type_wrappers.wrapper import Wrapper
from typed_python.compiler.type_wrappers.refcounted_wrapper import RefcountedWrapper
import typed_python.compiler.type_wrappers.runtime_functions as runtime_functions
from typed_python.compiler.conversion_level import ConversionLevel
from typed_python.compiler.type_wrappers.bound_method_wrapper import BoundMethodWrapper
from typed_python.compiler.type_wrappers.util import min
from typed_python.compiler.typed_expression import TypedExpression
from typed_python import Tuple
import typed_python.compiler.native_ast as native_ast
import typed_python.compiler
typeWrapper = lambda t: typed_python.compiler.python_object_representation.typedPythonTypeToTypeWrapper(t)
def const_dict_eq(l, r):
if len(l) != len(r):
return False
for i in range(len(l)):
if l.get_key_by_index_unsafe(i) != r.get_key_by_index_unsafe(i):
return False
if l.get_value_by_index_unsafe(i) != r.get_value_by_index_unsafe(i):
return False
return True
def const_dict_neq(l, r):
return not const_dict_eq(l, r)
def const_dict_lt(left, right):
"""Compare two 'ConstDict' instances by comparing their individual elements."""
for i in range(min(len(left), len(right))):
if left.get_key_by_index_unsafe(i) > right.get_key_by_index_unsafe(i):
return False
if left.get_key_by_index_unsafe(i) < right.get_key_by_index_unsafe(i):
return True
if left.get_value_by_index_unsafe(i) > right.get_value_by_index_unsafe(i):
return False
if left.get_value_by_index_unsafe(i) < right.get_value_by_index_unsafe(i):
return True
return len(left) < len(right)
def const_dict_lte(left, right):
"""Compare two 'ConstDict' instances by comparing their individual elements."""
for i in range(min(len(left), len(right))):
if left.get_key_by_index_unsafe(i) > right.get_key_by_index_unsafe(i):
return False
if left.get_key_by_index_unsafe(i) < right.get_key_by_index_unsafe(i):
return True
if left.get_value_by_index_unsafe(i) > right.get_value_by_index_unsafe(i):
return False
if left.get_value_by_index_unsafe(i) < right.get_value_by_index_unsafe(i):
return True
return len(left) <= len(right)
def const_dict_gt(left, right):
return not const_dict_lte(left, right)
def const_dict_gte(left, right):
return not const_dict_lt(left, right)
def const_dict_getitem(constDict, key):
# perform a binary search
lowIx = 0
highIx = len(constDict)
while lowIx < highIx:
mid = (lowIx + highIx) >> 1
keyAtVal = constDict.get_key_by_index_unsafe(mid)
if keyAtVal < key:
lowIx = mid + 1
elif key < keyAtVal:
highIx = mid
else:
return constDict.get_value_by_index_unsafe(mid)
raise KeyError(key)
def const_dict_get(constDict, key, default):
# perform a binary search
lowIx = 0
highIx = len(constDict)
while lowIx < highIx:
mid = (lowIx + highIx) >> 1
keyAtVal = constDict.get_key_by_index_unsafe(mid)
if keyAtVal < key:
lowIx = mid + 1
elif key < keyAtVal:
highIx = mid
else:
return constDict.get_value_by_index_unsafe(mid)
return default
def const_dict_contains(constDict, key):
# perform a binary search
lowIx = 0
highIx = len(constDict)
while lowIx < highIx:
mid = (lowIx + highIx) >> 1
keyAtVal = constDict.get_key_by_index_unsafe(mid)
if keyAtVal < key:
lowIx = mid + 1
elif key < keyAtVal:
highIx = mid
else:
return True
return False
class ConstDictWrapperBase(RefcountedWrapper):
"""Common method wrappers for all ConstDicts.
We subclass this for things like 'keys', 'values', and 'items' since
they all basically look like a const-dict with different methods
"""
is_pod = False
is_empty = False
is_pass_by_ref = True
def __init__(self, constDictType, behavior):
assert hasattr(constDictType, '__typed_python_category__')
super().__init__(constDictType if behavior is None else (constDictType, behavior))
self.constDictType = constDictType
self.keyType = typeWrapper(constDictType.KeyType)
self.valueType = typeWrapper(constDictType.ValueType)
self.itemType = typeWrapper(Tuple(constDictType.KeyType, constDictType.ValueType))
self.kvBytecount = self.keyType.getBytecount() + self.valueType.getBytecount()
self.keyBytecount = self.keyType.getBytecount()
self.layoutType = native_ast.Type.Struct(element_types=(
('refcount', native_ast.Int64),
('hash_cache', native_ast.Int32),
('count', native_ast.Int32),
('subpointers', native_ast.Int32),
('data', native_ast.UInt8)
), name='ConstDictLayout').pointer()
def getNativeLayoutType(self):
return self.layoutType
def on_refcount_zero(self, context, instance):
assert instance.isReference
if self.keyType.is_pod and self.valueType.is_pod:
return runtime_functions.free.call(instance.nonref_expr.cast(native_ast.UInt8Ptr))
else:
return (
context.converter.defineNativeFunction(
"destructor_" + str(self.constDictType),
('destructor', self),
[self],
typeWrapper(type(None)),
self.generateNativeDestructorFunction
)
.call(instance)
)
def generateNativeDestructorFunction(self, context, out, inst):
with context.loop(inst.convert_len()) as i:
self.convert_getkey_by_index_unsafe(context, inst, i).convert_destroy()
self.convert_getvalue_by_index_unsafe(context, inst, i).convert_destroy()
context.pushEffect(
runtime_functions.free.call(inst.nonref_expr.cast(native_ast.UInt8Ptr))
)
class ConstDictWrapper(ConstDictWrapperBase):
def __init__(self, constDictType):
super().__init__(constDictType, None)
def convert_attribute(self, context, instance, attr):
if attr in ("get_key_by_index_unsafe", "get_value_by_index_unsafe", "keys", "values", "items", "get"):
return instance.changeType(BoundMethodWrapper.Make(self, attr))
return super().convert_attribute(context, instance, attr)
def convert_default_initialize(self, context, instance):
context.pushEffect(
instance.expr.store(self.layoutType.zero())
)
def convert_method_call(self, context, instance, methodname, args, kwargs):
if methodname == "__iter__" and not args and not kwargs:
res = context.push(
ConstDictKeysIteratorWrapper(self.constDictType),
lambda instance:
instance.expr.ElementPtrIntegers(0, 0).store(-1)
# we initialize the dict pointer below, so technically
# if that were to throw, this would leak a bad value.
)
context.pushReference(
self,
res.expr.ElementPtrIntegers(0, 1)
).convert_copy_initialize(instance)
return res
if methodname == "get" and not kwargs:
if len(args) == 1:
return self.convert_get(context, instance, args[0], context.constant(None))
elif len(args) == 2:
return self.convert_get(context, instance, args[0], args[1])
if methodname == "keys" and not args and not kwargs:
return instance.changeType(ConstDictKeysWrapper(self.constDictType))
if methodname == "values" and not args and not kwargs:
return instance.changeType(ConstDictValuesWrapper(self.constDictType))
if methodname == "items" and not args and not kwargs:
return instance.changeType(ConstDictItemsWrapper(self.constDictType))
if kwargs:
return super().convert_method_call(context, instance, methodname, args, kwargs)
if methodname == "get_key_by_index_unsafe":
if len(args) == 1:
ix = args[0].toInt64()
if ix is None:
return
return self.convert_getkey_by_index_unsafe(context, instance, ix)
if methodname == "get_value_by_index_unsafe":
if len(args) == 1:
ix = args[0].toInt64()
if ix is None:
return
return self.convert_getvalue_by_index_unsafe(context, instance, ix)
return super().convert_method_call(context, instance, methodname, args, kwargs)
def convert_getkey_by_index_unsafe(self, context, expr, item):
return context.pushReference(
self.keyType,
expr.nonref_expr.ElementPtrIntegers(0, 4).elemPtr(
item.nonref_expr.mul(native_ast.const_int_expr(self.kvBytecount))
).cast(self.keyType.getNativeLayoutType().pointer())
)
def convert_getitem_by_index_unsafe(self, context, expr, item):
return context.pushReference(
self.itemType,
expr.nonref_expr.ElementPtrIntegers(0, 4).elemPtr(
item.nonref_expr.mul(native_ast.const_int_expr(self.kvBytecount))
).cast(self.itemType.getNativeLayoutType().pointer())
)
def convert_getvalue_by_index_unsafe(self, context, expr, item):
return context.pushReference(
self.valueType,
expr.nonref_expr.ElementPtrIntegers(0, 4).elemPtr(
item.nonref_expr.mul(native_ast.const_int_expr(self.kvBytecount))
.add(native_ast.const_int_expr(self.keyBytecount))
).cast(self.valueType.getNativeLayoutType().pointer())
)
def convert_bin_op(self, context, left, op, right, inplace):
if right.expr_type == left.expr_type:
if op.matches.Eq:
return context.call_py_function(const_dict_eq, (left, right), {})
if op.matches.NotEq:
return context.call_py_function(const_dict_neq, (left, right), {})
if op.matches.Lt:
return context.call_py_function(const_dict_lt, (left, right), {})
if op.matches.LtE:
return context.call_py_function(const_dict_lte, (left, right), {})
if op.matches.Gt:
return context.call_py_function(const_dict_gt, (left, right), {})
if op.matches.GtE:
return context.call_py_function(const_dict_gte, (left, right), {})
return super().convert_bin_op(context, left, op, right, inplace)
def convert_bin_op_reverse(self, context, left, op, right, inplace):
if op.matches.In:
right = right.convert_to_type(self.keyType, ConversionLevel.UpcastContainers)
if right is None:
return None
return context.call_py_function(const_dict_contains, (left, right), {})
return super().convert_bin_op_reverse(context, left, op, right, inplace)
def convert_getitem(self, context, instance, item):
item = item.convert_to_type(self.keyType, ConversionLevel.UpcastContainers)
if item is None:
return None
return context.call_py_function(const_dict_getitem, (instance, item), {})
def convert_get(self, context, expr, item, default):
if item is None or expr is None or default is None:
return None
item = item.convert_to_type(self.keyType, ConversionLevel.UpcastContainers)
if item is None:
return None
return context.call_py_function(const_dict_get, (expr, item, default), {})
def convert_len_native(self, expr):
if isinstance(expr, TypedExpression):
expr = expr.nonref_expr
return native_ast.Expression.Branch(
cond=expr,
false=native_ast.const_int_expr(0),
true=expr.ElementPtrIntegers(0, 2).load().cast(native_ast.Int64)
)
def convert_len(self, context, expr):
return context.pushPod(int, self.convert_len_native(expr.nonref_expr))
def _can_convert_to_type(self, targetType, conversionLevel):
if not conversionLevel.isNewOrHigher():
return False
if targetType.typeRepresentation is bool:
return True
if targetType.typeRepresentation is str:
return "Maybe"
return False
def convert_to_type_with_target(self, context, instance, targetVal, conversionLevel, mayThrowOnFailure=False):
if targetVal.expr_type.typeRepresentation is bool:
res = context.pushPod(bool, self.convert_len_native(instance.nonref_expr).neq(0))
context.pushEffect(
targetVal.expr.store(res.nonref_expr)
)
return context.constant(True)
return super().convert_to_type_with_target(context, instance, targetVal, conversionLevel, mayThrowOnFailure)
class ConstDictMakeIteratorWrapper(ConstDictWrapperBase):
def convert_method_call(self, context, expr, methodname, args, kwargs):
if methodname == "__iter__" and not args and not kwargs:
res = context.push(
# self.iteratorType is inherited from our specialized children
# who pick whether we're an interator over keys, values, items, etc.
self.iteratorType,
lambda instance:
instance.expr.ElementPtrIntegers(0, 0).store(-1)
)
context.pushReference(
self,
res.expr.ElementPtrIntegers(0, 1)
).convert_copy_initialize(expr)
return res
return super().convert_method_call(context, expr, methodname, args, kwargs)
class ConstDictKeysWrapper(ConstDictMakeIteratorWrapper):
def __init__(self, constDictType):
super().__init__(constDictType, "keys")
self.iteratorType = ConstDictKeysIteratorWrapper(constDictType)
class ConstDictValuesWrapper(ConstDictMakeIteratorWrapper):
def __init__(self, constDictType):
super().__init__(constDictType, "values")
self.iteratorType = ConstDictValuesIteratorWrapper(constDictType)
class ConstDictItemsWrapper(ConstDictMakeIteratorWrapper):
def __init__(self, constDictType):
super().__init__(constDictType, "items")
self.iteratorType = ConstDictItemsIteratorWrapper(constDictType)
class ConstDictIteratorWrapper(Wrapper):
is_pod = False
is_empty = False
is_pass_by_ref = True
def __init__(self, constDictType, iteratorType):
self.constDictType = constDictType
self.iteratorType = iteratorType
super().__init__((constDictType, "iterator", iteratorType))
def getNativeLayoutType(self):
return native_ast.Type.Struct(
element_types=(("pos", native_ast.Int64), ("dict", ConstDictWrapper(self.constDictType).getNativeLayoutType())),
name="const_dict_iterator"
)
def convert_fastnext(self, context, expr):
context.pushEffect(
expr.expr.ElementPtrIntegers(0, 0).store(
expr.expr.ElementPtrIntegers(0, 0).load().add(1)
)
)
self_len = self.refAs(context, expr, 1).convert_len()
canContinue = context.pushPod(
bool,
expr.expr.ElementPtrIntegers(0, 0).load().lt(self_len.nonref_expr)
)
nextIx = context.pushReference(int, expr.expr.ElementPtrIntegers(0, 0))
return self.iteratedItemForReference(context, expr, nextIx).asPointerIf(canContinue)
def refAs(self, context, expr, which):
assert expr.expr_type == self
if which == 0:
return context.pushReference(int, expr.expr.ElementPtrIntegers(0, 0))
if which == 1:
return context.pushReference(
self.constDictType,
expr.expr
.ElementPtrIntegers(0, 1)
.cast(ConstDictWrapper(self.constDictType).getNativeLayoutType().pointer())
)
def convert_assign(self, context, expr, other):
assert expr.isReference
for i in range(2):
self.refAs(context, expr, i).convert_assign(self.refAs(context, other, i))
def convert_copy_initialize(self, context, expr, other):
for i in range(2):
self.refAs(context, expr, i).convert_copy_initialize(self.refAs(context, other, i))
def convert_destroy(self, context, expr):
self.refAs(context, expr, 1).convert_destroy()
class ConstDictKeysIteratorWrapper(ConstDictIteratorWrapper):
def __init__(self, constDictType):
super().__init__(constDictType, "keys")
def iteratedItemForReference(self, context, expr, ixExpr):
return ConstDictWrapper(self.constDictType).convert_getkey_by_index_unsafe(
context,
self.refAs(context, expr, 1),
ixExpr
)
class ConstDictItemsIteratorWrapper(ConstDictIteratorWrapper):
def __init__(self, constDictType):
super().__init__(constDictType, "items")
def iteratedItemForReference(self, context, expr, ixExpr):
return ConstDictWrapper(self.constDictType).convert_getitem_by_index_unsafe(
context,
self.refAs(context, expr, 1),
ixExpr
)
class ConstDictValuesIteratorWrapper(ConstDictIteratorWrapper):
def __init__(self, constDictType):
super().__init__(constDictType, "values")
def iteratedItemForReference(self, context, expr, ixExpr):
return ConstDictWrapper(self.constDictType).convert_getvalue_by_index_unsafe(
context,
self.refAs(context, expr, 1),
ixExpr
)
|
MyPureCloud/platform-client-sdk-cli | build/gc/models/reportingturn.go | <filename>build/gc/models/reportingturn.go
package models
import (
"time"
"encoding/json"
"strconv"
"strings"
)
var (
ReportingturnMarshalled = false
)
// This struct is here to use the useless readonly properties so that their required imports don't throw an unused error (time, etc.)
type ReportingturnDud struct {
Conversation Addressableentityref `json:"conversation"`
}
// Reportingturn
type Reportingturn struct {
// UserInput - The chosen user input associated with this reporting turn.
UserInput string `json:"userInput"`
// BotPrompts - The bot prompts associated with this reporting turn.
BotPrompts []string `json:"botPrompts"`
// SessionId - The bot session ID that this reporting turn is grouped under.
SessionId string `json:"sessionId"`
// AskAction - The bot flow 'ask' action associated with this reporting turn (e.g. AskForIntent).
AskAction Reportingturnaction `json:"askAction"`
// Intent - The intent and associated slots detected during this reporting turn.
Intent Reportingturnintent `json:"intent"`
// Knowledge - The knowledge data captured during this reporting turn.
Knowledge Reportingturnknowledge `json:"knowledge"`
// DateCreated - Timestamp indicating when the original turn was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
DateCreated time.Time `json:"dateCreated"`
// AskActionResult - Result of the bot flow 'ask' action.
AskActionResult string `json:"askActionResult"`
}
// String returns a JSON representation of the model
func (o *Reportingturn) String() string {
o.BotPrompts = []string{""}
j, _ := json.Marshal(o)
str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\u`, `\u`, -1))
return str
}
func (u *Reportingturn) MarshalJSON() ([]byte, error) {
type Alias Reportingturn
if ReportingturnMarshalled {
return []byte("{}"), nil
}
ReportingturnMarshalled = true
return json.Marshal(&struct {
UserInput string `json:"userInput"`
BotPrompts []string `json:"botPrompts"`
SessionId string `json:"sessionId"`
AskAction Reportingturnaction `json:"askAction"`
Intent Reportingturnintent `json:"intent"`
Knowledge Reportingturnknowledge `json:"knowledge"`
DateCreated time.Time `json:"dateCreated"`
AskActionResult string `json:"askActionResult"`
*Alias
}{
BotPrompts: []string{""},
Alias: (*Alias)(u),
})
}
|
hjxp/juno-agent | pkg/core/api.go | <filename>pkg/core/api.go
// Copyright 2020 Douyu
//
// 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 core
import (
"strconv"
pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
"github.com/douyu/juno-agent/pkg/file"
"github.com/douyu/juno-agent/pkg/model"
"github.com/douyu/juno-agent/pkg/pmt"
"github.com/douyu/juno-agent/pkg/structs"
"github.com/douyu/juno-agent/util"
"github.com/douyu/jupiter/pkg/server/xecho"
"github.com/douyu/jupiter/pkg/server/xgrpc"
"github.com/labstack/echo/v4"
"google.golang.org/grpc/examples/helloworld/helloworld"
)
func (eng *Engine) serveHTTP() error {
s := xecho.StdConfig("http").Build()
group := s.Group("/api")
group.GET("/agent/reload", eng.agentReload) // restart confd monitoring
group.GET("/agent/process/status", eng.processStatus) // real time process status
group.POST("/agent/process/shell", eng.pmtShell)
group.GET("/agent/file", eng.readFile) // 文件读取
v1Group := s.Group("/api/v1")
v1Group.GET("/agent/:target", eng.getAppConfig) // get app config
v1Group.GET("/agent/config", eng.listenConfig) // listenConfig
v1Group.POST("/agent/check", eng.agentCheck) // 加入依赖探活检测
v1Group.POST("/conf/command_line/status", eng.confStatus)
v1Group.GET("/agent/rawKey/getConfig", eng.getRawAppConfig) // 根据原生key获取配置信息
v1Group.GET("/agent/rawKey/listenConfig", eng.listenRawKeyConfig) // 根据原生key长轮训监听配置
return eng.Serve(s)
}
func (eng *Engine) serveGRPC() error {
config := xgrpc.StdConfig("grpc")
server := config.Build()
pb.RegisterKVServer(server.Server, eng.regProxy)
pb.RegisterWatchServer(server.Server, eng.regProxy)
pb.RegisterLeaseServer(server.Server, eng.regProxy)
helloworld.RegisterGreeterServer(server.Server, eng.regProxy)
return eng.Serve(server)
}
// agentReload reload agent watch
func (eng *Engine) agentReload(ctx echo.Context) error {
if err := eng.confProxy.Reload(); err != nil {
return reply400(ctx, "reload err "+err.Error())
}
return reply200(ctx, nil)
}
type confStatusBind struct {
Config string `json:"config"` //path to profile
}
// confStatus returns whether the configuration corresponding to systemd or supervisor is connected to the configuration center
// input: config path
// output:return whether the corresponding access
func (eng *Engine) confStatus(ctx echo.Context) error {
bind := confStatusBind{}
if err := ctx.Bind(&bind); err != nil {
return reply400(ctx, err.Error())
}
if bind.Config == "" {
return reply400(ctx, "input parameter is empty")
}
confStatus := eng.getConfigStatus(bind.Config)
return reply200(ctx, confStatus)
}
// listenConfig record the change of config
// if the config change in internal time(default 60s),return the changed config
// other return the status 400
func (eng *Engine) listenConfig(ctx echo.Context) error {
var defaultListenInternal = 60
appName := ctx.QueryParam("name")
appEnv := ctx.QueryParam("env")
target := ctx.QueryParam("target")
port := ctx.QueryParam("port")
enableWatch, _ := strconv.ParseBool(ctx.QueryParam("watch"))
listenInternal, _ := strconv.Atoi(ctx.QueryParam("internal"))
if listenInternal > 0 {
defaultListenInternal = listenInternal
}
var (
config structs.ContentNode
err error
)
if config, err = eng.confProxy.ListenAppConfig(ctx, appName, appEnv, target, port, enableWatch, defaultListenInternal); err != nil {
return reply400(ctx, "no data change")
}
return reply200(ctx, config)
}
// listenRawKeyConfig record the change of config
// if the config change in internal time(default 60s),return the changed config
// other return the status 400
func (eng *Engine) listenRawKeyConfig(ctx echo.Context) error {
var defaultListenInternal = 60
rawKey := ctx.QueryParam("rawKey")
if rawKey == "" {
return reply400(ctx, "listen config, raw key is null")
}
enableWatch, _ := strconv.ParseBool(ctx.QueryParam("watch"))
listenInternal, _ := strconv.Atoi(ctx.QueryParam("internal"))
if listenInternal > 0 {
defaultListenInternal = listenInternal
}
var (
config structs.ContentNode
err error
)
if config, err = eng.confProxy.ListenRawKeyAppConfig(ctx, rawKey, enableWatch, defaultListenInternal); err != nil {
return reply400(ctx, "no data change")
}
return reply200(ctx, config)
}
// getAppConfig get the app config data
func (eng *Engine) getAppConfig(ctx echo.Context) error {
appName := ctx.QueryParam("name")
appEnv := ctx.QueryParam("env")
port := ctx.QueryParam("port")
target := ctx.Param("target")
res, err := eng.confProxy.GetValues(ctx, appName, appEnv, target, port)
if err != nil {
return reply400(ctx, err.Error())
}
return reply200(ctx, res)
}
func (eng *Engine) getRawAppConfig(ctx echo.Context) error {
rawKey := ctx.QueryParam("rawKey")
if rawKey == "" {
return reply400(ctx, "get raw app config, the raw key is null")
}
res, err := eng.confProxy.GetRawValues(ctx, rawKey)
if err != nil {
return reply400(ctx, err.Error())
}
return reply200(ctx, res)
}
// processStatus show the process status of machine
func (eng *Engine) processStatus(ctx echo.Context) error {
list, err := eng.process.GetProcessStatus()
if err != nil {
return reply400(ctx, "process list parser err:"+err.Error())
}
return reply200(ctx, list)
}
// agentCheck add the health check of relies
func (eng *Engine) agentCheck(ctx echo.Context) error {
checkDatas := model.CheckReq{}
if err := ctx.Bind(&checkDatas); err != nil {
return ctx.JSON(400, err.Error())
}
res := eng.healthCheck.HealthCheck(checkDatas)
return reply200(ctx, res)
}
// PMTShell pmt shell exec
func (eng *Engine) pmtShell(ctx echo.Context) error {
pmtShellReq := model.PMTShell{}
if err := ctx.Bind(&pmtShellReq); err != nil {
return reply400(ctx, err.Error())
}
args, err := pmt.GenCommand(pmtShellReq.Pmt, pmtShellReq.AppName, pmtShellReq.Op)
if err != nil {
return reply400(ctx, err.Error())
}
reply, err := pmt.Exec(args)
if err != nil {
return reply400(ctx, err.Error())
}
return reply200(ctx, reply)
}
func (eng *Engine) readFile(c echo.Context) error {
var param model.GetFileReq
err := c.Bind(¶m)
if err != nil {
return reply400(c, err.Error())
}
content, err := file.ReadFile(param.FileName)
if err != nil {
return reply400(c, err.Error())
}
content = util.EncryptAPIResp(content)
return reply200(c, map[string]interface{}{
"content": content,
})
}
func reply200(ctx echo.Context, data interface{}) error {
return ctx.JSON(200, map[string]interface{}{
"code": 200,
"data": data,
"msg": "success",
})
}
func reply400(ctx echo.Context, msg string) error {
return ctx.JSON(200, map[string]interface{}{
"code": 400,
"msg": msg,
})
}
|
xirc/cp-algorithm | lib/main/tree/lca/main-lca-binary-lifting.cpp | <filename>lib/main/tree/lca/main-lca-binary-lifting.cpp
#include <iostream>
#include "template-solver-interp.hpp"
#include "cpalgo/tree/lca/lca_binary_lifting.hpp"
using namespace std;
using Interp = SolverInterp<LCABinaryLifting>;
Interp* interp = new Interp();
void setup(string& header, map<string,Command>& commands) {
header = "Lowest Common Ancestor using Binary Lifting";
setup(interp, header, commands);
} |
Faiz/mapr2 | matrix_game_experiment.py | from maci.environments import MatrixGame
from agent import Agent
import numpy as np
import matplotlib.pyplot as plt
AGENT_NUM = 2
ACTION_NUM = 2
GAME_NAME = "stag_hunt"
ITERATION = 100
SAMPLE_SIZE = 1
K = 1
opp_style = 'rommeo'
temperature_decay = True
if __name__ == "__main__":
env = MatrixGame(
game=GAME_NAME,
agent_num=AGENT_NUM,
action_num=ACTION_NUM,
)
agents = []
for i in range(AGENT_NUM):
agent = Agent(id, ACTION_NUM, env, opp_style=opp_style, temperature_decay=temperature_decay)
agents.append(agent)
reward_history = []
for _ in range(ITERATION):
# reset resets the game and returns [0, 0]
# since in matrix game, you don't really have a
# state or think of it as start state.
for _ in range(SAMPLE_SIZE):
states = env.reset()
actions = np.array([
agent.act(state)[0] for state, agent in zip(states, agents)
])
state_primes, rewards, _, _ = env.step(actions)
reward_history.append(rewards)
for agent_index, (state, reward, state_prime, agent) in enumerate(
zip(states, rewards, state_primes, agents)):
agent.update_opponent_action_prob(
state,
actions[agent_index],
actions[1 - agent_index],
state_prime,
reward,
)
# Update Q
for agent in agents:
agent.update_policy(sample_size=SAMPLE_SIZE, k=K)
history_pi_0 = [p[1] for p in agents[0].pi_history]
history_pi_1 = [p[1] for p in agents[1].pi_history]
print(agents[0].Q[0])
print(agents[1].Q[0])
cmap = plt.get_cmap('viridis')
colors = range(len(history_pi_1))
fig = plt.figure(figsize=(6, 10))
ax = fig.add_subplot(211)
scatter = ax.scatter(history_pi_0, history_pi_1, c=colors, s=1)
ax.scatter(0.5, 0.5, c='r', s=10., marker='*')
colorbar = fig.colorbar(scatter, ax=ax)
ax.set_ylabel("Policy of Player 2")
ax.set_xlabel("Policy of Player 1")
ax.set_ylim(0, 1)
ax.set_xlim(0, 1)
# ax = fig.add_subplot(212)
# ax.plot(history_pi_0)
# ax.plot(history_pi_1)
plt.tight_layout()
plt.show() |
a4-data/a4-UI-EXT | api-docs/ux/ajax/DataSimlet.js | /**
* @class Ext.ux.ajax.DataSimlet
* This base class is used to handle data preparation (e.g., sorting, filtering and
* group summary).
*/
|
Ivan1pl/netherite | witchcraft-context/src/main/java/com/ivan1pl/witchcraft/context/WitchCraftContext.java | package com.ivan1pl.witchcraft.context;
import com.google.common.primitives.Primitives;
import com.ivan1pl.witchcraft.context.annotations.ConfigurationValue;
import com.ivan1pl.witchcraft.context.annotations.ConfigurationValues;
import com.ivan1pl.witchcraft.context.annotations.Managed;
import com.ivan1pl.witchcraft.context.annotations.Module;
import com.ivan1pl.witchcraft.context.exception.*;
import com.ivan1pl.witchcraft.context.proxy.Aspect;
import com.ivan1pl.witchcraft.context.proxy.ProxyInvocationHandler;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyFactory;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.stream.Stream;
/**
* WitchCraft's dependency injection context.
*/
public final class WitchCraftContext {
/**
* Plugin instance.
*/
private final JavaPlugin javaPlugin;
/**
* Packages to scan.
*/
private final String[] basePackages;
/**
* Annotations indicating managed classes.
*/
private final List<Class<? extends Annotation>> annotations;
/**
* Context containing instances of all managed classes.
*/
private final Map<String, List<Object>> context = new HashMap<>();
/**
* Invocation handler for all managed classes.
*/
private final ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
/**
* Create new context for given plugin.
* @param javaPlugin plugin instance
*/
public WitchCraftContext(JavaPlugin javaPlugin) {
this(javaPlugin, javaPlugin.getClass().getPackage() == null ?
new String[0] : new String[] { javaPlugin.getClass().getPackage().getName() });
}
/**
* Create new context for given plugin.
* @param javaPlugin plugin instance
* @param basePackages package scan path
*/
public WitchCraftContext(JavaPlugin javaPlugin, String[] basePackages) {
this(javaPlugin, basePackages, Managed.class);
}
/**
* Create new context for given plugin.
* @param javaPlugin plugin instance
* @param basePackages package scan path
* @param annotations annotations marking managed classes
*/
@SafeVarargs
public WitchCraftContext(JavaPlugin javaPlugin, String[] basePackages, Class<? extends Annotation>... annotations) {
this.javaPlugin = javaPlugin;
this.basePackages = getBasePackages(javaPlugin, basePackages);
this.annotations = Arrays.asList(annotations);
}
/**
* Get an array of packages to scan, including provided packages and all enabled module packages.
* @param javaPlugin plugin instance
* @param basePackages package scan path
* @return provided packages and all enabled module packages
*/
private static String[] getBasePackages(JavaPlugin javaPlugin, String[] basePackages) {
List<String> packageList = new ArrayList<>(Arrays.asList(basePackages));
for (Annotation annotation : javaPlugin.getClass().getAnnotations()) {
Module module = annotation.annotationType().getAnnotation(Module.class);
if (module != null && annotation.annotationType().getPackage() != null) {
javaPlugin.getLogger().info(String.format(
"Detected module in package: %s", annotation.annotationType().getPackage().getName()));
packageList.add(annotation.annotationType().getPackage().getName());
}
}
return packageList.toArray(new String[0]);
}
/**
* Initialize context.
* @throws InitializationFailedException when WitchCraft is unable to initialize context
*/
public void init() throws InitializationFailedException {
List<Class<?>> classes = new LinkedList<>();
try {
for (String basePackage : basePackages) {
javaPlugin.getLogger().info(String.format("Starting package scan for package: %s", basePackage));
for (Class<? extends Annotation> annotation : annotations) {
classes.addAll(new Reflections(basePackage).getTypesAnnotatedWith(annotation));
}
javaPlugin.getLogger().info(String.format("Package scan completed for package: %s", basePackage));
}
Queue<Class<?>> creationQueue = new CreationQueueBuilder(javaPlugin, classes).createQueue();
add(this);
add(javaPlugin);
while (!creationQueue.isEmpty()) {
Class<?> clazz = creationQueue.poll();
Object instance = attemptCreate(clazz);
add(instance);
}
initAspects();
} catch (Exception e) {
throw new InitializationFailedException("Failed to initialize WitchCraft context", e);
}
}
/**
* Find all declared aspects and add them to invocation handler.
*/
private void initAspects() {
for (Annotation annotation : javaPlugin.getClass().getAnnotations()) {
Module module = annotation.annotationType().getAnnotation(Module.class);
if (module != null) {
for (Class<? extends Aspect> aspect : module.aspects()) {
proxyInvocationHandler.addAspect(get(aspect));
}
}
}
}
/**
* Attempt to create new instance of given type.
* @param clazz requested type
* @return instance of given type
*/
private Object attemptCreate(Class<?> clazz) throws IllegalAccessException, InvocationTargetException,
InstantiationException, InitializationFailedException, NoSuchMethodException {
Constructor<?> constructor = clazz.getConstructors()[0];
Parameter[] parameterTypes = constructor.getParameters();
Object[] parameters = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; ++i) {
ConfigurationValue configurationValue = parameterTypes[i].getAnnotation(ConfigurationValue.class);
if (configurationValue == null) {
ConfigurationValues configurationValues = parameterTypes[i].getAnnotation(ConfigurationValues.class);
if (configurationValues == null) {
parameters[i] = get(parameterTypes[i].getType());
} else if (!parameterTypes[i].getType().isAssignableFrom(Properties.class)) {
throw new InitializationFailedException("Parameter " + parameterTypes[i].getName() + " of type " +
parameterTypes[i].getType().getCanonicalName() + " cannot be assigned from " +
Properties.class.getCanonicalName());
} else {
parameters[i] = createProperties(configurationValues);
}
} else {
parameters[i] = javaPlugin.getConfig().getObject(
configurationValue.value(), Primitives.wrap(parameterTypes[i].getType()), null);
}
}
return createProxy(clazz, parameterTypes, parameters);
}
/**
* Create proxy of given class. This will create proxy of any given class except aspects.
* @param clazz class to proxy
* @param parameterDefinitions constructor parameter definitions
* @param parameters constructor parameters
* @return proxy instance (or just an object of the requested type in case of aspects)
*/
private Object createProxy(Class<?> clazz, Parameter[] parameterDefinitions, Object[] parameters)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?>[] parameterTypes = Stream.of(parameterDefinitions).map(Parameter::getType).toArray(Class[]::new);
if (Aspect.class.isAssignableFrom(clazz) || Listener.class.isAssignableFrom(clazz)) {
return clazz.getConstructor(parameterTypes).newInstance(parameters);
} else {
ProxyFactory f = new ProxyFactory();
f.setSuperclass(clazz);
Class<?> proxyClass = f.createClass();
Proxy proxy = (Proxy) proxyClass.getConstructor(parameterTypes).newInstance(parameters);
proxy.setHandler(proxyInvocationHandler);
return proxy;
}
}
/**
* Create and fill {@link Properties} instance from configuration values.
*/
private Properties createProperties(ConfigurationValues configurationValues) {
Properties properties = new Properties();
for (String key : configurationValues.keys()) {
String configKey = configurationValues.prefix().isEmpty() ? key : configurationValues.prefix() + "." + key;
String value = javaPlugin.getConfig().getString(configKey);
if (value != null && !value.isEmpty()) {
properties.setProperty(key, value);
}
}
return properties;
}
/**
* Add object to WitchCraft dependency injection context.
* @param object object to add
*/
private void add(Object object) {
Class<?> clazz = object.getClass();
Queue<Class<?>> classes = new LinkedList<>();
classes.add(clazz);
while (!classes.isEmpty()) {
Class<?> c = classes.poll();
List<Object> objects = context.computeIfAbsent(c.getCanonicalName(), o -> new LinkedList<>());
objects.add(object);
classes.addAll(Arrays.asList(c.getInterfaces()));
c = c.getSuperclass();
if (c != null) {
classes.add(c);
}
}
}
/**
* Get all managed objects for given type.
* @param type type
* @return all managed objects of given type
*/
private List<Object> getCandidatesForType(Class<?> type) {
if (type == null) {
return new ArrayList<>();
}
return context.getOrDefault(type.getCanonicalName(), new ArrayList<>());
}
/**
* Get object from context.
* @param clazz class object
* @param <T> requested object type
* @return object of the required type
*/
@SuppressWarnings("unchecked")
public <T> T get(Class<T> clazz) {
List<Object> candidates = getCandidatesForType(clazz);
if (candidates.size() > 1) {
throw new NonUniqueCandidateException("Non unique candidate of type " + clazz.getCanonicalName());
}
if (candidates.isEmpty()) {
throw new CandidateNotFoundException(
"Candidate of type " + clazz.getCanonicalName() + " could not be found");
}
return (T) candidates.get(0);
}
/**
* Clear the context.
* <p>
* Warning: the plugin might not work properly after invoking this method.
*/
public void clear() {
context.clear();
}
/**
* Builder class for creating instantiation queue.
*/
private static class CreationQueueBuilder {
private final Map<Class<?>, List<Class<?>>> before = new HashMap<>();
/**
* Create builder instance.
* @param javaPlugin plugin instance
* @param classes managed classes
* @throws InitializationFailedException when queue cannot be initialized
* @throws UnsatisfiedDependencyException when the builder is unable to determine unique dependency for some
* class
*/
CreationQueueBuilder(JavaPlugin javaPlugin, List<Class<?>> classes)
throws InitializationFailedException, UnsatisfiedDependencyException {
for (Class<?> clazz : classes) {
Constructor<?>[] constructors = clazz.getConstructors();
if (constructors.length != 1) {
throw new InitializationFailedException("Unable to instantiate class: " + clazz.getCanonicalName() +
". Invalid number of constructors (required exactly 1)");
}
Constructor<?> constructor = constructors[0];
List<Class<?>> beforeClass = before.computeIfAbsent(clazz, c -> new LinkedList<>());
for (Parameter parameter : constructor.getParameters()) {
if (!parameter.getType().isAssignableFrom(javaPlugin.getClass()) &&
!parameter.getType().isAssignableFrom(WitchCraftContext.class) &&
parameter.getAnnotation(ConfigurationValue.class) == null &&
parameter.getAnnotation(ConfigurationValues.class) == null) {
int numElements = 0;
for (Class<?> depClass : classes) {
if (parameter.getType().isAssignableFrom(depClass)) {
beforeClass.add(depClass);
numElements++;
}
}
if (numElements == 0) {
throw new UnsatisfiedDependencyException("Could not instantiate parameter of type " +
parameter.getType().getCanonicalName() + " while attempting to build an object of type " +
clazz.getCanonicalName() + ": no candidates found");
}
if (numElements > 1) {
throw new UnsatisfiedDependencyException("Could not instantiate parameter of type " +
parameter.getType().getCanonicalName() + " while attempting to build an object of type " +
clazz.getCanonicalName() + ": multiple candidates found");
}
}
}
}
}
/**
* Create queue containing classes in order they should be instantiated.
* @return instantiation queue
* @throws DependencyCycleException when there is a dependency cycle
*/
Queue<Class<?>> createQueue() throws DependencyCycleException {
Queue<Class<?>> result = new LinkedList<>();
while (!before.isEmpty()) {
Class<?> nextElement = getAnySatisfied();
if (nextElement == null) {
throw new DependencyCycleException("Detected cycle in dependency graph, unable to instantiate");
}
result.add(nextElement);
for (List<Class<?>> beforeList : before.values()) {
beforeList.remove(nextElement);
}
before.remove(nextElement);
}
return result;
}
/**
* Get any element with no further unsatisfied dependencies.
* @return any element with no unsatisfied dependencies
*/
private Class<?> getAnySatisfied() {
for (Map.Entry<Class<?>, List<Class<?>>> entry : before.entrySet()) {
if (entry.getValue().isEmpty()) {
return entry.getKey();
}
}
return null;
}
}
}
|
HarumeJs/Discord-Bot | commands/Guild/poll.js | // Dependencies
const Discord = require('discord.js');
module.exports.run = async (bot, message, args, emojis, settings) => {
if (message.deletable) message.delete();
// Check bot for add reaction permission
if (!message.guild.me.hasPermission('ADD_REACTIONS')) {
message.channel.send({ embed:{ color:15158332, description:`${emojis[0]} I am missing the permission: \`ADD_REACTIONS\`.` } }).then(m => m.delete({ timeout: 10000 }));
bot.logger.error(`Missing permission: \`ADD_REACTIONS\` in [${message.guild.id}]`);
return;
}
// Make sure a poll was provided
if (!args[0]) {
message.channel.send({ embed:{ color:15158332, description:`${emojis[0]} Please use the format \`${bot.commands.get('poll').help.usage.replace('${PREFIX}', settings.prefix)}\`.` } }).then(m => m.delete({ timeout: 3000 }));
return;
}
// Send poll to channel
const embed = new Discord.MessageEmbed()
.setColor(0xffffff)
.setTitle(`Poll created by ${message.author.username}`)
.setDescription(args.join(' '))
.setFooter('React to vote..')
.setTimestamp();
const msg = await message.channel.send(embed);
// Add reactions to message
await msg.react('✅');
await msg.react('❌');
};
module.exports.config = {
command: 'poll',
permissions: ['SEND_MESSAGES', 'EMBED_LINKS', 'ADD_REACTIONS'],
};
module.exports.help = {
name: 'Poll',
category: 'Guild',
description: 'Will create a poll for users to answer',
usage: '${PREFIX}poll <question>',
example: '${PREFIX}poll is Egglord the best?',
};
|
mirwansyahs/siabanks | assets/ckeditor/tests/plugins/image2/states.js | <gh_stars>1-10
/* bender-tags: editor,widget */
/* bender-ckeditor-plugins: image2,link */
/* global image2TestsTools */
( function() {
'use strict';
var tools = image2TestsTools,
states = {
// Captioned widgets without links.
'caption:true_align:none_link:no': {
hasCaption: true,
align: 'none'
},
'caption:true_align:center_link:no': {
hasCaption: true,
align: 'center'
},
'caption:true_align:left_link:no': {
hasCaption: true,
align: 'left'
},
// Captioned widgets with link.
'caption:true_align:none_link:yes': {
hasCaption: true,
align: 'none',
link: {
type: 'url',
url: {
protocol: 'http://',
url: 'x'
}
}
},
'caption:true_align:center_link:yes': {
hasCaption: true,
align: 'center',
link: {
type: 'url',
url: {
protocol: 'http://',
url: 'x'
}
}
},
'caption:true_align:left_link:yes': {
hasCaption: true,
align: 'left',
link: {
type: 'url',
url: {
protocol: 'http://',
url: 'x'
}
}
},
// Non-captioned widgets without links.
'caption:false_align:none_link:no': {
hasCaption: false,
align: 'none'
},
'caption:false_align:center_link:no': {
hasCaption: false,
align: 'center'
},
'caption:false_align:left_link:no': {
hasCaption: false,
align: 'left'
},
// Non-captioned widgets without links.
'caption:false_align:none_link:yes': {
hasCaption: false,
align: 'none',
link: {
type: 'url',
url: {
protocol: 'http://',
url: 'x'
}
}
},
'caption:false_align:center_link:yes': {
hasCaption: false,
align: 'center',
link: {
type: 'url',
url: {
protocol: 'http://',
url: 'x'
}
}
},
'caption:false_align:left_link:yes': {
hasCaption: false,
align: 'left',
link: {
type: 'url',
url: {
protocol: 'http://',
url: 'x'
}
}
}
},
contexts = {
'test split paragraph when caption is added': {
context: 'plainParagraph',
oldState: 'caption:false_align:none_link:no',
newState: 'caption:true_align:none_link:no'
},
'test split paragraph with span when caption is added': {
context: 'paragraphWithSpan',
oldState: 'caption:false_align:none_link:no',
newState: 'caption:true_align:none_link:no'
},
'test split paragraph when widget is centered': {
context: 'plainParagraph',
oldState: 'caption:false_align:none_link:no',
newState: 'caption:false_align:center_link:no'
}
};
bender.editorBot.create( {
config: {
language: 'en',
allowedContent: true,
enterMode: CKEDITOR.ENTER_P,
autoParagraph: false
}
}, function( bot ) {
var tcs = {},
shiftState = CKEDITOR.plugins.image2.stateShifter( bot.editor );
tools.createStateTransitionTests( tcs, states, shiftState );
tools.createContextualStateTransitionTests( tcs, states, contexts, shiftState );
tcs.editorBot = bot;
bender.test( tcs );
} );
} )();
|
goplus/libc | x2g__stdio_exit.c.i.go | <reponame>goplus/libc<filename>x2g__stdio_exit.c.i.go
package libc
import unsafe "unsafe"
var dummy_file_cgo764 *struct__IO_FILE = nil
func close_file_cgo765(f *struct__IO_FILE) {
if !(f != nil) {
return
}
func() int32 {
if f.lock >= int32(0) {
return __lockfile(f)
} else {
return int32(0)
}
}()
if uintptr(unsafe.Pointer(f.wpos)) != uintptr(unsafe.Pointer(f.wbase)) {
f.write(f, nil, uint64(0))
}
if uintptr(unsafe.Pointer(f.rpos)) != uintptr(unsafe.Pointer(f.rend)) {
f.seek(f, int64(uintptr(unsafe.Pointer(f.rpos))-uintptr(unsafe.Pointer(f.rend))), int32(1))
}
}
func __stdio_exit() {
var f *struct__IO_FILE
for f = *__ofl_lock(); f != nil; f = f.next {
close_file_cgo765(f)
}
close_file_cgo765(__stdin_used)
close_file_cgo765(__stdout_used)
close_file_cgo765(__stderr_used)
}
|
xushuhui/mall_go | app/coupon/service/internal/data/model/migrate/schema.go | <reponame>xushuhui/mall_go<gh_stars>1-10
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// CouponsColumns holds the columns for the "coupons" table.
CouponsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "create_time", Type: field.TypeTime},
{Name: "update_time", Type: field.TypeTime},
{Name: "delete_time", Type: field.TypeTime, Nullable: true},
{Name: "title", Type: field.TypeString},
{Name: "start_time", Type: field.TypeTime},
{Name: "end_time", Type: field.TypeTime},
{Name: "description", Type: field.TypeString},
{Name: "full_money", Type: field.TypeFloat64},
{Name: "minus", Type: field.TypeFloat64},
{Name: "rate", Type: field.TypeFloat64},
{Name: "type", Type: field.TypeInt},
{Name: "valitiy", Type: field.TypeInt},
{Name: "activity_id", Type: field.TypeInt64, Nullable: true},
{Name: "remark", Type: field.TypeString},
{Name: "whole_store", Type: field.TypeInt},
}
// CouponsTable holds the schema information for the "coupons" table.
CouponsTable = &schema.Table{
Name: "coupons",
Columns: CouponsColumns,
PrimaryKey: []*schema.Column{CouponsColumns[0]},
}
// CouponTemplatesColumns holds the columns for the "coupon_templates" table.
CouponTemplatesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "create_time", Type: field.TypeTime},
{Name: "update_time", Type: field.TypeTime},
{Name: "delete_time", Type: field.TypeTime, Nullable: true},
{Name: "title", Type: field.TypeString},
{Name: "description", Type: field.TypeString},
{Name: "full_money", Type: field.TypeFloat64},
{Name: "minus", Type: field.TypeFloat64},
{Name: "discount", Type: field.TypeFloat64},
{Name: "type", Type: field.TypeInt},
}
// CouponTemplatesTable holds the schema information for the "coupon_templates" table.
CouponTemplatesTable = &schema.Table{
Name: "coupon_templates",
Columns: CouponTemplatesColumns,
PrimaryKey: []*schema.Column{CouponTemplatesColumns[0]},
}
// CouponTypesColumns holds the columns for the "coupon_types" table.
CouponTypesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "create_time", Type: field.TypeTime},
{Name: "update_time", Type: field.TypeTime},
{Name: "delete_time", Type: field.TypeTime, Nullable: true},
{Name: "name", Type: field.TypeString},
{Name: "code", Type: field.TypeInt},
{Name: "description", Type: field.TypeString},
}
// CouponTypesTable holds the schema information for the "coupon_types" table.
CouponTypesTable = &schema.Table{
Name: "coupon_types",
Columns: CouponTypesColumns,
PrimaryKey: []*schema.Column{CouponTypesColumns[0]},
}
// UserCouponColumns holds the columns for the "user_coupon" table.
UserCouponColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "create_time", Type: field.TypeTime},
{Name: "update_time", Type: field.TypeTime},
{Name: "delete_time", Type: field.TypeTime, Nullable: true},
{Name: "user_id", Type: field.TypeInt64},
{Name: "coupon_id", Type: field.TypeInt64, Nullable: true},
{Name: "status", Type: field.TypeInt, Default: 1},
{Name: "order_id", Type: field.TypeInt},
}
// UserCouponTable holds the schema information for the "user_coupon" table.
UserCouponTable = &schema.Table{
Name: "user_coupon",
Columns: UserCouponColumns,
PrimaryKey: []*schema.Column{UserCouponColumns[0]},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
CouponsTable,
CouponTemplatesTable,
CouponTypesTable,
UserCouponTable,
}
)
func init() {
UserCouponTable.Annotation = &entsql.Annotation{
Table: "user_coupon",
}
}
|
vizee/misc | go/livedmc/notify_stub.go | <filename>go/livedmc/notify_stub.go
// +build !linux
package main
type notifier struct {
appName string
delay int
}
func (n *notifier) init() error {
return nil
}
func (n *notifier) show(summary string, body string) error {
return nil
}
func (n *notifier) close() {
}
|
Mozilla-GitHub-Standards/b55f95984015e193bf0af8041de6a30a1841dd9461fffd41c5216d98d645963d | app/scienceapi/users/tests/test_models.py | <reponame>Mozilla-GitHub-Standards/b55f95984015e193bf0af8041de6a30a1841dd9461fffd41c5216d98d645963d
import factory
from faker import Factory as FakerFactory
from scienceapi.users.models import User
faker = FakerFactory.create()
class UserFactory(factory.Factory):
name = factory.LazyAttribute(lambda o: faker.name())
username = factory.LazyAttribute(lambda o: faker.user_name())
designation = factory.LazyAttribute(
lambda o: '{a}-designation'.format(a=o.username.lower())
)
email = factory.LazyAttribute(lambda o: <EMAIL>' % o.username)
location = factory.LazyAttribute(
lambda o: '{a}-location'.format(a=o.username.lower())
)
biography = factory.LazyAttribute(
lambda o: '{a}-biography'.format(a=o.username.lower())
)
github_id = factory.Sequence(lambda n: str(n))
github_username = factory.LazyAttribute(
lambda o: '{a}-github_username'.format(a=o.username.lower())
)
twitter_handle = factory.LazyAttribute(
lambda o: '{a}-twitter_handle'.format(a=o.username.lower())
)
avatar_url = factory.LazyAttribute(
lambda o: 'http://{a}-avatar_url.com'.format(a=o.username.lower())
)
blog = factory.LazyAttribute(
lambda o: '{a}-blog'.format(a=o.username.lower())
)
company = factory.LazyAttribute(
lambda o: '{a}-company'.format(a=o.username.lower())
)
role = factory.LazyAttribute(
lambda o: '{a}-role'.format(a=o.username.lower())
)
class Meta:
model = User
|
wwongkamjan/dipnet_press | diplomacy_research/proto/tensorflow_serving/config/platform_config.pb.h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow_serving/config/platform_config.proto
#ifndef PROTOBUF_INCLUDED_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto
#define PROTOBUF_INCLUDED_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/map.h> // IWYU pragma: export
#include <google/protobuf/map_entry.h>
#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/any.pb.h>
// @@protoc_insertion_point(includes)
#define PROTOBUF_INTERNAL_EXPORT_protobuf_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto
namespace protobuf_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto {
// Internal implementation detail -- do not use these members.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[3];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
void AddDescriptors();
} // namespace protobuf_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto
namespace tensorflow {
namespace serving {
class PlatformConfig;
class PlatformConfigDefaultTypeInternal;
extern PlatformConfigDefaultTypeInternal _PlatformConfig_default_instance_;
class PlatformConfigMap;
class PlatformConfigMapDefaultTypeInternal;
extern PlatformConfigMapDefaultTypeInternal _PlatformConfigMap_default_instance_;
class PlatformConfigMap_PlatformConfigsEntry_DoNotUse;
class PlatformConfigMap_PlatformConfigsEntry_DoNotUseDefaultTypeInternal;
extern PlatformConfigMap_PlatformConfigsEntry_DoNotUseDefaultTypeInternal _PlatformConfigMap_PlatformConfigsEntry_DoNotUse_default_instance_;
} // namespace serving
} // namespace tensorflow
namespace google {
namespace protobuf {
template<> ::tensorflow::serving::PlatformConfig* Arena::CreateMaybeMessage<::tensorflow::serving::PlatformConfig>(Arena*);
template<> ::tensorflow::serving::PlatformConfigMap* Arena::CreateMaybeMessage<::tensorflow::serving::PlatformConfigMap>(Arena*);
template<> ::tensorflow::serving::PlatformConfigMap_PlatformConfigsEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::serving::PlatformConfigMap_PlatformConfigsEntry_DoNotUse>(Arena*);
} // namespace protobuf
} // namespace google
namespace tensorflow {
namespace serving {
// ===================================================================
class PlatformConfig : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tensorflow.serving.PlatformConfig) */ {
public:
PlatformConfig();
virtual ~PlatformConfig();
PlatformConfig(const PlatformConfig& from);
inline PlatformConfig& operator=(const PlatformConfig& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
PlatformConfig(PlatformConfig&& from) noexcept
: PlatformConfig() {
*this = ::std::move(from);
}
inline PlatformConfig& operator=(PlatformConfig&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
static const PlatformConfig& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const PlatformConfig* internal_default_instance() {
return reinterpret_cast<const PlatformConfig*>(
&_PlatformConfig_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
void UnsafeArenaSwap(PlatformConfig* other);
void Swap(PlatformConfig* other);
friend void swap(PlatformConfig& a, PlatformConfig& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline PlatformConfig* New() const final {
return CreateMaybeMessage<PlatformConfig>(NULL);
}
PlatformConfig* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<PlatformConfig>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const PlatformConfig& from);
void MergeFrom(const PlatformConfig& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(PlatformConfig* other);
protected:
explicit PlatformConfig(::google::protobuf::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
return _internal_metadata_.raw_arena_ptr();
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// .google.protobuf.Any source_adapter_config = 1;
bool has_source_adapter_config() const;
void clear_source_adapter_config();
static const int kSourceAdapterConfigFieldNumber = 1;
private:
const ::google::protobuf::Any& _internal_source_adapter_config() const;
public:
const ::google::protobuf::Any& source_adapter_config() const;
::google::protobuf::Any* release_source_adapter_config();
::google::protobuf::Any* mutable_source_adapter_config();
void set_allocated_source_adapter_config(::google::protobuf::Any* source_adapter_config);
void unsafe_arena_set_allocated_source_adapter_config(
::google::protobuf::Any* source_adapter_config);
::google::protobuf::Any* unsafe_arena_release_source_adapter_config();
// @@protoc_insertion_point(class_scope:tensorflow.serving.PlatformConfig)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::Any* source_adapter_config_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class PlatformConfigMap_PlatformConfigsEntry_DoNotUse : public ::google::protobuf::internal::MapEntry<PlatformConfigMap_PlatformConfigsEntry_DoNotUse,
::std::string, ::tensorflow::serving::PlatformConfig,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > {
public:
typedef ::google::protobuf::internal::MapEntry<PlatformConfigMap_PlatformConfigsEntry_DoNotUse,
::std::string, ::tensorflow::serving::PlatformConfig,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > SuperType;
PlatformConfigMap_PlatformConfigsEntry_DoNotUse();
PlatformConfigMap_PlatformConfigsEntry_DoNotUse(::google::protobuf::Arena* arena);
void MergeFrom(const PlatformConfigMap_PlatformConfigsEntry_DoNotUse& other);
static const PlatformConfigMap_PlatformConfigsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const PlatformConfigMap_PlatformConfigsEntry_DoNotUse*>(&_PlatformConfigMap_PlatformConfigsEntry_DoNotUse_default_instance_); }
void MergeFrom(const ::google::protobuf::Message& other) final;
::google::protobuf::Metadata GetMetadata() const;
};
// -------------------------------------------------------------------
class PlatformConfigMap : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tensorflow.serving.PlatformConfigMap) */ {
public:
PlatformConfigMap();
virtual ~PlatformConfigMap();
PlatformConfigMap(const PlatformConfigMap& from);
inline PlatformConfigMap& operator=(const PlatformConfigMap& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
PlatformConfigMap(PlatformConfigMap&& from) noexcept
: PlatformConfigMap() {
*this = ::std::move(from);
}
inline PlatformConfigMap& operator=(PlatformConfigMap&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline ::google::protobuf::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::google::protobuf::Descriptor* descriptor();
static const PlatformConfigMap& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const PlatformConfigMap* internal_default_instance() {
return reinterpret_cast<const PlatformConfigMap*>(
&_PlatformConfigMap_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
void UnsafeArenaSwap(PlatformConfigMap* other);
void Swap(PlatformConfigMap* other);
friend void swap(PlatformConfigMap& a, PlatformConfigMap& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline PlatformConfigMap* New() const final {
return CreateMaybeMessage<PlatformConfigMap>(NULL);
}
PlatformConfigMap* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<PlatformConfigMap>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const PlatformConfigMap& from);
void MergeFrom(const PlatformConfigMap& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(PlatformConfigMap* other);
protected:
explicit PlatformConfigMap(::google::protobuf::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
return _internal_metadata_.raw_arena_ptr();
}
public:
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// map<string, .tensorflow.serving.PlatformConfig> platform_configs = 1;
int platform_configs_size() const;
void clear_platform_configs();
static const int kPlatformConfigsFieldNumber = 1;
const ::google::protobuf::Map< ::std::string, ::tensorflow::serving::PlatformConfig >&
platform_configs() const;
::google::protobuf::Map< ::std::string, ::tensorflow::serving::PlatformConfig >*
mutable_platform_configs();
// @@protoc_insertion_point(class_scope:tensorflow.serving.PlatformConfigMap)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::internal::MapField<
PlatformConfigMap_PlatformConfigsEntry_DoNotUse,
::std::string, ::tensorflow::serving::PlatformConfig,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > platform_configs_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// PlatformConfig
// .google.protobuf.Any source_adapter_config = 1;
inline bool PlatformConfig::has_source_adapter_config() const {
return this != internal_default_instance() && source_adapter_config_ != NULL;
}
inline const ::google::protobuf::Any& PlatformConfig::_internal_source_adapter_config() const {
return *source_adapter_config_;
}
inline const ::google::protobuf::Any& PlatformConfig::source_adapter_config() const {
const ::google::protobuf::Any* p = source_adapter_config_;
// @@protoc_insertion_point(field_get:tensorflow.serving.PlatformConfig.source_adapter_config)
return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::Any*>(
&::google::protobuf::_Any_default_instance_);
}
inline ::google::protobuf::Any* PlatformConfig::release_source_adapter_config() {
// @@protoc_insertion_point(field_release:tensorflow.serving.PlatformConfig.source_adapter_config)
::google::protobuf::Any* temp = source_adapter_config_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
}
source_adapter_config_ = NULL;
return temp;
}
inline ::google::protobuf::Any* PlatformConfig::unsafe_arena_release_source_adapter_config() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.serving.PlatformConfig.source_adapter_config)
::google::protobuf::Any* temp = source_adapter_config_;
source_adapter_config_ = NULL;
return temp;
}
inline ::google::protobuf::Any* PlatformConfig::mutable_source_adapter_config() {
if (source_adapter_config_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::Any>(GetArenaNoVirtual());
source_adapter_config_ = p;
}
// @@protoc_insertion_point(field_mutable:tensorflow.serving.PlatformConfig.source_adapter_config)
return source_adapter_config_;
}
inline void PlatformConfig::set_allocated_source_adapter_config(::google::protobuf::Any* source_adapter_config) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete reinterpret_cast< ::google::protobuf::MessageLite*>(source_adapter_config_);
}
if (source_adapter_config) {
::google::protobuf::Arena* submessage_arena = NULL;
if (message_arena != submessage_arena) {
source_adapter_config = ::google::protobuf::internal::GetOwnedMessage(
message_arena, source_adapter_config, submessage_arena);
}
} else {
}
source_adapter_config_ = source_adapter_config;
// @@protoc_insertion_point(field_set_allocated:tensorflow.serving.PlatformConfig.source_adapter_config)
}
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// PlatformConfigMap
// map<string, .tensorflow.serving.PlatformConfig> platform_configs = 1;
inline int PlatformConfigMap::platform_configs_size() const {
return platform_configs_.size();
}
inline void PlatformConfigMap::clear_platform_configs() {
platform_configs_.Clear();
}
inline const ::google::protobuf::Map< ::std::string, ::tensorflow::serving::PlatformConfig >&
PlatformConfigMap::platform_configs() const {
// @@protoc_insertion_point(field_map:tensorflow.serving.PlatformConfigMap.platform_configs)
return platform_configs_.GetMap();
}
inline ::google::protobuf::Map< ::std::string, ::tensorflow::serving::PlatformConfig >*
PlatformConfigMap::mutable_platform_configs() {
// @@protoc_insertion_point(field_mutable_map:tensorflow.serving.PlatformConfigMap.platform_configs)
return platform_configs_.MutableMap();
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace serving
} // namespace tensorflow
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_INCLUDED_tensorflow_5fserving_2fconfig_2fplatform_5fconfig_2eproto
|
lacc97/media-driver | media_driver/agnostic/gen11/codec/hal/codechal_kernel_header_g11.h | <reponame>lacc97/media-driver<filename>media_driver/agnostic/gen11/codec/hal/codechal_kernel_header_g11.h
/*
* Copyright (c) 2017-2019, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file codechal_kernel_header_g11.h
//! \brief Gen11 kernel header definitions.
//!
#ifndef __CODECHAL_KERNEL_HEADER_G11_H__
#define __CODECHAL_KERNEL_HEADER_G11_H__
#include "codechal_encoder_base.h"
struct HmeDsScoreboardKernelHeaderG11 {
int nKernelCount;
union
{
struct
{
CODECHAL_KERNEL_HEADER hmeDownscaleGenX0;
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_KERNEL_HEADER hmeDownscaleGenX1;
#endif
CODECHAL_KERNEL_HEADER hmeDownscaleGenX2;
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_KERNEL_HEADER hmeDownscaleGenX3;
#endif
CODECHAL_KERNEL_HEADER hmeP;
CODECHAL_KERNEL_HEADER hmeB;
CODECHAL_KERNEL_HEADER hmeVdenc;
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_KERNEL_HEADER hmeHevcVdenc;
CODECHAL_KERNEL_HEADER hmeDetectionGenX0;
#endif
CODECHAL_KERNEL_HEADER dsConvertGenX0;
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_KERNEL_HEADER initSwScoreboard;
CODECHAL_KERNEL_HEADER intraDistortion;
CODECHAL_KERNEL_HEADER dynamicScaling;
CODECHAL_KERNEL_HEADER weightedPrediction;
#endif
};
};
};
enum HmeDsScoreboardKernelIdxG11
{
// HME + Scoreboard Kernel Surface
CODECHAL_HME_DOWNSCALE_GENX_0_KRNIDX = 0,
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_HME_DOWNSCALE_GENX_1_KRNIDX,
#endif
CODECHAL_HME_DOWNSCALE_GENX_2_KRNIDX,
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_HME_DOWNSCALE_GENX_3_KRNIDX,
#endif
CODECHAL_HME_GENX_0_KRNIDX,
CODECHAL_HME_GENX_1_KRNIDX,
CODECHAL_HME_GENX_2_KRNIDX,
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_HME_HEVC_VDENC_KRNIDX,
CODECHAL_HMEDetection_GENX_0_KRNIDX,
#endif
CODECHAL_DS_CONVERT_GENX_0_KRNIDX,
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
CODECHAL_SW_SCOREBOARD_G11_KRNIDX,
CODECHAL_INTRA_DISTORTION_G11_KRNIDX,
CODECHAL_DYNAMIC_SCALING_G11_KRNIDX,
#endif
CODECHAL_HmeDsSwScoreboardInit_NUM_KRN_G11
};
//!
//! \brief Get common kernel header and size
//!
//! \param [in] binary
//! Kernel binary
//!
//! \param [in] operation
//! Encode operation
//!
//! \param [in] krnStateIdx
//! Kernel state index
//!
//! \param [in] krnHeader
//! Kernel header
//!
//! \param [in] krnSize
//! Kernel size
//!
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
static MOS_STATUS GetCommonKernelHeaderAndSizeG11(
void *binary,
EncOperation operation,
uint32_t krnStateIdx,
void *krnHeader,
uint32_t *krnSize)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_ENCODE_FUNCTION_ENTER;
CODECHAL_ENCODE_CHK_NULL_RETURN(binary);
CODECHAL_ENCODE_CHK_NULL_RETURN(krnHeader);
CODECHAL_ENCODE_CHK_NULL_RETURN(krnSize);
HmeDsScoreboardKernelHeaderG11 *kernelHeaderTable;
kernelHeaderTable = (HmeDsScoreboardKernelHeaderG11*)binary;
PCODECHAL_KERNEL_HEADER currKrnHeader;
switch (operation)
{
case ENC_SCALING4X:
currKrnHeader = &kernelHeaderTable->hmeDownscaleGenX0;
break;
case ENC_SCALING2X:
currKrnHeader = &kernelHeaderTable->hmeDownscaleGenX2;
break;
case ENC_ME:
currKrnHeader = &kernelHeaderTable->hmeP;
break;
case VDENC_ME_B:
currKrnHeader = &kernelHeaderTable->hmeB;
break;
case VDENC_ME:
currKrnHeader = &kernelHeaderTable->hmeVdenc;
break;
case ENC_SCALING_CONVERSION:
currKrnHeader = &kernelHeaderTable->dsConvertGenX0;
break;
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
case VDENC_STREAMIN_HEVC:
currKrnHeader = &kernelHeaderTable->hmeHevcVdenc;
break;
case ENC_SFD:
currKrnHeader = &kernelHeaderTable->hmeDetectionGenX0;
break;
case ENC_SCOREBOARD:
currKrnHeader = &kernelHeaderTable->initSwScoreboard;
break;
case ENC_INTRA_DISTORTION:
currKrnHeader = &kernelHeaderTable->intraDistortion;
break;
case ENC_DYS:
currKrnHeader = &kernelHeaderTable->dynamicScaling;
break;
case ENC_WP:
currKrnHeader = &kernelHeaderTable->weightedPrediction;
break;
#endif
default:
CODECHAL_ENCODE_ASSERTMESSAGE("Unsupported ENC mode requested");
eStatus = MOS_STATUS_INVALID_PARAMETER;
return eStatus;
}
currKrnHeader += krnStateIdx;
*((PCODECHAL_KERNEL_HEADER)krnHeader) = *currKrnHeader;
PCODECHAL_KERNEL_HEADER invalidEntry;
invalidEntry = &(kernelHeaderTable->hmeDownscaleGenX0) + CODECHAL_HmeDsSwScoreboardInit_NUM_KRN_G11;
PCODECHAL_KERNEL_HEADER nextKrnHeader;
nextKrnHeader = (currKrnHeader + 1);
uint32_t nextKrnOffset;
nextKrnOffset = *krnSize;
if (nextKrnHeader < invalidEntry)
{
nextKrnOffset = nextKrnHeader->KernelStartPointer << MHW_KERNEL_OFFSET_SHIFT;
}
*krnSize = nextKrnOffset - (currKrnHeader->KernelStartPointer << MHW_KERNEL_OFFSET_SHIFT);
return eStatus;
}
#endif // __CODECHAL_KERNEL_HEADER_G11_H__
|
daviddahl/js-ipfs | packages/ipfs/src/core/components/files/touch.js | <filename>packages/ipfs/src/core/components/files/touch.js
'use strict'
const applyDefaultOptions = require('./utils/apply-default-options')
const toMfsPath = require('./utils/to-mfs-path')
const log = require('debug')('ipfs:mfs:touch')
const errCode = require('err-code')
const UnixFS = require('ipfs-unixfs')
const toTrail = require('./utils/to-trail')
const addLink = require('./utils/add-link')
const updateTree = require('./utils/update-tree')
const updateMfsRoot = require('./utils/update-mfs-root')
const { DAGNode } = require('ipld-dag-pb')
const mc = require('multicodec')
const mh = require('multihashes')
const { withTimeoutOption } = require('../../utils')
const defaultOptions = {
mtime: undefined,
flush: true,
shardSplitThreshold: 1000,
cidVersion: 0,
hashAlg: 'sha2-256'
}
module.exports = (context) => {
return withTimeoutOption(async function mfsTouch (path, options) {
options = options || {}
options = applyDefaultOptions(options, defaultOptions)
options.mtime = options.mtime || new Date()
log(`Touching ${path} mtime: ${options.mtime}`)
const {
cid,
mfsDirectory,
name,
exists
} = await toMfsPath(context, path)
let node
let updatedCid
let cidVersion = options.cidVersion
if (!exists) {
const metadata = new UnixFS({
type: 'file',
mtime: options.mtime
})
node = new DAGNode(metadata.marshal())
updatedCid = await context.ipld.put(node, mc.DAG_PB, {
cidVersion: options.cidVersion,
hashAlg: mh.names['sha2-256'],
onlyHash: !options.flush
})
} else {
if (cid.codec !== 'dag-pb') {
throw errCode(new Error(`${path} was not a UnixFS node`), 'ERR_NOT_UNIXFS')
}
cidVersion = cid.version
node = await context.ipld.get(cid)
const metadata = UnixFS.unmarshal(node.Data)
metadata.mtime = options.mtime
node = new DAGNode(metadata.marshal(), node.Links)
updatedCid = await context.ipld.put(node, mc.DAG_PB, {
cidVersion: cid.version,
hashAlg: mh.names['sha2-256'],
onlyHash: !options.flush
})
}
const trail = await toTrail(context, mfsDirectory, options)
const parent = trail[trail.length - 1]
const parentNode = await context.ipld.get(parent.cid)
const result = await addLink(context, {
parent: parentNode,
name: name,
cid: updatedCid,
size: node.serialize().length,
flush: options.flush,
shardSplitThreshold: options.shardSplitThreshold,
hashAlg: 'sha2-256',
cidVersion
})
parent.cid = result.cid
// update the tree with the new child
const newRootCid = await updateTree(context, trail, options)
// Update the MFS record with the new CID for the root of the tree
await updateMfsRoot(context, newRootCid)
})
}
|
fnando/validators | test/validators/validates_datetime/after_option_test.rb | # frozen_string_literal: true
require "test_helper"
class ValidatesDatetimeAfterOptionTest < Minitest::Test
let(:user) { User.new }
test "rejects when date is set to before :after option" do
future_date = 1.week.from_now
User.validates_datetime :registered_at, after: future_date
user.registered_at = Time.now
refute user.valid?
assert_includes user.errors[:registered_at], "needs to be after #{I18n.l(future_date)}"
end
test "accepts when date is set accordingly to the :after option" do
User.validates_datetime :registered_at, after: 1.week.from_now
user.registered_at = 2.weeks.from_now
assert user.valid?
end
test "validates using today as date" do
User.validates_datetime :registered_at, after: :today
user.registered_at = Time.now
refute user.valid?
user.registered_at = Date.today
refute user.valid?
user.registered_at = Date.tomorrow
assert user.valid?
user.registered_at = 1.day.from_now
assert user.valid?
end
test "validates using now as date" do
User.validates_datetime :registered_at, after: :now
user.registered_at = Time.now
refute user.valid?
user.registered_at = Date.today
refute user.valid?
user.registered_at = Date.tomorrow
assert user.valid?
user.registered_at = 1.day.from_now
assert user.valid?
end
test "validates using method as date" do
User.validates_datetime :starts_at
User.validates_datetime :ends_at, after: :starts_at, if: :starts_at?
user.starts_at = nil
user.ends_at = Time.now
refute user.valid?
assert user.errors[:ends_at].empty?
user.starts_at = Time.parse("Apr 26 2010")
user.ends_at = Time.parse("Apr 25 2010")
formatted_date = I18n.l(Time.parse("Apr 26 2010"))
refute user.valid?
assert_includes user.errors[:ends_at], "needs to be after #{formatted_date}"
user.starts_at = Time.now
user.ends_at = 1.hour.from_now
assert user.valid?
end
test "validates using proc as date" do
User.validates_datetime :starts_at
User.validates_datetime :ends_at, after: ->(record) { record.starts_at }, if: :starts_at?
user.starts_at = nil
user.ends_at = Time.now
refute user.valid?
assert user.errors[:ends_at].empty?
user.starts_at = Time.parse("Apr 26 2010")
user.ends_at = Time.parse("Apr 25 2010")
formatted_date = I18n.l(Time.parse("Apr 26 2010"))
refute user.valid?
assert_includes user.errors[:ends_at], "needs to be after #{formatted_date}"
user.starts_at = Time.now
user.ends_at = 1.hour.from_now
assert user.valid?
end
end
|
lpj1986/java9 | src/main/java/win/elegentjs/designpattern/strategy/CalcStrategy.java | <reponame>lpj1986/java9
package win.elegentjs.designpattern.strategy;
public interface CalcStrategy {
int calc(int a, int b);
}
|
Tecknowlegy/open-idea-station | spec/presenters/user_presenter_spec.rb | <reponame>Tecknowlegy/open-idea-station<filename>spec/presenters/user_presenter_spec.rb
require "rails_helper"
describe UserPresenter do
let!(:user) { create :user }
let(:user_presenter) { described_class.new(user, ActionView::Helpers::DateHelper) }
describe "#provider" do
it "returns the provider of the user account" do
user.update(provider: "github")
expect(user_presenter.provider).to eql "github"
end
context "when provider is `google_oauth2`" do
it "changes the provider name to google" do
user.update(provider: "google_oauth2")
expect(user_presenter.provider).to eql "google"
end
end
end
describe "#username" do
it "returns the username of the account" do
user.update(username: "Dinobi")
expect(user_presenter.username).to eql "Dinobi"
end
end
describe "#picture" do
it "returns the picture of the account" do
user.update(picture: "my_profile_picture_url")
expect(user_presenter.picture).to eql "my_profile_picture_url"
end
end
describe "#email" do
it "returns the email of the account" do
user.update(email: "<EMAIL>")
expect(user_presenter.email).to eql "<EMAIL>"
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.