content
stringlengths 10
4.9M
|
---|
// Copyright (c) 2006 - 2008, Clark & Parsia, LLC. <http://www.clarkparsia.com>
// This source code is available under the terms of the Affero General Public License v3.
//
// Please see LICENSE.txt for full license terms, including the availability of proprietary exceptions.
// Questions, comments, or requests for clarification: [email protected]
package com.clarkparsia.pellet.sparqldl.engine;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mindswap.pellet.PelletOptions;
import com.clarkparsia.pellet.sparqldl.model.Query;
/**
* <p>
* Title: Optimizer of the query. Provides query atoms for the engine in
* particular ordering.
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2007
* </p>
* <p>
* Company: Clark & Parsia, LLC. <http://www.clarkparsia.com>
* </p>
*
* @author Petr Kremen
*/
public class QueryOptimizer {
private static final Logger LOG = Logger.getLogger(QueryOptimizer.class.getName());
public QueryPlan getExecutionPlan(Query query) {
if (PelletOptions.SAMPLING_RATIO == 0) {
return new NoReorderingQueryPlan(query);
}
if (query.getAtoms().size() > PelletOptions.STATIC_REORDERING_LIMIT) {
if (LOG.isLoggable( Level.FINE )) {
LOG.fine("Using incremental query plan.");
}
return new IncrementalQueryPlan(query);
} else {
if (LOG.isLoggable( Level.FINE )) {
LOG.fine("Using full query plan.");
}
return new CostBasedQueryPlanNew(query);
}
}
}
|
//Filtro o metodo buscar se usara para el tf de buscar
private void buscar (String consulta, JTable Tabla) {
dm = (DefaultTableModel) Tabla.getModel();
TableRowSorter<DefaultTableModel> tr = new TableRowSorter<>(dm);
Tabla.setRowSorter(tr);
tr.setRowFilter(RowFilter.regexFilter(consulta));
} |
<reponame>KirillNikoda/library
import {
Body,
Controller,
Delete,
Get,
HttpException,
HttpStatus,
Param,
ParseIntPipe,
Put,
Req,
UseGuards
} from "@nestjs/common";
import { UsersService } from './users.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { UpdateUserDto } from "./dto/updateUser.dto";
@Controller('users')
export class UsersController {
constructor(private usersService: UsersService) {}
@Get()
getUsers() {
return this.usersService.findAll();
}
@Get(":id/subscription")
getSubscriptionInfo(@Param("id", ParseIntPipe) id: number) {
return this.usersService.getSubscriptionInfo(id);
}
@Get(':id')
getOneUser(@Param('id', ParseIntPipe) id: number) {
return this.usersService.findOne(id);
}
@UseGuards(JwtAuthGuard)
@Delete(':id')
deleteUser(@Param('id', ParseIntPipe) id: number, @Req() req) {
if (+req.user.id !== id) {
throw new HttpException(
'You are not permitted to delete this profile',
HttpStatus.UNAUTHORIZED,
);
}
return this.usersService.remove(id);
}
@UseGuards(JwtAuthGuard)
@Put(':id')
updateUser(@Req() req, @Param('id', ParseIntPipe) id: number, @Body() updateUserDto: UpdateUserDto) {
if (+req.user.id !== id) {
throw new HttpException(
'You are not permitted to update this profile',
HttpStatus.UNAUTHORIZED,
);
}
return this.usersService.update(updateUserDto, id);
}
}
|
<gh_stars>0
'''
Created on 2014-01-30
@author: Nich
'''
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from contextlib import contextmanager
def engine(dbstring = 'sqlite:///fake.db', echo=False):
engine = create_engine(dbstring, echo=echo)
return engine
def create_sessionmaker(engine):
Session = sessionmaker(bind=engine)
my_scoped_session = scoped_session(Session)
return my_scoped_session
class SessionManager():
def __init__(self, Session):
self.Session = Session
@contextmanager
def get_session(self):
try:
session = self.Session()
yield session
except:
raise
finally:
session.commit()
session.close()
Base = declarative_base() |
def format_result(self):
translators_formated_list = format_list(self.translators)
formated_dict = {'translators': translators_formated_list}
if self.return_list and self.return_dict or self.return_dict:
self.result = formated_dict
elif self.return_list:
self.result = translators_formated_list
else:
self.result = formated_dict |
/*
The following program calculates the approximate value of the irrational mathematical constant e using Monte Carlo sampling.
The algorithm involved is as follows:
* Draw random variables S_r in the real open interval (0, 1).
* We then count the number of draws required N_i such that the Sum(S_r) > 1.
* We repeat this process K number of times where K is the total number of samples.
* approx_e = Sum(N_i(1,K)) / K
*/
#include <iostream>
#include <random>
#include <chrono>
#include <iomanip>
int getRandomDrawCount(std::default_random_engine &);
int main()
{
unsigned samples = 0;
long double sum = 0.0, approx_e = 0.0, error = 1.0, eps = 1e-12;
const long double e_const = 2.718281828459045;
std::cout << "This program estimates the value of the irrational constant e using Monte Carlo sampling." <<std::endl;
std::default_random_engine generator;
auto start = std::chrono::high_resolution_clock::now();
while(error > eps)
{
sum += getRandomDrawCount(generator);
samples++;
approx_e = sum / samples;
error = fabs(approx_e - e_const);
}
std::cout << std::setprecision(14) << "The approximate value of e is " << approx_e << "." << std::endl;
std::cout << "The absolute error is " << error << "." << std::endl;
auto stop = std::chrono::high_resolution_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::seconds>(stop - start);
std::cout << "Time taken is " << diff.count() << " seconds." << std::endl;
}
int getRandomDrawCount(std::default_random_engine &generator)
{
double s = 0.0;
int count = 0;
std::uniform_real_distribution<double> rnd(0.0, 1.0);
while (s <= 1.0)
{
s += rnd(generator);
count++;
}
return count;
} |
package org.snobot.nt.path_plotter;
public class PathSetpoint
{
public enum TrapezoidSegment
{
Acceleration, ConstantVelocity, Deceleration
}
/** The segment of the profile this segment is in. */
public TrapezoidSegment mSegment;
/** The desired position for this setpoint. */
public double mPosition;
/** The desired velocity for this setpoint. */
public double mVelocity;
/** The desired acceleration for this setpoint. */
public double mAcceleration;
/**
* Constructor.
*/
public PathSetpoint()
{
this(TrapezoidSegment.Acceleration, .02, 0, 0, 0);
}
/**
* Constructor.
*
* @param aSegment
* The individual segment for an instance in time
* @param aDt
* The expected time
* @param aPosition
* The position, in inches
* @param aVelocity
* The velocity, in in/sec
* @param aAccel
* The acceleration
*/
public PathSetpoint(TrapezoidSegment aSegment, double aDt, double aPosition, double aVelocity, double aAccel)
{
mSegment = aSegment;
mPosition = aPosition;
mVelocity = aVelocity;
mAcceleration = aAccel;
}
public TrapezoidSegment getSegment()
{
return mSegment;
}
public double getPosition()
{
return mPosition;
}
public double getVelocity()
{
return mVelocity;
}
public double getAcceleration()
{
return mAcceleration;
}
@Override
public String toString()
{
return "PathSetpoint [mSegment=" + mSegment + ", mPosition=" + mPosition + ", mVelocity=" + mVelocity + ", mAcceleration=" + mAcceleration
+ "]";
}
}
|
The “Right to Wage War” against Empire: Anticolonialism and the Challenge to International Law in the Indian National Army Trial of 1945
This Article treats the Indian National Army Trial of 1945 as a key moment in the elaboration of an anticolonial critique of international law in India. The trial was actually a court-martial of three Indian officers by the British colonial government on charges of high treason for defecting from the British Indian Army, joining up with Indian National Army forces in Singapore, and waging war in alliance with Imperial Japan against the British. In this trial, the defense made the radical claim that anticolonial wars fought in Asia against European powers were legitimate and just and should be recognized as such under international law. The aim of this Article is to draw attention to the understudied role of anticolonial movements in challenging the premises of international law in the aftermath of World War II. |
<reponame>dawidkotarba/QTGameEngine
#ifndef CLOUD_H
#define CLOUD_H
#include "engine/items/item.h"
#include "game/resources.h"
class Cloud : public Item {
public:
Cloud():
Item(Asset(PATH_CLOUD)){}
};
class Cloud2 : public Item {
public:
Cloud2():
Item(Asset(PATH_CLOUD2)){}
};
class Cloud3 : public Item {
public:
Cloud3():
Item(Asset(PATH_CLOUD3)){}
};
class Cloud4 : public Item {
public:
Cloud4():
Item(Asset(PATH_CLOUD4)){}
};
class Cloud5 : public Item {
public:
Cloud5():
Item(Asset(PATH_CLOUD5)){}
};
class Cloud6 : public Item {
public:
Cloud6():
Item(Asset(PATH_CLOUD6)){}
};
#endif // CLOUD_H
|
import { area } from './area'
import { assertLower } from './assert-lower'
import { beside } from './beside'
import { bind } from './bind'
import { camelClassCase } from './camel-class-case'
import { chars } from './chars'
import { charsAll } from './chars-all'
import { createStyle } from './create-style'
import { delRecursive } from './del-recursive'
import { doDeclare } from './do-declare'
import { eachDiff } from './each-diff'
import { easyStyleShadow } from './easy-style-shadow'
import { ensureUnique } from './ensure-unique'
import { extractLastNumber } from './extract-last-number'
import { includesMany } from './includes-many'
import { incrementLast } from './increment-last'
import { interval } from './interval'
import { invoke } from './invoke'
import { lastPlaceOf } from './last-place-of'
import { mapDiff } from './map-diff'
import { mapZIndex } from './map-z-index'
import { maxByLastNumber } from './max-by-last-number'
import { numericCode } from './numeric-code'
import { offset } from './offset'
import { oneOrAll } from './one-or-all'
import { partialEqual } from './partial-equal'
import { placeOf } from './place-of'
import { prefix } from './prefix'
import { push } from './push'
import { rangeWithNames } from './range-with-names'
import { returns } from './returns'
import { scenarios } from './scenarios'
import { set } from './set'
import { setEach } from './set-each'
import { setRecursive } from './set-recursive'
import { someTruthy } from './some-truthy'
import { someTruthyRight } from './some-truthy-right'
import { suffix } from './suffix'
import { suffixFrom } from './suffix-from'
import { sumBestMatch } from './sum-best-match'
import { titleCase } from './title-case'
import { toEnum } from './to-enum'
import { toggle } from './toggle'
import { visiblePartOf } from './visible-part-of'
import { omitNil } from './omit-nil'
const utilizes = {
area,
bind,
camelClassCase,
chars,
charsAll,
createStyle,
delRecursive,
doDeclare,
ensureUnique,
extractLastNumber,
incrementLast,
interval,
invoke,
mapZIndex,
maxByLastNumber,
offset,
oneOrAll,
prefix,
push,
rangeWithNames,
returns,
set,
setEach,
setRecursive,
someTruthy,
someTruthyRight,
sumBestMatch,
toEnum,
visiblePartOf,
titleCase,
mapDiff,
eachDiff,
easyStyleShadow,
includesMany,
beside,
toggle,
placeOf,
lastPlaceOf,
scenarios,
suffix,
numericCode,
assertLower,
suffixFrom,
partialEqual,
omitNil
}
export {
utilizes,
area,
bind,
camelClassCase,
chars,
charsAll,
createStyle,
delRecursive,
doDeclare,
ensureUnique,
extractLastNumber,
incrementLast,
interval,
invoke,
mapZIndex,
maxByLastNumber,
offset,
oneOrAll,
prefix,
push,
rangeWithNames,
returns,
set,
setEach,
setRecursive,
someTruthy,
someTruthyRight,
sumBestMatch,
toEnum,
visiblePartOf,
titleCase,
mapDiff,
eachDiff,
easyStyleShadow,
includesMany,
beside,
toggle,
placeOf,
lastPlaceOf,
scenarios,
suffix,
numericCode,
assertLower,
suffixFrom,
partialEqual,
omitNil
}
export default utilizes |
<reponame>erocs/AOC
import collections
import itertools
def solve():
cities = set()
dists = collections.defaultdict(dict)
with open('day9.txt') as fin:
for line in fin:
line = line.strip()
idx = line.find(' to ')
if idx < 0:
raise Exception('Bad line: ' + line)
idy = line.find(' = ')
if idy < 0:
raise Exception('Bad line: ' + line)
t1 = line[:idx]
t2 = line[idx+4:idy]
cities.add(t1)
cities.add(t2)
d = int(line[idy+3:])
if t1 < t2:
dists[t1][t2] = d
else:
dists[t2][t1] = d
best_dist = 0xFFFFFFFF
for comb in itertools.permutations(cities, len(cities)):
dist = 0
i = 0
while i < len(comb) - 1:
if comb[i] < comb[i + 1]:
t1 = comb[i]
t2 = comb[i + 1]
else:
t1 = comb[i + 1]
t2 = comb[i]
d = dists[t1][t2]
dist += d
i += 1
if dist < best_dist:
best_dist = dist
print best_dist
# 251
if __name__ == '__main__':
solve()
|
Defects in T-cell-mediated immunity to influenza virus in murine Wiskott-Aldrich syndrome are corrected by oncoretroviral vector-mediated gene transfer into repopulating hematopoietic cells.
The Wiskott-Aldrich syndrome (WAS) is an X-linked disorder characterized by immune dysfunction, thrombocytopenia, and eczema. We used a murine model created by knockout of the WAS protein gene (WASP) to evaluate the potential of gene therapy for WAS. Lethally irradiated, male WASP- animals that received transplants of mixtures of wild type (WT) and WASP- bone marrow cells demonstrated enrichment of WT cells in the lymphoid and myeloid lineages with a progressive increase in the proportion of WT T-lymphoid and B-lymphoid cells. WASP- mice had a defective secondary T-cell response to influenza virus which was normalized in animals that received transplants of 35% or more WT cells. The WASP gene was inserted into WASP- bone marrow cells with a bicistronic oncoretroviral vector also encoding green fluorescent protein (GFP), followed by transplantation into irradiated male WASP- recipients. There was a selective advantage for gene-corrected cells in multiple lineages. Animals with higher proportions of GFP+ T cells showed normalization of their lymphocyte counts. Gene-corrected, blood T cells exhibited full and partial correction, respectively, of their defective proliferative and cytokine secretory responses to in vitro T-cell-receptor stimulation. The defective secondary T-cell response to influenza virus was also improved in gene-corrected animals. |
str_insert=input()
#str_insert = "1+2+3+1"
#print(str_insert)
#print(str_insert.split("+"))
list1=str_insert.split("+")
#converts every element to str
list1_str = [str(x) for x in list1]
#print(list1_str)
#sorts elenments
list1_str.sort()
#print(list1_str)
list1_pluses = list("+".join(list1_str))
#print(list1_pluses)
#converts list to string
list1_str2 = "".join(list1_pluses)
print(list1_str2) |
//before calling this method call cfg_switch
//segment a logical dma command in multiple dma commands.
//if one of the DMA is not used fill the corresponding address with NULL
static inline int dma_movement( unsigned int len,
unsigned long long DMA0_rx_addr,
unsigned long long DMA1_rx_addr,
unsigned long long DMA1_tx_addr,
unsigned long long DMA2_rx_addr,
unsigned int what_DMAS) {
unsigned int curr_len;
while ( len > 0){
curr_len = dma_movement_DMA_MAX_TRANSACTIONS( len, DMA0_rx_addr, DMA1_rx_addr, DMA1_tx_addr, DMA2_rx_addr, what_DMAS);
len -= curr_len;
DMA0_rx_addr += curr_len;
DMA1_rx_addr += curr_len;
DMA1_tx_addr += curr_len;
DMA2_rx_addr += curr_len;
}
return COLLECTIVE_OP_SUCCESS;
} |
//-----------------------------------------------------------------------------
//! Given an element an the natural coordinates of a point in this element, this
//! function returns the global position vector.
vec3d FESurface::Local2Global(FESurfaceElement &el, double r, double s)
{
FEMesh& mesh = *m_pMesh;
int ne = el.Nodes();
vec3d y[FEElement::MAX_NODES];
for (int l=0; l<ne; ++l) y[l] = mesh.Node(el.m_node[l]).m_rt;
return el.eval(y, r, s);
} |
/**
* @brief updates the collaborator's score
*/
void Collaborator::updateScore() {
double sum{}, average{};
if (_classifications.empty()) _score = newHere;
else {
std::for_each(_classifications.begin(), _classifications.end(), [&](int n) {
sum += n;
});
average = (int(_score) + sum / static_cast<double>(_classifications.size())) / 2;
_score = static_cast<Classification>(int(round(average)));
}
} |
/**
* Synchronization routine, with the help of the coordinator
*
* @throws IOException
*/
private static void sync(int message, String log) throws IOException {
for (Socket peer : nodes) {
peer.getInputStream().read();
}
if (!log.isEmpty()) {
System.out.println(log);
}
for (Socket peer : nodes) {
peer.getOutputStream().write(message);
}
} |
def encrypt(mmap_instance, exact_cover_collection):
n = mmap_instance.get_n()
lmda = mmap_instance.get_lambda()
a = [mmap_instance.sample() for x in range(n)]
a_prime = [mmap_instance.encode(1, a[x]) for x in range(n)]
ciphertext = []
for exact_cover_subset in exact_cover_collection:
for x in a_prime:
mmap_instance.rerandomize(1, x)
product = mmap_instance.copy_encoding(a_prime[exact_cover_subset[0]])
for x in exact_cover_subset[1:]:
mmap_instance.multiply(product, a_prime[x], store_in=product)
encoded = mmap_instance.encode(len(exact_cover_subset), product)
ciphertext.append(encoded)
product = mmap_instance.copy_encoding(a_prime[0])
for x in a_prime[1:]:
mmap_instance.multiply(product, x, store_in=product)
encoding = mmap_instance.encode(n, product)
key = mmap_instance.extract(encoding)
key = _format_key_string(key, lmda)
return (key, ciphertext) |
<gh_stars>1-10
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Type-safe identifiers for specific use cases.
*/
/**
* A 128-bit Universally Unique IDentifier. Represented here
* with a string of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,
* where x is a lowercase hex digit.
* @public
*/
export type UuidString = string & { readonly UuidString: '9d40d0ae-90d9-44b1-9482-9f55d59d5465' };
/**
* An identifier associated with a session for the purpose of attributing its created content to some user/entity.
*/
export type AttributionId = UuidString;
/**
* A version 4, variant 2 uuid (https://datatracker.ietf.org/doc/html/rfc4122).
* @internal
*/
export type StableId = UuidString & { readonly StableId: '53172b0d-a3d5-41ea-bd75-b43839c97f5a' };
/**
* A StableId which is suitable for use as a session identifier
* @internal
*/
export type SessionId = StableId & { readonly SessionId: '4498f850-e14e-4be9-8db0-89ec00997e58' };
/**
* Edit identifier
* @public
*/
export type EditId = UuidString & { readonly EditId: '56897beb-53e4-4e66-85da-4bf5cd5d0d49' };
/**
* Scoped to a single edit: identifies a sequences of nodes that can be moved into a trait.
*
* Within a given Edit, any DetachedSequenceId must be a source at most once, and a destination at most once.
* If used as a source, it must be after it is used as a destination.
* If this is violated, the Edit is considered malformed.
* @public
*/
export type DetachedSequenceId = number & { readonly DetachedSequenceId: 'f7d7903a-194e-45e7-8e82-c9ef4333577d' };
/**
* An identifier (UUID) that has been shortened by a distributed compression algorithm.
* @public
*/
export type CompressedId = FinalCompressedId | LocalCompressedId;
/**
* The ID of the string that has been interned, which can be used by a {@link StringInterner} to retrieve the original string.
* @public
*/
export type InternedStringId = number & { readonly InternedStringId: 'e221abc9-9d17-4493-8db0-70c871a1c27c' };
/**
* A brand for identity types that are unique within a particular session (SharedTree instance).
*/
export interface SessionUnique {
readonly SessionUnique: 'cea55054-6b82-4cbf-ad19-1fa645ea3b3e';
}
/**
* A compressed ID that has been normalized into "session space" (see `IdCompressor` for more).
* Consumer-facing APIs and data structures should use session-space IDs as their lifetime and equality is stable and tied to the
* compressor that produced them.
* @public
*/
export type SessionSpaceCompressedId = CompressedId & SessionUnique;
/**
* A compressed ID that has been normalized into "op space" (see `IdCompressor` for more).
* Serialized/persisted structures (e.g. ops) should use op-space IDs as a performance optimization, as they require no normalizing when
* received by a remote client due to the fact that op space for a given compressor is session space for all other compressors.
* @internal
*/
export type OpSpaceCompressedId = CompressedId & {
readonly OpNormalized: '9209432d-a959-4df7-b2ad-767ead4dbcae';
};
/**
* A compressed ID that is local to a document. Stable across all revisions of a document starting from the one in which it was created.
* It should not be persisted outside of the history as it can only be decompressed in the context of the originating document.
* If external persistence is needed (e.g. by a client), a StableId should be used instead.
* @public
*/
export type FinalCompressedId = number & {
readonly FinalCompressedId: '5d83d1e2-98b7-4e4e-a889-54c855cfa73d';
// Same brand as OpNormalizedCompressedId, as final IDs are always finally normalized
readonly OpNormalized: '9209432d-a959-4df7-b2ad-767ead4dbcae';
};
/**
* A compressed ID that is local to a session (can only be decompressed when paired with a SessionId).
* It should not be persisted outside of the history as it can only be decompressed in the context of the originating session.
* If external persistence is needed (e.g. by a client), a StableId should be used instead.
* @public
*/
export type LocalCompressedId = number & {
readonly LocalCompressedId: '6fccb42f-e2a4-4243-bd29-f13d12b9c6d1';
} & SessionUnique; // Same brand as CompressedId, as local IDs are always locally normalized
export interface NodeIdBrand {
readonly NodeId: 'e53e7d6b-c8b9-431a-8805-4843fc639342';
}
/**
* Node identifier.
* Identifies a node within a document.
* @public
*/
export type NodeId = number & SessionSpaceCompressedId & NodeIdBrand;
export type FinalNodeId = FinalCompressedId & NodeIdBrand;
/**
* A Node identifier which is persisted by SharedTree internals. Not usable as a {@link NodeId}.
* @internal
*/
export type OpSpaceNodeId = number & OpSpaceCompressedId & NodeIdBrand;
/**
* Globally unique node identifier.
* Uniquely identifies a node within and across documents. Can be used across SharedTree instances.
* @public
*/
export type StableNodeId = string & { readonly StableNodeId: 'a0843b38-699d-4bb2-aa7a-16c502a71151' };
/**
* Definition.
* A full (Uuid) persistable definition.
* @public
*/
export type Definition = UuidString & { readonly Definition: 'c0ef9488-2a78-482d-aeed-37fba996354c' };
/**
* Definition.
* A full (Uuid) persistable label for a trait.
* @public
*/
export type TraitLabel = UuidString & { readonly TraitLabel: '613826ed-49cc-4df3-b2b8-bfc6866af8e3' };
/**
* Determine if a node is a DetachedSequenceId.
* @internal
*/
// Nodes can be an `object` type which is a banned type.
export function isDetachedSequenceId(node: DetachedSequenceId | object): node is DetachedSequenceId {
return typeof node !== 'object';
}
|
def broker(config, requests_mock):
ig_request_login(requests_mock)
ig_request_set_account(requests_mock)
return Broker(BrokerFactory(config)) |
<reponame>wyvie/syndesis<filename>app/ui-react/syndesis/src/modules/data/pages/VirtualizationViewsPage.tsx<gh_stars>0
import { useViewEditorStates, useVirtualization, useVirtualizationHelpers } from '@syndesis/api';
import { ViewDefinition, ViewEditorState } from '@syndesis/models';
import { RestDataService } from '@syndesis/models';
import { PageSection, ViewHeaderBreadcrumb, VirtualizationDetailsHeader } from '@syndesis/ui';
import { useRouteData } from '@syndesis/utils';
import { useContext } from 'react';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import i18n from '../../../i18n';
import { ApiError } from '../../../shared';
import { VirtualizationNavBar } from '../shared';
import { VirtualizationHandlers } from '../shared/VirtualizationHandlers';
import { getOdataUrl, getPublishingDetails } from '../shared/VirtualizationUtils';
import {
IActiveFilter,
IFilterType,
ISortType,
ViewList,
ViewListItem,
ViewListSkeleton,
} from '@syndesis/ui';
import { WithListViewToolbarHelpers, WithLoader } from '@syndesis/utils';
import { AppContext, UIContext } from '../../../app';
import resolvers from '../../resolvers';
/**
* @param virtualizationId - the ID of the virtualization whose details are being shown by this page.
*/
export interface IVirtualizationViewsPageRouteParams {
virtualizationId: string;
virtualization: RestDataService;
}
/**
* @param virtualizationId - the virtualization whose details are being shown by this page. If
* exists, it must equal to the [virtualizationId]{@link IVirtualizationViewsPageRouteParams#virtualizationId}.
*/
export interface IVirtualizationViewsPageRouteState {
virtualization: RestDataService;
}
function getFilteredAndSortedViewDefns(
viewDefinitions: ViewDefinition[],
activeFilters: IActiveFilter[],
currentSortType: ISortType,
isSortAscending: boolean
) {
let filteredAndSorted = viewDefinitions;
activeFilters.forEach((filter: IActiveFilter) => {
const valueToLower = filter.value.toLowerCase();
filteredAndSorted = filteredAndSorted.filter((view: ViewDefinition) =>
view.viewName.toLowerCase().includes(valueToLower)
);
});
filteredAndSorted = filteredAndSorted.sort((thisView, thatView) => {
if (isSortAscending) {
return thisView.viewName.localeCompare(thatView.viewName);
}
// sort descending
return thatView.viewName.localeCompare(thisView.viewName);
});
return filteredAndSorted;
}
const filterByName = {
filterType: 'text',
id: 'name',
placeholder: i18n.t('shared:filterByNamePlaceholder'),
title: i18n.t('shared:Name'),
} as IFilterType;
const filterTypes: IFilterType[] = [filterByName];
const sortByName = {
id: 'name',
isNumeric: false,
title: i18n.t('shared:Name'),
} as ISortType;
const sortTypes: ISortType[] = [sortByName];
export const VirtualizationViewsPage: React.FunctionComponent = () => {
const appContext = React.useContext(AppContext);
const { pushNotification } = useContext(UIContext);
const { t } = useTranslation(['data', 'shared']);
const { params, history } = useRouteData<
IVirtualizationViewsPageRouteParams,
IVirtualizationViewsPageRouteState
>();
const { deleteView, updateVirtualizationDescription } = useVirtualizationHelpers();
const { handleDeleteVirtualization, handlePublishVirtualization, handleUnpublishServiceVdb } = VirtualizationHandlers();
const filterUndefinedId = (view: ViewDefinition): boolean => {
return view.viewName !== undefined;
};
const { resource: virtualization } = useVirtualization(params.virtualizationId);
const {
resource: editorStates,
hasData: hasEditorStates,
error: editorStatesError,
read,
} = useViewEditorStates(virtualization.serviceVdbName + '*');
const publishingDetails = getPublishingDetails(
appContext.config.consoleUrl,
virtualization
);
const doDelete = async (
pVirtualizationId: string
) => {
const success = await handleDeleteVirtualization(pVirtualizationId);
if(success) {
history.push(
resolvers.data.virtualizations.list()
);
}
};
const doPublish = async (
pVirtualizationId: string,
hasViews: boolean
) => {
await handlePublishVirtualization(pVirtualizationId,hasViews);
}
const doUnpublish = async (
serviceVdbName: string
) => {
await handleUnpublishServiceVdb(serviceVdbName);
};
const doSetDescription = async (newDescription: string) => {
await updateVirtualizationDescription(
appContext.user.username || 'developer',
params.virtualizationId,
newDescription
);
virtualization.tko__description = newDescription;
return true;
};
const handleDeleteView = async (
viewName: string
) => {
try {
await deleteView(
virtualization,
viewName
);
pushNotification(
t(
'virtualization.deleteViewSuccess',
{
name: viewName,
}
),
'success'
);
await read();
} catch (error) {
const details = error.message
? error.message
: '';
pushNotification(
t(
'virtualization.deleteViewFailed',
{
details,
name: viewName,
}
),
'error'
);
}
};
return (
<WithListViewToolbarHelpers
defaultFilterType={filterByName}
defaultSortType={sortByName}
>
{helpers => {
const viewDefns = editorStates.map(
(editorState: ViewEditorState) => editorState.viewDefinition
) as ViewDefinition[];
const filteredAndSorted = getFilteredAndSortedViewDefns(
viewDefns,
helpers.activeFilters,
helpers.currentSortType,
helpers.isSortAscending
);
return (
<PageSection variant={'light'} noPadding={true}>
<WithLoader
error={editorStatesError !== false}
loading={!hasEditorStates}
loaderChildren={
<ViewListSkeleton
width={800}
style={{
backgroundColor: '#FFF',
marginTop: 30,
}}
/>
}
errorChildren={<ApiError error={editorStatesError as Error} />}
>
{() => (
<>
<PageSection variant={'light'} noPadding={true}>
<ViewHeaderBreadcrumb
currentPublishedState={publishingDetails.state}
virtualizationName={virtualization.keng__id}
dashboardHref={resolvers.dashboard.root()}
dashboardString={t('shared:Home')}
dataHref={resolvers.data.root()}
dataString={t('shared:Virtualizations')}
i18nViews={t('virtualization.views')}
i18nCancelText={t('shared:Cancel')}
i18nDelete={t('shared:Delete')}
i18nDeleteModalMessage={t(
'virtualization.deleteModalMessage',
{
name: virtualization.keng__id,
}
)}
i18nDeleteModalTitle={t(
'virtualization.deleteModalTitle'
)}
/* TD-636: Commented out for TP
i18nExport={t('shared:Export')}
*/
i18nPublish={t('shared:Publish')}
i18nUnpublish={t('shared:Unpublish')}
i18nUnpublishModalMessage={t(
'virtualization.unpublishModalMessage',
{
name: virtualization.keng__id,
}
)}
i18nUnpublishModalTitle={t(
'virtualization.unpublishModalTitle'
)}
onDelete={doDelete}
/* TD-636: Commented out for TP
onExport={
this.handleExportVirtualization
} */
onUnpublish={doUnpublish}
onPublish={doPublish}
serviceVdbName={virtualization.serviceVdbName}
hasViews={viewDefns.length > 0}
/>
<VirtualizationDetailsHeader
i18nDescriptionPlaceholder={t('virtualization.descriptionPlaceholder')}
i18nDraft={t('shared:Draft')}
i18nError={t('shared:Error')}
i18nPublished={t(
'virtualization.publishedDataVirtualization'
)}
i18nPublishInProgress={t(
'virtualization.publishInProgress'
)}
i18nUnpublishInProgress={t(
'virtualization.unpublishInProgress'
)}
i18nPublishLogUrlText={t('shared:viewLogs')}
odataUrl={getOdataUrl(virtualization)}
publishedState={publishingDetails.state}
publishingCurrentStep={publishingDetails.stepNumber}
publishingLogUrl={publishingDetails.logUrl}
publishingTotalSteps={publishingDetails.stepTotal}
publishingStepText={publishingDetails.stepText}
virtualizationDescription={virtualization.tko__description}
virtualizationName={virtualization.keng__id}
isWorking={false}
onChangeDescription={doSetDescription}
/>
<VirtualizationNavBar virtualization={virtualization} />
</PageSection>
<ViewList
filterTypes={filterTypes}
sortTypes={sortTypes}
resultsCount={filteredAndSorted.length}
{...helpers}
i18nDescription={t(
'data:virtualization.viewsPageDescription'
)}
i18nEmptyStateInfo={t(
'data:virtualization.viewEmptyStateInfo'
)}
i18nEmptyStateTitle={t(
'data:virtualization.viewEmptyStateTitle'
)}
i18nImportViews={t('data:virtualization.importDataSource')}
i18nImportViewsTip={t(
'data:virtualization.importDataSourceTip'
)}
i18nCreateView={t('data:virtualization.createView')}
i18nCreateViewTip={t('data:virtualization.createViewTip')}
i18nName={t('shared:Name')}
i18nNameFilterPlaceholder={t(
'shared:nameFilterPlaceholder'
)}
i18nResultsCount={t('shared:resultsCount', {
count: filteredAndSorted.length,
})}
linkCreateViewHRef={resolvers.data.virtualizations.views.createView.selectSources(
{
virtualization,
}
)}
linkImportViewsHRef={resolvers.data.virtualizations.views.importSource.selectConnection(
{
virtualization,
}
)}
hasListData={editorStates.length > 0}
>
{filteredAndSorted
.filter((viewDefinition: ViewDefinition) =>
filterUndefinedId(viewDefinition)
)
.map((viewDefinition: ViewDefinition, index: number) => (
<ViewListItem
key={index}
viewName={viewDefinition.viewName}
viewDescription={viewDefinition.keng__description}
viewEditPageLink={resolvers.data.virtualizations.views.edit(
{
virtualization,
// tslint:disable-next-line: object-literal-sort-keys
viewDefinition,
}
)}
i18nCancelText={t('shared:Cancel')}
i18nDelete={t('shared:Delete')}
i18nDeleteModalMessage={t(
'virtualization.deleteViewModalMessage',
{
name: viewDefinition.viewName,
}
)}
i18nDeleteModalTitle={t(
'virtualization.deleteModalTitle'
)}
i18nEdit={t('shared:Edit')}
i18nEditTip={t('view.editViewTip')}
onDelete={handleDeleteView}
/>
))}
</ViewList>
</>
)}
</WithLoader>
</PageSection>
);
}}
</WithListViewToolbarHelpers>
);
};
|
/**
* Added by Jacob Schrum
*
* Used to extract a more human understandable representation
* of the level by printing out int values for each byte in the
* map description. Compare with the save method above.
*/
public void saveText(PrintStream dos) throws IOException
{
dos.println("Header:" + Level.FILE_HEADER);
dos.println("Seperator:" + 0);
dos.println("Width:"+ width);
dos.println("Height:" + height);
dos.println("Map:");
for(int j = 0; j < height; j++) {
for (int i = 0; i < width; i++)
{
dos.printf("%4d,",map[i][j]);
}
dos.println();
}
dos.println("Data:");
for(int j = 0; j < height; j++) {
for (int i = 0; i < width; i++)
{
dos.printf("%4d,",data[i][j]);
}
dos.println();
}
} |
Arsène Wenger "was not surprised" to hear of Sir Alex Ferguson's decision to retire as manager of Manchester United and suggested he knew the Scot would quit at the end of this season when United decided to sign Robin van Persie from Arsenal last summer.
Speaking for the first time since his long-time adversary announced his decision to step away from management following 27, trophy-laden years at Old Trafford, Wenger said: "I was not surprised and I told my staff a long time ago that I think it will be Alex Ferguson's last year. I detected a few signs through the season – there was already one of them before the season started, that it could be his final year."
The Frenchman was then asked if Ferguson's retirement was discussed during the negotiations that led to Van Persie's £24m transfer last August and, after smiling coyly, he replied: "I wouldn't like to come back on that. I will let you know one day."
That answer pointed towards the "sign" Wenger had seen, with regard to Ferguson's retirement, prior to the start of this campaign. The deal certainly raised some eyebrows at the time given the expensive capture of a 29-year-old went against United's policy of not spending a significant amount of money on players in the final stages of their career. Ferguson, Wenger may have been suggesting, pursued the deal as part of a short-term plan to regain the Premier League title from Manchester City before he walked away.
Wenger also praised Ferguson for his "remarkable career" at United but expressed concerns that having been involved in football for such a long time, the 71-year-old may find life away from the spotlight difficult to adjust to. "There is a double challenge now," he said. "The first is for Manchester United to replace a guy of that stature, and the second challenge for Alex Ferguson is to have a life as passionate and as interesting as the life he had until now.
"He is luckier than me because he likes horses, he likes golf, so he can certainly have an interesting life again. But of course when you have been such a long time involved in every [game] … our job is always looking forward to the next game, so you are always motivated by that. At the start it is difficult to miss that."
He added: "But after 26 years, he just won the championship, he knows it will be more difficult even for Man United to have that consistency now because there are so many teams who have financial power. You have to respect his decision." |
<commit_msg>Remove duplicate lines from cron file without sorting
<commit_before>import fabric.api as fab
import cuisine
def install(filename, user="root", append=False):
"""
Installs crontab from a given cronfile
"""
new_crontab = fab.run("mktemp fabixcron.XXXX")
cuisine.file_upload(new_crontab, filename)
if append is True:
sorted_crontab = fab.run("mktemp fabixcron.XXXX")
# When user have no crontab, then crontab command returns 1 error code
with fab.settings(warn_only=True):
fab.sudo("crontab -u {} -l >> {} 2> /dev/null".format(user, new_crontab))
fab.sudo("sort -u -o {} {}".format(sorted_crontab, new_crontab))
new_crontab = sorted_crontab
fab.sudo("crontab -u {} {}".format(user, new_crontab))
<commit_after>import fabric.api as fab
import cuisine
def install(filename, user="root", append=False):
"""
Installs crontab from a given cronfile
"""
new_crontab = fab.run("mktemp fabixcron.XXXX")
cuisine.file_upload(new_crontab, filename)
if append is True:
# When user have no crontab, then crontab command returns 1 error code
with fab.settings(warn_only=True):
fab.sudo("crontab -u {} -l 2> /dev/null | awk '!x[$0]++{{print $0}}' >> {}".format(user, new_crontab))
fab.sudo("crontab -u {} {}".format(user, new_crontab))
|
// Endian Swaps the passed in blob representing a constant into the passed in StgPool
HRESULT CMiniMdBase::SwapConstant(
const void *pBlobValue,
DWORD dwType,
void *pConstant,
ULONG ValueLength)
{
HRESULT hr = NOERROR;
switch (dwType)
{
case ELEMENT_TYPE_BOOLEAN:
case ELEMENT_TYPE_I1:
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_VOID:
*(BYTE *)pConstant = *(BYTE *)pBlobValue;
return NOERROR;
case ELEMENT_TYPE_I2:
case ELEMENT_TYPE_U2:
case ELEMENT_TYPE_CHAR:
_ASSERTE(ValueLength == 2);
*(SHORT *)pConstant = GET_UNALIGNED_VAL16(pBlobValue);
break;
case ELEMENT_TYPE_CLASS:
case ELEMENT_TYPE_I4:
case ELEMENT_TYPE_U4:
_ASSERTE(ValueLength == 4);
*(__int32 *)pConstant = GET_UNALIGNED_VAL32(pBlobValue);
break;
case ELEMENT_TYPE_R4:
{
__int32 Value = GET_UNALIGNED_VAL32(pBlobValue);
*(float *)pConstant = (float &)Value;
}
break;
case ELEMENT_TYPE_R8:
{
__int64 Value = GET_UNALIGNED_VAL64(pBlobValue);
*(double *)pConstant = (double &) Value;
}
break;
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
_ASSERTE(ValueLength == 8);
*(__int64 *)pConstant = GET_UNALIGNED_VAL64(pBlobValue);
break;
case ELEMENT_TYPE_STRING:
memcpy(pConstant, pBlobValue, ValueLength);
SwapStringLength((WCHAR *)pConstant, (ValueLength)/sizeof(WCHAR));
break;
default:
_ASSERTE(!"BAD TYPE!");
return E_INVALIDARG;
break;
}
return hr;
} |
Photodetector with giant internal current amplification: experiment and numerically calculated model
New silicon based optical sensors with a metal - insulator - semiconductor structure (MIS) are developed and investigated both theoretically and experimentally. The physical properties of these sensors are described with a model of MIS capacitor where a presence of depletion layer of electrons and an inversion layer of holes of a finite depth is taken into account. Two-level voltage bias provides a transient between two quasi-equilibrium inversion modes. This transient is applied both for storage and for readout of the input optical signal for quantitative measurements of a weak infra red radiation. Proposed simple readout procedure provides reading the integrated information with a significant amplification. The amplification (or the current transformation coefficient) is determined by the ratio of integration and readout times and it may exceed 104. A theoretical model is given to explain a behavior of the sensor under storage by thermo generated carries and by photo generated ones jointly. Numerical simulations are of an agreement with experimental investigations of proposed sensors. |
n=int(input())
i=0
r=0
while(i<n):
str1=str(input())
get1=int(str1[0])
get2=int(str1[2])
get3=int(str1[4])
if((get1==1 and get2==1)or(get1==1 and get3==1)or(get2==1 and get3==1)):
r+=1
i+=1
else:
i+=1
else:
print(r)
SystemExit |
def update_app_insight_counter(
project_obj,
has_new_parts: bool,
has_new_images: bool,
parts_last_train: int,
images_last_train: int,
):
try:
retrain = train = 0
if has_new_parts:
logger.info("This is a training job")
train = 1
elif has_new_images:
logger.info("This is a re-training job")
retrain = 1
else:
logger.info("Project not changed")
logger.info(
"Sending Data to App Insight %s", project_obj.setting.is_collect_data
)
if project_obj.setting.is_collect_data:
logger.info("Sending Logs to App Insight")
trainer = project_obj.setting.get_trainer_obj()
images_now = trainer.get_tagged_image_count(project_obj.customvision_id)
parts_now = len(trainer.get_tags(project_obj.customvision_id))
az_logger = get_app_insight_logger()
az_logger.warning(
"training",
extra={
"custom_dimensions": {
"train": train,
"images": images_now - images_last_train,
"parts": parts_now - parts_last_train,
"retrain": retrain,
}
},
)
except Exception:
logger.exception("update_app_insight_counter occur unexcepted error")
raise |
"""
CLI functions to setup scout
There are two options.
`scout setup demo` will setup a database that are loaded with more example
data but the gene definitions etc are reduced.
`scout setup database` will create a full scale instance of scout. There will not be any cases
and one admin user is added.
"""
import logging
import pathlib
import click
from flask.cli import current_app, with_appcontext
from pymongo.errors import ServerSelectionTimeoutError
# Adapter stuff
from scout.adapter import MongoAdapter
from scout.load.setup import setup_scout
LOG = logging.getLogger(__name__)
def abort_if_false(ctx, param, value):
"""Small function to quit if flag is not used"""
if not value:
ctx.abort()
@click.command("database", short_help="Setup a basic scout instance")
@click.option("-i", "--institute-name", type=str)
@click.option("-u", "--user-name", type=str)
@click.option("-m", "--user-mail", type=str)
@click.option("--api-key", help="Specify the api key")
@click.option(
"--yes",
is_flag=True,
callback=abort_if_false,
expose_value=False,
prompt="This will delete existing database, do you wish to continue?",
)
@click.option(
"--files",
type=click.Path(exists=True, dir_okay=True, file_okay=False),
help="Path to directory with resource files",
)
@click.option("--hgnc", type=click.Path(exists=True))
@click.option("--exac", type=click.Path(exists=True), help="Path to file with EXAC pLi scores")
@click.option(
"--ensgenes37",
type=click.Path(exists=True),
help="Path to file with ENSEMBL genes, build 37",
)
@click.option(
"--ensgenes38",
type=click.Path(exists=True),
help="Path to file with ENSEMBL genes, build 38",
)
@click.option(
"--enstx37",
type=click.Path(exists=True),
help="Path to file with ENSEMBL transcripts, build 37",
)
@click.option(
"--enstx38",
type=click.Path(exists=True),
help="Path to file with ENSEMBL transcripts, build 38",
)
@click.option("--mim2gene", type=click.Path(exists=True))
@click.option("--genemap", type=click.Path(exists=True))
@click.option(
"--hpogenes",
type=click.Path(exists=True),
help=(
"Path to file with HPO to gene information. This is the file called"
"genes_to_phenotype.txt"
),
)
@click.option(
"--hpoterms",
type=click.Path(exists=True),
help=("Path to file with HPO terms. This is the " "file called hpo.obo"),
)
@click.option(
"--hpo_to_genes",
type=click.Path(exists=True),
help=(
"Path to file with map from HPO terms to genes. This is the file called "
"phenotype_to_genes.txt"
),
)
@with_appcontext
@click.pass_context
def database(
context,
institute_name,
user_name,
user_mail,
api_key,
mim2gene,
genemap,
hgnc,
exac,
ensgenes37,
ensgenes38,
enstx37,
enstx38,
hpogenes,
hpoterms,
hpo_to_genes,
files,
):
"""Setup a scout database."""
LOG.info("Running scout setup database")
# Fetch the omim information
api_key = api_key or current_app.config.get("OMIM_API_KEY")
if not api_key:
LOG.warning("No omim api key provided. This means information will be lost in scout")
LOG.info("Please request an OMIM api key and run scout update genes")
institute_name = institute_name or context.obj["institute_name"]
user_name = user_name or context.obj["user_name"]
user_mail = user_mail or context.obj["user_mail"]
adapter = context.obj["adapter"]
resource_files = {
"mim2gene_path": mim2gene,
"genemap_path": genemap,
"hgnc_path": hgnc,
"exac_path": exac,
"genes37_path": ensgenes37,
"genes38_path": ensgenes38,
"transcripts37_path": enstx37,
"transcripts38_path": enstx38,
"hpogenes_path": hpogenes,
"hpoterms_path": hpoterms,
"hpo_to_genes_path": hpo_to_genes,
}
LOG.info("Setting up database %s", context.obj["mongodb"])
if files:
for path in pathlib.Path(files).glob("**/*"):
if path.stem == "mim2genes":
resource_files["mim2gene_path"] = str(path.resolve())
if path.stem == "genemap2":
resource_files["genemap_path"] = str(path.resolve())
if path.stem == "hgnc":
resource_files["hgnc_path"] = str(path.resolve())
if path.stem == "fordist_cleaned_exac_r03_march16_z_pli_rec_null_data":
resource_files["exac_path"] = str(path.resolve())
if path.stem == "ensembl_genes_37":
resource_files["genes37_path"] = str(path.resolve())
if path.stem == "ensembl_genes_38":
resource_files["genes38_path"] = str(path.resolve())
if path.stem == "ensembl_transcripts_37":
resource_files["transcripts37_path"] = str(path.resolve())
if path.stem == "ensembl_transcripts_38":
resource_files["transcripts38_path"] = str(path.resolve())
if path.stem == "genes_to_phenotype":
resource_files["hpogenes_path"] = str(path.resolve())
if path.stem == "hpo":
resource_files["hpoterms_path"] = str(path.resolve())
if path.stem == "phenotype_to_genes":
resource_files["hpo_to_genes_path"] = str(path.resolve())
setup_scout(
adapter=adapter,
institute_id=institute_name,
user_name=user_name,
user_mail=user_mail,
api_key=api_key,
resource_files=resource_files,
)
@click.command("demo", short_help="Setup a scout demo instance")
@click.pass_context
def demo(context):
"""Setup a scout demo instance. This instance will be populated with a
case, a gene panel and some variants.
"""
LOG.info("Running scout setup demo")
institute_name = context.obj["institute_name"]
user_name = context.obj["user_name"]
user_mail = context.obj["user_mail"]
adapter = context.obj["adapter"]
setup_scout(
adapter=adapter,
institute_id=institute_name,
user_name=user_name,
user_mail=user_mail,
demo=True,
)
@click.group()
@click.option(
"-i",
"--institute",
default="cust000",
show_default=True,
help="Name of initial institute",
)
@click.option(
"-e",
"--user-mail",
default="<EMAIL>",
show_default=True,
help="Mail of initial user",
)
@click.option(
"-n",
"--user-name",
default="<NAME>",
show_default=True,
help="Name of initial user",
)
@with_appcontext
@click.pass_context
def setup(context, institute, user_mail, user_name):
"""
Setup scout instances: a demo database or a production database, according to the
according to the subcommand specified by user.
"""
setup_config = {
"institute_name": institute,
"user_name": user_name,
"user_mail": user_mail,
}
mongodb_name = current_app.config["MONGO_DBNAME"]
client = current_app.config["MONGO_CLIENT"]
if context.invoked_subcommand == "demo":
# Modify the name of the database that will be created
LOG.debug("Change database name to scout-demo")
mongodb_name = "scout-demo"
mongo_database = client[mongodb_name]
LOG.info("Test if mongod is running")
try:
mongo_database.test.find_one()
except ServerSelectionTimeoutError as err:
LOG.warning("Connection could not be established")
LOG.warning("Please check if mongod is running")
LOG.warning(err)
raise click.Abort()
setup_config["mongodb"] = mongodb_name
setup_config["adapter"] = MongoAdapter(mongo_database)
context.obj = setup_config
setup.add_command(database)
setup.add_command(demo)
|
def pd2np(pandas_dataframe):
pandas_dataframe = pandas_dataframe.fillna(-9999)
x = np.array(np.rec.fromrecords(pandas_dataframe.values))
names = pandas_dataframe.dtypes.index.tolist()
x.dtype.names = tuple(names)
field_dtypes = dict_field_types(pandas_dataframe)
if six.PY2:
new_types = field_dtypes.items()
elif six.PY3:
new_types = list(field_dtypes.items())
x = x.astype(new_types)
return x |
#ifndef __FillAble__
#define __FillAble__
#include "Utility/PCH.h"
#include "Stereo/StereoSetting.h"
#include "Event/KeyBoardState.h"
#include "Helper/MeshLoader10.h"
#include "Helper/MeshHelper.h"
#include "FillObject.h"
namespace EyeStereo {
class FillAble {
public:
ID3D10Device* pd3dDevice;
ID3D10Effect* pEffect;
ID3D10EffectTechnique* pTech;
ID3D10InputLayout* pInputLayout;
ID3D10EffectShaderResourceVariable* pShaderRV;
IDXGISwapChain* pSwapChain;
CModelViewerCamera* pCamera;
long int windowsWidth, windowsHeight;
StereoSetting* pStereoSetting;
bool bactive;
D3DXVECTOR3 eyePos;
bool bStereo;
float initDepth, initRadius;
WCHAR* mShareMessage;
bool* mShareChanged;
ID3D10RasterizerState* pSolidState;
float g_fLastMoveTime;
float g_fObjectMoveSpace;
/* CMeshLoader10 g_earthMesh;*/
ModelObjectCreator* g_pFillAbleCreator;
MeshHelper* g_pMeshHelper;
KeyBoard* g_pKeyBoard;
CMeshLoader10 *g_BackGroundMesh;
D3DXVECTOR3 g_BackGroundPosition;
UINT g_ActiveCube;
typedef std::pair<UINT, UINT> uupair;
std::vector< uupair > g_Cubesflg;
//enum {CONST_Z_ = 5};
FillAble() :initRadius(2), initDepth(4), pd3dDevice(NULL) {}
bool init(ID3D10Device* pd3d, StereoSetting* pstereo, CModelViewerCamera *pcamera, KeyBoard* pkeyboard);
void Restart();
UINT FindConnectedCubes(std::vector< uupair > &stack, ModelObject::Status dir);
bool Collision(ModelObject::Status dir);
void DestoryCubes(std::vector< std::pair<UINT, UINT> > &stack);
void DeleteIfFullLine();
void UpdateObjectPosition(float fTime);
void stereoRender(float fTime);
void Rotate90();
void HandMessages(UINT uMsg, LPARAM lParam) {
switch (uMsg) {
case WM_LBUTTONDOWN:
pick(LOWORD(lParam), HIWORD(lParam));
return;
};
}
void ShareMessage(WCHAR* sharestr, bool *sharechanged) {
mShareChanged = sharechanged;
mShareMessage = sharestr;
}
~FillAble() {
SAFE_RELEASE(pd3dDevice);
SAFE_RELEASE(pEffect);
//pTech;
SAFE_RELEASE(pInputLayout);
SAFE_RELEASE(pSwapChain);
SAFE_RELEASE(pSolidState);
SAFE_DELETE(g_pMeshHelper);
SAFE_DELETE(g_pFillAbleCreator);
SAFE_DELETE(g_BackGroundMesh);
//SAFE_RELEASE(pShaderRV);
}
void ClearScreen(ID3D10Device *pd3dDevice)
{
float ClearColor[4] = { 0.176f, 0.196f, 0.667f, 0.0f };
ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView();
pd3dDevice->ClearRenderTargetView(pRTV, ClearColor);
// Clear the depth stencil
ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView();
pd3dDevice->ClearDepthStencilView(pDSV, D3D10_CLEAR_DEPTH, 1.0, 0);
return;
}
//protected:
};
}
#endif //__FillAble_H__ |
<gh_stars>0
/*
* Copyright 2019 Scott Logic Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.scottlogic.deg.profile.reader;
import com.scottlogic.deg.common.profile.constraints.atomic.*;
import com.scottlogic.deg.common.profile.constraints.delayed.IsAfterDynamicDateConstraint;
import com.scottlogic.deg.common.profile.constraints.delayed.IsBeforeDynamicDateConstraint;
import com.scottlogic.deg.common.util.Defaults;
import com.scottlogic.deg.profile.reader.constraintreaders.EqualToFieldReader;
import com.scottlogic.deg.profile.reader.constraintreaders.InSetReader;
import com.scottlogic.deg.profile.reader.constraintreaders.GranularToReader;
import com.scottlogic.deg.profile.reader.constraintreaders.OfTypeReader;
import com.scottlogic.deg.profile.dto.AtomicConstraintType;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import static com.scottlogic.deg.profile.reader.ConstraintReaderHelpers.*;
import static com.scottlogic.deg.profile.reader.ConstraintReaderHelpers.getValidatedValue;
import static com.scottlogic.deg.profile.dto.AtomicConstraintType.*;
public class AtomicConstraintTypeReaderMap {
private final String fromFilePath;
private final boolean isDelayedConstraintsEnabled;
public AtomicConstraintTypeReaderMap(final String fromFilePath, boolean isDelayedConstraintsEnabled) {
this.fromFilePath = fromFilePath;
this.isDelayedConstraintsEnabled = isDelayedConstraintsEnabled;
}
public boolean isDelayedConstraintsEnabled() {
return isDelayedConstraintsEnabled;
}
public Map<AtomicConstraintType, AtomicConstraintReader> getConstraintReaderMapEntries() {
BigDecimal maxStringLength = BigDecimal.valueOf(Defaults.MAX_STRING_LENGTH);
Map<AtomicConstraintType, AtomicConstraintReader> map = new HashMap<>();
map.put(IS_OF_TYPE, new OfTypeReader());
map.put(IS_GRANULAR_TO, new GranularToReader());
map.put(IS_IN_SET, new InSetReader(fromFilePath));
map.put(FORMATTED_AS,
(dto, fields) -> new FormatConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, String.class)));
map.put(IS_EQUAL_TO_CONSTANT,
(dto, fields) -> new EqualToConstraint(
fields.getByName(dto.field),
getValidatedValue(dto)));
map.put(CONTAINS_REGEX,
(dto, fields) ->
new ContainsRegexConstraint(
fields.getByName(dto.field),
Pattern.compile(getValidatedValue(dto, String.class))));
map.put(MATCHES_REGEX,
(dto, fields) ->
new MatchesRegexConstraint(
fields.getByName(dto.field),
Pattern.compile(getValidatedValue(dto, String.class))));
map.put(IS_GREATER_THAN_CONSTANT,
(dto, fields) ->
new IsGreaterThanConstantConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, Number.class)));
map.put(IS_GREATER_THAN_OR_EQUAL_TO_CONSTANT,
(dto, fields) ->
new IsGreaterThanOrEqualToConstantConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, Number.class)));
map.put(IS_LESS_THAN_CONSTANT,
(dto, fields) ->
new IsLessThanConstantConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, Number.class)));
map.put(IS_LESS_THAN_OR_EQUAL_TO_CONSTANT,
(dto, fields) ->
new IsLessThanOrEqualToConstantConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, Number.class)));
map.put(IS_BEFORE_CONSTANT_DATE_TIME,
(dto, fields) ->
new IsBeforeConstantDateTimeConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, OffsetDateTime.class)));
map.put(IS_BEFORE_OR_EQUAL_TO_CONSTANT_DATE_TIME,
(dto, fields) ->
new IsBeforeOrEqualToConstantDateTimeConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, OffsetDateTime.class)));
map.put(IS_AFTER_CONSTANT_DATE_TIME,
(dto, fields) ->
new IsAfterConstantDateTimeConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, OffsetDateTime.class)));
map.put(IS_AFTER_OR_EQUAL_TO_CONSTANT_DATE_TIME,
(dto, fields) ->
new IsAfterOrEqualToConstantDateTimeConstraint(
fields.getByName(dto.field),
getValidatedValue(dto, OffsetDateTime.class)));
map.put(IS_NULL,
(dto, fields) -> new IsNullConstraint(fields.getByName(dto.field)));
map.put(IS_STRING_LONGER_THAN,
(dto, fields) ->
new IsStringLongerThanConstraint(
fields.getByName(dto.field),
ensureValueBetween(
dto,
Integer.class,
BigDecimal.ZERO,
maxStringLength.subtract(BigDecimal.ONE))));
map.put(IS_STRING_SHORTER_THAN,
(dto, fields) ->
new IsStringShorterThanConstraint(
fields.getByName(dto.field),
ensureValueBetween(
dto,
Integer.class,
BigDecimal.ONE,
maxStringLength.add(BigDecimal.ONE))));
map.put(HAS_LENGTH,
(dto, fields) ->
new StringHasLengthConstraint(
fields.getByName(dto.field),
ensureValueBetween(
dto,
Integer.class,
BigDecimal.ZERO,
maxStringLength)));
if (isDelayedConstraintsEnabled) {
map.putAll(getDelayedMapEntries());
}
return map;
}
private Map<AtomicConstraintType, AtomicConstraintReader> getDelayedMapEntries() {
Map<AtomicConstraintType, AtomicConstraintReader> map = new HashMap<>();
map.put(IS_EQUAL_TO_FIELD, new EqualToFieldReader());
map.put(IS_BEFORE_FIELD_DATE_TIME,
(dto, fields) ->
new IsBeforeDynamicDateConstraint(
new IsBeforeConstantDateTimeConstraint(
fields.getByName(dto.field),
OffsetDateTime.MIN
),
fields.getByName(getValueAsString(dto)),
false
)
);
map.put(IS_BEFORE_OR_EQUAL_TO_FIELD_DATE_TIME,
(dto, fields) ->
new IsBeforeDynamicDateConstraint(
new IsBeforeOrEqualToConstantDateTimeConstraint(
fields.getByName(dto.field),
OffsetDateTime.MIN
),
fields.getByName(getValueAsString(dto)),
true
)
);
map.put(IS_AFTER_FIELD_DATE_TIME,
(dto, fields) ->
new IsAfterDynamicDateConstraint(
new IsAfterConstantDateTimeConstraint(
fields.getByName(dto.field),
OffsetDateTime.MAX
),
fields.getByName(getValueAsString(dto)),
false
));
map.put(IS_AFTER_OR_EQUAL_TO_FIELD_DATE_TIME,
(dto, fields) ->
new IsAfterDynamicDateConstraint(
new IsAfterOrEqualToConstantDateTimeConstraint(
fields.getByName(dto.field),
OffsetDateTime.MAX
),
fields.getByName(getValueAsString(dto)),
true
)
);
return map;
}
}
|
// Copyright (c) 2014-2019 <NAME>
// Licensed under the MIT license
package mirrors
import (
"encoding/json"
"fmt"
"time"
"github.com/etix/mirrorbits/core"
"github.com/etix/mirrorbits/database"
"github.com/gomodule/redigo/redis"
"github.com/op/go-logging"
)
var (
log = logging.MustGetLogger("main")
)
type LogType uint
const (
_ LogType = iota
LOGTYPE_ERROR
LOGTYPE_ADDED
LOGTYPE_EDITED
LOGTYPE_ENABLED
LOGTYPE_DISABLED
LOGTYPE_STATECHANGED
LOGTYPE_SCANSTARTED
LOGTYPE_SCANCOMPLETED
)
func typeToInstance(typ LogType) LogAction {
switch LogType(typ) {
case LOGTYPE_ERROR:
return &LogError{}
case LOGTYPE_ADDED:
return &LogAdded{}
case LOGTYPE_EDITED:
return &LogEdited{}
case LOGTYPE_ENABLED:
return &LogEnabled{}
case LOGTYPE_DISABLED:
return &LogDisabled{}
case LOGTYPE_STATECHANGED:
return &LogStateChanged{}
case LOGTYPE_SCANSTARTED:
return &LogScanStarted{}
case LOGTYPE_SCANCOMPLETED:
return &LogScanCompleted{}
default:
}
return nil
}
type LogAction interface {
GetType() LogType
GetMirrorID() int
GetTimestamp() time.Time
GetOutput() string
}
type LogCommonAction struct {
Type LogType
MirrorID int
Timestamp time.Time
}
func (l LogCommonAction) GetType() LogType {
return l.Type
}
func (l LogCommonAction) GetMirrorID() int {
return l.MirrorID
}
func (l LogCommonAction) GetTimestamp() time.Time {
return l.Timestamp
}
type LogError struct {
LogCommonAction
Err string
}
func (l *LogError) GetOutput() string {
return fmt.Sprintf("Error: %s", l.Err)
}
func NewLogError(id int, err error) LogAction {
return &LogError{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_ERROR,
MirrorID: id,
Timestamp: time.Now(),
},
Err: err.Error(),
}
}
type LogAdded struct {
LogCommonAction
}
func (l *LogAdded) GetOutput() string {
return "Mirror added"
}
func NewLogAdded(id int) LogAction {
return &LogAdded{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_ADDED,
MirrorID: id,
Timestamp: time.Now(),
},
}
}
type LogEdited struct {
LogCommonAction
}
func (l *LogEdited) GetOutput() string {
return "Mirror edited"
}
func NewLogEdited(id int) LogAction {
return &LogEdited{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_EDITED,
MirrorID: id,
Timestamp: time.Now(),
},
}
}
type LogEnabled struct {
LogCommonAction
}
func (l *LogEnabled) GetOutput() string {
return "Mirror enabled"
}
func NewLogEnabled(id int) LogAction {
return &LogEnabled{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_ENABLED,
MirrorID: id,
Timestamp: time.Now(),
},
}
}
type LogDisabled struct {
LogCommonAction
}
func (l *LogDisabled) GetOutput() string {
return "Mirror disabled"
}
func NewLogDisabled(id int) LogAction {
return &LogDisabled{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_DISABLED,
MirrorID: id,
Timestamp: time.Now(),
},
}
}
type LogStateChanged struct {
LogCommonAction
Up bool
Reason string
}
func (l *LogStateChanged) GetOutput() string {
if l.Up == false {
if len(l.Reason) == 0 {
return "Mirror is down"
}
return "Mirror is down: " + l.Reason
}
return "Mirror is up"
}
func NewLogStateChanged(id int, up bool, reason string) LogAction {
return &LogStateChanged{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_STATECHANGED,
MirrorID: id,
Timestamp: time.Now(),
},
Up: up,
Reason: reason,
}
}
type LogScanStarted struct {
LogCommonAction
Typ core.ScannerType
}
func (l *LogScanStarted) GetOutput() string {
switch l.Typ {
case core.RSYNC:
return "RSYNC scan started"
case core.FTP:
return "FTP scan started"
default:
return "Scan started using a unknown protocol"
}
}
func NewLogScanStarted(id int, typ core.ScannerType) LogAction {
return &LogScanStarted{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_SCANSTARTED,
MirrorID: id,
Timestamp: time.Now(),
},
Typ: typ,
}
}
type LogScanCompleted struct {
LogCommonAction
FilesIndexed int64
KnownIndexed int64
Removed int64
TZOffset int64
}
func (l *LogScanCompleted) GetOutput() string {
output := fmt.Sprintf("Scan completed: %d files (%d known), %d removed", l.FilesIndexed, l.KnownIndexed, l.Removed)
if l.TZOffset != 0 {
offset, _ := time.ParseDuration(fmt.Sprintf("%dms", l.TZOffset))
output += fmt.Sprintf(" (corrected timezone offset: %s)", offset)
}
return output
}
func NewLogScanCompleted(id int, files, known, removed, tzoffset int64) LogAction {
return &LogScanCompleted{
LogCommonAction: LogCommonAction{
Type: LOGTYPE_SCANCOMPLETED,
MirrorID: id,
Timestamp: time.Now(),
},
FilesIndexed: files,
KnownIndexed: known,
Removed: removed,
TZOffset: tzoffset,
}
}
func PushLog(r *database.Redis, logAction LogAction) error {
conn := r.Get()
defer conn.Close()
key := fmt.Sprintf("MIRRORLOGS_%d", logAction.GetMirrorID())
value, err := json.Marshal(logAction)
if err != nil {
return err
}
_, err = conn.Do("RPUSH", key, value)
return err
}
func ReadLogs(r *database.Redis, mirrorid, max int) ([]string, error) {
conn := r.Get()
defer conn.Close()
if max <= 0 {
// Get the latest 500 events by default
max = 500
}
key := fmt.Sprintf("MIRRORLOGS_%d", mirrorid)
lines, err := redis.Strings(conn.Do("LRANGE", key, max*-1, -1))
if err != nil {
return nil, err
}
outputs := make([]string, 0, len(lines))
for _, line := range lines {
var objmap map[string]interface{}
err = json.Unmarshal([]byte(line), &objmap)
if err != nil {
log.Warningf("Unable to parse mirror log line: %s", err)
continue
}
typf, ok := objmap["Type"].(float64)
if !ok {
log.Warning("Unable to parse mirror log line")
continue
}
// Truncate the received float64 back to int
typ := int(typf)
action := typeToInstance(LogType(typ))
if action == nil {
log.Warning("Unknown mirror log action")
continue
}
err = json.Unmarshal([]byte(line), action)
if err != nil {
log.Warningf("Unable to unmarshal mirror log line: %s", err)
continue
}
line := fmt.Sprintf("%s: %s", action.GetTimestamp().Format("2006-01-02 15:04:05 MST"), action.GetOutput())
outputs = append(outputs, line)
}
return outputs, nil
}
|
def implicit_ae(data, zero_num):
mean = np.sum(data) / (len(data) + zero_num)
return np.sum(np.absolute(data - mean)) + np.absolute(mean)*zero_num |
package com.ebank.util;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME>
* @email <EMAIL>
* @date 17.09.2018
* @description TODO: Class Description
*/
public enum FeeConstant {
EXTERNAL(0.8), INTERNAL(0.2);
private final double rate;
private static final Map<String, FeeConstant> lookup = new HashMap<>();
static {
for (FeeConstant d : FeeConstant.values()) {
lookup.put(d.name(), d);
}
}
public static FeeConstant get(String name) {
return lookup.get(name);
}
public double getRate() {
return rate;
}
FeeConstant(double rate) {
this.rate = rate;
}
}
|
def pec(msg='press Enter to continue or "q" to quit'):
ch = ''
while ch == '':
print(msg)
ch = sys.stdin.read(1)
return ch |
<gh_stars>0
package com.sc.reminder.common.base;
import android.content.Context;
import com.sc.reminder.common.configure.Packet;
import com.sc.reminder.common.configure.RequestAction;
public abstract class BaseTaskInfo<T> implements RequestAction {
public Context context;
private int actionType;
private String handlerID;
public BaseTaskInfo(Context context, int actionType, String handlerID) {
this.context = context;
this.actionType = actionType;
this.handlerID = handlerID;
}
public abstract T request();
@Override
public int getActionType() {
return actionType;
}
@Override
public String getHandlerID() {
return handlerID;
}
@Override
public String getRequestBody() {
return null;
}
@Override
public Object processHttpResponse(String data) {
return null;
}
@Override
public Object processXmppResponse(Packet packet) {
return null;
}
}
|
/**
* A UL with a numeric value; returns a <code>NumericParser</code>
* @author jforaci
*/
public class NumericUL extends UL {
private final boolean signed;
private final int size;
public NumericUL(String name, byte[] value, boolean signed, int size) {
super(name, value);
this.signed = signed;
this.size = size;
}
public boolean isSigned() {
return signed;
}
public int getSize() {
return size;
}
@Override
public Class getParserClass() {
return NumericParser.class;
}
@Override
protected Parser parser(BigInteger length, MxfInputStream in) {
return new NumericParser(length, in, signed, size);
}
} |
Event Details:
WOMEN IN TECH: A PANEL AT THE BERKELEY FORUM
Despite the tech industry’s efforts towards inclusion and diversity, the number of women in some tech-related fields has plummeted. In many of the largest tech companies, women make up less than a quarter of the employee population. Women who enter the tech industry face rampant biases and stereotypes; for example, a study showed that half of women with careers in STEM fields eventually leave their jobs because of hostile work environments. This problem is just as present at UC Berkeley, as only 11% of EECS graduates in 2016 were female. This panel aims to bring together women in the tech field to discuss solutions to the systemic issues they face.
Panelists:
Iris Kuo, co-founder and CEO of LedBetter
Natalie Nakai, co-founder of the XX+UX Mentorship Program and Design Manager at Course Hero
Fatema Kothari, Board Member at SF-Internet Society & Girls in Tech SF and Senior Consultant at T-Mobile
Paulette Penzvalto, Lead, Autistics@ and AutisticWomen@Google, Member of the Google Disability Alliance
Date: February 22, 2017
Time: 6:00 PM
Location: Banatao Auditorium, Sutardja Dai Hall
Admission
This event is open to the public. Entry to the event will be open to ticketholders and, space-permitting, a limited number of walk-ins. Ticketholders are encouraged to arrive early to maximize their chances of getting in. Having a ticket does not guarantee access to the event but does give the ticketholder priority over walk-ins until 6:00 p.m., at which point walk-ins and ticketholders will have equal access to remaining seats. Our standard event policies apply. What follows is an overview of the admissions timeline. It may be subject to revisions as the event approaches. Seating in the venue is first-come, first served.
5:00 p.m. Event Admission Opens for Ticket Holders
5:50 p.m. Event Admission No Longer Guaranteed for Ticket Holders
5:50 p.m. Admission Opens for Walk-Ins (Limited Seating)
5:55 p.m. Admission Closed (No Late Seating)
6:00 p.m. Event Begins
More details will be shared very soon here and on our Facebook page. We encourage that you “Like” our Facebook page, The Berkeley Forum, to keep up to date on Forum events.
Note on Tickets
Tickets are non-transferable. While you may purchase a ticket on someone's behalf, their name must be listed on the ticket. All attendees will be asked to present a Valid ID at the venue that matches the name on the ticket.
All tickets sales are final. Tickets are non-transferable and non-refundable.
To secure a seat for more than one person, simply fill out the form once again for each subsequent person with his or her information.
Please visit our website for a complete list of event policies. |
/**
* hibernation_restore - quiesce devices and restore the hibernation
* snapshot image. If successful, control returns in hibernation_snaphot()
* @platform_mode - if set, use the platform driver, if available, to
* prepare the platform firmware for the transition.
*
* Must be called with pm_mutex held
*/
int hibernation_restore(int platform_mode)
{
int error;
pm_prepare_console();
suspend_console();
error = dpm_suspend_start(PMSG_QUIESCE);
if (!error) {
error = resume_target_kernel(platform_mode);
dpm_resume_end(PMSG_RECOVER);
}
resume_console();
pm_restore_console();
return error;
} |
// streamResources receives system resource usage information from the server and copies
// them into the build state.
func streamResources(state *core.BuildState, client pb.PlzEventsClient) {
stream, err := client.ResourceUsage(context.Background(), &pb.ResourceUsageRequest{})
if err != nil {
log.Error("Error receiving resource usage: %s", err)
return
}
for {
resources, err := stream.Recv()
if err == io.EOF {
break
} else if err != nil {
log.Error("Error receiving resource usage: %s", err)
break
}
state.Stats = resourceFromProto(resources)
}
} |
/*
* This is a regression test for antlr/antlr4#224: "Parentheses without
* quantifier in lexer rules have unclear effect".
* https://github.com/antlr/antlr4/issues/224
*/
public static class Parentheses extends BaseLexerTestDescriptor {
public String input = "-.-.-!";
/**
[@0,0:4='-.-.-',<1>,1:0]
[@1,5:5='!',<3>,1:5]
[@2,6:5='<EOF>',<-1>,1:6]
*/
@CommentHasStringValue
public String output;
public String errors = null;
public String startRule = "";
public String grammarName = "L";
/**
lexer grammar L;
START_BLOCK: '-.-.-';
ID : (LETTER SEPARATOR) (LETTER SEPARATOR)+;
fragment LETTER: L_A|L_K;
fragment L_A: '.-';
fragment L_K: '-.-';
SEPARATOR: '!';
*/
@CommentHasStringValue
public String grammar;
} |
/** The Door class is a component of a room */
public class Door {
/** The state of the door (is the door open?) */
private boolean isOpen;
private boolean isLockable;
private boolean isLocked;
/** Default constructor */
public Door() {
this.isOpen = false;
this.isLockable = false;
this.isLocked = false;
}
public Door(boolean lockable) {
this.isOpen = false;
this.isLockable = lockable;
this.isLocked = false;
}
/**
* Getter for checking if the door is open
*
* @return boolean
*/
public boolean isOpen() {
return this.isOpen;
}
/**
* Setter for changing the door status
*
* @param open the new state of the door
*/
public void setIsOpen(boolean open) {
this.isOpen = open;
}
/**
* Getter for checking if the door can be locked
*
* @return boolean
*/
public boolean isLockable() {
return this.isLockable;
}
/**
* Getter for the locking state of the door
*
* @return boolean
*/
public boolean isLocked() {
return this.isLocked;
}
/**
* Setter for the locking state of the door
*
* @param locked locked state boolean
*/
public void setLocked(boolean locked) {
this.isLocked = locked;
}
} |
import React from "react";
interface Props {
title?: string;
hideIcon?: boolean;
message: string | React.ReactNode;
type: "info" | "warning" | "error" | "success";
slim?: boolean;
}
function Alert(props: Props) {
let className = "usa-alert usa-alert--".concat(props.type);
if (props.slim) {
className += " usa-alert--slim";
}
if (props.hideIcon) {
className += " usa-alert--no-icon";
}
return (
<div className={className}>
{typeof props.message === "object" ? (
props.message
) : (
<div className="usa-alert__body">
{props.title && !props.slim && (
<h3 className="usa-alert__heading">{props.title}</h3>
)}
<p className="usa-alert__text">{props.message}</p>
</div>
)}
</div>
);
}
export default Alert;
|
import java.util.*;
public class Main {
public static void main(String [] args){
Scanner in = new Scanner(System.in);
int n =in.nextInt();
Point array[]=new Point[n];
int pos = 0;
int neg = 0;
for(int i = 0;i<n;i++){
array[i] = new Point(in.nextInt(),in.nextInt());
if(array[i].pos > 0)pos++;
else neg++;
}
Arrays.sort(array);
int start = 0;
for(int i = 0;i < n;i++)
if(array[i].pos > 0){
start = i;break;
}
if(pos == 0){
System.out.print(array[n-1].val);
return;
}
if(neg == 0){
System.out.print(array[0].val);
return;
}
if(pos >= neg){
int ans = 0;
for(int i = 0;i < Math.min(neg + neg + 1,n);i++)ans += array[i].val;
System.out.print(ans);
return;
}
else{
int ans = 0;
for(int i = start - pos - 1;i < n;i++)ans += array[i].val;
System.out.print(ans);
}
}
static class Point implements Comparable<Point>{
int pos;
int val;
public Point(int pos,int val){
this.pos = pos;
this.val = val;
}
public int compareTo(Point o){
return pos - o.pos;
}
}
}
|
J. Scott Applewhite
John Boehner held a presser in the Capitol just now, to press the message that there has been no progress in the fiscal cliff talks, and that Boehner’s plan — proposed last week — tosses the ball back into Obama’s court. It’s unclear what this presser accomplished for him. He resembled nothing so much as a football coach nervously eying the clock with time running out — with his team losing and no new set of plays to run.
Here’s what Boehner said:
This isn’t a progress report because there’s no progress to report. […] The President wants to raise tax rates. But even if the President got the tax hike rate that he wanted, understand that we could continue to see trillion dollar deficits for as far as the eye can see. Washington’s got a spending problem, not a revenue problem. If the president doesn’t agree with our proposal, I believe that he’s got an obligation to families and small businesses to offer a plan of his own — a plan that can pass both chambers of the Congress. […] When is he going to take a step towards us?
Assuming the idea here was to inject the GOP’s version of events into the bloodstream in advance of the weekend, what exactly did this accomplish? Boehner said the talks are going nowhere. Fine, but polls show that majorities blame the GOP for the failure to reach a compromise. Boehner said that “Washington’s got a spending problem, not a revenue problem.” Okay, but the American people disagree: Polls consistently show that a majority wants a mix of spending cuts and tax hikes to solve our fiscal problems. The public understands that, yes, to some degree, we do have a revenue problem.
Boehner said Obama has an obligation to offer a plan that can pass both Houses of Congress. But even some Republicans, such as Reps. Tom Cole and Tim Scott — believe that extending just the middle class tax cuts — which Obama is demanding — could pass the House. Boehner has this option; it’s on him if he isn’t taking it.
What’s more, there’s that scenario we talked about yesterday: House Republicans could hold two votes, one on extending all the tax cuts, which would pass with votes from Republicans, and one on extending just the middle class tax cuts, which would pass with votes mostly from Democrats. The Senate would just pass the latter. Some observers have noted it might not be able to pass the House, because virtually no Republicans would vote for it. But House Republicans already would have voted to extend all the cuts, so enough of them might have cover to extend the middle class cuts — particularly since this would get Republicans out of the box they’re in and allow them to evade blame for the tax cuts expiring.
As for Boehner’s demand that the president move towards Republicans, Politico reports today that there are conflicting accounts of the latest meeting between White House negotiators and the House GOP leadership. One account holds that if Republicans give ground on rates, they could get a deal worked out quickly. There’s little reason to doubt that if the GOP did agree to a hike in rates, the White House would serve up some concessions in return — probably ones that the left would dislike.
I really hope that what we saw today is Boehner holding out for as long as he can, until more Republicans — contemplating the prospect of going home for the holidays and explaining why middle class taxes went up — begin to break with the leadership, forcing him to allow the House to vote on extending them. Then he can claim he had no choice and fought to the bitter end. I still suspect that this is how it will play out. If not, we’re going over the cliff. |
import { NodeHeader } from "../node/NodeHeader";
import { IBulkMetadata, INodeKey, NodeMetadata } from "../proto/rocktree";
export class BulkData {
public node_metadata: NodeHeader[];
public bulks: Map<string, NodeHeader>;
public nodes: Map<string, NodeHeader>;
public head_node_key: INodeKey;
public head_node_center: number[];
public meters_per_texel: number[];
public default_imagery_epoch: number;
public default_available_texture_formats: number;
public default_available_view_dependent_textures: number;
public default_available_view_dependent_texture_formats: number;
constructor(metadata: IBulkMetadata) {
this.head_node_key = metadata.head_node_key;
this.head_node_center = metadata.head_node_center;
this.meters_per_texel = metadata.meters_per_texel;
this.default_imagery_epoch = metadata.default_imagery_epoch;
this.default_available_texture_formats = metadata.default_available_texture_formats;
this.default_available_view_dependent_textures = metadata.default_available_view_dependent_textures;
this.default_available_view_dependent_texture_formats = metadata.default_available_view_dependent_texture_formats;
this.node_metadata = [];
this.bulks = new Map();
this.nodes = new Map();
for (let nodeMetadata of metadata.node_metadata) {
const nodeHeader = new NodeHeader(metadata, nodeMetadata);
this.node_metadata.push(nodeHeader);
if (nodeHeader.is_bulk) {
this.bulks.set(nodeHeader.path, nodeHeader);
}
if ((nodeHeader.can_have_data || !(nodeHeader.flags & NodeMetadata.Flags.LEAF.value)) && nodeHeader.obb) {
this.nodes.set(nodeHeader.path, nodeHeader);
}
}
}
} |
package useractions
import (
"github.com/fragmenta/router"
"github.com/fragmenta/view"
"github.com/send-to/server/src/users"
)
// NB no authorisation for access
// HandleShow displays a single user
func HandleShow(context router.Context) error {
// Find the user
user, err := users.Find(context.ParamInt("id"))
if err != nil {
return router.NotFoundError(err)
}
// Render the template
view := view.New(context)
view.AddKey("user", user)
return view.Render()
}
// HandleShowName displays a single user by name
func HandleShowName(context router.Context) error {
// Find the user
user, err := users.FindName(context.Param("name"))
if err != nil {
return router.NotFoundError(err)
}
// Render the template
view := view.New(context)
view.AddKey("user", user)
view.Template("users/views/show.html.got")
return view.Render()
}
|
/**
* @author <a href="mailto:[email protected]">Ivan Budayeu</a>
*/
public final class JarUtil {
private JarUtil() {
//static only
}
public static boolean loadFromJar(Path jarPath, Path targetPath, String resource) throws IOException {
JarFile jar = new JarFile(jarPath.toFile());
if (!Files.isDirectory(targetPath)) {
Files.createDirectories(targetPath);
}
return copyResource(jar, targetPath.toFile(), resource);
}
private static boolean copyResource(JarFile jarFile, File destination, String resource) {
return jarFile.stream().filter(jarEntry -> resource.equals(jarEntry.getName())).findFirst().map(entry -> {
try {
copyEntry(entry, jarFile, destination, resource);
} catch (IOException e) {
return false;
}
return true;
}).orElse(Boolean.FALSE);
}
private static void copyEntry(JarEntry entry, JarFile jarFile, File destination, String resource) throws IOException {
if (!entry.isDirectory()) {
try (InputStream entryInputStream = jarFile.getInputStream(entry)) {
FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, resource));
}
} else {
Files.createDirectories(Paths.get(destination.getAbsolutePath(), resource));
}
}
} |
CHICAGO -- The Chicago Bears agreed to terms on a one-year contract with linebacker Geno Hayes, a league source confirmed on Thursday.
Hayes was one of several veteran linebackers the Bears brought to Halas Hall for an official visit earlier in the week.
Hayes spent the past four seasons as a member of the Tampa Bay Buccaneers, with whom he started a total of 42 games. Originally a sixth-round draft choice by the Bucs out of Florida State, Hayes recorded a career-high 98 tackles in 2009.
The Bears were in the market for experienced depth at linebacker behind veteran starters Brian Urlacher, Lance Briggs and Nick Roach. Rounding out the depth chart at the position are two former undrafted rookie free agents, Dom DeCicco and Patrick Trahan; former St. Louis seventh-round selection Jabara Williams; the Bears' 2011 sixth-round pick, J.T. Thomas; and newly signed special teams ace Blake Costanzo.
Thomas spent his entire rookie season on injured reserve and was arrested in the offseason on a misdemeanor drug possession charge.
Urlacher and Roach both have one year remaining on their current contracts. Briggs recently was rewarded with an extension and is under contract through 2014.
The club may still opt to select a linebacker at some point in the upcoming NFL draft.
The Bears released receiver Max Komar, who appeared in two games and did not make a catch. |
Brokers, Social Networks, Reciprocity, and Clientelism
Although canonical models of clientelism argue that brokers use dense social networks to monitor and enforce vote buying, recent evidence suggests that brokers can instead target intrinsically reciprocal voters and reduce the need for active monitoring and enforcement. Combining a trove of survey data on brokers and voters in the Philippines with an experiment-based measure of reciprocity, and relying on local naming conventions to build social networks, we demonstrate that brokers employ both strategies conditional on the underlying social network structure. We show that brokers are chosen for their central position in networks and are knowledgeable about voters, including their reciprocity levels. We then show that, where village social networks are dense, brokers prefer to target voters who have many ties in the network because their votes are easiest to monitor. Where networks are sparse, brokers target intrinsically reciprocal voters whose behavior they |
<reponame>dlguswo333/react-simple-spinner
import React from 'react';
import Spinner from './Spinner';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<Spinner fill={false} colors={['#25f', '#ff0', '#f22']} />
<p>
Edit <code>src/Spinner.tsx</code> and save to reload.
</p>
</header>
</div>
);
}
export default App;
|
Thermophysical Properties of Pipe Steel in the Liquid State
The temperature dependences of the kinematic viscosity and surface tension of liquid pipe steel with different modes of melt preparation were investigated. A transition zone was found on the temperature dependences of the thermophysical properties, which separates the regions with different activation energies of viscous flow and surface tension. At the heating stage in the transition zone, the thermal decomposition of clusters based on cementite Fe3C occurs. As a result of the decomposition, free carbon atoms appear which tend to give a uniform distribution in liquid iron with increasing temperature. At a low content of alloying elements and impurities, a high-temperature melt should have a large-scale cluster structure, which provides a more uniform distribution of chemical elements. The melt after vacuum degassing has a narrow transition zone near 1920 K, in contrast to the wide transition zone of the melt without vacuum degassing. The wider transition zone is shifted to high-temperature and this shift is associated with the thermal decomposition of carbides and oxides. Studies have shown that heating liquid pipe steel above the temperature of the liquid–liquid structural transition makes it possible to obtain a more homogeneous structure with a more uniform distribution of alloying and impurity elements in the melt. The sharp drop in surface tension at temperatures above 1920 K in the melt without vacuum degassing is associated with the diffusion of free S and O atoms, which are released after thermal decomposition of sulfides and oxides. |
Share your craft ideas for a share of the ad revenue. Click on Write For Us.
Leaf Casts
Time
Age
Level
Materials
Craft plaster of Paris
Dish or lid
Leaf with interesting texture
Several small coins (weights)
Method
Choose a dish or lid with a depth at least a centimetre thick. The plaster needs to be deep enough to press the leaf into.
Plastic lid with rim
Find a leaf with an interesting texture. It needs to fit inside your lid.
Mix the craft plaster of Paris with water in a disposable container. We made ours slightly thicker than the guidance on the pack. We used about half a cup of plaster and half a cup of water.
Pour the plaster of Paris into the lid.
Tap the lid to let any air bubbles escape. Let the plaster start to set for a few minutes then press the leaf carefully onto the top of the plaster.
We carefully placed several small coins on top of the leaf to ensure it was well pressed in and didn't spring up.
We let the plaster of Paris set further for about an hour (until it was firm to touch) then peeled off the leaf.
Allow at least a further 24 hours for the plaster to fully dry out.
Categories
Create a cast of a leaf in plaster of Paris. This is a fun nature craft for kids of any age.: 15 minutes plus 24 hours drying time: Any age: MediumOnce dry you could paint your creation if you wish with acrylic paints. |
Unlabeled data classification via support vector machines and k-means clustering
Support vector machines (SVMS), a powerful machine method developed from statistical learning and have made significant achievement in some field. Introduced in the early 90's, they led to an explosion of interest in machine learning. However, like most machine learning algorithms, they are generally applied using a selected training set classified in advance. With the repaid development of the Internet and telecommunication, huge of information has been produced as digital data format, generally the data is unlabeled. It is impossible to classify the data with one's own hand one by one in many realistic problems, so that the research on unlabeled data classification has been grown. Improvements in databases technology, computing performance and artificial intelligence have contributed to the development of intelligent data analysis. A SVM classifier based on k-means algorithm is presented for the classification of unlabeled data. |
#ifndef _RAY_H_
#define _RAY_H_
#include "scene.h"
#include "vector3.h"
#include "color.h"
#include "object.h"
#include <algorithm>
extern const float EPS;
class Object;
class Scene;
class Ray {
bool insideObj;
Vector3 startPoint, direction;
std::pair<Object*, Vector3> detectCollide(Scene*);
Color calcReflection(Scene*, Object*, Vector3, int, bool);
Color calcRefraction(Scene*, Object*, Vector3, int, bool);
Color calcDiffusion(Scene*, Object*, Object*, Vector3);
Ray reflectRay(Vector3, Vector3);
Ray refractRay(Vector3, Vector3, float);
public:
Ray(Vector3, Vector3, bool inside = 0);
Vector3 getStartPoint() {return startPoint;}
Vector3 getDirection() {return direction;}
Color rayTracing(Scene*, int, bool pt = 1);
};
#endif
|
//
// SIALogLevel.h
// SIALogger
//
// Created by <NAME> on 02/06/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SIALogLevel : NSObject
@property (nonatomic, readonly) NSUInteger priority;
@property (nonatomic, readonly) NSString* name;
@property (nonatomic, readonly) NSString* shortName;
- (id)init __attribute__((unavailable("Used initWithPriority:Name:ShortName: instead.")));
- (instancetype)initWithPriority:(NSUInteger)priority Name:(NSString*)name ShortName:(NSString*)shortName;
@end |
The effects of trunk endurance training on running kinematics and its variability in novice female runners.
The functional importance of trunk muscle strength for running movement is widely recognised, but the kinematic effects of undertaking specific training are unclear. This study investigated the change in joint angle and its variability during running following trunk muscle training. Eighteen young female and novice runners participated. Using Plug-in-gait model with infrared markers attached to the body surface, the lower limb and lumber angles during running were measured, and the variability was examined by calculating the coefficient variation and Lyapunov exponent. Measurements of trunk endurance were also performed. Over four weeks of training, the subjects performed trunk muscle endurance trainings three times a week. Following this intervention, trunk endurance was found to have significantly increased. The Lyapunov exponent of lumbar flexion-extension angle also significantly increased. Moreover, a decreased range of the ankle angle and increased range of the hip angle were observed following the training. These results demonstrate that the trunk training promoted adjustments to lumbar movement and altered the movement patterns of the participants' lower limbs during running. |
/**
* Build the model for the Invite assessors for Assessment Panel Find view.
*/
@Component
public class ReviewInviteAssessorsFindModelPopulator extends ReviewInviteAssessorsModelPopulator<ReviewInviteAssessorsFindViewModel> {
@Autowired
private ReviewInviteRestService reviewInviteRestService;
@Autowired
private CompetitionRestService competitionRestService;
public ReviewInviteAssessorsFindViewModel populateModel(long competitionId,
int page) {
CompetitionResource competition = competitionRestService
.getCompetitionById(competitionId)
.getSuccess();
ReviewInviteAssessorsFindViewModel model = super.populateModel(competition);
AvailableAssessorPageResource pageResource = reviewInviteRestService.getAvailableAssessors(
competition.getId(),
page)
.getSuccess();
List<ReviewAvailableAssessorRowViewModel> assessors = simpleMap(pageResource.getContent(), this::getRowViewModel);
model.setAssessors(assessors);
model.setPagination(new Pagination(pageResource));
model.setSelectAllDisabled(pageResource.getTotalElements() > SELECTION_LIMIT);
return model;
}
private ReviewAvailableAssessorRowViewModel getRowViewModel(AvailableAssessorResource assessorInviteOverviewResource) {
return new ReviewAvailableAssessorRowViewModel(
assessorInviteOverviewResource.getId(),
assessorInviteOverviewResource.getName(),
assessorInviteOverviewResource.getInnovationAreas(),
assessorInviteOverviewResource.isCompliant(),
assessorInviteOverviewResource.getBusinessType()
);
}
@Override
protected ReviewInviteAssessorsFindViewModel createModel() {
return new ReviewInviteAssessorsFindViewModel();
}
} |
#include "includes.h"
WelcomeMessage::WelcomeMessage()
{
cout << "\t\t\tHey, My name is Synthetic i was designed\n\t\t\tto make calculating easier and\n\t\t\tfun!.\n\t\t\tIt was my duty to welcome you all\n\t\t\tremember math is fun so have fun using me to solve problems!";
system("start welcome.vbs");//calls on a file to get the program talking
}
void WelcomeMessage::UserLogin(){
cout << "\n\nEnter -1 in any menu to terminate this software.\n\n";
cout << "\n\n\tEnter Your UserName: ";
cin >> tempUser;//hold what the user enters
cout << "\n\tEnter your Password: ";
cin >> tempPass;//hold the password the user entered
if(tempPass == "-1" || tempUser == "-1"){
int x = 10;
while(x > 0){
cout << "Program Closing in: " << x <<"s\n\n";
Sleep(800);
x--;
system("cls");
}
rlutil::setColor(92);
cout << "Thanks for using, Goodbye!";
rlutil::setColor(0);
Sleep(800);
exit(0);
}
int p = 0, u = 10;
while (tempUser != user || tempPass != pass){//user validation
cin.clear();
rlutil::setColor(12);
cout << "\n\nIncorrect Credentials";
rlutil::setColor(0);
cout << "\n\n\tEnter A Valid UserName: ";
cin >> tempUser;
cout << "\n\tEnter A Valid Password: ";
cin >> tempPass;
rlutil::setColor(12);
cout <<"\nAttemps Left: "<<u<<endl;
rlutil::setColor(0);
if(u == 0){
int x = 10;
while(x > 0){
cout << "Program Closing in: " << x <<"s\n\n";
Sleep(800);
x--;
system("cls");
}
rlutil::setColor(92);
cout << "Thanks for using, Goodbye!";
rlutil::setColor(0);
Sleep(800);
exit(0);
}
if(tempPass == "-1" || tempUser == "-1"){
int x = 10;
while(x > 0){
cout << "Program Closing in: " << x <<"s\n\n";
Sleep(800);
x--;
system("cls");
}
rlutil::setColor(92);
cout << "Thanks for using, Goodbye!";
rlutil::setColor(0);
Sleep(800);
exit(0);
}
u--;
}
rlutil::setColor(13);
cout << "\n\nCredentials Match\n\nLoading: ";//loading the program files
int x = 0;
char t = 219;
rlutil::setColor(9);// set the color
while(x <= 50){
cout <<t;
Sleep(100);
if(x == 50){
Beep(500,900);
rlutil::setColor(0);
}
x++;
}
}
|
A study of the effect of hydrogen on the fatigue behaviour of metals
Hydrogen Embrittlement is a phenomenon in which the presence of hydrogen can lead to various detrimental effects on the mechanical properties of the material. These effects include reduction in ductility, delayed fracture under constant loading, increase in fatigue crack initiation and growth rates, and subcritical cracking even below the threshold fracture toughness of the material. Fatigue is one of the most common modes of material nature during the operation of components during their service life. Hence it is very important to study the effect of hydrogen on the fatigue behaviour of steel and find methods for their prevention. This paper deals with the study of hydrogen on various types of fatigue in materials, various factors that affect the susceptibility to HE in fatigue, the effect on the microscopic morphology of the fatigue crack generated and the methods suggested for the prevention of HE in fatigue. |
// Carries out the "break list" command.
void CmdBreak::processList(DebuggerClient &client) {
m_breakpoints = client.getBreakPoints();
updateServer(client);
for (auto& bpi : *m_breakpoints) {
auto bound = bpi->m_bindState != BreakPointInfo::Unknown;
if (!bound && !client.isLocal() &&
(bpi->m_interruptType == RequestStarted ||
bpi->m_interruptType == RequestEnded ||
bpi->m_interruptType == PSPEnded)) {
bound = true;
}
auto const boundStr = bound ? "" : " (unbound)";
client.print(" %d\t%s %s%s", bpi->index(), bpi->state(true).c_str(),
bpi->desc().c_str(), boundStr);
}
if (m_breakpoints->empty()) {
client.tutorial(
"Use '[b]reak ?|[h]elp' to read how to set breakpoints. "
);
} else {
client.tutorial(
"Use '[b]reak [c]lear {index}|[a]ll' to remove breakpoint(s). "
"Use '[b]reak [t]oggle {index}|[a]ll' to change their states."
);
}
} |
<reponame>jfxcore/compiler
// Copyright (c) 2022, JFXcore. All rights reserved.
// Use of this source code is governed by the BSD-3-Clause license that can be found in the LICENSE file.
package org.jfxcore.compiler.util;
import org.jfxcore.compiler.TestBase;
import org.jfxcore.compiler.diagnostic.SourceInfo;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class AccessVerifierTest extends TestBase {
private static Resolver resolver;
private static String C(String c) {
return "org.jfxcore.compiler.util.verifiertest_" + c;
}
@BeforeAll
static void setup() {
resolver = new Resolver(SourceInfo.none());
}
@Test
public void Public_TopLevel_Class_Is_Always_Accessible() {
var publicA = resolver.resolveClass(C("a.PublicA"));
var packageB = resolver.resolveClass(C("b.PackageB"));
assertTrue(AccessVerifier.isAccessible(publicA, packageB, SourceInfo.none()));
}
@Test
public void Public_Nested_Class_Is_Accessible_Outside_Of_Package() {
var nested = resolver.resolveClass(C("a.PublicA.NestedPublic"));
var packageB = resolver.resolveClass(C("b.PackageB"));
assertTrue(AccessVerifier.isAccessible(nested, packageB, SourceInfo.none()));
}
@Test
public void NonPublic_Nested_Class_Is_Not_Accessible_Outside_Of_Package() {
var packageNested = resolver.resolveClass(C("a.PublicA.NestedPackage"));
var protectedNested = resolver.resolveClass(C("a.PublicA.NestedProtected"));
var publicNested = resolver.resolveClass(C("a.PublicA.NestedPackage.NestedPublic"));
var packageB = resolver.resolveClass(C("b.PackageB"));
assertFalse(AccessVerifier.isAccessible(packageNested, packageB, SourceInfo.none()));
assertFalse(AccessVerifier.isAccessible(protectedNested, packageB, SourceInfo.none()));
assertFalse(AccessVerifier.isAccessible(publicNested, packageB, SourceInfo.none()));
}
@Test
public void NonPrivate_Nested_Class_Is_Accessible_Within_Package() {
var packageNested = resolver.resolveClass(C("a.PublicA.NestedPackage"));
var protectedNested = resolver.resolveClass(C("a.PublicA.NestedProtected"));
var publicNested = resolver.resolveClass(C("a.PublicA.NestedPackage.NestedPublic"));
var packageA = resolver.resolveClass(C("a.PackageA"));
assertTrue(AccessVerifier.isAccessible(packageNested, packageA, SourceInfo.none()));
assertTrue(AccessVerifier.isAccessible(protectedNested, packageA, SourceInfo.none()));
assertTrue(AccessVerifier.isAccessible(publicNested, packageA, SourceInfo.none()));
}
@Test
public void Package_TopLevel_Class_Is_Not_Accessible_Outside_Of_Package() {
var publicA = resolver.resolveClass(C("a.PublicA"));
var packageB = resolver.resolveClass(C("b.PackageB"));
assertFalse(AccessVerifier.isAccessible(packageB, publicA, SourceInfo.none()));
}
@Test
public void Protected_Members_Are_Accessible_In_Derived_Class_Outside_Of_Package() {
var packageNested = resolver.resolveClass(C("a.PublicA.NestedPackage"));
var protectedNested = resolver.resolveClass(C("a.PublicA.NestedProtected"));
var publicNested = resolver.resolveClass(C("a.PublicA.NestedPackage.NestedPublic"));
var derived = resolver.resolveClass(C("b.PackageBInheritsA"));
assertFalse(AccessVerifier.isAccessible(packageNested, derived, SourceInfo.none()));
assertTrue(AccessVerifier.isAccessible(protectedNested, derived, SourceInfo.none()));
assertFalse(AccessVerifier.isAccessible(publicNested, derived, SourceInfo.none()));
}
@Test
public void Nested_Protected_Members_Are_Not_Accessible_In_Derived_Class_Outside_Of_Package() {
var protectedNested2 = resolver.resolveClass(C("a.PublicA.NestedProtected.NestedProtected2"));
var derived = resolver.resolveClass(C("b.PackageBInheritsA"));
assertFalse(AccessVerifier.isAccessible(protectedNested2, derived, SourceInfo.none()));
}
@Test
public void Nested_Protected_Fields_Are_Not_Accessible_In_Derived_Class_Outside_Of_Package() {
var publicField = resolver.resolveField(resolver.resolveClass(C("a.PublicA.NestedProtected")), "publicField");
var protectedField = resolver.resolveField(resolver.resolveClass(C("a.PublicA.NestedProtected")), "protectedField");
var derived = resolver.resolveClass(C("b.PackageBInheritsA"));
assertTrue(AccessVerifier.isAccessible(publicField, derived, SourceInfo.none()));
assertFalse(AccessVerifier.isAccessible(protectedField, derived, SourceInfo.none()));
}
}
|
// WithCache enable response caching.
func WithCache() BitcoinClientOptFunc {
return func(c *clientOpts) {
c.cache = true
}
} |
// GetComments returns all comments by a user
func GetComments(user User) []Comment {
rows, _ := Db.Query("SELECT `id`, `text`, `date` FROM `reacties` WHERE `address` = ? ORDER BY `id` DESC", user.Address)
defer rows.Close()
var comments []Comment
for rows.Next() {
var (
id int
text string
date time.Time
)
rows.Scan(&id, &text, &date)
comments = append(comments, Comment{
ID: id,
Text: text,
Date: date,
})
}
return comments
} |
n = input()
flag3 = 0
counter = 0
while True:
if counter >= len(n):
print("YES")
break
if counter < len(n) - 2:
if [n[counter], n[counter+1], n[counter+2]] == ['1',"4","4"]:
counter += 3
elif [n[counter], n[counter+1] ] == ['1',"4"]:
counter += 2
elif [n[counter]] == ['1']:
counter += 1
else:
print("NO")
break
elif counter < len(n) - 1:
if [n[counter], n[counter+1] ] == ['1',"4"]:
counter += 2
elif [n[counter]] == ['1']:
counter += 1
else:
print("NO")
break
else:
if [n[counter]] == ['1']:
counter += 1
else:
print("NO")
break
# if flag3 == 0:
# print("YES") |
export default class HealthState {
status: string
constructor(status: string) {
this.status = status;
}
} |
N, M = map(int, input().split())
ks_lists = [list(map(int, input().split())) for _ in range(M)]
p_list = list(map(int, input().split()))
n_combi = 0
for combi in range(1 << N):
Flag = True
for i in range(M):
k = ks_lists[i][0]
s_list = ks_lists[i][1:]
p = p_list[i]
tmp_sum = 0
for s in s_list:
tmp_sum += (combi >> (s-1)) & 1
if tmp_sum % 2 != p:
Flag = False
break
if Flag:
n_combi += 1
print(n_combi)
|
/*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:01:54 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/PrivateFrameworks/WebCore.framework/WebCore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@interface WebCookieStorageObjCAdapter : NSObject {
/*function pointer*/void* m_cookieChangeCallback;
}
-(void)notifyCookiesChangedOnMainThread;
-(void)cookiesChangedNotificationHandler:(id)arg1 ;
-(void)startListeningForCookieChangeNotificationsWithCallback:(/*function pointer*/void*)arg1 ;
-(void)stopListeningForCookieChangeNotifications;
@end
|
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { validate } from 'class-validator'
import { getAddress } from 'ethers/utils'
import {
ContractEntity,
UserEntity
} from '../entities'
import { notDefined } from '../utils/notDefined';
import { ContractDto } from './ContractDto'
import { AbiService } from '../abis/AbiService';
import { ContractsQuery } from './ContractsQuery';
import { ValidationException } from '../common/ValidationException';
import { InjectConnection } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { Service } from '../Service';
const debug = require('debug')('notus:ContractService')
@Injectable()
export class ContractService extends Service {
constructor (
private readonly abiService: AbiService,
@InjectConnection()
connection: Connection
) {
super(connection)
}
checkUnauthorizedFields(contractDto: ContractDto, user: UserEntity): ContractDto {
if (!user.isPaid() && contractDto.isPublic === false) {
throw new UnauthorizedException('Only paid users can make their contracts private')
}
return contractDto
}
async findAndCount(params: ContractsQuery, userId: number): Promise<[ContractEntity[], number]> {
let query = await this.connection.createQueryBuilder(ContractEntity, 'contracts')
.leftJoinAndSelect("contracts.abi", "abis")
.leftJoinAndSelect("contracts.owner", "owners")
.leftJoinAndSelect("abis.abiEvents", "abiEvents")
query = query.where('"contracts"."deletedAt" IS NULL')
params = params || new ContractsQuery()
if (params.hasAbiEvents) {
query = query.andWhere('"contracts"."abiId" IN (SELECT "abi_events"."abiId" FROM abi_events GROUP BY "abi_events"."abiId" HAVING COUNT(*) > 0)')
}
const queryOwnerIsUser = params.ownerId && params.ownerId === userId
if (queryOwnerIsUser || !params.ownerId) {
query = query.andWhere('(("contracts"."isPublic" IS TRUE AND "owners"."confirmedAt" IS NOT NULL) OR "contracts"."ownerId" = :id)', { id: userId })
} else if (params.ownerId) {
query = query.andWhere('("contracts"."isPublic" IS TRUE AND "owners"."confirmedAt" IS NOT NULL AND "contracts"."ownerId" = :id)', { id: params.ownerId })
}
if (params.networkId) {
query = query.andWhere('"contracts"."networkId" = :networkId', { networkId: params.networkId })
}
if (params.address) {
query = query.andWhere('"contracts"."address" ILIKE :address', { address: params.address })
}
if (params.name) {
query = query.andWhere('"contracts"."name" ILIKE :name', { name: params.name })
}
if (params.skip) {
query = query.offset(params.skip)
}
if (params.take) {
query = query.limit(params.take)
}
return query.printSql().orderBy('"contracts"."createdAt"', 'DESC').getManyAndCount()
}
async findOneOrFail(id: number): Promise<ContractEntity> {
if (notDefined(id)) { throw new Error('id must be defined') }
return await this.manager().findOneOrFail(ContractEntity, id)
}
async createContract(user: UserEntity, contractDto: ContractDto): Promise<ContractEntity> {
const contract = new ContractEntity()
contract.owner = user
contract.name = contractDto.name
contract.address = contractDto.address
contract.abi = await this.abiService.findOrCreate(user, contractDto.abi)
contract.networkId = contractDto.networkId
contract.isPublic = contractDto.isPublic
await this.validate(contract)
contract.address = getAddress(contract.address)
await this.manager().save(contract)
return contract
}
async updateAndSave(contract: ContractEntity, contractDto: ContractDto): Promise<ContractEntity> {
if (contractDto.name !== undefined) {
contract.name = contractDto.name
}
if (contractDto.address !== undefined) {
contract.address = contractDto.address
}
if (contractDto.networkId !== undefined) {
contract.networkId = contractDto.networkId
}
if (contractDto.isPublic !== undefined) {
contract.isPublic = contractDto.isPublic
}
await this.validate(contract)
contract.address = getAddress(contract.address)
await this.manager().save(contract)
return contract
}
async destroy(contract: ContractEntity) {
await this.manager().delete(ContractEntity, contract.id)
}
async validate(contract: ContractEntity) {
const errors = await validate(contract)
if (!(contract.abi || contract.abiId)) {
errors.push({
target: contract,
property: 'abi',
value: contract.abi,
constraints: {
'abi': `Must have an abi`
},
children: []
})
}
if (!(contract.owner || contract.ownerId)) {
errors.push({
target: contract,
property: 'owner',
value: contract.owner,
constraints: {
'owner': `Must have an Owner`
},
children: []
})
}
if (errors.length > 0) {
throw new ValidationException(`Contract is invalid`, errors)
}
}
} |
/* C A N C E L A L L O U T G O I N G C A L L S */
/*-------------------------------------------------------------------------
%%Function: CancelAllOutgoingCalls
-------------------------------------------------------------------------*/
VOID CancelAllOutgoingCalls(void)
{
if (NULL == g_pCallList)
return;
POSITION pos = g_pCallList->GetHeadPosition();
while (pos)
{
CCall * pCall = (CCall *) g_pCallList->GetNext(pos);
ASSERT(NULL != pCall);
if (!pCall->FIncoming())
{
pCall->AddRef();
pCall->Cancel(TRUE);
pCall->Release();
}
}
} |
/**
* Parses the command line arguments.
*/
public void parseArguments(String[] arguments) {
LinkedList<String> args = new LinkedList<>(Arrays.asList(arguments));
boolean valid = true;
while (!args.isEmpty()) {
String arg = args.removeFirst();
boolean handled = false;
for (Option option : options) {
if (option.processOption(arg, args)) {
handled = true;
break;
}
}
if (!handled) {
System.out.println("Unknown option: " + arg);
System.out.println();
valid = false;
break;
}
}
if (!valid) {
showOptions();
completed();
}
} |
<gh_stars>0
import { initializeApp, AppOptions, cert, App } from "firebase-admin/app";
import { getStorage, Storage } from 'firebase-admin/storage';
import { EStorageErrorMessage } from "../../constants/apis/EStorageErrorMessage";
import { EStorageErrorStatus } from "../../constants/apis/EStorageErrorStatus";
import { EAppDefaultString } from "../../constants/EAppDefaultString";
import { FileStorageError } from "../../errors/FileStorageError";
import { IHttpError } from "../../errors/IHttpError";
import { UnexpectedError } from "../../errors/UnexpectedError";
export class FirebaseApi {
private static _instance: FirebaseApi;
private firebaseOptions: AppOptions;
public firebase: App;
public storage: Storage;
public avatarsFolder: string;
private constructor(){
this.firebaseOptions = {
credential: cert({
clientEmail: process.env.FIREBASE_ADM_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_ADM_PRIVATE_KEY,
projectId: process.env.FIREBASE_ADM_PROJECT_ID
}),
storageBucket: "heroku-todolist-server.appspot.com"
}
this.firebase = initializeApp(this.firebaseOptions);
this.storage = getStorage(this.firebase);
this.avatarsFolder = "uploads/avatars/";
}
public static getInstance(): FirebaseApi {
return this._instance || (this._instance = new FirebaseApi());
}
public removeAvatar(avatarUrl: string): Promise<void> {
return new Promise<void>( async (resolve, reject) => {
const isDevEnv = process.env.NODE_ENV === "development";
if (!avatarUrl){ return reject(new UnexpectedError); }
const fileLocation: string = avatarUrl.replace(
EAppDefaultString.GOOGLE_STORAGE_BUCKET_URL,
""
);
if (fileLocation.includes("default")){ return resolve(); }
const fileAtStorage = this.storage.bucket().file(fileLocation);
/**
* Attention: ".delete()" triggers "unhandledRejection" Node.js event if the file is not found or being processed somehow.
**/
const removalError: IHttpError | null = await fileAtStorage
.delete()
.then((apiResponse) => {
return null;
})
.catch((error) => {
return new FileStorageError(
EStorageErrorStatus.FILE_REMOVAL_ERROR,
EStorageErrorMessage.FILE_REMOVAL_ERROR,
isDevEnv ? error : undefined
);
});
if (removalError){ return reject(removalError); }
return resolve();
});
}
} |
/**
* Given: A submission from a student whose name is in the grade book,
* but whose id is not
*
* When: The submission is recorded
*
* Then: The submission is noted under the expected id and a new Student
* is <b>not</b> created.
*
* This tests issue #52 (https://github.com/DavidWhitlock/PortlandStateJava/issues/52)
*/
@Test
public void matchStudentBasedOnFirstAndLastName() throws StudentEmailAttachmentProcessor.SubmissionException {
String projectName = "Project";
GradeBook gradebook = createGradeBookWithAssignment(projectName);
Student student = createStudentInGradeBook(gradebook);
String studentName = student.getFirstName() + " " + student.getLastName();
String wrongStudentId = "Not the student id we expect";
String wrongEmail = "Not the email that we expect";
String submissionComment = "This is only a test";
Manifest manifest = createManifest(projectName, studentName, wrongStudentId, wrongEmail, submissionComment);
noteProjectSubmissionInGradeBook(gradebook, manifest);
assertThat(gradebook.getStudent(wrongStudentId), isNotPresent());
assertThatProjectSubmissionWasRecordedForStudent(projectName, student);
} |
// exportDNATMappings exports the corresponding list of D-NAT mappings from a Contiv service.
func (rndr *Renderer) exportDNATMappings(service *renderer.ContivService) []*vpp_nat.DNat44_StaticMapping {
mappings := []*vpp_nat.DNat44_StaticMapping{}
if service.HasNodePort() {
mappings = append(mappings, rndr.exportServiceIPMappings(service, rndr.nodeIPs, nodeIP)...)
}
mappings = append(mappings, rndr.exportServiceIPMappings(service, service.ClusterIPs, clusterIP)...)
mappings = append(mappings, rndr.exportServiceIPMappings(service, service.ExternalIPs, externalIP)...)
return mappings
} |
/* compiled from: lambda */
public final /* synthetic */ class C4002Na implements C0129b {
/* renamed from: a */
private final /* synthetic */ InstalledIntentService f7488a;
public /* synthetic */ C4002Na(InstalledIntentService installedIntentService) {
this.f7488a = installedIntentService;
}
public final void call(Object obj) {
this.f7488a.mo15054a((MinimalAd) obj);
}
} |
/**
* Update status mobil di table mobil menjadi sesuai status
* @param idMobil
* @param status
* @throws SQLException
*/
public void updateStatus(int idMobil, String status) throws SQLException{
SQL = "UPDATE tb_mobil SET status=? WHERE id_mobil=?";
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(SQL);
stmt.setString(1, status);
stmt.setInt(2, idMobil);
stmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(TransaksiDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
} finally {
System.out.println(stmt);
stmt.close();
}
} |
package com.yhy.common.beans.net.model;
/**
* Created with Android Studio.
* Title:AboutAndFeedController
* Description:
* Copyright:Copyright (c) 2015
* Company:quanyan
* Author:zhaoxiaopo
* Date:16/4/1
* Time:14:04
* Version 1.0
*/
public class DefaultCityBean {
public static final String cityName = "昆明";
public static final String cityDisc= "大理";
public static final String cityCode = "530100";
}
|
// OnDelete checks if a metric is registered based on the ConfigMap
// labels, if not it createds and registers it and then records it
// if it does, it just records it.
func (m *Server) OnDelete(obj interface{}) {
configMap := obj.(*corev1.ConfigMap)
if strings.HasPrefix(configMap.Name, c2mNamePrefix) {
metricname := configMap.ObjectMeta.Labels["prom_metric"]
metric := m.Registeredmetrics[metricname]
prometheus.Unregister(metric)
log.Println("Deleting metric: " + metricname)
}
} |
/**
* This is the RTIndirection class/interface.
* This class is used as a place holder in the recursive let situation.
* <p>
* Created: May 22, 2003 11:46:48 AM
* @author RCypher
*/
public class RTIndirection extends RTResultFunction {
/* (non-Javadoc)
* @see org.openquark.cal.internal.runtime.lecc.RTValue#unwind()
*/
@Override
protected final RTValue reduce(RTExecutionContext ec) throws CALExecutorException {
if (result == null) {
throw new NullPointerException ("Invalid reduction state in indirection. This is probably caused by a circular let variable definition.");
}
if (LECCMachineConfiguration.concurrentRuntime()) {
return result.synchronizedReduce(ec);
}
return result.reduce(ec);
}
/**
* Determine if this value should represent a logical 'true' if employed in
* a logical expression (particularly the condition of an 'if').
* @return boolean
*/
@Override
public final boolean isLogicalTrue() {
// All normal values are assumed to represent 'true'
// The one special value 'CAL_Boolean.CAL_False' in the kernel overrides this
// to 'false'
if (result != null) {
return result.isLogicalTrue();
}
return true;
}
/**
* Return the evaluated RTValue. This may cause the value to be evaluated
* if this hasn't already been done.
* @param ec
* @return RTValue the result of evaluating this RTValue
* @throws CALExecutorException
*/
@Override
public final RTValue evaluate(RTExecutionContext ec) throws CALExecutorException {
if (LECCMachineConfiguration.concurrentRuntime()) {
return synchronizedEvaluate(ec);
}
return unsynchronizedEvaluate(ec);
}
synchronized private final RTValue synchronizedEvaluate(RTExecutionContext ec) throws CALExecutorException {
return unsynchronizedEvaluate(ec);
}
private final RTValue unsynchronizedEvaluate(RTExecutionContext ec) throws CALExecutorException {
if (result == null) {
throw new NullPointerException ("Invalid reduction state in indirection. This is probably caused by a circular let variable definition.");
}
setResult (result.evaluate(ec));
return result;
}
/*
* (non-Javadoc)
* @see org.openquark.cal.internal.runtime.lecc.RTResultFunction#clearMembers()
*/
@Override
public void clearMembers () {
// No members to clear in an RTIndirection.
}
} |
#include "H_Hartree_pw.h"
#include "efield.h"
#include "gatefield.h"
#include "module_base/global_function.h"
#include "module_base/global_variable.h"
#include "module_base/memory.h"
#include "module_base/timer.h"
#include "module_base/tool_quit.h"
#include "module_base/tool_title.h"
#include "pot_local.h"
#include "pot_surchem.hpp"
#include "pot_xc.h"
#include "potential_new.h"
#ifdef __LCAO
#include "H_TDDFT_pw.h"
#endif
namespace elecstate
{
PotBase* Potential::get_pot_type(const std::string& pot_type)
{
ModuleBase::TITLE("Potential", "get_pot_type");
if (pot_type == "local")
{
return new PotLocal(this->vloc_, &(this->structure_factors_->strucFac), this->rho_basis_);
}
else if (pot_type == "hartree")
{
return new PotHartree(this->rho_basis_);
}
else if (pot_type == "xc")
{
return new PotXC(this->rho_basis_, this->etxc_, this->vtxc_, &(this->vofk_effective));
}
else if (pot_type == "surchem")
{
return new PotSurChem(this->rho_basis_,
this->structure_factors_,
this->v_effective_fixed.data(),
&GlobalC::solvent_model);
}
else if (pot_type == "efield")
{
return new PotEfield(this->rho_basis_, this->ucell_, GlobalV::DIP_COR_FLAG);
}
else if (pot_type == "gatefield")
{
return new PotGate(this->rho_basis_, this->ucell_);
}
#ifdef __LCAO
else if (pot_type == "tddft")
{
return new H_TDDFT_pw(this->rho_basis_, this->ucell_);
}
#endif
else
{
ModuleBase::WARNING_QUIT("Potential::get_pot_type", "Please input correct component of potential!");
__builtin_unreachable();
}
}
} // namespace elecstate |
def _cp(repository_ctx, src, dest = None):
if dest == None:
if type(src) != "Label":
fail("src must be a Label if dest is not specified explicitly.")
dest = "/".join([
component
for component in [src.workspace_root, src.package, src.name]
if component
])
repository_ctx.file(repository_ctx.path(dest),
repository_ctx.read(repository_ctx.path(src)),
executable=False,
legacy_utf8=False)
return dest |
// Add - Append (or create and append) a new sample to the series
// args:
// key - time series key name
// timestamp - time of value
// value - value
func (client *Client) Add(key string, timestamp int64, value float64) (storedTimestamp int64, err error) {
conn := client.Pool.Get()
defer conn.Close()
return redis.Int64(conn.Do(ADD_CMD, key, timestamp, floatToStr(value)))
} |
Commitment to exporting as an antecedent of organizational skills and firm performance
This study proposes the role of leader’s commitment to export activities as an antecedent of specific organizational skills. In particular, this research investigates whether the leaders’ commitment to exporting affects firm performance, through the mediating effect of entrepreneurial orientation, network competence, and dynamic capabilities of a firm, using survey data collected from 976 companies in Portugal. Results from the structural equation model show that leaders’ commitment to exporting, defined as a positive attitude towards the internationalization of their firms, acts as an antecedent of entrepreneurial orientation and network competence. Additionally, we conclude that the relation between this commitment and firm performance is mediated through entrepreneurial orientation, network competence, and dynamic capabilities. This study contributes to the understanding of the mediating effect of these specific organizational skills in the proposed relationship between leaders’ commitment to exporting and firm performance and provides a new insight into the important role of the entrepreneur or top manager.
Introduction
In a globalized economy, firms find themselves competing both national and across borders. The search for factors which enhance the overcoming of barriers and exploring opportunities leading to achieve success in national and international markets, has become of paramount importance in management (Javalgi and Todd 2011). The literature regarding international strategic management recognizes the importance of internal firm capabilities, which includes entrepreneurial orientation, dynamic capabilities, market orientation, network ties, among others, to improve firm performance, to expand abroad and compete internationally.
Entrepreneurial actions with an innovative, proactive and risk-taking behavior allow firms to identify and to explore opportunities in different markets (Dai et al. 2013;Oviatt and McDougall 2005). Hence, entrepreneurial orientation can provide firms a better preparation to foster international new market entry and to increase firm performance (e.g., Jin et al. 2018;Covin and Slevin 1989;Rauch et al. 2009). Given the current pace of change, firms need to continually develop skills to sustain competitive advantage, i.e. they need to develop dynamic capabilities, which contribute to a better adaptation of firms (Zahra et al. 2006), lead to competitive advantage (Fainshmidt et al. 2019) and to sustain a better performance over time (Teece et al. 1997;Wilden et al. 2013).
Nowadays, networking is a key skill in social and business life. This is an important facilitator of business opportunities and has been emphasized in the entrepreneurship literature. Networks are useful to acquire the resources to a better adaptation in markets (Ibeh and Kasem 2011), being the management of these a key issue. It has been shown that the higher the level of environmental uncertainty and hostility, the greater is the dependence that firms have on their networks to adapt to the environmental changes, and in the context of international operations, to influence the internationalization process (Musteen et al. 2010). In 1999, Ritter introduced the concept of network competence (Ritter 1999). This competence allows intensifying firm external relationships and influences firm performance (Ritter and Gemünden 2003;Ritter et al. 2002;Ritter 1999). Additionally, networks may facilitate the development of new capabilities by promoting a constant flow of information from external and internal sources, and in turn affect performance.
In recent years, several firms faced a context of financial crisis which has demanded quick responses and adaptations by firms. Opportunities are hand with hand with risks and internationalization is no exception either. In Portugal, and to minimize the impact of economic crisis on activity stagnation and firms' bankruptcy, the Portuguese Government developed an export promotion strategy to boost firm's performance. In this context, international expansion has become a strategic response for many firms, which increasingly look to international market as an opportunity. In fact, the international competitiveness of a country reflects the ability of its organizations to achieve success in the markets. Nevertheless, for that success, the firm leadership or manager may play a significant role.
Despite these insights, the interrelation between the individual level and the organizational level and its relationship with firm performance deserves additional research. In this study, we focus on the effect of individual level through leaders' commitment to exporting, which reflects the importance that decision makers attribute to the firm's international operations, their intention to increase the exporting activities and to actively explore international market opportunities (Cadogan et al. 2001). This commitment may induce the development of organizational skills, such as entrepreneurial orientation and network competence, to achieve a better firm performance.
In this way, we explore the intersection of two strands of research. On the one hand, studying the firm's skills (entrepreneurial orientation, dynamic capabilities, network competence) and its direct and/or indirect effects on firm performance. While these skills provide directions for organizations pursue new opportunities, their effective implementation requires someone's commitment in implementing this culture (Wobodo 2019). On the other hand, we introduce the role of the leader (at the individual level) in the development of each of these organizational skills (at the firm level). Thus, in line with recent literature, which began to introduce individual components along with organizational skills, our research aims to take the individual-level perspective on firm's behavior and performance (e.g., Ensley et al. 2006;Ling et al. 2008;Engelen et al. 2015;Pureta and Pureta 2018). Additionally, this paper contributes to the management literature by extending the available conceptual models that explain firm's performance by adding leaders' commitment to exporting as an antecedent of organizational skills. This approach is timely and relevant, given recent studies that consider the top manager characteristics (Miller and Le Breton-Miller 2011;van Doorn et al. 2017) as drivers of entrepreneurial orientation. Additionally, the development of trust relationships with business partners is improved, while the international commitment increases (Johanson and Vahlne 2009) and, with a perspective of knowledge acquisition, the international commitment improves the network relationships (Zhou et al. 2012). This commitment can lead to the development of entrepreneurial behavior and to develop relationships with other firms as his/her entrepreneur's values, tendencies, and orientation have impacts on the entrepreneurial orientation of the organization (Covin and Miller 2014). Therefore, this study investigates the importance of leaders' commitment to exporting role in the formation of organizational skills, such as entrepreneurial orientation and network competence, and its effects on performance using data collected from 976 companies in Portugal.
This article is organized as follows. After the introduction section, Sect. 2 surveys the relevant literature to this study that supports the theoretical framework and hypotheses to be tested and concludes with the conceptual model. Section 3 describes the methodology of data collection, sample characteristics, measures of variables and procedures for reliability verification of instruments measuring constructs. Section 4 presents the results of our research; and a discussion of the theoretical and management implications can be found in Sect. 5.
Entrepreneurial orientation
The entrepreneurship or entrepreneurial behavior is an important way to explore new opportunities Slevin 1989, 1991), since firms with this behavior can be better prepared to deal with obstacles (Zahra 1993;Zahra and Covin 1995) and will take more risks. Being a relevant topic of research in the field of entrepreneurship and strategy for several decades (Covin and Lumpkin 2011;Simsek et al. 2010;Wales 2016), the roots of research in the field of entrepreneurial orientation (EO) are attributed to the work of Mintzberg (1973) who considers that firm's entrepreneurial orientation is based on active search for new opportunities. For Covin and Slevin (1989), when managers are entrepreneurial orientated that is reflected on the strategic decisions of firm and on its management philosophy. Firms need to innovate and look for market leadership, whereby entrepreneurial orientation occurs simultaneously with three dimensions (Miller 1983): innovativeness, risk-taking, and proactiveness. The innovativeness dimension is related to the ability of the company to create new products or transform the existing ones, new services or technological processes in order to satisfy the demand of current and future markets. Risktaking refers to the will of the company allocate resources to projects, whose results can be highly uncertain, which allow increasing its ability to identify and exploit market opportunities before competitors. Finally, proactiveness dimension refers to processes of acting in anticipation of future demand and of future needs, with which companies size opportunities for initiative and strong emphasis on leadership. Additionally, Anderson et al. (2009) provide a definition of EO as a firm-level strategic orientation, which captures an organization's decision-making practices, managerial philosophies, and strategic behaviors that are entrepreneurial in nature. EO has generally been conceived of as an organizational decision-making proclivity favoring entrepreneurial activities (Lumpkin and Dess 1996).
Network competence
The role of networking has been recently considered one of the most relevant topics in the entrepreneurship literature. Firms facing difficulties, e.g. the lack of the necessary resources (Knight and Cavusgil 2004), may use network relationships to minimize them by accessing necessary resources such as knowledge, technology, and capital that are needed for international expansion (Ibeh and Kasem 2011). The lack of studies on the definition of the relationship between the organizational capabilities and the networking led to the development of the concept of network competence (Ritter 1999;Ritter et al. 2002). Despite the progress in networking research, the organizational network-level competences have not been widely studied. Network competence (Ritter 1999) is the firms' ability to develop and manage relationships with business partners and deal with the interactions between them effectively (Ritter 1999;Ritter et al. 2002). It is a relational core competence that organizations develop (Ritter et al. 2002), i.e., an internal organizational ability that allows 1 3 Commitment to exporting as an antecedent of organizational… reconfiguring the relationship activities in specific situations (Knight and Cavusgil 2004).
Leaders' commitment to exporting and its relationship with entrepreneurial orientation and network competence
Commitment is the attitude underlying decision makers. In the international context it relates to the degree of commitment that managers put on the internationalization process and increase of activities in foreign markets (Cadogan et al. 2001;Zhou et al. 2012). According to Gencturk et al. (1995) the favorable management attitudes towards internationalization leads to greater commitment to foreign marketing activities. This commitment is an important indicator of leaders' willingness to act in international markets and on the activity of their firms' internationalization. The firm's owners or managers that develop a positive attitude towards international expansion and think outside the domestic market are more likely to succeed (Javalgi and Todd 2011).
In addition, international operations involve risks due to the higher probability of failure in a competitive and generally unknown environment (Ripollés-Meliá et al. 2007). To minimize the probability of failure and achieve success, the search for opportunities, in general, and international opportunities, in particular, requires an entrepreneurial orientation, since firms that opt for internationalization face more risks and need to be more proactive and innovative (Santos and García 2011;Knight and Cavusgil 2004), and such behaviors facilitate the entry into new markets.
The top management team plays a key role in values formation and in firm orientation, being the main driving force into this direction (Javalgi and Todd 2011). According to Covin and Miller (2014), the entrepreneur or "key manager" is the reason that explains the entrepreneurial behavior of a firm. Studies suggest that the CEO, the decision-making styles and practices of managers, as well as their commitment influence the firm and its entrepreneurial orientation (Grühn et al. 2017;Navarro-García et al. 2017). To Lumpkin and Dess (2001), internationalization is seen as a form of entrepreneurship and Ripollés-Meliá et al. (2007) consider that, due to the identification and exploitation of new opportunities in a new environment, international activity is an entrepreneurial act. Therefore, we explore how the commitment of managers towards exporting influences the entrepreneurial orientation of the firm, since international operations require an entrepreneurial behavior. As entrepreneurial orientation is important in the search for new opportunities Slevin 1989, 1991), we believe that the leaders' commitment to exporting will contribute to the development of this entrepreneurial behavior. Thus, we set out first hypothesis: H1: Leaders' commitment to exporting promotes the formation of the firm's entrepreneurial orientation.
The lack of resources (Knight and Cavusgil 2004) and cultural differences between countries of origin and destination (Johanson and Vahlne 1977) impose constraints to the growth of international operations. In this context, many authors have suggested that network relationships can provide access to key resources, such as knowledge, technology, and capital, which facilitate firm internationalization (Ibeh and Kasem 2011), without taking much risk (Covin and Miller 2014;Lee et al. 2012). Knight and Cavusgil (2004) and Torkkeli et al. (2012) emphasize the possession of internal organizational competences, such as network competence, in order to support the international expansion into other markets. Given the importance of networks, firms with higher degree of international commitment have a greater capacity to develop trust relationships with business partners and overcome obstacles (Johanson and Vahlne 2009). Thus, commitment to international markets facilitates the acquisition of knowledge, since this can be acquired through relationships (Zhou et al. 2012). Consequently, given the importance of the networks for the firms' internationalization, it is expected that top managers committed to exporting will be concerned with the firm's network competence development. Based on this preposition, we test whether leaders' commitment to exporting is an antecedent of network competence, i.e., a greater commitment to international activity can lead to the development of this important competence for current or future internationalization processes. Hence, our second hypothesis is: H2: Leaders' commitment to exporting positively influences network competence development.
Dynamic capabilities
The Resource Based View (RBV) of Barney (1991) aims to explain how firms can achieve a sustainable competitive advantage, given their resources and capabilities (Lin and Wu 2014). The utilization of resources that are unique, i.e., valuable, rare, difficult to imitate and non-substitutable (VRIN), allows the firm to obtain sustainable competitive advantages over time against other firms (Barney 1991). In this line of arguing, Teece et al. (1997) proposed the concept of dynamic capabilities as an extension of RBV. This framework is relevant, since dynamic capabilities refer to the ability to anticipate changes and react to them in a systematic way, referred to as dynamic capabilities (Teece et al. 1997), being a way for firms to sustain superior performance over time (Wilden et al. 2013).
Entrepreneurial orientation and dynamic capabilities
In a recent meta-analysis, Eriksson identified key antecedents of dynamic capabilities that can be either of external or internal nature (Eriksson 2014). The internal antecedents of dynamic capabilities of social nature contain many orientations such as entrepreneurial orientation that is an individual orientation (Jantunen et al. 2005). Given the importance of management style, Teece (2007) defines the entrepreneurial component as an antecedent to dynamic capabilities. Indeed, entrepreneurial managers more easily shape firm management and, consequently, better sustain dynamic capabilities (Teece 2007). It is important that managers seek innovation in order to sustain and renew the competitive advantage across borders by combining dynamic capabilities with motivation to innovate (Michailova and Zhan 2015). Thereby, we proposed to test the relationship between entrepreneurial orientation and dynamic capabilities. Thus, our third hypothesis follows: H3: Entrepreneurial orientation positively influences dynamic capabilities.
Network competence and dynamic capabilities
In a competitive and changing environment, firms need capabilities that enhance innovation, anticipate changes, and provide a quick response to threats. These capabilities can be developed internally or externally in cooperation with the network partners (Lew et al. 2013). According to Hessels and Parker (2013) firms which do not possess unique resources and capabilities can alternatively establish external relations or cooperate with other firms in order to access them. Thus, network relationships between firms may strengths their resource base, which positively influences organizational performance. Vahlne (2003, 2009) consider essential to be in relevant networks, because it is within relationships that parties interact by learning and improving their dynamic capabilities. Indeed, entrepreneurs can employ the necessary resources across networks as a basis for the generation and promotion of dynamic capabilities. Therefore, we hypothesize that network competence is an antecedent of firm's dynamic capabilities, i.e., H4: Network competence contributes to the development of dynamic capabilities.
Entrepreneurial orientation and firm performance
It has been suggested that entrepreneurial orientation positively influences the firm performance (Covin and Slevin 1989;Lee et al. 2019;Miller 1983;Rauch et al. 2009;Rezaei and Ortt 2018). In fast-changing environments, an entrepreneurial orientation facilitates firms in seeking new opportunities (Rauch et al. 2009), as a result of the proactive nature and willingness to take risks (Ripollés-Meliá et al. 2007). Lumpkin and Dess (1996) argue that the impact of entrepreneurial orientation on firm performance depends on the specific context of the firm. The strength of the relation between the two constructs may vary (Rauch et al. 2009): firms with higher entrepreneurial orientation tend to be more successful. Nevertheless, Li et al. (2005) failed to find any relation and Tang et al. (2008) found a nonlinear one. Su et al. (2011) attribute the explanation for these different results to the existence of other factors that mediate this relation. The lack of control of mediator factors may explain the negative relation between entrepreneurial orientation and firm performance found by Hart (1992). Given that most of studies support a positive influence, we hypothesize direct and indirect effects between entrepreneurial orientation and firm performance. Thus, our fifth hypothesis is: H5: Entrepreneurial orientation positively influences the firm performance. Ritter (1999) emphasizes the importance of network competence to explain firm performance, since the ability of firms to sustain their networks becomes a core competency and a skill that can determine their performance (Ritter et al. 2002). This competence enhances external relationships of firm, which may impact measures of performance such as survival and growth, sales volume, and competitive position (Ritter and Gemünden 2003). Thus, we test the hypothesis:
Network competence and firm performance
H6: Network competence contributes to improve firm performance.
Dynamic capabilities and firm performance
To Lin and Wu (2014), firms can improve their performance whenever they accumulate VRIN resources and develop their dynamic capabilities. According to Wilden et al. (2013), the dynamic capabilities positively influence the firm performance. As an RBV's extension, dynamic capabilities are a critical source of superior performance (El Akremi et al. 2015), which explain performance differentials between firms (Wang et al. 2015). As the dynamic capabilities allow firms to reconfigure its resource base and promote the search of opportunities (Jantunen et al. 2005), firms are endowed with new decision options with potential to increase performance (Eisenhardt and Martin 2000;Teece 2007). Thus, dynamic capabilities are important antecedents, and are positively related to firm performance (Drnevich and Kriauciunas 2011;Eisenhardt and Martin 2000;Hung et al. 2010;Knight and Liesch 2015;Monteiro et al. 2017;Zahra et al. 2006 The conceptual model is summarized in Fig. 1. It defines leaders' commitment to exporting as an antecedent of entrepreneurial orientation and network competence, the influence of these last two variables on the development of dynamic capabilities and ultimately of these constructs on firm performance, evaluating the associated mediator effects. We also test for control variables such as firm age, size, sector or industry, and location, as they have the potential to influence performance of firms and are widely used in the strategic management literature (e.g. Dai et al. 2013;Lechner and Gudmundsson 2014;Karami and Tang 2019). 1
Data and methodology
Data was collected through an application of a structured questionnaire, which was pilot tested to check for clarity of the questions and easiness to filling in. Firms were selected using a population representative database designed for this specific purpose. Geographical strata were set to respect the regional distribution of Portuguese 1 3 firms. Firm managers or decision makers were contacted as they had the decision power and knowledge to fill in the questionnaire. Data collection was conducted online using an online platform. We obtained 976 validated responses and the data analysis was conducted using SPSS and MPlus software. Table 1 presents the main sample characteristics of the firms in the sample: firm age, firm size, turnover, industry, and geographical location. Concerning firms' age, 27% of firms in our sample have more than 25 years, 30% are aged between 16 and 25 years, 23% between 11 and 15 years, and 21% are younger firms with less than 10 years. In terms of size measured by the number of employees, 60% of firms have less than 10 employees, 31% between 10 and 49 employees, and only 10% have 50 or more employees. Regarding the amount of turnover, 13% of firms have a turnover inferior to 50,000€, 32% between 50,000€ and 250,000€, 29% between 250,001€ and 1,000,000€, and 27% of firms have more than 1 million €. Almost half of the firms operate in the Services sector, 26% in the Commerce sector, and 25% dedicates to Productive activities. In terms of location, 32% of firms are in the North of Portugal, 31% in Lisbon area, 20% in the Center of Portugal and 17% are distributed by the South region and Portuguese islands.
Additionally, as regards the firms operating markets, 56.1% of firms operate only in the domestic market and 43.9% have international activities (34.6% exporters and 9.3% making direct investment and/or direct investment and export). Of exporting firms, 39.4% export up to 10% of its production, 38% exports up to 50%, and 22.6% export more than 50%. Regarding the scope of internationalization, about 17% of overall sample firms export to up to two countries, 12% export to 3-4 countries, and 14% export to five or more countries. Indeed, for a large proportion of exporting firms (47.7%), two or more countries of destination of their exports is outside the European Union (EU). These firms export on average to 6.6 countries, of which 3.1 are outside the EU. The average speed of internationalization-difference between the years of first entry into the international market and firm creation-is 9.5 years.
Leaders' commitment to exporting
Leaders' commitment to exporting was measured by the scale of Cadogan et al. (2001) with three items that focus on the manager's commitment to the importance of international activities (importance of exporting activities, intention to increase this activities, and an active exploration of opportunities in international market). We replace the term "senior management" by "those responsible for making management decisions", because Portuguese firms, mostly SMEs, tend to lack a formal structure with senior management.
Entrepreneurial orientation
Entrepreneurial orientation proposed by Miller (1983) is measured by nine items developed by Covin and Slevin (1989). In line with other studies (e.g., Moreno and Casillas 2008), we used the semantic differential method. Respondents classified their firms' orientation towards two opposing statements that are graded on a 7-point scale. This measurement scale has been applied in other studies (e.g., Covin and Slevin 1989;Ripollés-Meliá et al. 2007) and allows the characterization of the degree of firm entrepreneurial orientation with high levels of reliability and validity. However, the meta-analysis study by Rauch et al. (2009) shows that most of the studies use an one-dimensional scale to measure entrepreneurial orientation.
Network competence
The concept of network competence has been conceived as a two-dimensional construct related to the degree of network management task execution and to the degree of network management qualification possessed by those who handle firm's relationships (Ritter et al. 2002). The original scale consists of 22 items that measure two dimensions. This study focuses on the first dimension-task-execution from relationship-specific to cross-relational tasks-that was measured by 11 items. The second dimension-social and specialist qualifications possessed by the networking management team-was not included in the model, because the population at study is characterized mostly by Portuguese SMEs, whose management skills are concentrated in the owner given the lack of managerial team supporting him/her.
Dynamic capabilities
Dynamic capabilities are measured by the scale of organizational dynamic capabilities of Hung et al. (2010). It contains 11 items: 4 evaluate the organizational strategic capability; 3 measure the R&D innovative capability; and 4 assess the organizational management capability.
Firm performance
Firm performance is measured by six items, focusing on changes in terms of competitive advantage, market share, profits, costs, sales, and customer satisfaction (Hung et al. 2010). Since this construct takes the main competitor into account, it reflects the relative advantage of the firm. The 7-point Likert scale from 1-completely disagree to 7-completely agree was used to measure all items used to evaluate all constructs of the study, with the exception of entrepreneurial orientation.
Control variables
A set of control variables associated with performance that were identified in previous studies (Dai et al. 2013;Ge and Wang 2012;Zahra and Garvis 2000;Zhou and Wu 2014) are included: firm size (measured by the number of employees and turnover), age, industry, and location. Some of these variables were categorized to facilitate data collection and analysis.
Firm size
The firm size was controlled because large firms have more resources, which influences its willingness and capability of internationalization, innovation, opportunitiesdetection (Chen et al. 2012;Ge and Wang 2012;Zahra and Garvis 2000;Zhou and Wu 2014), the dynamic capabilities development (Drnevich and Kriauciunas 2011),and their relationship with competitive advantage (Li and Liu 2014). Regarding the number of employees (Ge and Wang 2012;Wilden et al. 2013), the study categorizesfirms into 3 groups: less than 10, between 10 and 49, and 50 or more employees. The turnover variable, which can also be used to measure the firm size, is divided into 4groups: less than 50,000€, between 50,000 and 250,000€, between 250 001 and 1 million €, and more than 1 million € 3.1.6.2 Firm age Firm age is likely to influence the level of international operations and entrepreneurial activity (Zahra and Garvis 2000). Additionally, younger firms tend to have access to limited resources, which can affect their capability for opportunities exploration and the relationship between dynamic capabilities and results (Li and Liu 2014). The sample was classified into four groups: up to 10 years, between 11 and 15 years, between 16 to 25 years, and more than 25 years.
Firm industry
We used industry variable as firms from different sectors show differences in entrepreneurial activities. Moreover, different industries face distinct competitive challenges, which can explain different views on the commitment of their managers regarding internationalization and unequal opportunities and hence distinct levels of firm performance (Dai et al. 2013;Zahra and Garvis 2000;Zhou and Wu 2014). The industry variable was divided into three categories: services, manufacturing, and commerce.
Location
This variable encompasses the four Portuguese statistical regions: NUTS II North, NUTS II Lisbon, NUTS II Center, and South and Portuguese islands that includes Alentejo, Algarve, Azores, and Madeira.
Scale validation
Confirmatory factor analysis was applied to assess the reliability and validity of the scales of measurement used in this study. A threshold of 0.5 was set as minimum for the standardized factor loadings. Thereby, it was necessary to eliminate items with low factor loadings, indicating poor reliability of the item as measurement of the construct (a factor loading of 0.5 means that the construct only explains 25.0% of the variance of the item). As a result, the final selection of retained items was: three for the scale of leaders' commitment to exporting; seven for the one-dimensional scale of dynamic capabilities; six for the network competence; five for the onedimensional scale of entrepreneurial orientation; and five for the firm performance. The list of items kept in the analysis is provided in the "Appendix".
Reliability of the measures is assessed by the Cronbach's alpha, the composite reliability (CR), and the average variance extracted (AVE). CR and AVE were evaluated as described by Fornell and Larcker (1981). A good consistency, acceptable consistency, and weaker consistency is reached for a Cronbach's alpha greater than 0.80, between 0.60 and 0.80, and below 0.6, respectively (Hair et al. 2010). Table 2 summarizes the results on reliability. Almost all Cronbach's alpha and CR values exceed 0.8 and AVE exceeds the 0.5 value, suggesting that the indicators of each variable have good internal consistency, except entrepreneurial orientation that has an acceptable consistency (Cronbach's alpha between 0.6 and 0.8). Overall, constructs are measured by the retained items.
Results
We estimated the structural equation model (SEM) by the maximum likelihood method in order to test the hypotheses and the impact of the five control variables on performance. The fit of the structural equation model is checked using the chisquare test. As it is sample size sensitive, the following fit indices were also applied: Comparative Fit Index (CFI), Tucker-Lewis index (TLI), and Root Mean Square Error of Approximation (RMSEA).
Results show that the model has a very good fit to the variance and covariance structure of the analyzed items: 2 (663) = 61, 849.693 , 2 ∕df = 93.288 , Comparative fit index = 0.988, Tucker-Lewis index = 0.987, RMSEA = 0.035, P 0.033;0.038 |
<filename>app/src/test/contrib/components/Responsibilities/ModelRunParameters/ModelRunParametersStatusTests.tsx
import * as React from "react";
import {shallow} from "enzyme";
import {Store} from "redux";
import "../../../../helper";
import {
mockDisease,
mockModellingGroup,
mockModelRunParameterSet,
mockTouchstoneVersion
} from "../../../../mocks/mockModels";
import {Sandbox} from "../../../../Sandbox";
import {createMockContribStore, createMockStore} from "../../../../mocks/mockStore";
import {ContribAppState} from "../../../../../main/contrib/reducers/contribAppReducers";
import {LoadingElement} from "../../../../../main/shared/partials/LoadingElement/LoadingElement";
import {
ModelRunParametersStatus,
ModelRunParametersStatusComponent,
ModelRunParametersStatusProps
} from "../../../../../main/contrib/components/Responsibilities/ModelRunParameters/ModelRunParametersStatus";
import {longestTimestamp} from "../../../../../main/shared/Helpers";
import {ModelRunParameterDownloadCertificate} from "../../../../../main/contrib/components/Responsibilities/ModelRunParameters/ModelRunParameterDownloadCertificate";
import {FileDownloadLink} from "../../../../../main/shared/components/FileDownloadLink";
describe("Model Run Parameters Status component tests", () => {
const testGroup = mockModellingGroup({ id: "group-1" });
const testDisease = mockDisease();
const testTouchstone = mockTouchstoneVersion({ id: "touchstone-1" });
const testRunParametersSet = mockModelRunParameterSet({disease: testDisease.id, id: 1});
const testState = {
groups: {currentUserGroup: testGroup},
touchstones: {currentTouchstoneVersion: testTouchstone},
runParameters: {sets: [testRunParametersSet], tokens:{[testRunParametersSet.id]: 'test-token'}}
};
let store : Store<ContribAppState>;
const sandbox = new Sandbox();
beforeEach(() => {
store = createMockContribStore(testState);
});
afterEach(() => sandbox.restore());
it("renders on connect level", () => {
const rendered = shallow(<ModelRunParametersStatus disease={testDisease.id}/>, {context: {store}});
expect(rendered.props().touchstone).toEqual(testTouchstone);
expect(rendered.props().group).toEqual(testGroup);
expect(rendered.props().set).toEqual(testRunParametersSet);
expect(rendered.props().disease).toEqual(testDisease.id);
});
it("renders on branch level, passes", () => {
const rendered = shallow(<ModelRunParametersStatus disease={testDisease.id}/>, {context: {store}}).dive();
expect(rendered.find(ModelRunParametersStatusComponent).length).toEqual(1);
});
it("renders on branch level, not passes", () => {
store = createMockStore({...testState, touchstones: {currentTouchstone: null}});
const rendered = shallow(<ModelRunParametersStatus disease={testDisease.id}/>, {context: {store}}).dive().dive();
expect(rendered.find(LoadingElement).length).toEqual(1);
});
it("renders on component level, shows alert if no set received ", () => {
store = createMockStore({...testState, runParameters: {...testState.runParameters, sets: []}});
const rendered = shallow(<ModelRunParametersStatus disease={testDisease.id}/>, {context: {store}}).dive().dive();
expect(rendered.find('Alert').find('span').text()).toBe(`You have not uploaded any parameter sets for ${testDisease.id}`);
});
it("renders on component level, shows message of downloadable files", () => {
const rendered = shallow(<ModelRunParametersStatus disease={testDisease.id}/>, {context: {store}}).dive().dive();
expect(rendered.find("Alert").find('span').text()
.indexOf(`You last uploaded a parameter set on ${longestTimestamp(new Date(testRunParametersSet.uploaded_on))}`))
.toEqual(0);
});
it(
"renders on component level, passes params to certificate download",
() => {
const rendered = shallow(<ModelRunParametersStatus disease={testDisease.id}/>, {context: {store}}).dive().dive();
const certificate = rendered.find(ModelRunParameterDownloadCertificate);
expect(certificate.props().set).toEqual(testRunParametersSet);
}
);
it("renders on component level, passes URL to set download link", () => {
const props: ModelRunParametersStatusProps = {
disease: testDisease.id,
group: testGroup,
set: testRunParametersSet,
touchstone: testTouchstone
};
const rendered = shallow(<ModelRunParametersStatus {...props}/>, {context: {store}}).dive().dive();
const button = rendered.find(FileDownloadLink);
expect(button.prop("href")).toEqual("/modelling-groups/group-1/model-run-parameters/touchstone-1/1/");
});
}); |
// For Cloud SQL volumes, contains the specific instances that should be mounted. Visit https://cloud.google.com/sql/docs/mysql/connect-run for more information on how to connect Cloud SQL and Cloud Run.
func (o GoogleCloudRunOpV2VolumeResponseOutput) CloudSqlInstance() GoogleCloudRunOpV2CloudSqlInstanceResponseOutput {
return o.ApplyT(func(v GoogleCloudRunOpV2VolumeResponse) GoogleCloudRunOpV2CloudSqlInstanceResponse {
return v.CloudSqlInstance
}).(GoogleCloudRunOpV2CloudSqlInstanceResponseOutput)
} |
<gh_stars>0
package bootcommand
import (
"testing"
"github.com/hashicorp/packer/template/interpolate"
)
func TestConfigPrepare(t *testing.T) {
var c *BootConfig
// Test a default boot_wait
c = new(BootConfig)
c.RawBootWait = ""
errs := c.Prepare(&interpolate.Context{})
if len(errs) > 0 {
t.Fatalf("bad: %#v", errs)
}
if c.RawBootWait != "10s" {
t.Fatalf("bad value: %s", c.RawBootWait)
}
// Test with a bad boot_wait
c = new(BootConfig)
c.RawBootWait = "this is not good"
errs = c.Prepare(&interpolate.Context{})
if len(errs) == 0 {
t.Fatal("should error")
}
// Test with a good one
c = new(BootConfig)
c.RawBootWait = "5s"
errs = c.Prepare(&interpolate.Context{})
if len(errs) > 0 {
t.Fatalf("bad: %#v", errs)
}
}
func TestVNCConfigPrepare(t *testing.T) {
var c *VNCConfig
// Test with a boot command
c = new(VNCConfig)
c.BootCommand = []string{"a", "b"}
errs := c.Prepare(&interpolate.Context{})
if len(errs) > 0 {
t.Fatalf("bad: %#v", errs)
}
// Test with disabled vnc
c.DisableVNC = true
errs = c.Prepare(&interpolate.Context{})
if len(errs) == 0 {
t.Fatal("should error")
}
// Test no boot command with no vnc
c = new(VNCConfig)
c.DisableVNC = true
errs = c.Prepare(&interpolate.Context{})
if len(errs) > 0 {
t.Fatalf("bad: %#v", errs)
}
}
|
/**
* A cache of PropertyEditorAdaptors
*/
@ApplicationScoped
public class PropertyEditorAdaptorsCache {
@Inject
private SyncBeanManager iocManager;
private Set<PropertyEditorAdaptor> adaptors = new HashSet<PropertyEditorAdaptor>();
@PostConstruct
private void setup() {
this.adaptors = getAvailableAdaptors();
}
public Set<PropertyEditorAdaptor> getAdaptors() {
return adaptors;
}
private Set<PropertyEditorAdaptor> getAvailableAdaptors() {
final Set<PropertyEditorAdaptor> factories = new HashSet<PropertyEditorAdaptor>();
final Collection<SyncBeanDef<PropertyEditorAdaptor>> factoryBeans = iocManager.lookupBeans( PropertyEditorAdaptor.class );
for ( SyncBeanDef<PropertyEditorAdaptor> factoryBean : factoryBeans ) {
factories.add( factoryBean.getInstance() );
}
return factories;
}
} |
def health(request):
if SANDBOX_MODE and request.headers.get("sandbox-mode", str(SANDBOX_MODE)).lower() != 'true':
request.response.status = "400 Sandbox modes mismatch between proxy and bot"
return '' |
In Silico Analysis of Seven PCR Markers Developed from the CHD1, NIPBL and SPIN Genes Followed by Laboratory Testing Shows How to Reliably Determine the Sex of Musophagiformes Species
Sex determination in birds, due to the very common lack of sexual dimorphism, is challenging. Therefore, molecular sexing is often the only reliable way to differentiate between the sexes. However, for many bird species, very few genetic markers are available to accurately, quickly, and cost-effectively type sex. Therefore, in our study, using 14 species belonging to the order Musophagiformes, we tested the usefulness of seven PCR markers (three of which have never been used to determine the sex of turacos), developed based on the CHD1, NIPBL, and SPIN genes, to validate existing and develop new strategies/methods of sex determination. After in silico analysis, for which we used the three turaco nuclear genomes available in GenBank, the suitability of the seven selected markers for sexing turacos was tested in the laboratory. It turned out that the best of the markers tested was the 17th intron in the NIPBL gene (not previously tested in turacos), allowing reliable sex determination in 13 of the 14 species tested. For the one species not sexed by this marker, the 9th intron in the CHD1 gene proved to be effective. The remaining markers were of little (4 markers developed based on the CHD1 gene) or no use (marker developed based on the SPIN gene).
Introduction
Modern birds (the subclass Neornithes), which are divided into two clades, Palaeognathae (ratites and flying tinamous) and Neognathae (all other extant birds), are represented by more than 10,000, highly diverse species, spread throughout the world. Such great diversity of extant birds was initiated by their ancestors that survived a mass extinction event (66 million years ago) and then evolved into such a large number of species . Despite the high phenotypic variability that characterizes birds, sexual dimorphism is absent or hardly noticeable in many bird species (they are monomorphic). Even in sexually dimorphic birds, distinguishing sex in chicks based on morphological features is rarely possible. This causes serious problems because sex determination is crucial in ecological and demographic studies, in captive breeding for conservation programs, in efficient reproduction in zoos, and in scientific research . Despite being challenging, there are many methods for sexing birds that can be divided into invasive (e.g., morphometric measurement, cloacal examination, laparotomy, and laparoscopy) and noninvasive (e.g., behavior observation, the ratio assay between estrogen and androgen in faces) . However, the sexing methods listed are not accurate enough, and the invasive ones often put the birds at risk of injury. Therefore, molecular sexing of birds has become a non-invasive (or minimally invasive) and accurate method for reliable, rapid, and cost-effective sex differentiation.
The most widely used molecular methods to determine the sex of birds are based on PCR (Polymerase Chain Reaction) markers developed using the conserved CHD1 (the PCR (Polymerase Chain Reaction) markers developed using the conserved CHD Chromo Helicase DNA binding protein gene) , NIPBL (the Nipped-B homolo , SPIN (the Spindlin gene) and RASA1 (the RAS p21 protein activator 1 gen The basis of using these genes for avian sex typing is detecting differences betwee copies located on Z and W sex chromosomes (in birds, a sex chromosomal syste ZW heterogametes in females and ZZ homogametes in males occurs ). One o differences is the length polymorphism of introns in avian genes located on differ chromosomes. This allows the amplification of specific gene fragments located o and W sex chromosomes and their subsequent separation in agarose or polyacry gels. In males, a single PCR product appears (a gene copies from the two Z chrom are usually of identical length), while in females, two products are detected due length polymorphism of the copies of genes located on the chromosomes Z and Various methods and molecular markers used to determine the sex of many bird have been described, applied or reviewed by a number of authors . Des tempts to find a single universal DNA marker useful for sexing birds, this has so f unsuccessful .
One of the many orders that belong to the class Aves are the (Musophagiformes). They are endemic to Sub-Saharan Africa, arboreal, usually b colored, and almost exclusively herbivorous . According to Perktaş et al. . The species studied in this paper are indicated in bold. . The species studied in this paper are indicated in bold.
With the exception of the white-bellied go-away-bird (Crinifer leucogaster), turaco species do not exhibit sexual dimorphism , therefore molecular sexing is the only reliable way to determine the sex of species in this avian order. To our knowledge, three PCR markers (primer sets) developed based on the CHD1 gene were used for molecular sexing of the turacos: P2/P8 for sex typing of Corythaeola cristata , 1272H/1237L for sex typing of C. cristata and Tauraco persa , and 2550F/2718R for sex typing of T. persa . Additionally, markers developed using the SPIN gene (USP1/USP3 and INT-F/INT-R, multiplex PCR ) were used for sexing Musophaga violacea , P2/P8 + EcoRI (PCR-RFLP) for sexing T. persa , and P2/NP/MP (multiplex PCR) for sexing T. persa . As can be seen from the studies cited, only three taxa of turacos have been molecularly sexed using these markers. In addition, some reports cannot be considered sufficiently reliable because images of the electrophoretic patterns of amplicons obtained for the individuals tested were not provided or only one individual was studied . Furthermore, when we used the Basic Local Alignment Search Tool (BLAST) to search the nuclear genomes of selected species of the order Musophagiformes, available in the database, we did not find the amplicon sequences used by Jensen et al. for sex determination in C. cristata.
With this in mind, using a relatively large group of species representing the family Musophagidae (fourteen out of thirty-three recognized species), we tested the usefulness of seven PCR markers (three of which have never been used to determine the sex of turacos) to validate existing and develop new strategies/methods of sex determination for a wide range of turaco species. Here, we present the results of this investigation.
Biological Samples and DNA Extraction
Thanks to the courtesy of the Wrocław Zoological Garden and private breeding facilities in Poland, we were able to collect blood and feather samples from fourteen turaco species (86 individuals in total). From the Wroclaw Zoo, we received blood samples from male and female M. violacea, blood samples from male Crinifer personatus, and feather samples from female C. personatus. Blood samples of males and females of the remaining twelve turaco species came from private Polish breeding centers. The sex of the tested individuals was determined using a laparoscope (both C. personatus from the Wrocław Zoo), or blood samples were taken from selected breeding pairs that had repeatedly reared their offspring (the other species studied). Detailed information on the studied turaco species and differences in the names of the studied taxa suggested by different authors are given in Table 1. In our study, we used the new classification of the family Musophagidae developed by Perktaş et al. .
Blood samples were collected for laboratory analysis as dry blood spots on a fiber filter to prevent potential microbial degradation of blood cells and degradation of genomic DNA. They were then preserved in parafilm-sealed Eppendorf tubes at −20 • C until use to avoid dampness. For freshly collected breast feather samples, the feather shafts were cut off and stored under the same conditions until use. Total DNA was extracted from both tissue types using the Sherlock AX Kit (A&A Biotechnology, Gdynia, Poland) according to the manufacturer's protocol.
We tested the use of seven different amplicons (named for the purpose of this study M1, M2, M3, M4, M5, M6 and M7) as potential markers for sexing turaco taxa using the previously described PCR primers. The details of the primers used (names, sequences and references) are given in Table 2. 35 times, and 72 • C 5 min. For each amplified fragment, 5 µL of the PCR reaction mixtures was loaded onto the 1%, 2% or 3% agarose gels. The gel contained ethidium bromide at a concentration of 0.5 µg/mL. The electrophoresis was performed in 1× TAE buffer at a voltage of 5 V/cm.
In Silico Analysis of the Genetic Markers Tested
Genome resources from the GenBank database were searched for nuclear genomes of Musophagiformes. The available genomes were checked for annotation of the chromosomes and genes located on them. The genome of male T. erythrolophus (GenBank assembly accession: GCA_000709365.1) was used to analyze the structure of the CHD1, SPIN, and NIPBL genes. Their entire sequences and exon sequences were aligned using the MEGA program to determine the length and position of the introns within the genes analyzed. Next, to predict the size of the potential Z-specific amplicons for the seven markers analyzed, the appropriate forward and reverse primers were aligned with the sequences of the CHD1, SPIN, and NIPBL genes using the MEGA program . To define the position of characterized Z-specific amplicons within the genes analyzed, the appropriate primer locations were compared with their exon/intron structure. To find W-specific amplicons, the genome of female T. erythrolophus (GenBank assembly accession: GCA_009769465.1) was searched using BLAST (Basic Local Alignment Search Tool) and the sequences of identified Z-specific amplicons as queries. The two-copy sequences (Z-and W-specific) of the markers tested were aligned using the MUSCLE algorithm in MEGA . The same approach was used for the rest of the available turaco genomes.
In Silico Analysis of the Gene Content of T. erythrolophus Chromosomes
Genome Data Viewer was used to check if genes identified by Smeds et al. on the Z chromosome of Collared flycatcher (Ficedula albicollis) are also located on the Z chromosome of Melopsittacus undulatus (NC_047557). The exon sequences for 42 identified genes were then downloaded. Using BLAST and selected exons of these genes as query sequences, we searched the nuclear genome of female T. erythrolophus. Information on their genomic location was used to determine their chromosomal positions.
In Silico Analysis of the Genetic Markers Tested
Before laboratory testing, in silico analysis of seven selected PCR markers (M1, M2, M3, M4, M5, M6, M7), which are introns located in three genes (CHD1, SPIN, and NIPBL) was performed. Its purpose was to verify whether the amplicon sequences to be used for turaco sexing have Z and W-specific copies (variants located on the Z and W sex chromosomes) and whether there is a polymorphism in their length that would allow distinguishing male from female.
Searching GenBank resources, we found nuclear genomes of three species of turacos: Crinifer concolor (GenBank assembly accession: GCA_013399495.1-BioSample: SAMN12253899, female only); C. cristata (GenBank assembly accession: GCA_013396815.1-BioSample: SAMN12253763, male only), and T. erythrolophus (GenBank assembly accession: GCA_ 000709365.1-BioSample: SAMN02339893-for male, and GenBank assembly accession: GCA_ 009769465.1-BioSample: SAMN12621036-for female). After analysis of the retrieved nuclear genomes, it turned out that only scaffolds with unknown gene coding regions (CDSs-coding DNA sequences) were available for the first two species. Furthermore, there was no information on their location on the avian chromosomes. For the third species (T. erythrolophus), 16,054 CDS were identified in the male genome (but the number and length of chromosomes has not been determined), while no CDSs were provided in the female genome, but 33 chromosomes were identified in its assembly (31 +Z/W). Since CDSs were only determined in the genome of male T. erythrolophus, this genome was used to analyze the structure of genes containing marker sequences (CHD1, SPIN, and NIPBL).
For the CHD1 gene (GenBank assembly accession NW_010038079.1-73,805 bp) and the SPIN gene (GenBank assembly accession NW_010072932.1-49,958 bp), their entire sequences and exon sequences could be found (exon sequences: CHD1-XM_009991467.1-mRNA length 6.776 bp; SPIN-XM_009988563.1-mRNA length 4.346 bp). However, intron sequences were not available. Regarding the NIPBL gene, four sequences were available for four different loci (LOC104371354, LOC104370058, LOC104383964 and LOC104377353). To select the right one for our study, we used BLAST (Basic Local Alignment Search Tool) to search the nuclear genome of Tauraco erythrolphus. Using the Z-specific sequence of intron sixteen in the NIPBL gene (NIPBLi16) of Columba palumbus (Accession: JF279580.1) as a query, we searched the Z chromosome (WOXW01000129.1-93,020,717 bp) of female T. erythrolphus (assembly GCA_009769465.1). As a result, we found the corresponding sequence of length 801 bp, which was located at LOC104377353. Therefore, we found that the sequence of this locus (out of four available in GenBank) is the correct NIBPL gene for our analysis (GenBank assembly accession NW_010032872.1-102.535 bp; exon sequences-XM_009984506.1-mRNA length 4.972 bp).
The selected sequences allowed us to determine the exact position and length of exons and introns (Supplementary Table S1) within the CHD1, SPIN, and NIPBL genes. We then related the position of the primers used to amplify markers M1-M7 (Table 2) to the positioned exons and introns. In this way, we determined the sizes and sequences of potential Z-specific amplicons (Table 3), as well as which introns would be amplified and the lengths of the exons flanking them (Table 3). We found that M2 is an inner variant of M1, and M5 is an inner variant of M4 (it means that the same intron is amplified by different primers located on different positions in the flanking exons; this is indicated by the mutual location of the following primers: P8 and 1272 H; P2 and 1237 L; 2550 F and CHD1i16-F; 2718R and CHD1i16-R). Our analysis also showed that the NIPBL primers in T. erythrolphus amplify intron 17 rather than intron 16. Unfortunately, we could not obtain information for SPIN because the MEGA program did not find sequences within this gene that matched the sequences of the primers used for M6 (Table 3). Table 3. Components of M1-M7 amplicons predicted based on the location of the appropriate primer pairs within the CHD1, SPIN, and NIPBL genes. The lengths of the amplified exon (E) and intron (I) fragments are given in brackets. Afterwards, Z-specific M1-M5 and M7 amplicons obtained for male T. erythrolophus (BioSample: SAMN02339893), were used to search the genome of the female of this species (BioSample: SAMN12621036). This analysis revealed that the amplicon sequences for M1-M5 and M7 identical in length and sequence (100% identity) to those previously found in the male were located on the Z chromosome in the female (GenBank WOXW01000129.1-93,020,717 bp) (Table 4). Interestingly, second copies of the sequences of these amplicons were additionally found in the female genome, but differed in length from the Z-specific copies. For M1 and M2, the length difference was 11 bp, for M3 it was 2374 bp, for M4 and M5 it was 43 bp, and for M7 it was 413 bp. The Z-specific copy was shorter for M1 and M2, while for M3, M4, M5 and M7 the Z-specific copy was longer. This indicates the possible use of these markers for sex typing (length polymorphism occurs). The results of this alignment are visualized in Supplementary Figure S1. Table 4. Turaco species analyzed in this study for length polymorphisms of the ninth, sixteenth, and twenty-second intron of the CHD1 gene and the seventeenth intron of the NIPBL gene. The accession numbers and lengths of the identified fragments, as well as their assigned sex and biosample numbers, are shown. A single (*) or double (**) asterisk indicates different copies of the respective introns identified for T. erythrolophus. A copy with only a partial sequence identified for C. cristata is indicated with (p). The same in silico analysis as for the female T. erythrolophus was conducted for female C. concolor (BioSample: SAMN12253899) and male C. cristata (BioSample: SAMN12253763). In female C. concolor, two copies of M1, M2, M4, and M5 were found on different scaffolds (VXAM01002689.1-14,797 bp, and VXAM01001990.1-45,938 bp). However, for these four markers, both copies were identical in length. For M3 and M7 only one copy was found. The length of the M3 sequence corresponds to the longer copy, and the length of the M7 sequence corresponds to the shorter copy previously found in T. erythrolophus (Table 4). No M1 and M2 amplicon sequences were found in the genome of male C. cristata, and only one sequence corresponding to the Z-specific copy of male and female T. erythrolophus was correctly found for M3. Additionally, for M4 and M5 only one sequence was found for each amplicon. Both amplicon sequences were much longer than the sequences found for C. concolor and T. erythrolophus (Table 4). In the case of M7, only a fragment of the amplicon sequence was found at positions 1 to 525 of the 1255 bp long WBMX01031976.1 scaffold, corresponding to positions 398 to 923 of the reference sequence. So, it seems that this is not a shorter version of the amplicon, but an incomplete longer version.
Marker
Only in the case of intron 17 in the NIPBL gene (M7) its second copy was found on the W chromosome (WOXW01000067.1-29,633,611 bp). The other second copies of the markers tested (M1-M5) were located on scaffold 37 (GenBank: WOXW01000076.1) with a length of 1,556,041 bp. Therefore, the question arises of whether the second copy of the CHD1 gene is located on the W chromosome. To answer this question, exons and introns of the CHD1 gene (Supplementary Table S1) were used as reference sequences (queries) to BLAST the genome of female T. erythrolophus. The results of this analysis are shown in Supplementary Table S2. Unfortunately, for most queries, analogous sequences were found on scaffold 37, where the query cover for exons and introns was 92-100% (identity 83.45% to 97.62%) and 10-100% (identity 66.78% to 92.32%), respectively. Only one sequence was found on the W chromosome that strongly matches the Z-copy-the 9th intron with a query cover of 80% and an identity of 84.30%. The other sequence found-the 1st intron-had a higher identity (92.89%), but with a very low query cover of 16%. On the contrary, all identified exons of the NIPBL gene (Supplementary Table S1) have their counterparts on the W chromosome with a query cover of 99-100% (with identities ranging from 90.42% to 98.89%), and most introns (except intron 11) have their copies on the W chromosome where the query cover ranges from 40% to 100% with identities ranging from 74.72% to 99.41% (Supplementary Table S3). In light of these results, it is difficult to determine with certainty whether scaffold 37 is a fragment of an incorrectly assembled W chromosome or whether the W copy of the CHD1 gene has translocated to another part of the nuclear genome.
In an attempt to answer this question we determined the gene contents of the T. erythrolophus Z chromosome (WOXW01000129.1-93,020,717 bp), W chromosome (WOXW01000067.1-29,633,611 bp) and scaffold 37 (WOXW01000076.1-1,556,041 bp). We searched for 42 genes identified by Smeds et al. on the Z chromosome in C. flycatcher (F. albicollis) (see Table 1 in the cited paper; two genes were omitted in our analysis: novel1 and novel2). This analysis revealed that 41 of the 42 selected genes were found on the Z chromosome of T. erythrolophus. Information on their chromosomal location allowed us to determine their positions on the Z chromosome ( Figure 2). Only one of these 42 genes (RPL37) was found on the W chromosome. The 14 genes located on the Z chromosome (indicated in bold and CHD1 indicated in red) were not found on the W chromosome. The CHD1 gene and HINT1 were identified on scaffold 37. Therefore, it is still unclear what scaffold 37 is, whether it is a microchromosome or a missing fragment of an incorrectly assembled W chromosome. To summarize our in silico analysis, we concluded that there is a need for laboratory verification of the presence of the sequences of the markers studied (M1-M7) in the nuclear genomes of the fourteen turaco species analyzed and to identify possible length differences between the Z-copies and the second copies of these amplicons. Except for NIPBL To summarize our in silico analysis, we concluded that there is a need for laboratory verification of the presence of the sequences of the markers studied (M1-M7) in the nuclear genomes of the fourteen turaco species analyzed and to identify possible length differences between the Z-copies and the second copies of these amplicons. Except for NIPBL (M7) having a second copy located on the W chromosome, it is not known whether the second copies of markers associated with the CHD1 gene are located on the W chromosome or in another part of the genome (this question requires further research). In this context, it is of particular interest whether markers M1-M5 can still be considered sex-specific and whether there are more than two copies of these amplicons due to their potential jumping in the genome (perhaps they are TEs -Transposable Elements). This scenario cannot be ruled out because according to Peona et al. , the density of transposable elements of the avian W chromosome exceeds 55%, compared to less than 10% genome-wide density. An earlier study by Suh et al. also detected insertions of retroposons (mobile elements that integrate randomly in genomes) into introns 9 and 16 of the avian CHD1 gene.
Laboratory Verification of the Usefulness of the Tested Markers for Sex Typing in the Turaco Species Studied
Laboratory tests of PCR markers developed based on the CHD1 gene (M1-M5), the SPIN gene (M6), and the NIPBL gene (M7) allowed us to verify information (earlier obtained through our in silico analysis and previously published sparse reports ) on their suitability for sex typing of 14 studied species belonging to the order Musophagiformes, and to recommend those PCR markers that reliably, rapidly, and cost-effectively enable sex determination in a wide range of species. It is worth emphasizing that three of the seven markers we tested (M3, M5, and M7) have never been used to determine the sex of turacos.
Markers M1 and M2 were previously tested for sexing two species belonging to the order Musophagiformes: C. cristata and T. persa . For C. cristata (we did not study this species in the laboratory), the authors reported that both M1 and M2 can be used for sex determination. However, in our in silico study (Table 4), when we searched the nuclear genome of this species (using BLAST), we could not find the sequences of both amplicons. In the case of T. persa, the cited authors tested M2, showing that this marker effectively determines sex. However, the authors did not provide images of the banding patterns or the number of males and females tested. In our study, M2 did not allow sex Figure 3. Patterns of the PCR products representing M1 (A) and M2 (B) markers obtained for male (M) and female (F) individuals of fourteen turaco species (S1-S14, see Table 1). The amplicons were resolved in 2% agarose gel. The amplicons resolved in 3% agarose gel (S2 and S5) are shown in (C). Lane 1 kb-GeneRuler 1 kb DNA Ladder (Thermo Scientific, Waltham, MA, USA). Lane LR-FastRuler Low Range DNA Ladder (Thermo Scientific).
The M3 marker (CHD1i9) due to the distinct differences in the size of the Z and W amplicons (500 bp) was suggested for molecular sex determination of Neoaves . However, so far it has not been tested in species belonging to the order Musophagiformes. The results of our analysis showing the suitability of this marker for sexing turacos are shown in Figure 5A. A single amplicon of ~600 bp is evident for females of all species, which and female (F) individuals of fourteen turaco species (S1-S14, see Table 1). The amplicons were resolved in 2% agarose gel. The female amplicons resolved in 3% agarose gel (S2-S5) are shown in (C). Lane 1 kb-GeneRuler 1 kb DNA Ladder (Thermo Scientific). Lane LR-FastRuler Low Range DNA Ladder (Thermo Scientific). pattern, the M3 marker is of little use for sexing the vast majority of species tested S14). It is specific mainly to W amplicons, and additional bands make interpretation result difficult. The only species tested for which M3 can be used for sex determinat S1, because in the female it yields in silico predicted amplicons of 600 bp and 3000 bp additional 2400 bp amplicon observed in the male S1 does not affect the interpret because in this species no artifact appears in the male (a nonspecific band at a leve corresponds to the female 600 bp band). and female (F) individuals of fourteen turaco species (S1-S14, see Table 1). The amplicon resolved in 1% agarose gel. Lane 1 kb-GeneRuler 1 kb DNA Ladder (Thermo Scientific).
Reports by other authors on the use of PCR markers for sex determination in tu describe the use of more time-consuming and expensive methods such as PCR-RFLP mer set P2/P8 + EcoRI) and multiplex-PCR (primer set P2/NP/MP) . In both the authors tested T. persa. Although the reported results confirm the efficacy of the ods and markers tested (developed from the CHD gene), their reliability should be tr with caution. In the first case , only one female sample was tested and the autho not provide images of banding patterns, and in the second case only one sa supposedly a male, was tested.
Length Polymorphism of the 17th Intron in the NIPBL Gene
The M7 marker (NIPBLi17), like M3, has not been previously tested for sex typ turaco species. It was recommended by Suh et al. as a reliable marker for sex mination of Neoaves. It appears in the literature as NIPBLi16 (intron 16 of the N gene). However, our thorough in silico analysis revealed that M7 in the and female (F) individuals of fourteen turaco species (S1-S14, see Table 1). The amplicons were resolved in 1% agarose gel. Lane 1 kb-GeneRuler 1 kb DNA Ladder (Thermo Scientific).
We used a 2% agarose gel to test M1 and M2 ( Figure 3A,B) because our in silico analysis for T. erythrolophus indicated that a small size difference (11 bp) between the Z and Wspecific copies of these markers would be expected (Table 4). In the case of M1 ( Figure 3A), only one Z-specific amplicon of~380 bp in length was detected for all species tested, which corresponds to our earlier performed in silico analyzes. The W-specific amplicon is not visible, which may be due to its length being similar to that of the Z-specific amplicon (they cannot be separated in a 2% agarose gel). However, the indistinct band for the female S2 may indicate the presence of two unseparated fragments. A similar situation was observed for M2, which is an inner variant of M1 ( Figure 3B). Only one Z-specific amplicon with a length of 250-260 bp is visible in all tested species, which corresponds to the results of in silico studies. If the W-specific amplicon is present, it is very similar in size to the Z-specific amplicon, and in a 2% agarose gel the two fragments cannot be separated. However, the indistinct band for S2 female may indicate the presence of two unseparated fragments. Furthermore, nonspecific bands of~700 bp are observed in S1 and S2, and additional nonspecific bands of~2000 bp and~4000 bp are observed in S3 and S5, respectively. As potentially unseparated bands were observed in the 2% agarose gel for S2, we used a 3% agarose gel to separate the M1 and M2 amplicons obtained for both S2 and S5 ( Figure 3C). For S2, we were able to separate both M1 and M2. However, a very small length difference was found that corresponded to~10 bp. Furthermore, for S5 it was possible to separate M2, but the difference in length of the fragments was very small and it was difficult to visually distinguish the two bands.
Markers M1 and M2 were previously tested for sexing two species belonging to the order Musophagiformes: C. cristata and T. persa . For C. cristata (we did not study this species in the laboratory), the authors reported that both M1 and M2 can be used for sex determination. However, in our in silico study (Table 4), when we searched the nuclear genome of this species (using BLAST), we could not find the sequences of both amplicons. In the case of T. persa, the cited authors tested M2, showing that this marker effectively determines sex. However, the authors did not provide images of the banding patterns or the number of males and females tested. In our study, M2 did not allow sex typing in T. persa due to the small difference in length between Z and W-specific amplicons. In conclusion, M1 and M2 are not useful for sexing the studied turaco species using standard percentages of agarose gels. It is due to very small size differences between Z and W-specific amplicons, which are impossible to visualize in 1% and 2% agarose gel ( Figure 3A,B). The use of a 3% agarose gel allowed for separation Z and W-specific amplicons only in the case of S2 (M1 and M2) and S5 (M2) (illustrated in Figure 3C). It cannot be ruled out that M1 and M2 might be suitable for sexing turacos if high resolution equipment is used (polyacrylamine gels or capillary sequencers). However, these methods are more expensive and more elaborate, and thus less easy to use.
To test the usefulness of M4 and M5 in typing the sex of turacos, as with M1 and M2, we used a 2% agarose gel because in silico analysis (Table 4) indicated that a small size difference (43 bp) between Z and W-specific amplicons should be expected. In the case of M4, two separated Z and W-specific bands are seen for twelve (S3-S14) of the fourteen species studied ( Figure 4A). The Z-specific band of 490-500 bp matches the predictions of the in silico analysis (504 bp for T. erythrolophus). The W-specific amplicon of 460-470 bp in length is also clearly visible. In the case of S1 and S2, this marker proved to be useless as only the Z-specific amplicon is visible. For most of the remaining (successfully sexed) species, a faintly visible additional band above the Z-specific amplicon is visible in females. One might speculate why these additional faintly visible bands were detected. If we assume that the Z-specific M4 was duplicated, jumped elsewhere in the genome, and then some mutations occurred in the primer annealing sites of the copied sequence, this could have altered the primer annealing ability. As a result, additional PCR products (of varying lengths) may have appeared as faintly visible bands. This also raises the question of the location of the second copy of the CHD1 gene in the genome, is it located on the W chromosome, and if so, is it the only copy of the CHD1 gene (our in silico study did not find the CHD1 gene on the W chromosome, but located it in scaffold 37). These questions remain unanswered for now.
The M5 marker (which is an inner variant of M4) differentiates sex in the thirteen species studied, only in the case of S1 it is useless ( Figure 4B). The Z-specific amplicon of 460-470 bp, corresponding to our prediction from in silico analysis, is separated from the W-specific amplicon of 420-430 bp. For many species studied (both males and females), nonspecific bands of~380 bp in length are visible.
As the 2% agarose gel in S2 showed two separated bands for the M5 marker, but in the same individual two bands could not be detected for M4, samples of selected females (S2-S5) were tested on a 3% agarose gel to make sure how many amplicons (one or two) for these markers are actually produced ( Figure 4C). The results of this test revealed the unsuitability of the M4 marker for S2 sexing even in 3% agarose gel, and confirmed the small difference in the size of Z and W-specific amplicons in the other species tested. In conclusion, M4 and M5, due to the small difference in the length of Z and W-specific amplicons, are not reliable and easily interpretable markers when used to determine the sex of turacos, especially since additional bands are present in female samples for M4, and some nonspecific bands for M5 are observed in samples of both sexes.
The suitability of the M4 marker for sexing turacos (T. persa only) was studied by Vuicevic et al. and Wang et al. . Both authors reported the inability to determine the sex of the species studied using this marker (the first authors tested only two males, while the second authors reported only the conclusion without providing images of banding patterns). In our study, in T. persa, both Z and W-specific bands were separated and visualized in a 2% agarose gel. Regarding the M5 marker, to our knowledge it has not been previously tested for sex determination in turacos.
The M3 marker (CHD1i9) due to the distinct differences in the size of the Z and W amplicons (500 bp) was suggested for molecular sex determination of Neoaves . However, so far it has not been tested in species belonging to the order Musophagiformes. The results of our analysis showing the suitability of this marker for sexing turacos are shown in Figure 5A. A single amplicon of~600 bp is evident for females of all species, which corresponds with the results of our in silico analysis (Table 4). Unfortunately, a faint band,~600 bp in length, appears in many males. This is not necessarily the same band as in females, but it is difficult to determine this unambiguously in a 1% agarose gel (a 1% agarose gel was used because the expected difference in length between Z and W-specific amplicons was 2374 bp; see Table 4). The predicted in silico Z-specific amplicon of~3000 bp length appears only in S1, S5 and S11 males, as well as in S1 female. In addition, a third additional band of~1300 bp in length appears in S2 and S11 males. Due to the banding pattern, the M3 marker is of little use for sexing the vast majority of species tested (S2-S14). It is specific mainly to W amplicons, and additional bands make interpretation of the result difficult. The only species tested for which M3 can be used for sex determination is S1, because in the female it yields in silico predicted amplicons of 600 bp and 3000 bp. The additional 2400 bp amplicon observed in the male S1 does not affect the interpretation, because in this species no artifact appears in the male (a nonspecific band at a level that corresponds to the female 600 bp band).
Reports by other authors on the use of PCR markers for sex determination in turacos describe the use of more time-consuming and expensive methods such as PCR-RFLP (primer set P2/P8 + EcoRI) and multiplex-PCR (primer set P2/NP/MP) . In both cases, the authors tested T. persa. Although the reported results confirm the efficacy of the methods and markers tested (developed from the CHD gene), their reliability should be treated with caution. In the first case , only one female sample was tested and the authors did not provide images of banding patterns, and in the second case only one sample, supposedly a male, was tested.
Length Polymorphism of the 17th Intron in the NIPBL Gene
The M7 marker (NIPBLi17), like M3, has not been previously tested for sex typing in turaco species. It was recommended by Suh et al. as a reliable marker for sex determination of Neoaves. It appears in the literature as NIPBLi16 (intron 16 of the NIPBL gene). However, our thorough in silico analysis revealed that M7 in the order Musophagiformes is the 17th intron in the NIPBL gene (see Table 3). The results of testing this marker for sex typing in turacos are shown in Figure 5B. The M7 marker proved to be reliable and easy to interpret in determining the sex of the 13 species studied (S2-S14). Two bands, a~900 bp long Z-specific, and a~500 bp long W-specific, are clearly visible in a 1% agarose gel. The lengths of the Z and W amplicons detected correspond to our in silico predictions. For S1, only the Z-specific amplicon was detected, for both the female and the male, indicating that this marker is not useful for this species.
Testing of the M6 Marker Developed on the Basis of the SPIN Gene
Although our in silico analysis did not reveal Z and W-specific amplicon sequences representing the M6 marker in the turaco genomes examined (Table 4), we decided to test its utility by using the primer set USP1/USP3, which allows amplification of a W-chromosome specific amplicon. However, the use of this marker may not give reliable and conclusive results because the absence of an amplicon may indicate that the sample tested is a male, or it may falsely indicate a male due to degraded DNA (false identification of a male may then result from a mismatch between primers and a potentially recognized annealing site in the species tested). The results of our analysis are shown in Supplementary Figure S2. A Wspecific amplicon of~390 bp is clearly visible in females of species S2, S4 and S5. However, no Z-specific amplicons were detected in these species (both males and females). A faintly visible W-specific amplicon was also detected in female S3. No amplicons were detected in the remaining species (S1, S6-S14), which would indicate that there is a mismatch between the sequence at the SPIN gene annealing site and the primer sequence. Thus, it appears, that the M6 marker is not useful for sex determination of the species tested.
Markers developed from the SPIN gene (primer sets USP1/USP3 and INT-F/INT-R) for sex typing of a turaco species, M. violacea, were tested by Itoh et al. . The authors used multiplex-PCR and reported that both markers successfully sexed the species tested. However, when standard PCR is used, the set of primers USP1/USP3 produces only a W-specific amplicon.
To summarize our research, the PCR marker for sex determination of species belonging to the order Musophagiformes giving the most reliable and easy to interpret results is M7 (intron 17 in the NIPBL gene), which allows sex typing in thirteen (S2-S14) of the species we studied. The M3 marker (intron 9 in the CHD1 gene) proved to be the only marker allowing sex determination in S1. Although both M4 and M5 can be used for many turaco species (to determine the sex of S3-S14, and S2-S14, respectively), the M7 marker is more useful because its PCR products can be successfully separated in a 1% agarose gel. An additional advantage of this marker is that the sexing results (size difference between Z and W specific amplicons) can be visualized after only 10 min of electrophoresis ( Figure 6). For M4 and M5, two amplicons are detected in females after 60 min of electrophoresis.
Supplementary Materials:
The following supporting information can be downloaded at: www.mdpi.com/xxx/s1, Table S1: Number, position and length of exons and introns identified in CHD1, SPIN and NIPBL genes; Table S2: Identity of sequences homologous to the exons and introns of the Tauraco erythrolophus CHD1-Z gene, that were identified within Scaffold 37 or the W chromosome of this species; Table S3: Identity of sequences homologous to the exons and introns of the Tauraco erythrolophus NIPBL-Z gene, that were identified within the W chromosome of this species; Figure S1: Two-copy (Z and X-specific) sequence comparison of six markers (M1-M5 and M7) tested in this study. The alignments are shown for Tauraco erythrolophus. Dots indicate residues identical Figure 6. Patterns of the PCR products representing M4, M5 and M7 markers obtained for female individual of four turaco species (S7, S9, S10, and S14, see Table 1). The image shows the separation of amplicons in a 1% agarose gel after 10, 20, 30, 40 and 60 min of electrophoresis. Lane 1 kb-GeneRuler 1 kb DNA Ladder (Thermo Scientific). Lane LR-FastRuler Low Range DNA Ladder (Thermo Scientific).
Supplementary Materials:
The following supporting information can be downloaded at: https:// www.mdpi.com/article/10.3390/genes13050932/s1, Table S1: Number, position and length of exons and introns identified in CHD1, SPIN and NIPBL genes; Table S2: Identity of sequences homologous to the exons and introns of the Tauraco erythrolophus CHD1-Z gene, that were identified within Scaffold 37 or the W chromosome of this species; Table S3: Identity of sequences homologous to the exons and introns of the Tauraco erythrolophus NIPBL-Z gene, that were identified within the W chromosome of this species; Figure S1: Two-copy (Z and X-specific) sequence comparison of six markers (M1-M5 and M7) tested in this study. The alignments are shown for Tauraco erythrolophus. Dots indicate residues identical in both copies. The sequences were aligned with MUSCLE in MEGA ; Figure S2: Patterns of the PCR products representing M6 marker obtained for male (M) and female (F) individuals of fourteen turaco species (S1-S14, see Table 1). The amplicons were resolved in 2% agarose gel. Lane 1 kb-GeneRuler 1 kb DNA Ladder (Thermo Scientific). Lane LR-FastRuler Low Range DNA Ladder (Thermo Scientific). Institutional Review Board Statement: Ethical review and approval were waived for this study, because tissue samples were collected by veterinarians during their routine clinical practice as the result of periodic veterinary examinations of birds.
Informed Consent Statement: Not applicable.
Data Availability Statement: Our research does not involve any nucleotide or amino acid sequence data which should be archived in publicly accessible repositories. All PCR patterns obtained are presented in figures included in the manuscript. |
def check_aws_credential() -> None:
sts = boto3.client('sts')
try:
sts.get_caller_identity()
except ClientError:
log.error("AWS Credentials are not valid\nTry to run 'aws configure' to set them.")
raise AWSCredentialError("AWS Credentials are not valid. Please run 'aws configure' to set them.")
except NoCredentialsError:
log.error("Credentials are not set.\nTry to run 'aws configure' to set them.")
raise MyNoCredentialError("Credentials are not set. Please run 'aws configure' to set them.") |
from styx_msgs.msg import TrafficLight
import numpy as np
import cv2
RED_THRESHOLD = 200
GREEN_THRESHOLD = 100
class TLClassifier(object):
def __init__(self):
#TODO load classifier
pass
def get_classification(self, image):
"""Determines the color of the traffic light in the image
Args:
image (cv::Mat): image containing the traffic light
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
#TODO implement light color prediction
b, g, r = cv2.split(image)
r[r <= RED_THRESHOLD] = 0
r[r > RED_THRESHOLD] = 255
g[g > GREEN_THRESHOLD] = 255
g[g <= GREEN_THRESHOLD] = 0
g = 255 - g
mask = np.array(r) * (np.array(g) / 255)
num_red = np.sum(mask / 255)
mask = cv2.merge((mask, 0 * r, 0 * r))
if num_red >= 40:
return TrafficLight.RED
else:
return TrafficLight.UNKNOWN
|
"""Unit testing for matrix multiplication operator, @"""
import unittest
class MatMulTests(unittest.TestCase):
def test_matmul(self):
class A:
def __init__(self,x):
self.x = x
def __matmul__(self,other):
return self.x*(other.x)
a = A(2)
b = A(3)
c = a @ b
self.assertEqual(c, 6)
self.assertEqual((a.x, b.x), (2,3))
self.assertEqual(a.__matmul__(b), 6)
#self.assertEqual(repr(a.__matmul__), '<bound method A.__matmul__ of <__main__.A object>>')
class B:
def __init__(self,x):
self.x = x
a = B(2)
b = B(3)
self.assertRaises(TypeError, lambda x, y: x @ y, a, b)
self.assertRaises(AttributeError, lambda x: x.__matmul__, a)
def test_imatmul(self):
class A:
def __init__(self,x):
self.x = x
def __imatmul__(self,other):
return A(self.x * other.x)
a = A(2)
b = A(3)
a @= b
self.assertEqual(a.x, 6)
self.assertEqual(a.__imatmul__(b).x, 18)
class B:
def __init__(self,x):
self.x = x
a = B(2)
b = B(3)
def foo(x, y):
x @= y
return x
self.assertRaises(TypeError, foo, a, b)
self.assertRaises(AttributeError, lambda x: x.__imatmul__, a)
class C:
def __init__(self,x):
self.x = x
def __matmult__(self, other):
return self.x * other.x
def __imatmul__(self,other):
return C(self.x * other.x)
a = C(2)
b = C(3)
a @= b
self.assertEqual(a.x, 6)
self.assertEqual(type(a), C)
self.assertEqual(a.__imatmul__(b).x, 18)
class D:
def __init__(self,x):
self.x = x
def __matmul__(self, other):
return self.x * other.x
a = D(2)
b = D(3)
a @= b
self.assertEqual(a, 6)
self.assertEqual(type(a), int)
self.assertRaises(AttributeError, lambda x: x.__imatmul__, a)
def test_rmatmul(self):
class A:
def __init__(self,x):
self.x = x
class B:
def __init__(self, x):
self.x = x
def __rmatmul__(self, other):
return self.x * other.x
a = A(2)
b = B(3)
c = a @ b
self.assertEqual(c, 6)
def foo(x, y):
z = x @ y
return z
self.assertRaises(TypeError, foo, b, a)
self.assertRaises(AttributeError, lambda x: x.__rmatmul__, a)
class C:
def __init__(self,x):
self.x = x
def __matmul__(self,other):
return self.x*(other.x)
def __rmatmul__(self, other):
return 0
class D:
def __init__(self, x):
self.x = x
def __matmul__(self, other):
return -1
def __rmatmul__(self, other):
return -2
a = C(2)
b = D(3)
c = a @ b
self.assertEqual(c, 6)
d = b @ a
self.assertEqual(d, -1)
if __name__ == '__main__':
unittest.main()
|
It is one of the foundational myths of contemporary liberalism: the idea that American culture in the 1950s was not only stifling in its banality but a subtle form of fascism that constituted a danger to the Republic. Whatever the excesses of the 1960s might have been, so the argument goes, that decade represented the necessary struggle to free America’s mind-damaged automatons from their captivity at the hands of the Lords of Conformity and Kitsch. And yet, from a remove of more than a half century, we can see that the 1950s were in fact a high point for American culture—a period when many in the vast middle class aspired to elevate their tastes and were given the means and opportunity to do so.
The wildly successful attack on American popular culture in the 1950s was an outgrowth of noxious ideas that consumed the intellectual classes of the West in the first five decades of the 20th century—ideas so vague and so general that they were not discredited by the unprecedented flowering of popular art in the United States in the years after World War II. And, in the most savage of ironies, that attack ended up not changing popular culture for the better but instead has led to a popular culture so debased as to obviate parody.
Throughout the opening decades of the 20th century, American liberals engaged in a spirited critique of Americanism, a condition they understood as the pursuit of mass prosperity by an energetic but crude, grasping people chasing their private ambitions without the benefit of a clerisy to guide them. In thrall to their futile quest for material well-being, and numbed by the popular entertainments that appealed to the lowest common denominator in a nation of immigrants, Americans were supposedly incapable of recognizing the superiority of European culture as defined by its literary achievements.
This critique gave rise to the ferment of the 1920s, described by the literary critic Malcolm Cowley as the “exciting years…when…the young intellectuals seized power in the literary world almost like the Bolsheviks in Russia.” The writers Cowley referred to—Sinclair Lewis, F. Scott Fitzgerald, Sherwood Anderson, and Waldo Frank especially—had “a vague belief in aristocracy” and a sense that they were being “oppressed” by the culture of Main Street. But they believed America could be rescued from the pits of its popular culture by secular priests of sufficient insight to redeem the country from the depredations of the mass culture produced by democracy and capitalism. They were championed not only by leftists such as Cowley, but also by Nietzscheans such as H.L. Mencken, the critic and editor whom Walter Lippmann described in 1926 as “the most powerful influence on this whole generation of educated people” who famously mocked the hapless “herd,” “the imbeciles,” the “booboisie,” all of whom he deemed the “peasantry” that blighted American cultural life.
The concept of mass culture as a deadening danger took on a new power and coherence with the publication in 1932 of two major works, José Ortega y Gasset’s The Revolt of the Masses and Aldous Huxley’s Brave New World. Both books, which became required reading for a half century of college students in the wake of World War II, came to be seen as prophecies of 1950s American conformism. Their warnings about the dangers of a consumerist dystopia have long been integrated into the American liberal worldview.
Ortega’s extended essay and Huxley’s novel were written at a dark time for democracy. In the course of the 1920s, first Portugal, then Spain, Italy, Greece, Japan, Poland, and Czechoslovakia, followed by Austria, Hungary, Yugoslavia, and a host of Latin American countries had turned to dictatorship. Fascism was in the saddle in Italy and the Nazis were threatening to seize power in Germany as both The Revolt of the Masses and Brave New World were being composed—yet both Ortega and Huxley saw American culture as the greatest threat to the future.
Ortega mocked common sense and empiricism as the “idiot,” “plebeian,” and “demagogic” “criteriology of Sancho Panza.” It was, he argued, the tradition of the mob. Like Huxley, he had a literary sense of reality that drew heavily on rhetorical flourishes. He saw no irony in first publishing The Revolt of the Masses denouncing popular culture in a popularly circulated Spanish newspaper. Obsessed with the danger of overpopulation, Ortega set himself squarely against admitting the upwardly mobile into civilization. Ortega’s assertions about the resentful, barely literate mob were built in part on Martin Heidegger’s Being and Time (1927), which declaimed the inauthentic life led by mass man. Both Heidegger and Ortega wrote in the tradition of imperial Germany, arguing that World War I was in part a struggle to defend the Teutonic soul from the debased modernity of modern machinery and mass production represented by Americanization.
The Revolt of the Masses, which has been described as a Communist Manifesto in reverse, was a bestseller in 1930s Germany. Such success with the mass book-buying public of the Third Reich should have unnerved Ortega, but it didn’t. When he added a prologue in 1937, he neglected to mention the Nazis while decrying the “stifling monotony” mass man had imposed on Europe, converting it into a vast anthill. Congratulating himself on the anti-Americanism of his text, Ortega scoffed at the idea that America, that “paradise of the masses,” could ever defend European civilization.
Huxley’s Brave New World was heavily influenced by Mencken. Unlike the other great totalitarian dystopias, Huxley’s World State is ordered on the wants of the governed rather than the governors. The only people with any capacity for dissatisfaction in Huxley’s dystopia are a handful of Alphas—or what we would today call “the creative class”—who, unlike the cow-like masses, aren’t satisfied with a steady diet of sex and drugs.
Mencken and Huxley shared an aristocratic ideal based on an idyllic past. They romanticized a time before the age of machinery and mass production, when the lower orders lived in happy subordination and when intellectual eccentricity was encouraged among the elites. In this beautiful world, alienation was as unknown as bearbaiting and cockfighting, “and those who wanted to amuse themselves were,” in Huxley’s words, “compelled, in their humble way, to be artists.”
They considered the egalitarianism of American democracy a degraded form of government which, in Ortega’s words, discouraged “respect or esteem for superior individuals.” Intellectuals, they complained, weren’t given their due by the human detritus of this new world. Huxley, a member of the Eugenics Society, saw mass literacy, mass education, and popular newspapers as having “created an immense class of what I may call the New Stupid.” He proposed the British government raise the price of newsprint ten or twentyfold because “the new stupid,” manipulated by newspaper plutocrats, were imposing a soul-crushing conformity on humanity. The masses, so his argument went, needed to be curtailed for their own good and for the greater good of high culture.
Huxley, writing in a 1927 issue of Harper’s, called for an aristocracy of intellect, and in a slim volume entitled Proper Studies, published the same year, he called for culling the masses through negative eugenics. “The active and intelligent oligarchies of the ideal state do not yet exist,” he told Harper’s readers, “but the Fascist party in Italy, the Communist party in Russia, the Kuomintang in China are still their inadequate precursors.” In the future, he insisted, “political democracy as now practiced, will be unknown; our descendants will want a more efficient and rational form of government.” He warned America that while it was wedded to “the old-fashioned democratic and humanitarian ideas of the eighteenth century…the force of circumstances will be too powerful for them” and they, too, would come to be governed by a new aristocracy of spirituality and intellect.
In 1931, as Huxley was composing Brave New World, he wrote newspaper articles arguing that “we must abandon democracy and allow ourselves to be ruled dictatorially by men who will compel us to do and suffer what a rational foresight demands.” It was Huxley’s view that “dictatorship and scientific propaganda may provide the only means of saving humanity from the misery of anarchy.” Many of the elements in the “brave new world” that contemporary readers find jarring actually appealed to Huxley. The sorting of individuals by type, eugenic breeding, and hierarchic leadership were policies for which he had proselytized. The problem with the world he created is the lack of spiritual insight, spiritual greatness, on the part of its leader.
The “brave new world” is America, to some extent, or rather, Huxley’s bleak view of America, which he once described as “a land where there is probably less personal freedom than in any other country in the world with the possible exception of Bolshevik Russia.” In the Americanized Brave New World, workers are mass-produced, Henry Ford–style. Those workers live in a mindless drug-induced state of happiness little different from the drug-like effects of the Americanized popular culture Huxley so loathed. In the “brave new world,” as in America, Huxley argues, the lack of freedom isn’t externally imposed—it is, rather, an expression of a culture and polity organized around the wishes of the masses.
America’s failing was its “lack of an intellectual aristocracy…secure in its position and authority” so that it could constrain people from “thinking and acting…like the characters in a novel by Sinclair Lewis,” a man whose novels offered a stinging portrait of the stifling conformity of middle-class bourgeois life.
This potent critique of mass culture was suddenly muted in the 1930s by the rise of the Communist party in the United States, which required of the intellectuals who flocked to it a sentimental attachment to the masses. And it seemed as though it had been discredited to some degree by World War II. The “hollow men” of the middle class, whom liberal intellectuals had been taught to despise by T.S. Eliot’s poem of the same name, proved their mettle by defeating the Nazis and saving Western civilization itself.
But writing in 1944, the literary critic and historian Bernard DeVoto saw that the surcease would only be temporary. “The squares, boobs, Babbits, and Rotarians despised by literary liberals would soon again become targets for their betters. America would once again become the land where the masses were organized to crush an artist’s hopes.”
When the Second World War ended in 1945, the New York intellectual Delmore Schwartz kept repeating, “It’s 1919 over again.” His friend, the philosopher William Barrett, explained Schwartz’s excitement: “Our generation had been brought up on the remembrance of the 1920s as the great golden age of the avant-garde….We expected history to repeat itself.” And in some ways it did. An incessant flow of talk and writing about “mass society” and “mass culture” were the amniotic fluid from which young liberals emerged in the 1950s. As the critic Nora Sayre explained in a memoir, she grew up in that decade around Hollywood writers and New York leftists, for whom the loathing of Main Street and Mencken’s scabrous view of the booboisie were still “the values and tropisms” that were “very much alive in our living room.”
With each new advance in American prosperity, peculiarly, the reactionary vision of Huxley and Ortega gained ground. But the target had changed. In the 1950s version of the mass-culture critique, the men and women of America were said to have become alienated from their authentic selves not by the Babbitts of conformity but by a pervasive popular culture that kept them in a state of vegetative torpor. Everything from women’s magazines to radio to comic books was implicated in this scheme, driven by the need of American capitalists to keep people in a perpetual state of false consciousness.
Mass Culture: The Popular Arts in America, a 1956 collection of essays co-edited by Bernard Rosenberg, a contributing editor of the socialist magazine Dissent, explained the dangers at hand. “Contemporary man finds that his life has been emptied of meaning, that it has been trivialized,” Rosenberg wrote. “He is alienated from his past, from his work, his community, and possibly from himself—although this ‘self’ is hard to locate. At the same time he has an unprecedented amount of time on his hands which he must kill…lest it kill him.”
The evidence for this epidemic of inauthenticity was 561 pages of articles on such pressing concerns as “The Problem of the Paper-Backs,” “Card-playing as Mass Culture,” and “Television and the Patterns of Mass Culture.” One short article by Irving Howe, who would go on to become a distinguished literary critic and founder of Dissent, contained the following passage:
On the surface the Donald Duck…cartoons seem merely pleasant little fictions but they are actually overladen with the most aggressive, competitive, and sadistic themes. On the verge of hysteria, Donald Duck is a frustrated little monster who has something of the SS man in him and whom we, also having something of the SS man in us, naturally find…quite charming.
Howe would later distance himself from such effusions and mock “the endless chatter about ‘conformity’ that has swept the country.” But the fanciful fears of “suburban fascism,” the danger of stable families, backyard barbecues, white bread, and tail fins came to seem all too real to those influenced by exiled German academics and philosophers who came to enjoy an enormous (and often undeserved) intellectual prestige. Their writings always seemed to carry the intimidating rumble of profundity, which, it turned out, was largely a matter of misdirection aimed at obscuring their own relationship with the German traditions that had led to the horrors.
The Frankfurt School, led by Theodor Adorno and Max Horkheimer, theorized that the rough beast of popular fascism would come round at last in bourgeois America. Relying on an unholy blend of Freud and early Marx, the Frankfurt School writers averred that private life had ceased to be private since it had been colonized by the forces of industrialized leisure—movies, radio, TV, and comic books. These amusements were, they argued, the modern equivalent of the “bread and circuses” used to contain Rome’s plebeians as the empire descended into decadence. With their formidable dialectical skills, they had the intellectual dexterity to argue past the lack of evidence and insist that the jackboots were coming. Because the underlying reality of American life, dominated by hectoring fathers à la Freud, was intrinsically fascist, they argued, there was no need for an overt movement of the sort represented by the Nazis. Nazism was inevitable in America.
The Frankfurt School represented a new kind of left. It did not accept the notion that man was progressing inevitably to a higher state of consciousness. The elimination of poverty and the reduction of back-breaking work through machinery—once seen as great achievements that would help the working man achieve his mastery of the bourgeoisie—were in fact the enslavement of man by mere technology.
“In the over-developed countries,” wrote Herbert Marcuse, who became the most famous Frankfurt School theoretician of the 1960s, “an ever-larger part of the population becomes one huge captive audience—captured not by a total regime, but by the liberties of the citizens whose media of amusement and elevation compels the Other to partake of their sounds, sights, and smells.” He was arguing, in effect, for greater social segregation between the elite and the hoi polloi.
Dwight Macdonald, the most influential American critic of mass culture in the late 1950s, concurred with the Frankfurt School. Writing in crackling prose redolent of Mencken’s, he too argued that bourgeois prosperity was creating a cultural wasteland: “The work week has shrunk, real wages have risen, and never in history have so many people attained such a high standard of living as in this country since 1945,” Macdonald complained.
“Money, leisure, and knowledge,” he went on, “the prerequisites for culture, are more plentiful and more evenly distributed than ever before.”
Macdonald, who was educated at Phillips Exeter Academy and Yale and associated with the anti-Stalinist leftists at Partisan Review, still couldn’t bring himself to support the United States against the Nazis in World War II on the grounds that “Europe has its Hitlers, but we have our Rotarians.”
Macdonald made himself the chief critic of the cultural category he dubbed the “middlebrow.” The great danger to America, he argued in his most famous essay, “Masscult and Midcult,” was the effort by the masses to elevate themselves culturally. Because of the middlebrow impulse, he said, book clubs had spread across the country like so much “ooze.” The result, Macdonald believed, could only be the pollution of high culture and its degradation in becoming popular culture. “Two cultures have developed in this country,” insisted Macdonald, and “it is to the national interest to keep them separate.”
His words were vicious. “Already we have far too much of this insipidity—masses of people who are half breeds” daring to partake of “the American culture of the cheap newspaper, the movies, the popular song, the ubiquitous automobile” and creating “hordes of men and women without a spiritual country…without taste, without standards but those of the mob.”
That was, Macdonald explained, because “the masses are not people, they are not The Man in the Street or The Average Man, they are not even that figment of liberal condescension, The Common Man. The masses are, rather, man as non-man.” He quoted the author Roger Fry approvingly as saying Americans “have lost the power to be individuals. They have become social insects like bees and ants.”
And what were these insects up to? They were sampling the greatest works of Western civilization for the first time. “Twenty years ago,” a salesman reveled in Mass Culture: The Popular Arts in America, “you couldn’t sell Beethoven out of New York. Today we sell Palestrina, Monteverdi, Gabrieli, and Renaissance and Baroque music in large quantities.” The public’s expanding taste and increased income produced a 250 percent growth in the number of local symphony orchestras between 1940 and 1955. In that same year, 1955, 15 million people paid to attend major league baseball games, while 35 million paid to attend classical music concerts. The New York Metropolitan Opera’s Saturday afternoon radio broadcast drew a listenership of 15 million out of an overall population of 165 million.
The overwhelming new medium of television was particularly decried by critics of mass culture. But as the sociologist David White, co-editor with Rosenberg of Mass Culture, noted, NBC spent $500,000 in 1956 to present a three-hour version of Shakespeare’s Richard III starring Laurence Olivier. The broadcast drew 50 million viewers; as many as 25 million watched all three hours. White went on to note that “on March 16, 1956, a Sunday chosen at random,” the viewer could have seen a discussion of the life and times of Toulouse-Lautrec by three prominent art critics, an interview with theologian Paul Tillich, an adaptation of Walter Van Tilburg Clark’s Hook, a documentary on mental illness with Dr. William Menninger, and a 90-minute performance of The Taming of the Shrew.
At the same time, book sales doubled. Saul Bellow’s The Adventures of Augie March, a National Book Award winner, had only modest sales when it was published in 1953. But it went on to sell a million copies in paperback—the softcover book having been introduced on a grand scale after the war. Anthropologist Ruth Benedict’s Patterns of Culture, published in 1934, sold modestly until the advent of the paperback. By the mid-50s this assault on Victorian moral absolutes in the name of cultural tolerance had sold a half million copies.
In 1947, notes Alex Beam in his recent book A Great Idea at the Time, Robert Hutchins, then president of the University of Chicago, and the autodidact philosopher Mortimer Adler launched an effort to bring the great books of Western Civilization to the people. In 1948 Hutchins and Adler drew 2,500 people to a Chicago auditorium to hear them lead a discussion of the trial of Socrates. By 1951 there were 2,500 Great Books discussion groups, with roughly 25,000 members meeting “all over the country, in public libraries, in church basements, Chamber of Commerce offices, corporate conference rooms at IBM and Grumman Aircraft, in private homes, on army bases,” and even prisons. At the peak of the Great Books boom, Beam writes, 50,000 Americans a year were buying collections of the writings of Plato, Aristotle, the Founding Fathers, and Hegel at prices that “started at $298 and topped out at $1,175, the equivalent of $2,500 to $9,800 today.”
This was the danger against which critics of mass culture, inflamed with indignation, arrayed themselves in righteous opposition.
But with the advent of the youth movement of the 1960s, the elite attack took a new and odd turn. The shift in sensibility was first announced by the 31-year-old Susan Sontag in a 1964 Partisan Review essay entitled “Notes on Camp.” The essay, which sent Sontag’s shares soaring on the intellectual stock exchange, dissolved the boundaries between high culture and mass culture in favor of a new sensibility she described as “camp.” Camp is playful, a rebuke of sorts to the cultural mandarins. More precisely, camp involves a new, more complex relation to what she called “the serious.” It allowed people to “be serious about the frivolous, [and] frivolous about the serious.” Sontag was saying it was all right for serious people to enjoy the kitsch of popular culture as long as they did it with the correct—superior and ironic—attitude.
Sontag, who thought of herself as a displaced European suffering among philistine Americans, argued that “intelligence” was “really a kind of taste: taste in ideas.” And the “new aristocrats of taste” were those led by homosexual men who saw that comic books, popular art, and pornography viewed with the right spirit of irony and mischief were an extension of the new sensibility that saw “life as theater.” In this victory of style over content and aesthetics over morality, Sontag defined the emerging ethos of the 60s. The middlebrow menace was banished to the sidelines.
By 1970 the aim of camp to “dethrone the serious” had all but succeeded. The last remnants of bourgeois morality having largely melted away as part of the national culture, there was little to make even mock cultural rebellion meaningful. The “serious” was replaced by a cheerful mindlessness, and the cultural striving of middlebrow culture came to a quiet end. Why should the well-meaning middle American labor to read a complex novel by an intellectual or try to work his way through a Great Book if the cultural poohbahs first mocked his efforts and then said they were pointless anyway because what mattered was living “life as theater”? Today, if there were a T.S. Eliot, Time Magazine would no more put him on the cover than it would sing the praises of George W. Bush. Time’s literary critic writes children’s fantasy novels and chose a science-fiction book about elves as one of the crowning cultural achievements of 2011. Since the highbrow have been given permission to view the “frivolous as the serious,” why shouldn’t everybody else?
Dwight Macdonald, who spat on the ambitions of the midcult man, took an interesting journey himself in the 1960s. He became a movie critic and later a contributor to the Today show. When student radicals took over buildings on the campus of Columbia University, Macdonald celebrated them and responded mildly when members of the Students for a Democratic Society (which gave birth to the terrorist Weathermen) literally set fire to the manuscript of a professor. The man who had denounced the barbarism of the American middle saw true barbarism in practice and found it wonderfully stimulating.
“You know how sympathetic in general I am to the Young, they’re the best generation I’ve known in this country, the cleverest and the most serious and decent,” he said. And then, speaking words that would mark the disgraceful epitaph of the successful assault on the remarkable American cultural moment of the 1950s, he said, wistfully, “I wish they’d read a little.” |
module Advent.Y2021.Day10.Part2 where
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Advent.Y2021.Day10.Chunk
solution :: IO ()
solution = do
input <- T.lines <$> T.readFile "data/2021/Day10.txt"
print $ part2Solution $ fromList input
|
package oauth
// UserInfo structure
type UserInfo struct {
Sub string `json:"sub"`
ID int `json:"id"`
Battletag string `json:"battletag"`
}
|
/**
* Returns an unmodifiable view of the given iterable.
* <p>
* The returned iterable's iterator does not support {@code remove()}.
*
* @param <E> the element type
* @param iterable the iterable to use, may not be null
* @return an unmodifiable view of the specified iterable
* @throws NullPointerException if iterable is null
*/
public static <E> Iterable<E> unmodifiableIterable(final Iterable<E> iterable) {
checkNotNull(iterable);
if (iterable instanceof UnmodifiableIterable<?>) {
return iterable;
}
return new UnmodifiableIterable<>(iterable);
} |
def report_on(self, issues, header=True):
r = Report(
table=[],
summary=dict(
title=self.title,
start_date=self.start_date,
end_date=self.end_date
)
)
r.table.append(["Lead Time", "Tickets"])
filtered_issues = self.filter_issues(issues)
if filtered_issues:
lead_times = [i.lead_time for i in filtered_issues]
lead_times = array(lead_times)
hist_values, hist_bins = histogram(
lead_times,
bins=arange(0, max(lead_times) + 2, 1)
)
for i in range(0, len(hist_values)):
if i == 0:
continue
row = [hist_bins[i], hist_values[i]]
r.table.append(row)
return r |
/**
* Created by Administrator on 2017/12/14.
*/
public class TestThread extends BaseThread {
public final String TAG = this.getClass().getSimpleName();
public TestThread(AccessibilityService context, Map<String, String> record,AccessibilityParameters parameters){
super(context,record,parameters);
}
@Override
public Object call() {
while (true){
AutoUtil.sleep(2000);
LogUtil.d(TAG,Thread.currentThread().getName());
AccessibilityNodeInfo root = context.getRootInActiveWindow();
if(root==null){
LogUtil.d(TAG,"root is null");
AutoUtil.sleep(500);
continue;
}
if(parameters.getIsStop()==1){
LogUtil.d(TAG,"暂停....");
continue;
}
System.out.println("deb==================================");
ParseRootUtil.debugRoot(root);
//ParseRootUtil.getCurrentViewAllNode(root);
NodeActionUtil.doClickByNodePathAndText(root,"通讯录|发现","030","发现",record,"sendFr点击发现",500);
NodeActionUtil.doClickByNodePathAndText(root,"扫一扫|摇一摇","00310","朋友圈",record,"sendFr点击朋友圈",500);
NodeActionUtil.doClickByNodePathAndText(root,"轻触更换主题照片|朋友圈封面,再点一次可以改封面","00310","朋友圈",record,"sendFr点击朋友圈",500);
if(AutoUtil.checkAction(record,"sendFr点击朋友圈")&&NodeActionUtil.isWindowContainStr(root,"朋友圈封面")){
AccessibilityNodeInfo node6 = ParseRootUtil.getNodePath(root,"002");
System.out.println("node6-->"+node6);
node6.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
}
NodeActionUtil.doClickByNodePathAndText(root,"长按拍照按钮发文字,为内部体验功能。后续版本可能取消,也有可能保留,请勿过于依赖此方法。|我知道了","001","我知道了",record,"sendFr点击我知道了",500);
NodeActionUtil.doInputByNodePathAndText(root,"这一刻的想法...|谁可以看","0000","tt3",record,"sendFr输入发送内容",1000);
NodeActionUtil.doClickByNodePathAndText(root,"这一刻的想法...|谁可以看","03","发送",record,"sendFr点击发送",500);
}
}
} |
/**
* Returns the sitemap.
*
* @param context the specified context
*/
@RequestProcessing(value = {"/sitemap.xml"}, method = HTTPRequestMethod.GET)
public void sitemap(final HTTPRequestContext context) {
final TextXMLRenderer renderer = new TextXMLRenderer();
context.setRenderer(renderer);
final Sitemap sitemap = new Sitemap();
try {
final JSONObject preference = preferenceQueryService.getPreference();
addArticles(sitemap, preference);
addNavigations(sitemap, preference);
addTags(sitemap, preference);
addArchives(sitemap, preference);
LOGGER.log(Level.INFO, "Generating sitemap....");
final String content = sitemap.toString();
LOGGER.log(Level.INFO, "Generated sitemap");
renderer.setContent(content);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Get blog article feed error", e);
try {
context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.