content
stringlengths 10
4.9M
|
---|
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 config
import (
"encoding/json"
)
// SensitiveRawMessage is a struct to store some data that should not be logged
// or printed.
// This struct is a Stringer which will not print its contents with 'String'.
// It is a json.Marshaler and json.Unmarshaler and will present its actual
// contents in plaintext when read/written from/to json.
type SensitiveRawMessage struct {
contents json.RawMessage
}
// NewSensitiveRawMessage returns a new encapsulated json.RawMessage or nil if
// the data is empty. It cannot be accidentally logged via .String/.GoString/%v/%#v
func NewSensitiveRawMessage(data json.RawMessage) *SensitiveRawMessage {
if len(data) == 0 {
return nil
}
return &SensitiveRawMessage{contents: data}
}
func (data SensitiveRawMessage) String() string {
return "[redacted]"
}
func (data SensitiveRawMessage) GoString() string {
return "[redacted]"
}
func (data SensitiveRawMessage) Contents() json.RawMessage {
return data.contents
}
func (data SensitiveRawMessage) MarshalJSON() ([]byte, error) {
return data.contents, nil
}
func (data *SensitiveRawMessage) UnmarshalJSON(jsonData []byte) error {
data.contents = json.RawMessage(jsonData)
return nil
}
|
/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hu.akarnokd.reactive4javaflow.impl.operators;
import hu.akarnokd.reactive4javaflow.*;
import hu.akarnokd.reactive4javaflow.functionals.*;
import hu.akarnokd.reactive4javaflow.fused.FusedSubscription;
import hu.akarnokd.reactive4javaflow.impl.FailingFusedSubscription;
import org.junit.Test;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public class FolyamFlatMapTest {
@Test
public void standard() {
TestHelper.assertResult(Folyam.empty().flatMap(Folyam::just));
}
@Test
public void standard1() {
TestHelper.assertResult(Folyam.just(1).flatMap(Folyam::just), 1);
}
@Test
public void standard2() {
TestHelper.assertResult(Folyam.range(1, 5).flatMap(Folyam::just), 1, 2, 3, 4, 5);
}
@Test
public void standard2Hidden() {
TestHelper.assertResult(Folyam.range(1, 5)
.flatMap(v -> Folyam.just(v).hide()), 1, 2, 3, 4, 5);
}
@Test
public void standard3() {
TestHelper.assertResult(
Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2)),
1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void standard3Hidden() {
TestHelper.assertResult(Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2).hide()),
1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void standard4() {
TestHelper.assertResult(
Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2), 1),
1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void standard4Hidden() {
TestHelper.assertResult(Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2).hide(), 1),
1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void standard5() {
TestHelper.assertResult(
Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2), 2),
1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void standard5Hidden() {
TestHelper.assertResult(Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2).hide(), 2),
1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void standard6() {
TestHelper.assertResult(
Folyam.range(1, 5).flatMap(Folyam::just, 1),
1, 2, 3, 4, 5);
}
@Test
public void standard7() {
TestHelper.assertResult(
Folyam.range(1, 5).flatMapDelayError(Folyam::just, 1),
1, 2, 3, 4, 5);
}
@Test
public void longScalar() {
Folyam.range(1, 1000)
.flatMap(Folyam::just)
.test()
.assertValueCount(1000)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarHidden() {
Folyam.range(1, 1000)
.flatMap(v -> Folyam.just(v).hide())
.test()
.assertValueCount(1000)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixed() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v) : Folyam.empty())
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixed2() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v).hide() : Folyam.empty())
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixed3() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v) : Folyam.empty().hide())
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixed4() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v).hide() : Folyam.empty().hide())
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarConditional() {
Folyam.range(1, 1000)
.flatMap(Folyam::just)
.filter(v -> true)
.test()
.assertValueCount(1000)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarHiddenConditional() {
Folyam.range(1, 1000)
.flatMap(v -> Folyam.just(v).hide())
.filter(v -> true)
.test()
.assertValueCount(1000)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixedConditional() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v) : Folyam.empty())
.filter(v -> true)
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixed2Conditional() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v).hide() : Folyam.empty())
.filter(v -> true)
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixed3Conditional() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v) : Folyam.empty().hide())
.filter(v -> true)
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void longScalarMixed4Conditional() {
Folyam.range(1, 1000)
.flatMap(v -> v % 2 == 0 ? Folyam.just(v).hide() : Folyam.empty().hide())
.filter(v -> true)
.test()
.assertValueCount(500)
.assertNoErrors()
.assertComplete();
}
@Test
public void error() {
TestHelper.assertFailureComposed(-1, f -> f.flatMap(Folyam::just), IOException.class);
}
@Test
public void error2() {
TestHelper.assertFailureComposed(-1, f -> f.flatMapDelayError(Folyam::just), IOException.class);
}
@Test
public void error3() {
TestHelper.assertFailureComposed(5, f -> f.flatMap(v -> {
if (v >= 4) {
return Folyam.error(new IOException());
}
return Folyam.just(v);
}), IOException.class, 1, 2, 3);
}
@Test
public void error4() {
TestHelper.assertFailureComposed(5, f -> f.flatMapDelayError(v -> {
if (v == 4) {
return Folyam.error(new IOException());
}
return Folyam.just(v);
}), IOException.class, 1, 2, 3, 5);
}
@Test
public void exactRequestShouldComplete() {
Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2))
.test(0)
.assertEmpty()
.requestMore(9)
.requestMore(1)
.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void exactRequestShouldCompleteConditional() {
Folyam.range(1, 5)
.flatMap(v -> Folyam.range(v, 2))
.filter(v -> true)
.test(0)
.assertEmpty()
.requestMore(9)
.requestMore(1)
.assertResult(1, 2, 2, 3, 3, 4, 4, 5, 5, 6);
}
@Test
public void longAsync() {
for (int i = 0; i < 1000; i++) {
assertBoth(Folyam.range(1, 1000)
.flatMap(v -> Folyam.just(1).subscribeOn(SchedulerServices.computation())));
}
}
@Test
public void longAsync2() {
for (int i = 0; i < 1000; i++) {
assertBoth(Folyam.range(1, 1000)
.flatMap(v -> Folyam.just(1).observeOn(SchedulerServices.computation())));
}
}
@Test
public void mapperCrash() {
TestHelper.assertFailureComposed(5, f -> f.flatMap(w -> { throw new IOException(); }), IOException.class);
}
@Test
public void mixedScalarAndAsync() {
assertBoth(Folyam.range(1, 1000)
.flatMap(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.observeOn(SchedulerServices.computation());
}
return f;
}));
}
@Test
public void mixedScalarAndAsync2() {
assertBoth(Folyam.range(1, 1000)
.flatMap(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.observeOn(SchedulerServices.computation());
}
return f;
}, 1));
}
@Test
public void mixedScalarAndAsync3() {
assertBoth(Folyam.range(1, 1000)
.flatMap(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.subscribeOn(SchedulerServices.computation());
}
return f;
}));
}
@Test
public void mixedScalarAndAsync4() {
assertBoth(Folyam.range(1, 1000)
.flatMap(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.subscribeOn(SchedulerServices.computation());
}
return f;
}, 1));
}
@Test
public void mixedScalarAndAsync5() {
assertBoth(Folyam.range(1, 1000)
.flatMapDelayError(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.observeOn(SchedulerServices.computation());
}
return f;
}));
}
@Test
public void mixedScalarAndAsync6() {
assertBoth(Folyam.range(1, 1000)
.flatMapDelayError(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.subscribeOn(SchedulerServices.computation());
}
return f;
}));
}
@Test
public void mixedScalarAndAsync7() {
assertBoth(Folyam.range(1, 2000)
.flatMapDelayError(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.observeOn(SchedulerServices.computation());
}
return f;
}).take(1000));
}
@Test
public void mixedScalarAndAsync8() {
assertBoth(Folyam.range(1, 2000)
.flatMapDelayError(v -> {
Folyam<Integer> f = Folyam.just(1);
if (v % 2 == 0) {
f = f.subscribeOn(SchedulerServices.computation());
}
return f;
}).take(1000));
}
void assertBoth(Folyam<?> f) {
f.test()
.withTag("Normal")
.awaitDone(5, TimeUnit.SECONDS)
.assertValueCount(1000)
.assertNoErrors()
.assertComplete();
f
.filter(v -> true)
.test()
.withTag("Conditional")
.awaitDone(5, TimeUnit.SECONDS)
.assertValueCount(1000)
.assertNoErrors()
.assertComplete();
}
@Test
public void innerError() {
Folyam.just(1).hide()
.flatMap(v -> Folyam.error(new IOException()).hide())
.test()
.assertFailure(IOException.class);
}
@Test
public void innerErrorDelayed() {
Folyam.just(1).hide()
.flatMapDelayError(v -> Folyam.error(new IOException()).hide())
.test()
.assertFailure(IOException.class);
}
@Test
public void scalar1Queue() {
Folyam.just(1).flatMap(v -> Folyam.just(1), 1)
.test(0)
.assertEmpty()
.requestMore(1)
.assertResult(1);
}
@Test
public void pollCrash() {
Folyam.just(1).hide()
.flatMap(v -> new Folyam<Integer>() {
@Override
protected void subscribeActual(FolyamSubscriber<? super Integer> s) {
s.onSubscribe(new FailingFusedSubscription(FusedSubscription.SYNC));
}
})
.test()
.assertFailure(IOException.class);
}
@Test
public void pollCrash2() {
Folyam.just(1).hide()
.flatMapDelayError(v -> new Folyam<Integer>() {
@Override
protected void subscribeActual(FolyamSubscriber<? super Integer> s) {
s.onSubscribe(new FailingFusedSubscription(FusedSubscription.SYNC));
}
})
.test()
.assertFailure(IOException.class);
}
@Test
public void pollCrashConditional() {
Folyam.just(1).hide()
.flatMap(v -> new Folyam<Integer>() {
@Override
protected void subscribeActual(FolyamSubscriber<? super Integer> s) {
s.onSubscribe(new FailingFusedSubscription(FusedSubscription.SYNC));
}
})
.filter(v -> true)
.test()
.assertFailure(IOException.class);
}
@Test
public void pollCrash2Conditional() {
Folyam.just(1).hide()
.flatMapDelayError(v -> new Folyam<Integer>() {
@Override
protected void subscribeActual(FolyamSubscriber<? super Integer> s) {
s.onSubscribe(new FailingFusedSubscription(FusedSubscription.SYNC));
}
})
.filter(v -> true)
.test()
.assertFailure(IOException.class);
}
@Test
public void crossMap() {
for (int i = 1; i <= 1_000_000; i *= 10) {
int j = 1_000_000 / i;
Folyam.range(1, i)
.flatMap(v -> Folyam.range(v, j))
.test()
.withTag("Normal, i = " + i + ", j = " + j)
.assertValueCount(1_000_000)
.assertNoErrors()
.assertComplete();
Folyam.range(1, i)
.flatMap(v -> Folyam.range(v, j))
.filter(v -> true)
.test()
.withTag("Conditional, i = " + i + ", j = " + j)
.assertValueCount(1_000_000)
.assertNoErrors()
.assertComplete();
}
}
@Test
public void publisher() {
Folyam.merge(Folyam.fromArray(Folyam.range(1, 3), Folyam.range(4, 3)))
.test()
.assertResult(1, 2, 3, 4, 5, 6);
}
@Test
public void publisher2() {
Folyam.merge(Folyam.fromArray(Folyam.range(1, 3), Folyam.range(4, 3)), 1)
.test()
.assertResult(1, 2, 3, 4, 5, 6);
}
@Test
public void publisher3() {
Folyam.mergeDelayError(Folyam.fromArray(Folyam.range(1, 3), Folyam.range(4, 3)))
.test()
.assertResult(1, 2, 3, 4, 5, 6);
}
@Test
public void publisher4() {
Folyam.mergeDelayError(Folyam.fromArray(Folyam.range(1, 3), Folyam.range(4, 3)), 1)
.test()
.assertResult(1, 2, 3, 4, 5, 6);
}
@Test
public void publisher5() {
Folyam.mergeDelayError(Folyam.fromArray(Folyam.range(1, 3), Folyam.error(new IOException()), Folyam.range(4, 3)))
.test()
.assertFailure(IOException.class, 1, 2, 3, 4, 5, 6);
}
@Test
public void publisher6() {
Folyam.mergeDelayError(Folyam.fromArray(Folyam.range(1, 3), Folyam.error(new IOException()), Folyam.range(4, 3)), 1)
.test()
.assertFailure(IOException.class, 1, 2, 3, 4, 5, 6);
}
@Test
public void failingFusedInnerCancelsSource() {
final AtomicInteger counter = new AtomicInteger();
Folyam.range(1, 5)
.doOnNext(v -> counter.getAndIncrement())
.flatMap((CheckedFunction<Integer, Folyam<Integer>>) v ->
Folyam.fromIterable(() -> new Iterator<Integer>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
throw new IllegalArgumentException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}))
.test()
.assertFailure(IllegalArgumentException.class);
assertEquals(1, counter.get());
}
}
|
<reponame>run-ai/runai-cli
package flags
import (
"strconv"
"time"
flag "github.com/spf13/pflag"
)
type intNullableArgument struct {
variableToSet **int
}
type float64NullableArgument struct {
variableToSet **float64
}
func newIntNullableArgument(variable **int) *intNullableArgument {
return &intNullableArgument{
variableToSet: variable,
}
}
func newFloat64NullableArgument(variable **float64) *float64NullableArgument {
return &float64NullableArgument{
variableToSet: variable,
}
}
func (argument *intNullableArgument) Set(s string) error {
v, err := strconv.Atoi(s)
*argument.variableToSet = &v
return err
}
func (argument *intNullableArgument) Type() string {
return "int"
}
func (argument *intNullableArgument) String() string {
if *argument.variableToSet == nil {
return ""
}
return strconv.Itoa(**argument.variableToSet)
}
func (argument *float64NullableArgument) Set(s string) error {
f, err := strconv.ParseFloat(s, 64)
*argument.variableToSet = &f
return err
}
func (argument *float64NullableArgument) Type() string {
return "float64"
}
func (argument *float64NullableArgument) String() string {
if *argument.variableToSet == nil {
return ""
}
return strconv.FormatFloat(**argument.variableToSet, 'f', -1, 64)
}
func AddIntNullableFlagP(f *flag.FlagSet, variableToSet **int, name string, shorthand string, usage string) {
f.VarPF(newIntNullableArgument(variableToSet), name, shorthand, usage)
}
func AddFloat64NullableFlagP(f *flag.FlagSet, variableToSet **float64, name string, shorthand string, usage string) {
f.VarPF(newFloat64NullableArgument(variableToSet), name, shorthand, usage)
}
func AddIntNullableFlag(f *flag.FlagSet, variableToSet **int, name string, usage string) {
AddIntNullableFlagP(f, variableToSet, name, "", usage)
}
type boolNullableArgument struct {
variableToSet **bool
}
func newBoolNullableArgument(variable **bool) *boolNullableArgument {
return &boolNullableArgument{
variableToSet: variable,
}
}
func (argument *boolNullableArgument) Set(s string) error {
v, err := strconv.ParseBool(s)
*argument.variableToSet = &v
return err
}
func (argument *boolNullableArgument) Type() string {
return "bool"
}
func (argument *boolNullableArgument) String() string {
if *argument.variableToSet == nil {
return ""
}
return strconv.FormatBool(**argument.variableToSet)
}
func AddBoolNullableFlagP(f *flag.FlagSet, variableToSet **bool, name string, shorthand string, usage string) {
flag := f.VarPF(newBoolNullableArgument(variableToSet), name, shorthand, usage)
flag.NoOptDefVal = "true"
}
func AddBoolNullableFlag(f *flag.FlagSet, variableToSet **bool, name string, shortcut, usage string) {
AddBoolNullableFlagP(f, variableToSet, name, shortcut, usage)
}
type durationNullableArgument struct {
variableToSet **time.Duration
}
func newDurationNullableArgument(variable **time.Duration) *durationNullableArgument {
return &durationNullableArgument{
variableToSet: variable,
}
}
func (argument *durationNullableArgument) Set(s string) error {
v, err := time.ParseDuration(s)
*argument.variableToSet = &v
return err
}
func (argument *durationNullableArgument) Type() string {
return "duration"
}
func (argument *durationNullableArgument) String() string {
if *argument.variableToSet == nil {
return ""
}
return (**argument.variableToSet).String()
}
func AddDurationNullableFlagP(f *flag.FlagSet, variableToSet **time.Duration, name string, shorthand string, usage string) {
f.VarP(newDurationNullableArgument(variableToSet), name, shorthand, usage)
}
|
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
package cloudsearch
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/aws/aws-sdk-go/internal/protocol/query"
"github.com/aws/aws-sdk-go/internal/signer/v4"
)
// You use the Amazon CloudSearch configuration service to create, configure,
// and manage search domains. Configuration service requests are submitted using
// the AWS Query protocol. AWS Query requests are HTTP or HTTPS requests submitted
// via HTTP GET or POST with a query parameter named Action.
//
// The endpoint for configuration service requests is region-specific: cloudsearch.region.amazonaws.com.
// For example, cloudsearch.us-east-1.amazonaws.com. For a current list of supported
// regions and endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#cloudsearch_region"
// target="_blank).
type CloudSearch struct {
*service.Service
}
// Used for custom service initialization logic
var initService func(*service.Service)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// New returns a new CloudSearch client.
func New(config *aws.Config) *CloudSearch {
service := &service.Service{
ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "cloudsearch",
APIVersion: "2013-01-01",
},
}
service.Initialize()
// Handlers
service.Handlers.Sign.PushBack(v4.Sign)
service.Handlers.Build.PushBack(query.Build)
service.Handlers.Unmarshal.PushBack(query.Unmarshal)
service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
service.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
// Run custom service initialization if present
if initService != nil {
initService(service)
}
return &CloudSearch{service}
}
// newRequest creates a new request for a CloudSearch operation and runs any
// custom request initialization.
func (c *CloudSearch) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
|
/**
* Checks to see if character's top and bottom have collision with the given
* ball object.
*
* @param character
* object which you want to check collision of.
* @param ball
* object with which you want to check collision.
*
* @return DOWN if character's bottom side has collided with the wall (he
* landed), RIGHT if character's top side has collided with the wall (his
* head hit the ceiling), NONE if no collision happened.
*/
public static Constants.Direction verticalOrientation(MBox character,
BBall ball)
{
if (character.getLeftX() < ball.getRightX() &&
character.getRightX() > ball.getLeftX())
{
if (character.getCenterY() < ball.getCenterY())
{
return Constants.Direction.Down;
}
else if (character.getCenterY() > ball.getCenterY())
{
return Constants.Direction.Up;
}
}
return Constants.Direction.None;
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { CoreModule } from '../../../core/core.module';
import { BooleanIndicatorComponent, BooleanIndicatorType } from './boolean-indicator.component';
describe('BooleanIndicatorComponent', () => {
let component: BooleanIndicatorComponent;
let fixture: ComponentFixture<BooleanIndicatorComponent>;
let element: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [BooleanIndicatorComponent],
imports: [CoreModule, NoopAnimationsModule]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BooleanIndicatorComponent);
component = fixture.componentInstance;
component.type = BooleanIndicatorType.enabledDisabled;
component.isTrue = true;
fixture.detectChanges();
element = fixture.nativeElement;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show text by default', () => {
expect(element.textContent).toContain('Enabled');
});
it('should hide text if set', () => {
component.showText = false;
fixture.detectChanges();
expect(element.textContent).not.toContain('Enabled');
});
it('should show unknown if not boolean value', () => {
component.isTrue = null;
fixture.detectChanges();
expect(element.textContent).toContain('Unknown');
});
});
|
'SNL': Melissa McCarthy is back as Sean Spicer, and with a leaf blower
CLOSE Melissa McCarthy completely killed it last week on SNL as White House Press Secretary Sean Spicer, and this week she returned for a much anticipated encore, showing up in the cold open. USA TODAY
Watch out, White House Press Corps: Spicey's back.
Melissa McCarthy answered comedy fans' prayers, rolling back onto the Saturday Night Live stage as the embattled press secretary, complete with a motorized podium, ready to take the fight right to the front row of the briefing room.
Her Spicer also swapped out last week's super soaker with a leaf blower trained on a reporter who dared question a White House statistic saying 80% of Chicagoans have been murdered.
Spicey is really blowing away the White House press corps. #SNLpic.twitter.com/HSbKAX07zz — Saturday Night Live (@nbcsnl) February 12, 2017
There was also a QVC-style pitch for Ivanka Trump's fashion line. "I'm wearing one of her bangles right now!" McCarthy/Spicer proclaimed before doing a Bridesmaids leg lift to reveal a pair of patterned pumps.
But our favorite? The presidential prop box, which was rolled back out to explain extreme vetting.
"Ya got your TSA agent right here. First, we got Barbie. Nice American girl, back from her dream vacation. We know she's OK because she's blond. So she gets in. Now, who's up next? Uh oh, it's Moana. Whoa. Slow your roll, honey. We're gonna pat her down. Then we're gonna read her emails and if we don't like the answers — which we won't — BOOM! Guantanamo Bay!"
Read or Share this story: http://usat.ly/2ky3o4e |
def rectSet(rectList):
toReturn = []
for rect in rectList:
if rect not in toReturn:
toReturn.append(rect)
return toReturn |
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ____ ___ __ _
// / __// o |,'_/ .' \
// / _/ / _,'/ /_n / o / _ __ _ ___ _ _ __
// /_/ /_/ |__,'/_n_/ / \,' /.' \ ,' _/,' \ / |/ /
// / \,' // o /_\ `./ o // || /
// /_/ /_//_n_//___,'|_,'/_/|_/
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Author : <NAME> (WTR)
// Design history : Review git logs.
// Description : Calculating the absolute value
// Concepts : f1 does not change value because variables become local in a
// : function.
// : Inputs parameters need to be of correct arguement types.
// : Likewise the output of a function is of type, thus float/int
// : at bottom.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <stdio.h>
float absVal (float x)
{
if (x < 0)
x = -x;
return x;
}
int main(void)
{
float f1 = -15.0, f2= 20.0, f3=-5.0;
int i1=-716;
float result;
result = absVal(f1);
printf("result = %.2f\n", result);
printf("f1 = %.2f\n", f1);
result = absVal(f2) + absVal(f3);
printf("result = %.2f\n", result);
result = absVal((float)i1);
printf("result = %.2f\n", result);
printf("%.2f\n", absVal(-6.0)/4);
return 0;
}
|
/*
* Copyright (c) 2015 Intellectual Reserve, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package cf.dropsonde.firehose;
import org.cloudfoundry.dropsonde.events.Envelope;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.CharsetUtil;
import rx.Subscriber;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManagerFactory;
import java.io.Closeable;
import java.net.URI;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
/**
* @author <NAME>
*/
class NettyFirehoseOnSubscribe implements rx.Observable.OnSubscribe<Envelope>, Closeable {
public static final String HANDLER_NAME = "handler";
private Channel channel;
// Set this EventLoopGroup if an EventLoopGroup was not provided. This groups needs to be shutdown when the
// firehose client shuts down.
private final EventLoopGroup eventLoopGroup;
private final Bootstrap bootstrap;
public NettyFirehoseOnSubscribe(URI uri, String token, String subscriptionId, boolean skipTlsValidation, EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) {
try {
final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
final int port = getPort(scheme, uri.getPort());
final URI fullUri = uri.resolve("/firehose/" + subscriptionId);
final SslContext sslContext;
if ("wss".equalsIgnoreCase(scheme)) {
final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
if (skipTlsValidation) {
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
} else {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore)null);
sslContextBuilder.trustManager(trustManagerFactory);
}
sslContext = sslContextBuilder.build();
} else {
sslContext = null;
}
bootstrap = new Bootstrap();
if (eventLoopGroup == null) {
this.eventLoopGroup = new NioEventLoopGroup();
bootstrap.group(this.eventLoopGroup);
} else {
this.eventLoopGroup = null;
bootstrap.group(eventLoopGroup);
}
bootstrap
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000)
.channel(channelClass == null ? NioSocketChannel.class : channelClass)
.remoteAddress(host, port)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel c) throws Exception {
final HttpHeaders headers = new DefaultHttpHeaders();
headers.add(HttpHeaders.Names.AUTHORIZATION, token);
final WebSocketClientHandler handler =
new WebSocketClientHandler(
WebSocketClientHandshakerFactory.newHandshaker(
fullUri, WebSocketVersion.V13, null, false, headers));
final ChannelPipeline pipeline = c.pipeline();
if (sslContext != null) {
pipeline.addLast(sslContext.newHandler(c.alloc(), host, port));
}
pipeline.addLast(new ReadTimeoutHandler(30));
pipeline.addLast(
new HttpClientCodec(),
new HttpObjectAggregator(8192));
pipeline.addLast(HANDLER_NAME, handler);
channel = c;
}
});
} catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) {
throw new RuntimeException(e);
}
}
@Override
public void call(Subscriber<? super Envelope> subscriber) {
bootstrap.connect().addListener((ChannelFutureListener)future -> {
if (future.isSuccess()) {
future.channel().pipeline().get(WebSocketClientHandler.class).setSubscriber(subscriber);
} else {
subscriber.onError(future.cause());
}
});
}
@Override
public void close() {
if (channel != null) {
channel.close();
}
if (eventLoopGroup != null) {
eventLoopGroup.shutdownGracefully();
}
}
private int getPort(String scheme, int port) {
if (port == -1) {
if ("ws".equalsIgnoreCase(scheme)) {
return 80;
} else if ("wss".equalsIgnoreCase(scheme)) {
return 443;
} else {
return -1;
}
} else {
return port;
}
}
public boolean isConnected() {
return channel != null && channel.isActive();
}
private static class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {
private final WebSocketClientHandshaker handshaker;
private Subscriber<? super Envelope> subscriber;
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
this.handshaker = handshaker;
}
@Override
public void channelActive(ChannelHandlerContext context) throws Exception {
handshaker.handshake(context.channel());
}
@Override
public void channelInactive(ChannelHandlerContext context) throws Exception {
subscriber.onCompleted();
}
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
context.close();
subscriber.onError(cause);
}
@Override
protected void channelRead0(ChannelHandlerContext context, Object message) throws Exception {
final Channel channel = context.channel();
if (!handshaker.isHandshakeComplete()) {
handshaker.finishHandshake(channel, (FullHttpResponse) message);
channel.pipeline().addBefore(HANDLER_NAME, "websocket-frame-aggregator", new WebSocketFrameAggregator(64 * 1024));
subscriber.onStart();
return;
}
if (message instanceof FullHttpResponse) {
final FullHttpResponse response = (FullHttpResponse) message;
throw new IllegalStateException(
"Unexpected FullHttpResponse (getStatus=" + response.getStatus() +
", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
}
final WebSocketFrame frame = (WebSocketFrame) message;
if (frame instanceof PingWebSocketFrame) {
context.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame)frame).retain().content()));
} else if (frame instanceof BinaryWebSocketFrame) {
final ByteBufInputStream input = new ByteBufInputStream(((BinaryWebSocketFrame)message).content());
final Envelope envelope = Envelope.ADAPTER.decode(input);
subscriber.onNext(envelope);
}
}
public void setSubscriber(Subscriber<? super Envelope> subscriber) {
this.subscriber = subscriber;
}
}
}
|
<reponame>DataDog/goshe<filename>cmd/tail.go
// +build linux darwin freebsd
package cmd
import (
"bufio"
"fmt"
"github.com/DataDog/datadog-go/statsd"
"github.com/hpcloud/tail"
"github.com/spf13/cobra"
"os"
"os/exec"
"regexp"
"strings"
)
var tailCmd = &cobra.Command{
Use: "tail",
Short: "Tail logs or stdout, match lines and send metrics to Datadog.",
Long: `Tail logs or stdout, match lines and send metrics to Datadog.`,
PreRun: func(cmd *cobra.Command, args []string) {
checkTailFlags()
},
Run: startTail,
}
func startTail(cmd *cobra.Command, args []string) {
// Try to compile the regex - throw an error if it doesn't work.
regex, err := regexp.Compile(Match)
if err != nil {
fmt.Println("There's something wrong with your regex. Try again.")
fmt.Printf("Error: %s\n", err)
os.Exit(1)
}
dog := DogConnect()
// For the Logfile option.
if LogFile != "" {
t := OpenLogfile(LogFile)
TailLog(t, dog, regex)
}
// If you're capturing stdout of a program.
if ProgramStdout != "" {
TailOutput(dog, regex)
}
}
func checkTailFlags() {
if LogFile == "" && ProgramStdout == "" {
fmt.Println("Please enter a filename to tail '--log' OR a program to run '--program'")
os.Exit(1)
}
if LogFile != "" && ProgramStdout != "" {
fmt.Println("Please choose '--log' OR '--program' - you cannot have both.")
os.Exit(1)
}
if Match == "" {
fmt.Println("Please enter a regex to match '--match'")
os.Exit(1)
}
if MetricName == "" {
fmt.Println("Please enter a metric name to send '--metric'")
os.Exit(1)
}
// If you're sending a MetricTag - it needs to have a ':'
if MetricTag != "" && !strings.Contains(MetricTag, ":") {
fmt.Println("Tags need to contain a ':'")
os.Exit(1)
}
fmt.Println("Press CTRL-C to shutdown.")
}
var (
// LogFile is the file to tail.
LogFile string
// ProgramStdout is a program to run to capture stdout.
ProgramStdout string
// Match is the regex to match in the file.
Match string
// MetricName is the name of the metric to send to Datadog.
MetricName string
// MetricTag is the name of the tag to add to the metric we're sending to Datadog.
MetricTag string
)
func init() {
tailCmd.Flags().StringVarP(&LogFile, "log", "", "", "File to tail.")
tailCmd.Flags().StringVarP(&ProgramStdout, "program", "", "", "Program to run for stdout.")
tailCmd.Flags().StringVarP(&Match, "match", "", "", "Match this regex.")
tailCmd.Flags().StringVarP(&MetricName, "metric", "", "", "Send this metric name.")
tailCmd.Flags().StringVarP(&MetricTag, "tag", "", "", "Add this tag to the metric.")
RootCmd.AddCommand(tailCmd)
}
// TailLog tails a file and sends stats to Datadog.
func TailLog(t *tail.Tail, dog *statsd.Client, r *regexp.Regexp) {
for line := range t.Lines {
// Blank lines really mess this up - this protects against it.
if line.Text == "" {
continue
}
match := r.FindAllStringSubmatch(line.Text, -1)
if match != nil {
Log(fmt.Sprintf("Match: %s", match), "debug")
Log(fmt.Sprintf("Sending Stat: %s", MetricName), "debug")
tags := dog.Tags
if MetricTag != "" {
tags = append(tags, MetricTag)
}
dog.Count(MetricName, 1, tags, 1)
}
}
}
// TailOutput watches the output of ProgramStdout and matches on those lines.
func TailOutput(dog *statsd.Client, r *regexp.Regexp) {
cli, args := processCommand(ProgramStdout)
runCommand(cli, args, r, dog)
}
func processCommand(command string) (string, []string) {
var cli string
var args []string
parts := strings.Fields(command)
cli = parts[0]
args = parts[1:]
Log(fmt.Sprintf("Cli: %s Args: %s", cli, args), "debug")
return cli, args
}
func runCommand(cli string, args []string, r *regexp.Regexp, dog *statsd.Client) {
cmd := exec.Command(cli, args...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
Log(fmt.Sprintf("There was an error running '%s': %s", ProgramStdout, err), "info")
os.Exit(1)
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
line := scanner.Text()
Log(fmt.Sprintf("Line: %s", line), "debug")
// Blank lines are bad for the matching software - it freaks out.
if line == "" {
continue
}
match := r.FindAllStringSubmatch(line, -1)
if match != nil {
Log(fmt.Sprintf("Match: %s", match), "debug")
Log(fmt.Sprintf("Sending Stat: %s", MetricName), "debug")
tags := dog.Tags
if MetricTag != "" {
tags = append(tags, MetricTag)
}
dog.Count(MetricName, 1, tags, 1)
}
}
}()
err = cmd.Start()
if err != nil {
Log("There was and error starting the command.", "info")
}
err = cmd.Wait()
if err != nil {
Log("There was and error waiting for the command.", "info")
}
}
|
#pragma once
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
// There are three types of records in a closed hash:
// Normal records, empty records, and tombstones
enum RecordType { normalRecord, emptyRecord, tombstone };
// Each record holds an integer key and a value of any type
// (hence the need for a template). The value type must be
// printable using << or this code will fail.
//
// In this implementation, the value is stored directly in
// the record. If the value is large, it would be more
// efficient to have the records hold pointers to the values.
// In this case, care would need to be taken to ensure
// that deep copies are made upon assignment, and that
// any values allocated are properly deleted in the Record
// destructor.
template <class K, class V> class Record {
private:
K key;
V value;
RecordType type;
public:
// The default constructor produces an empty record.
// A possibly better way to keep track of tombstones and emtpy
// records would be to use inheritance, similar to the way we
// avoided having null pointers in leaf nodes for binary trees.
Record() {
type = emptyRecord;
}
// This constructor uses an initialization list
// See "member initialization" at: http://www.cplusplus.com/doc/tutorial/classes/
Record(K newkey, V newvalue) : key(newkey), value(newvalue) {
type = normalRecord;
}
// Convert a record to a tombstone
void kill() {
type = tombstone;
}
// Get the integer key of a record
K getKey() const {
return key;
}
// Get the value of a record
V getValue() const {
return value;
}
// Check if a record is empty
bool isEmpty() const {
return(type == emptyRecord);
}
// Check if a record is a normal record
bool isNormal() const {
return(type == normalRecord);
}
// Check if a record is a tombstone
bool isTombstone() const {
return (type == tombstone);
}
// Overload the << operator for printing records
friend ostream& operator<<(ostream& os, const Record& me) {
if (me.isTombstone())
os << "<<Tombstone>>";
else if (me.isEmpty())
os << "<<Empty>>";
else
os << "Key: " << me.key << ", Value: " << me.value;
return os;
}
~Record() {}
};
|
<gh_stars>1-10
package models
// CommandWrapper struct for CommandWrapper
type CommandWrapper struct {
GroupId int64 `json:"groupId,omitempty"`
ClientId int64 `json:"clientId,omitempty"`
LoanId int64 `json:"loanId,omitempty"`
SavingsId int64 `json:"savingsId,omitempty"`
EntityName string `json:"entityName,omitempty"`
TaskPermissionName string `json:"taskPermissionName,omitempty"`
EntityId int64 `json:"entityId,omitempty"`
SubentityId int64 `json:"subentityId,omitempty"`
Href string `json:"href,omitempty"`
Json string `json:"json,omitempty"`
TransactionId string `json:"transactionId,omitempty"`
ProductId int64 `json:"productId,omitempty"`
CreditBureauId int64 `json:"creditBureauId,omitempty"`
OrganisationCreditBureauId int64 `json:"organisationCreditBureauId,omitempty"`
UpdateOperation bool `json:"updateOperation,omitempty"`
Delete bool `json:"delete,omitempty"`
DeleteOperation bool `json:"deleteOperation,omitempty"`
SurveyResource bool `json:"surveyResource,omitempty"`
RegisterSurvey bool `json:"registerSurvey,omitempty"`
FullFilSurvey bool `json:"fullFilSurvey,omitempty"`
WorkingDaysResource bool `json:"workingDaysResource,omitempty"`
PasswordPreferencesResource bool `json:"passwordPreferencesResource,omitempty"`
PermissionResource bool `json:"permissionResource,omitempty"`
UserResource bool `json:"userResource,omitempty"`
CurrencyResource bool `json:"currencyResource,omitempty"`
LoanDisburseDetailResource bool `json:"loanDisburseDetailResource,omitempty"`
UpdateDisbursementDate bool `json:"updateDisbursementDate,omitempty"`
Create bool `json:"create,omitempty"`
CreateDatatable bool `json:"createDatatable,omitempty"`
DeleteDatatable bool `json:"deleteDatatable,omitempty"`
UpdateDatatable bool `json:"updateDatatable,omitempty"`
DatatableResource bool `json:"datatableResource,omitempty"`
DeleteOneToOne bool `json:"deleteOneToOne,omitempty"`
DeleteMultiple bool `json:"deleteMultiple,omitempty"`
UpdateOneToOne bool `json:"updateOneToOne,omitempty"`
UpdateMultiple bool `json:"updateMultiple,omitempty"`
RegisterDatatable bool `json:"registerDatatable,omitempty"`
NoteResource bool `json:"noteResource,omitempty"`
CacheResource bool `json:"cacheResource,omitempty"`
Update bool `json:"update,omitempty"`
}
|
/**
* Get the enum constant with the given name (ignoring case), or {@code defaultValue} if no
* match is found.
*
* @return The enum constant with the given name, or {@code defaultValue} if invalid.
*/
public static <E extends Enum<E>> E byName(String name, E defaultValue) {
for (E e : defaultValue.getDeclaringClass().getEnumConstants()) {
if (e.name().equalsIgnoreCase(name)) {
return e;
}
}
return defaultValue;
} |
/**
* Parses a {@code String agenda} into a {@code Agenda}.
* Leading and trailing whitespaces will be trimmed.
*
* @throws ParseException if the given {@code agenda} is invalid.
*/
public static Agenda parseAgenda(String agenda) throws ParseException {
requireNonNull(agenda);
String trimmedAgenda = agenda.trim();
if (!Agenda.isValidAgenda(trimmedAgenda)) {
throw new ParseException(Agenda.MESSAGE_AGENDA_CONSTRAINTS);
}
return new Agenda(trimmedAgenda);
} |
def write_page(self, page_text, filepath):
if self.mode == "pdf":
base_folder = self.staging_folder
else:
base_folder = self.out_path
out_folder = os.path.join(base_folder, os.path.dirname(filepath))
if not os.path.isdir(out_folder):
logger.info("creating output folder %s" % out_folder)
os.makedirs(out_folder)
fileout = os.path.join(base_folder, filepath)
if os.path.isdir(fileout):
logger.info("Writing index file for out-file '%s'" % fileout)
fileout = fileout+"index.html"
with open(fileout, "w", encoding="utf-8") as f:
logger.info("writing to file: %s..." % fileout)
f.write(page_text) |
package mvc;
import javafx.application.Application;
import javafx.stage.Stage;
public class MVCCounter extends Application {
public static void main (String[] args) {
Application.launch(args);
}
public void start (Stage stage) {
CounterModel model = new CounterModel();
CounterController controller = new CounterController(model);
new WatchView(model, controller);
new CounterView(model, controller);
new CpView(model, controller);
new TotalView(model, controller);
}
}
|
// Clones the given selector and returns a new selector with the given key and value added.
// Returns the given selector, if labelKey is empty.
func CloneSelectorAndAddLabel(selector *metav1.LabelSelector, labelKey, labelValue string) *metav1.LabelSelector {
if labelKey == "" {
return selector
}
newSelector := new(metav1.LabelSelector)
newSelector.MatchLabels = make(map[string]string)
if selector.MatchLabels != nil {
for key, val := range selector.MatchLabels {
newSelector.MatchLabels[key] = val
}
}
newSelector.MatchLabels[labelKey] = labelValue
if selector.MatchExpressions != nil {
newMExps := make([]metav1.LabelSelectorRequirement, len(selector.MatchExpressions))
for i, me := range selector.MatchExpressions {
newMExps[i].Key = me.Key
newMExps[i].Operator = me.Operator
if me.Values != nil {
newMExps[i].Values = make([]string, len(me.Values))
copy(newMExps[i].Values, me.Values)
} else {
newMExps[i].Values = nil
}
}
newSelector.MatchExpressions = newMExps
} else {
newSelector.MatchExpressions = nil
}
return newSelector
} |
/**
* Sets the form style.
*The possible values are:
*DECORATED - Default style.
*UNDECORATED - Window without decorations.
*TRANSPARENT - Transparent window without decorations.
*UTILITY - Window with minimal decorations.
*/
public void SetFormStyle(String Style) {
if (Style.equals("UNIFIED"))
Style = "DECORATED";
stage.initStyle(StageStyle.valueOf(Style));
} |
Organizing the Unorganized Lifestyle Retailers in India: An Integrated Framework
India is one of the largest countries with consumers belonging to widest range of Religions, Regions, Languages, Sub-Cultures, Ethnicities, and Economic backgrounds which makes it difficult for just few organized lifestyle retailers to service divergent needs of such consumers. This makes it furthermore beneficial for unorganized lifestyle retailers spread across India in humongous numbers which are predominantly owned and operated by the store owner and their family members to take such divergent consumer needs to their advantage as far as their survival is concerned. Unless they attempt to adopt certain modifications and changes to their existing retailing model and store image this benefit will no longer be available to them in the long run. Organized lifestyle retailing in India is steadily growing its penetration into Tier-2 and Tier-3 cities and this is putting unorganized lifestyle retailers in these cities in quandary. In this study, we have analysed twelve months actual data across,
a) unit economics;
b) returns on investment;
c) 94 business deployment factors;
d) 192 critical effective factors; and,
e) qualitative factors of few select organized and unorganized lifestyle retailers in India thereby drawing inferences / insights to design and propose an integrated framework which is,
a) simple to understand;
b) easy to execute; and most importantly
c) demanding minimal additional capital investment and would possibly help unorganized lifestyle retailers in India to get organized.
INTRODUCTION :
1.1.Unorganized Lifestyle Retailing in India: For the purpose of limiting the focus of this research study, we define unorganized lifestyle retailers in India as, brick-and-mortar retail stores managed and operated by store owners and their family members themselves, offering lifestyle products such as Apparel, Footwear and Accessories, to consumers located in and around the store's catchment area and most importantly the sales pitch of sales personnel in the store is push technique driven owing to the concealed merchandise display methodology adopted. Each individual wants to have a unique identity which could be based on his / her, a) background such as nationality, ethnicity, culture, subculture, social class, affiliation, environment, etc; b) experiences and c) choices. Lifestyle retailers in fact attempt to evoke emotional connections between consumers and their need to have a unique identity and most importantly lifestyle retailers are increasingly becoming one of the key components of consumer's self-expression . Lifestyle retail market size in India is expected to reach 130 billion USD by the year 2023 which is a 77 percent growth when compared to the year 2013 . Based on India's 2011 census, United Nation's (UN) Department of Statistics and Programme Implementation estimates Indian population to reach close to 1.38 billion by the year 2020 . It is estimated that more than 300 Global lifestyle brands have plans to open their stores in India this year . In addition to this humongous population, exponential growth in number of working women, double income families, middle-class consumer segment, increasing disposable income, rapid adoption of fashion, urbanization, overall size of Indian retail industry, emergence of modern retailing formats and most importantly enormous increase different locations and distribution channel partner's stores as possible to have a competitive advantage over competitors and especially unorganized local favourites. Nevertheless, if unorganized lifestyle retailers fail to adopt basic aspects of organized retailing model and store image, it will possibly lead them to lose market share to organized lifestyle retailers.
LITERATURE REVIEW :
2.1. Store image had been one of the key elements of the retailing mix studied in the past. Lindquist was the first to list the key components of store image construct in the year 1974. Based on past studies Lindquist listed eight components of store image construct viz., i) merchandise, ii) clientele, iii) physical facilities, iv) convenience, v) promotion, vi) store atmosphere, vii) institutional factors and viii) post-transactional satisfaction . Later researchers have confirmed that the basic attributes of store image construct as listed by Lindquist in 1974 remain unchanged and were able to add few more attributes to store image construct such as ix) customer service, x) personal selling, and xi) sales incentive programs .Few studies argue that these factors together influence the overall store image in consumers minds only when the consumers have experienced these factors through actual shopping . There have been many studies confirming a positive correlation between store layout and consumer loyalty . Consumers perception of store image varies with store layout and consumers shopping at different store formats having different store layouts create their own perception of store image in their mind . Extending these studies recommend bricks-and-mortar retailers to align their store layout design keeping their target consumers in mind rather adopting standard layout designs . Retailers need to consider various location specific factors while planning for expansion such as a) attractiveness of the market, b) number of stores to be opened per market, c) store locations and d) ideal store size for each of these stores. In this study, they clearly indicate that every store needs to have size optimal for the location and market it is present rather a standard size being adopted across all the stores of a particular retailing format. In all these studies nowhere, researchers recommend retailers to adopt different price level of merchandise for different locations of stores . A retailer having a unique store image and using this unique store image as one of the key promotional and marketing/advertising propositions can possibly yield competitive advantage and it is important to note that copying a store image which is complex in its nature is a difficult task for competitors . One of the most important determinants of retailer success is store image . Retailers need to clearly understand various environmental factors relating to store image influencing their target consumers. It is very important to design strategies relating to store an image in a specific location in relation to retailers target consumers in that particular environment . Majority of retailers design strategies relating to specific locations based on the consumer behaviour pattern and knowledge available in the general market in the specific location which is also based on the general consumer population . These strategies lead retailers to align most of the store image attributes to the general consumer population and hence they might possibly fail to maintain their principal brand/store image standard across various locations or geographies. Retailer's store success and consumer loyalty is majorly influenced by store image along with store positioning and product-price differentiation in relation to market. Retailers could possibly use such store image attributes to promote and advertise their positioning in the consumers mind .Store location is not just about the physical space which has been occupied by a store, it is actually a catchment area of a store which witnesses heavy commercial and economic activities . Store size and location are the most important components of retailing as far as enhancing consumer experience is concerned. Few reputed retail brands like Zara have increased their store sizes exponentially along with changing the type of locations in the past, few retail brands such as Debenhams and Mother Care have downsized their existing store sizes to incorporate improved operating efficiencies, few retail brands such as Tesco entered city centre locations with smaller sized stores, few continually kept rationalizing their store sizes and few still believe that larger the store size higher the consumer walk-ins . One of the biggest challenges faced by brick-andmortar retailers is the higher cost involved in expanding store sizes even though it helps them in enhancing the overall consumer shopping experience. Retailers are finding it extremely difficult to find relevant spaces in the right locations owing to higher rentals and lesser spaces available in key retail locations , which proposes retailers to consider mall kiosks as one possible retailing format which can be cost effective as far as expensive rentals are concerned. It is true that store location plays an influential role in consumer store choice decisions, at the same time store location being a long-term capital lock-in decision plays an important role for retailer's overall strategic planning. Any location which has inherent properties of attracting consumers is the best location for any retailer and having a store in such locations brings both strategic and competitive advantages to the retailer, whereas, it will take longer time and huge store losses for any retailer to come out of a bad store location. Good store location could also be analysed by; a) the amount of relevant consumer traffic flow be it, pedestrian traffic or vehicular traffic; b) parking facilities; c) store composition; d) specific site; e) terms of occupancy, f) accessibility, g) travelling time, h) location convenience, i) other complimentary stores present in the catchment . Through our previous empirical and experimental research studies, we have concluded that; (i) if retailer considers building premium store image in consumers, competitors, and investors mind as the key indicator of judging best location for a store, mall stores are the ideal ones, and if the retailer is interested in overall retail performance with consistent growth and sustainable profits then a rational mix of each of these locations is the ideal solution ; (ii) there is no significant variance in contribution of different price bands to overall bills / invoices and revenue being generated by stores across Tier 1, Tier 2 and Tier 3 cities for a retailer who runs all these stores under a single store brand name and results have shown that stores in Tier 2 and Tier 3 cities generate lesser revenue compared to Tier1 city stores and this must not be mistaken as consumers in cities other than Tier1 cities face affordability issue ; and (iii) the fourth and important elements of Marketing Mix 'place' need be aligned based on the product / category grouping in relation to target consumer group and catchment area . 2.2. Consumer preference or choice of brand and the success of a brand depends upon the brand's personality. It is important for the marketer to constantly work on strategies to convert the existing brand image into equity . Few researchers have investigated the correlation among the competition of brands, formation of consumers' attitude and intention to choose a particular brand or alternatives being offered to the consumers at a given point of time and the place of the offering. Findings of these studies confirm that consumers' evaluations, understandings, and knowledge about a particular brand of their choice are not just the key influencer of creating intentions of buying a product belonging to a brand, it is also consumers' perspectives and perceptions toward another alternative or brand available in the offering . There are few brands which have gained strong brand equity owing to consumers having special, favourable association with such brands in their memories and these brands were able to create higher perceived quality, awareness about the brand name and ultimately leading huge loyal consumers over a period of time . Consumers tend to correlate their personality with the brand personality they are willing to associate with, wherein they attribute this to their demographic characteristics, physical characteristics, personal traits and, cognitive abilities consequently leading them to buy a brand's product to implicitly or explicitly express / showcase their personal image or identity . Abundant literature is available on Brand personality, image, equity, experience, association, advertisement, endorsements, and loyalty as a result of contributions from many researchers across domains. 2.3.Unorganized retailing had been one of the key research studies in the Policy Making and Economics domain since late 60's. Traditional retailing formats were perceived to be inefficient and weak in various aspects and hence successful modernization policies to be implemented in countries having majority of retailing in the unorganized form . Many countries have implemented policies favouring unorganized and informal sectors such as; (i) in the year 1979 Singapore Government launched 'Hawker centres upgrading programme', (ii) Taiwan launched upgrading programme for 'Old wet markets' in 1979; and, (iii) Russia and South Korea launched development programme for traditional sector in 1990 and in spite of many recommendations India is yet to launch such programmes . Singapore's 'retail sector development plan' initiative which was launched in the year 1992 even though driven by an exclusive organization 'Retail Promotion Center' which attempted to upgrade unorganized, informal and small-scale retailers was unsuccessful due to limited access and control over convincing the retailers . Organizing the unorganized retailing required additional capital investment which is not easily available on credit to small-scale retailers, many countries have assisted unorganized retailers through capital support to withstand challenges posed by organized and modern retailers, the capital assistance aspect is one of the most important aspects to convince and encourage unorganized retailers to get organized which in turn shall boost the overall economy of a country . Unorganized / small retailers are better in comparison to organized retailers such as,(a) they know the 'likes and dislikes' of their consumers, (b) customization while product showcasing, promotions and even information regarding new arrivals are higher, (c) credit facility to their loyal consumers, (d) easier systems and processes with respect to product returns and exchanges, (e) easy to shop for daily needs, (f) convenience of store location which is almost a neighbourhood store, and (g) store owners involvement with local communities and clubs, however, unorganized retailers must attempt to work on few aspects of their retailing model to gain an additional competitive advantage over organized retailers such as, (i) efficient supply chain and inventory management, (ii) matching discounts and offers with organized retailer's discounts and offers, and (iii) open merchandise display techniques . In spite of many studies indicating that the Indian retail market is all set to reach a trillion US Dollars, the fear of organizing retailers taking the market share away from unorganized retailers in India is not justified . Few studies have also expressed their concerns on predatory pricing being used as one of the tactics by the organized retailers to penetrate into new markets which are predominantly serviced by unorganized retailers . Approximately 80 percent of unorganized / small-scale retailing in India is run by family owned business houses in other words it represents 9.6 million stores, and this is one of the largest numbers of small-scale stores present in a country . Many researchers have also focussed on studying the influence of unorganized retailing with respect to the overall economy of a nation and argued that, a) overall economy of a country could be analysed based on the revenue and employment the retailing sector is generating, b) it is inevitable to continuously focus on improving key aspects of retail operations, systems, supply chain and processes which could possibly lead to better economy of a country, c) constant innovations in the business models have a positive impact on the overall performance of retailing company . 2.4. Need for this research aroused when we found that majority of empirical, theoretical, and descriptive literature available on the unorganized retailing in India focusses on analysing pros and cons of organized and unorganized retailing. We were not able to find frameworks which could guide unorganized lifestyle retailers in India to organize themselves to withstand increasing competition and market penetration from organized lifestyle retailers with which we could answer our research questions such as; (a) should we believe that the existing retailing model of lifestyle retailers in India is an appropriate strategy?; (b) should we believe that the existing retailing model is delivering optimal revenue and profit for the unorganized lifestyle retailers?; (c) should we believe that the existing retailing strategy is aligned with retailer's target consumers and consumer's changing attitude towards unorganized retailing?; (d) is it a misconception among unorganized lifestyle retailers in India that consumers are attracted to stores / retail formats located very close to their residence and these consumers tend to continue shopping in these mom and pop stores just because the store location is convenient? and; (e) are these unorganized lifestyle retailers aware of the impact on their sustainability and even existence owing to constantly growing market penetration of organized lifestyle retailers in India? Thus, we decided to select few National level, Regional level, Local level organized Indian lifestyle retailers in addition to few unorganized lifestyle retailers across the country, understand their existing retailing model, empirically evaluate their actual sales and consumer data in relation to retailer's key business goal, thereby drawing insights to recommend unorganized lifestyle retailers in India an integrated framework to gain longterm strategic and competitive advantage in addition to establishing themselves as organized lifestyle retailers image across their existing and potential employees, investors, competitors, and consumers mind. Most importantly unorganized lifestyle retailing being one of the major contributors to Indian GDP it is inevitable for these retailers to get organized thereby supporting the country's new vision of Aatmanirbhar Bharat / Self-Reliant India.
OBJECTIVES :
Key objectives of this research were to, i) understand lifestyle retailing market in India; ii) understand evolution and performance of lifestyle retailing in India; iii) understand the unit economics of organized and unorganized lifestyle retailers in India; iv) compare organized and unorganized lifestyle retailing in India; v) analyse recommendations from previous research studies; vi) determine key concepts which could possibly help unorganized lifestyle retailers to get organized; vii) design and propose an integrated framework, and vii) recommend a systematic approach for executing the integrated framework.
METHODOLOGY:
4.1. Secondary Research: Intense and in-depth analysis of data available in the public domain was carried to collect data relating to various aspects of organized and unorganized lifestyle retailers in India through company websites, company annual financial reports, Government data base, trade, and business journals. Research works relating to Indian lifestyle brands was surveyed extensively to collect insights, recommendations, and frameworks. 4.2. Quantitative Primary Research: In the first stage, few organized and unorganized lifestyle retailers in India were selected who can represent, a) different product categories such as fashion, functional, life-stage specific, product specific, gender specific, and need specific products; b) offering single-product category and multiple-product categories; c) serving different consumer target groups at low, mid-low, mid, mid-high, high, and premium price positioning; d)having single and multiple stores; e) offering single brand and multiple brands; f) having presence across Tier-1, Tier-2 and Tier-3 cities; g) having stores across high street, malls, institutions and neighbourhoods, and h) new and established retail store image. In the second stage, twelve months actual data was collected from these select organized and unorganized lifestyle retailers to quantitatively map their existing retailing model and draw inferences.
Qualitative Primary Research
: Series of open-ended direct interviews were conducted with employees selected through convenience sampling representing different departments/functions from Brands, Distributors and Retailers viz., Human Resource Development, Training, Strategy, Category, Communication, Customer Relationship, Warehousing, Finance, Information Technology, Sales, Distribution, Stores Operation along with Store Sales Personnel across select organized and unorganized lifestyle retailers in India to understand their perspective and attitude towards their existing retailing model and its implications on the overall performance and store image.
KEY FINDINGS AND INSIGHTS :
5.1. Qualitative: Prior to the empirical study, we were able to derive qualitative insights through mystery shopping and conduct open-ended direct interviews with employees representing all the departments and functions of lifestyle retailers chosen for the study. Key insights from the qualitative survey indicate that, these lifestyle retailers strongly had numerous beliefs and assumptions as detailed below separately for organized and unorganized retailers. 5.1.1. Unorganized Lifestyle Retailers: Key perceptions which were unanimous among the unorganized retailers were, a) for the products we offer in our stores it is less likely that our consumers purchase from elsewhere; b) unlike organized retailers we do not communicate anything to our consumers which is a computer driven, rather we call each consumer on our own to communicate any specific product and promotion information relevant for them while talking to them in general on matters unrelated to retailing; c) we buy only what sells and we know what is required by our consumers for which we do not require a computer to guide us on managing stocks in the store; d) majority of our product's original price (MRP) itself is so low as compared to organized retailers which is already known to our consumers and hence offering additional discounts is not a mandatory requirement; e) as we know the complete history, background, socio-economic status of every consumer and their family we showcase and recommend products based on these criterion; f) our consumers belief on us as owners of the shop overrides any deficiencies if at all found in the products and service we offer to them; g) we are more bothered about consistent and constant cash flow generated by the store rather only profits as we are aware of the fact that the store being operational since generations has already given us enough profits; h) sales personnel in our stores are committed and loyal to us and very rarely they disassociate from us; i) notwithstanding we pay less to our sales personnel compared to organized retailer, we make sure that we do solve their personal problems (both monetary and non-monetary) often; j) we need not to train our sales personnel as they are well versed with our product assortment; k) unlike organized retailers we do not use mass social media to connect with our consumers, WhatsApp is enough and is much more stronger tool to get connected with our consumers regularly; l) we do renovate our store once in a year even though it is at a smaller scale; m) we offer more trendy products aligned to latest trends inspired by the Indian Cinema as our supply chain is of small-scale and we manage to test many new products at lower inventory risks; n) our product assortment also has few National and Global brands in it; o) we do sell premium and high priced products, and p) decision making of any magnitude does not take longer time as we are appraised of all the activities related to our stores. 5.1.2. Organized Lifestyle Retailing: Key perceptions which were unanimous among the organized retailers were, a) more than online retailers, unorganized retailers are the biggest threat for us; b) unorganized retailers sell products which are sold at cheap prices with no guarantee on the product quality and durability; c) consumers need to spend some time in planning their shopping at organized retail stores which is not the case when it comes to shopping at unorganized retail shops owing their stores being located very close to consumers residence; d) we are struggling to witness success at Tier-2 and Tire-3 cities as consumers in these cities are still loyal to unorganized retailers; e) we spend a lot of time and money in communicating to consumers using all the latest software tools and solutions; f) our sales personnel are well groomed and trained and they are paid much higher than unorganized retailers; g) attrition rate of our sales personnel is significantly high; h) we follow open merchandise display techniques which enable consumers to choose their best choice unlike unorganized retailer who showcase only few products / models / brands to consumers; i) we have robust systems and standard operating procedures across all the processes of retailing; j) we offer best National and Global brands in addition to Private labels to consumers; k) we give the same shopping experience to consumers across all our stores irrespective of the city; l) revenue generated by our stores is significantly higher than unorganized stores; m) consumers spend is significantly higher in our stores; n) share of loyal and repeat consumers is significantly less in our stores; o) every transaction in organized retailing is trackable and traceable by government authorities thereby we contribute to Government's revenue by paying all kinds of taxes; p) we follow standard weights and measures guidelines on all our packaging and products tagging thereby maintaining transparency of product information with our consumers; q) we follow standard hierarchy systems for any decision making thereby ensuring unbiased decisions being taken; and, r) consumers believe in organized retailing as there is transparency across all the aspects. 5.2. Empirical: Interestingly, when we evaluated actual data related to product assortment, sales, consumers, supply chain partners, inventory level, inventory turns, product sell through and velocity, capital investment requirement, returns on investment, decision making process, communication techniques, discount methodologies, organization structure, and sales pitch techniques we have found many insights of which some are contrary and some are matching with what was believed by both the organized and unorganized lifestyle retailers as detailed below. 5.2.1. Unit Economics: Majority of lifestyle retailers in the study were not well versed with the concept of 'unit economics'. Thus, we attempted to understand the unit economics of stores across organized and unorganized lifestyle retailers in the study which could possibly enable us to understand the economical pros and cons of both the retailing models empirically rather than just looking at the qualitative pros and cons of these models. Table 1 shows the end to end flow of parameters for a lifestyle store. It was also observed that most of these parameters were never tracked by lifestyle retailers. Each of these parameters have been compared line by line between organized and unorganized retailing models in addition to capturing the percentage variance in an unorganized lifestyle retailing model with respect to organized retailing model. Based on this comparison we have noted that organized retailers were superior in comparison to unorganized retailers in parameters pertaining to, a) intake margin level by 31.80 percentage points which is almost double; b) average product pricing higher by 81.82 percent; c) annualized inventory turns by 96.05 percent; d) quantity sold by 30.04 percent; e) sales per day per square foot by 80.29 percent; f) revenue by 2.11 times and, g) gross earnings by 4.66 times. Whereas, an unorganized retailers were superior in comparison to organized retailers in parameters pertaining to, a) optimal utilization of trading area by 16.91 percent owing to the common area loading being 2.35 times lesser; b) product display density higher by 33.33 percent; c) number of product options being stocked in the store higher by 33.33 percent; d) annualized discounts lower by 2.32 times; e) store rental expenses by 3.74 times; f) store employee costs by 4.29 times; g) store overheads by 5.56 times; h) warehousing and logistics expenses by 33.73 times; i) store level EBITDA earning by 50.54 percent, and most importantly; j) net earnings for every unit of product being sold to consumers being higher by 62.16 percent. These findings demonstrate that the organized lifestyle retailers even though generate higher revenue and gross margins in comparison to unorganized retailers, they are significantly poor in generating higher store level profits in spite of 2.11 times higher revenue being generated at 4.66 times higher gross margin earnings, they generate 0.49 times lesser store level profits. Retailing expenditures of organized lifestyle retailers are significantly higher owing to their store location choice, store design, store organization structure and the overall ambiance they create for the consumers to have superior shopping experience as compared to unorganized lifestyle retailers. Results also indicate that if organized retailers attempt to reduce (predatory pricing) their original product price positioning to compete with unorganized lifestyle retailers then it is possible that organized retailers might even start losing the existing store level profits. This particular element has directed us to take an empirical look at the returns on investment (ROI) parameters for both lifestyle retailing models in the study to evaluate if organized retailing is superior in terms of ROI at least.
SRINIVAS PUBLICATION
(KPI) were skewed towards absolute revenue and percentage gross margin generated by the store whereas, only few organized retailers were tracking store level EBITDA earnings. Table 2 captures key parameters which are detrimental in evaluating the ROI for organized and unorganized lifestyle retailers in addition to indicating the percentage variance in unorganized retailing model over organized retailing model. Unorganized lifestyle retailing model has shown a significant 2.64 times higher ROI compared to organized retailing model thereby making it easier for unorganized retailers to recover the capital invested in launching a store significantly earlier than organized retailers. Most of the expenditures of organized lifestyle retailers in the capital expenditure are significantly higher owing to their store location choice, store design, store organization structure and the overall ambiance they are required to create for the consumers to have superior shopping experience as compared to unorganized lifestyle retailers. . 'ABCD' analysis technique by its nature is subjective and exploratory. To make sure we make it objective and empirical we have assigned values '0 and 1' for each of the 192 'critical effective elements' of the 'ABCD' analysis model wherein '0' represents one being 'inferior' in comparison to other and '1' represents one being 'superior' to another in this relative comparative study. Assigning these values enabled us to convert subjective results to objective outcomes. Before we come up with inferences and insights it was necessary for us to carry out a relative comparison analysis in as much detailed manner as possible. This detailed comparative analysis demanded us to cover vast number of constructs, elements and sub-elements of the organized and unorganized lifestyle retailing models keeping sustainable retailing model while designing the integrated framework for unorganized lifestyle retailers in India to get organized, and 192 'critical effective elements' in addition to 94 'key business deployment factors' outlined in the 'ABCD' analysis model were able to cover majority of the aspects an empirical relative comparative analysis of business models require. Table 4: Comparison between organized and unorganized lifestyle retailers using ABCD analysis: Benefits.
Benefits:
Out of 46 critical effective elements outlined in the advantages comparison across six key areas of focus such as i) organizational, ii) operational; iii) technological; iv) employees and employers; v) consumers and, vi) social and environmental, unorganized retailing model is superior in majority of the effective elements as compared to organized retailing model by 28.57 percent. Organized retailing model loses to unorganized mostly in the organizational, operational and employees / employers areas of evaluation. 5.3.3 Constraints: Out of 48 critical effective elements outlined in the advantages comparison across six key areas of focus such as i) organizational, ii) operational; iii) technological; iv) employees and employers; v) consumers and, vi) social and environmental, unorganized retailing model is superior in majority of the effective elements as compared to organized retailing model by 236.36 percent. Organized retailing model loses to unorganized in almost all the areas of evaluation. Table 6: Comparison between organized and unorganized lifestyle retailers using ABCD analysis:
In summary, the subjective comparison between organized and unorganized lifestyle retailing model indicates that organized retailers owing to their organization structure, decision making processes in addition to the models basic requirement to adhere to Government norms, standard systems, processes and investments their retailing model demands faces serious issues in comparison with unorganized retailing model especially in the 'constraints' and 'disadvantages' components of 'ABCD' relative comparison analysis technique. At an overall level unorganized retailing model is 49.45 percent superior in relative comparison with organized lifestyle retailing model in India.
PROPOSED INTEGRATED FRAMEWORK :
We have used the basic principles of "4P's" Marketing Mix proposition designed by McCarthy 60 years ago to design the proposed integrated framework which is expected to enable unorganized lifestyle retailers in India to get organized . We would like to define key concepts of the proposed integrated framework before we head to explain the effective execution of the framework.
Framework 1: Recommended integrated framework to enable unorganized lifestyle retailers to get organized.
6.1. Product (P1): Considering both supply and demand side attributes of unorganized lifestyle retailing model, we have classified products into different groups in the proposed framework. This grouping is based on numerous empirical and experimental research we have previously carried out and are relevant to Indian retailing context along with being helpful in getting all the store owners and store employees to focus on products / categories which are already proven to be capable of driving consumer repeat store visit frequency thereby enhancing consumers intention to get associated with their store on a long-term basis in addition to findings from this study . Essential (P1A): All the SKUs of the store which are required by the consumers for frequent usage and are 'need to-have' category of consumers wardrobe or in simple terms a daily need. All the instructions to Store Employees to be communicated by only one nominated member of the Owner Family in addition to Empowering Store Employees with Systematic and Rigorous Control Systems.
P3A. Discounts:
Continue with existing highly customized consumer demand based discounting technique.
P3B. Consumer Level Promotions:
Continue with existing highly customized consumer affordability level and characteristic based communication on new product arrivals and discount related information.
P3C. Store Level Promotions:
Convert all the local festivals (big or small) as occasions to invite entire family of existing and potential consumers outside the store for a small gathering and be vocal about new changes in the store which are comparable to organized lifestyle stores. P4B. In-Store Lighting: Replace the entire in-store lighting to low electricity consuming and high light throughput lighting systems.
P4C. Visual Merchandising:
Create open space across the store in few select places to open-up and display representative products of new arrivals. Keep this area changed every week.
P4D. Visuals of Reputed Brands:
Regularly ask reputed brands associated with the store to replace their visuals in areas assigned to them in-store and outside the store. must encompass price lining . Based on this concept we have classified the 'price' aspect of the proposed integrated framework as low, mid-low, and mid-price points. Low-Price Points(M2): All the SKUs which are offered by the store belonging to a particular product group bearing an average MRP (maximum retail price / objective price / original price) at least 50 percent lesser than the store's overall price positioning for that particular product group. Mid-Low-Price Points (M1): All the SKUs which are offered by the store belonging to a particular product group bearing an average MRP equivalent to store's overall price positioning for that particular product line. Mid-Price Points (M3): All the SKUs which are offered by the store belonging to a particular product line bearing an average MRP at least 50 percent higher than the store's overall price positioning for that particular product group. For example, if the overall price positioning of the store for Men's essential T-Shirt product line is INR 299 then the mid-low-price points SKUs in the line must be priced at INR 149 on an average and mid-price point SKUs to be priced at INR 449 on an average. We have also considered mid-low-price positioning as best suitable for unorganized lifestyle retailers based on findings from this study. 6.3. Promotion (P3): Promotion is one of the most important aspects in establishing an organized lifestyle store image in employees, competitors and consumers mind and discounts / offers have become even more important post emergence of online store format in India as consumer perspective towards discount has changed dramatically . We have classified promotions by discount type, discount method, discount level, scope of discount applicability / inventory coverage (P3A), consumer level (P3B) and store level promotions (P3C) in the proposed integrated framework. These classifications are based on numerous empirical and experimental research we have previously carried out and are relevant to Indian retailing context in addition to taking insights of qualitative findings of this study . 6.4. Place (P4): We are not proposing any specifics regarding where the store should be located in the new integrated framework as the qualitative and empirical findings of this study confirm that the existing store locations of unorganized retailers have a strong advantage to the retailing model. Thus, we have recommended (priority wise) changes to be made to the store itself, such as, a) Store Façade (P4A); b) In-Store Lighting (P4B); c) Visual Merchandising (P4C) and; d) Visuals of Reputed Brands (P4D). Grouping of each sub elements of "4P's" clubbed with priority matrix mix within and among "4P's" which have been designed as part of the proposed framework plays an important role in deriving the strength of the proposed model . The grouping and prioritization are the key changes cum rationalization being proposed to the existing retailing model / mix. Our proposed framework has deliberately considered the role of each of these components while designing the new proposition and significantly gives importance to 'input' variables and activities which directly have an impact on consumer repeat visit frequency to the store. 6.5. Employees and Consumers: In addition to these basic "4P's" what is also important in the retailing model / mix is 'People' both internal and external. During our exploratory phase of this research, we have noticed that all the unorganized lifestyle retailers in the study were following few standard practices such as, a) many representatives of the owner family were giving instructions to store employees across all the aspects of store operation; b) every decision irrespective of the magnitude has to be taken by the owner family members; c) absence of a store manager or in charge and, most importantly d) lower sales personnel strength in the store. Based our findings in this study and taking insights from our previous experimental study , we have defined people organization to help the unorganized lifestyle retailers to get organized. As far as the target consumer is concerned, while studying the select unorganized lifestyle retailers, it was observed that majority of them do not have 'focussed' consumer target group and even if they have, they are failing to offer products across life-stage needs of their target consumers. They are neither exploiting the product category they are strong at and nor the target consumer target group they are already catering to through their strong product category. To address this typical issue, we have grouped target consumers into C1: Baby (0-1 Year), Infant (1 to 3 Years), Pregnant Women and Nursing Women. C2: Kids (2 to 8 Years); Boys and Girls (8 to 16 Years); C3: Women (Above 18 Years); C4: Men (Above 18 Years); C5: Entire Family. Unorganized lifestyle retailers need to be cognizant of the universally proven fact that consumer's needs significantly change based on their age and always take this phenomenon into consideration while choosing their target consumers in relation to the product category they offer. Unless store owners and store employees adopt this modification, it becomes very difficult to achieve the organized lifestyle retailer image in competitors and consumers mind.
EXECUTING THE RECOMMENDED FRAMEWORK :
We are cognizant of the fact and it is inevitable that, the magnitude of changes and rationalizations proposed to the existing retailing model shall need significant attitudinal changes across owners, owners family members and the store employees. Thus, we have outlined key recommendations on the wholistic execution of the proposed integrated framework to increase the probability of the success of the proposed model. It is inevitable that to achieve the organized lifestyle retailer image, store owner must attempt to incorporate these recommendations together and across. The proposed model shall not be effective and efficient if the store owner attempts to change its existing retailing model in phases or steps or in silos. As mentioned earlier there are more than 5000 Indian lifestyle brands in addition to well-known global lifestyle brands in India. It is very important to have association and affiliation with reputed Global, National and Local brands which plays an important role in establishing an organized lifestyle retailer image in competitors and consumers mind and it is imperative to all the unorganized lifestyle retailers to strive for constantly associating with reputed brands in such a way it creates positive perceptions and long term memories in consumers mind about the store. If direct association with reputed brands is difficult then it is recommended to use modern online B2B distribution stores (Example: Udaan) which is accessible easily without any hassles. Associating with reputed brands also empowers the store owners to use the brand visuals with or without celebrity pictures, promotion collaterals to enhance the overall store look. In addition, owners can engage their store employees to participate in product training and product range shows arranged by reputed brands from time to time. The proposed integrated framework does not demand the owners to additionally invest on capital on any element of the basic retailing mix except the fourth 'P' which is place. Even as far as 'Place' is concerned we have proposed activities which require new capital to be infused but nevertheless it does not demand any large amount of capital.
DISCUSSION AND CONCLUSION :
Findings and insights of this exhaustive study which attempted to relatively compare organized and unorganized lifestyle retailing models in India across, a) unit economics; b) returns on investment; c) 94 business deployment factors; d) 192 critical effective factors; and, e) qualitative factors have indicated that in spite of general perception which is in favour of organized retailing models the unorganized lifestyle retailing models in India are superior in majority of retailing model aspects evaluated by us in this study. We do agree that organized retailing model looks good / attractive owing to their store location choice, investment on store design, store ambiance created, capability of spreading their store presence across multiple cities of the country and ability to use mass media to advertise about their store brand, nevertheless they are struggling to make their financials look good on a sustainable basis. What was more concerning and glaring observation in this study was, organized lifestyle retailers believe that they understand their consumers much better than unorganized retailers due to the advanced software tools they have deployed in their customer relationship management (CRM) processes in addition to artificial intelligence (AI) programming they apply to understand consumer behaviour and sales forecasting. Whereas, contradictory to this belief we have found that the key input stage of obtaining relevant consumer data is managed by cashiers of the store at the stage of final billing thereby making the majority of this consumer data obtained irrelevant for efficient usage. As the reliability of this key input consumer data itself is in question they spend most of their time in analysing consumer level performance which does not lead them to any relevant conclusions as far as their communication strategy is concerned. Organized lifestyle retailers understanding of knowing a consumer is successfully obtaining mobile number of a person who shops at their stores and nothing beyond that, whereas understanding a consumer for unorganized retailer means having clear understanding about a consumer's psychological, physiological, socio-economical status in addition to their real-time needs. At the beginning of this study, we assumed that organized lifestyle retailing model is superior in comparison with unorganized retailing, whereas, when we dwelled deep into this study, we realized that there are many aspects of retailing in which organized retailers were inferior to unorganized retailers. Notwithstanding the impact of steadily growing organized retailing in India and its impact on consumer perceptions about unorganized retailers in addition to consumers steadily shifting to organized retailing, it is becoming more and more important and inevitable for unorganized lifestyle retailers in India to get themselves organized at the earliest to arrest this consumer and market share shift to organized retailers. In this context we have attempted to design an integrated framework which is, a) simple to understand; b) easy to execute; and most importantly c) demanding minimal additional capital investment. The proposed framework consciously takes into consideration the fact that the owners of small-scale unorganized lifestyle store would not be able to raise huge funds to invest on beautification of their existing store. We are also not recommending Government agencies to come up with policies or programmes to help these unorganized retailers merely due to the sheer number of such retailers present in India. It would be difficult for any Government agencies to execute any such programmes successfully on such a widely spread number of unorganized lifestyle retailers in India. Rather we believe that the unorganized lifestyle retailers implement the proposed framework which integrates all the basic "P's" of the retailing mix to gain long-term, sustainable, competitive, and strategical advantage over organized retailers in India in addition to these unorganized lifestyle retailers getting a chance to become part of the successful organized lifestyle retailers community of the country thereby rationally contributing to the new vision of the country which is known as 'Aatmanirbhar Bharat' or 'Self-Reliant India'.
SUGGESTIONS TO UNORGANIZED LIFESTYLE RETAILERS IN INDIA :
Based on this research outcome, we would like to determinedly suggest unorganized lifestyle retailers in India that, they need to clearly understand the role of every 'P' of Marketing Mix in relation to their existing / potential consumers, catchment, and merchandise assortment they offer. You also need to clearly understand organized lifestyle retailer's key business objectives behind having stores in cities or locations wherein your store has been operational since generations. Few organized lifestyle retailers may be trying to show exponential growth in their revenue to attract more investors; few may be assuming that consumers acquired based on rich store look, ambiance and advertising tactics as their key components of selling proposition are going to be loyal to their stores forever; few may be trying to create different perceptions in consumers mind over their store image, few may be opening many new stores in premium locations with larger size to tag them as experiential, anchor or destination stores assuming that this effort would lead them to create a premium retailer image in consumers, competitors and investors mind; few may be expanding their presence in catchment areas irrespective of their target consumer groups to promote their retail brand to attract new investors, franchisees and licensees; few conglomerates may be trying to show their presence in the lifestyle retailing segment to strengthen their group portfolio; few may be selling premium priced products, categories, brands to position themselves as premium lifestyle retailers. What is very important is the key business goal of your store, your target consumer group, target consumer group's attitude towards you, your family and the store and most importantly your aim to establish a 'my-store' image in employees and consumers mind. You have many retailing practices which make it very difficult for existing organized retailers to copy and execute in their stores. Continue practising them in addition to implementing the proposed integrated framework.
LIMITATIONS OF RESEARCH :
The main limitation of this research work is the coverage of various stakeholders viz., number of organized and unorganized lifestyle retailers, product categories, consumer groups, employees, price positioning, regions and cities covered in deriving the proposed framework. This might limit the generalizability of research findings to other set of unorganized retailers in India. The second limitation would be the empirical validation is restricted to few organized and unorganized lifestyle retailers selected for the study and hence the generalizability of the findings and suggestions to other organized and unorganized lifestyle retailers in India. The third limitation would be our ability to carry out an experiment, though we were firm in our approach that, the integrated framework has to be tested in the field before we recommend, it was not that easy merely because of the vast scope of the experiment. Unlike other experiments wherein the treatment is limited to few concepts, components or variables this experiment in fact required us to cover practically almost all the elements of the lifestyle retailing mix which do require longer duration for preparations prior to testing, longer duration prior to the beginning of extracting the results and longer period of time for the experimentation itself to ensure findings and insights are derived holistically. At best we were able to derive recommendations based on our research findings of similar experiments and empirical studies and we shall in some time implement the recommended framework with few select unorganized lifestyle retailers and publish the results. However, as the recommended framework is being derived based on this empirical and previous experimental research finding, it provides significant input regarding the ways in which unorganized lifestyle retailers could utilise these recommendations to start their journey towards becoming a 'successful organized lifestyle retailer' in a sustainably profitable manner.
SCOPE FOR FURTHER RESEARCH :
We strongly recommended that the recommended framework is experimented by researchers and the same is finetuned further if required for organizing as many unorganized lifestyle retailers in India as possible. Based on the key short-term and long-term business objectives and their target consumer group, unorganized lifestyle retailers can implement the recommended framework and finetune the same based on real-time findings relevant to them. The basic principles of the proposed framework with modifications can also be implemented for unorganized retailers in India catering to non-lifestyle product categories too. |
def make_wsgi_app(registry=REGISTRY):
def prometheus_app(environ, start_response):
params = parse_qs(environ.get('QUERY_STRING', ''))
r = registry
encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT'))
if 'name[]' in params:
r = r.restricted_registry(params['name[]'])
output = encoder(r)
status = str('200 OK')
headers = [(str('Content-type'), content_type)]
start_response(status, headers)
return [output]
return prometheus_app |
<reponame>sidmani/OsuBot
#include "mouse.h"
#include "definitions.h"
void click(point p);
void beginDrag(point p);
void endDrag(point p);
void endDragNull();
void moveTo(point p);
void click(point p)
{
CGEventRef leftDown = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, CGPointMake(p.x, p.y), kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, leftDown);
CFRelease(leftDown);
CGEventRef leftUp = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, CGPointMake(p.x, p.y), kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, leftUp);
CFRelease(leftUp);
}
void endDrag(point p)
{
CGEventRef leftUp = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, CGPointMake(p.x, p.y), kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, leftUp);
CFRelease(leftUp);
}
void endDragNull()
{
CGEventRef mouse_position = CGEventCreate(NULL);
CGPoint p = CGEventGetLocation(mouse_position);
CGEventRef leftUp = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, p, kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, leftUp);
CFRelease(leftUp);
}
void beginDrag(point p)
{
CGEventRef leftDown = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, CGPointMake(p.x, p.y), kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, leftDown);
CFRelease(leftDown);
}
void moveTo(point p)
{
CGEventRef moved = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, CGPointMake(p.x, p.y), kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, moved);
CFRelease(moved);
}
|
package models
import (
"time"
)
// Course defines the structure of a course
// swagger:model
type Course struct {
// Name of the course
// required: true
Name string `json:"name" bson:"name" validate:"required"`
// Code for the course
// required: true
Code string `json:"code" bson:"code" validate:"required"`
// Number of credits for the course
// required: true
// min: 1
Credits int `json:"course_credits" bson:"course_credits" validate:"required,gt=0"`
// Grade received by the student
// required: true
Grade string `json:"grade" bson:"grade" validate:"required"`
}
// Semester defines the structure of a semester
// swagger:model
type Semester struct {
// Semester number
// required: true
Number int `json:"number" bson:"number" validate:"required"`
// Credits earned by the student in that semester
// required: true
// min: 1
Credits int `json:"earned_credits" bson:"earned_credits" validate:"required,gt=0"`
// SGPA earned for the semester by the student
// required: true
SGPA float32 `json:"sgpa" bson:"sgpa" validate:"required"`
// CGPA after this semester
// required: true
CGPA float32 `json:"cgpa" bson:"cgpa" validate:"required"`
// Information about courses taken by the student in the semester
// required: true
Courses []Course `json:"courses" bson:"courses" validatre:"required,dive"`
}
// Student defines the structure of a student
// swagger:model
type Student struct {
// Roll number of student
// required: true
Roll string `json:"roll_no" bson:"roll_no" validate:"required,numeric,len=9"`
// Name of the student
// required: true
Name string `json:"name" bson:"name" validate:"required"`
// Program in which the student is enrolled in
// required: true
Program string `json:"program" bson:"program" validate:"required"`
// Branch of the student
// required: true
Branch string `json:"branch" bson:"branch" validate:"required"`
// Current CGPA of the student
// required: true
CGPA float32 `json:"cgpa" bson:"cgpa" validate:"required"`
// Information about the previous semesters of a student
// required: true
Semesters []Semester `json:"semesters" bson:"semesters" validate:"required,dive"`
// Time at which the instance was created in the database
// required: false
// read only: true
CreatedAt time.Time `json:"created_at" bson:"created_at"`
// Time at which the student instance was last updated in the database
// required: false
// read only: true
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}
|
/**
* Tests the general case when a user account is created.
*
* @throws Exception ex
*/
@Test
public void testAccountCreation() throws Exception {
AuthorizeUserAction authorizeUser = new AuthorizeUserAction(USER_DN_6, 0);
NiFiUser user = authorizeUser.execute(daoFactory, authorityProvider);
Assert.assertEquals(USER_DN_6, user.getDn());
Assert.assertEquals(1, user.getAuthorities().size());
Assert.assertTrue(user.getAuthorities().contains(Authority.ROLE_MONITOR));
Mockito.verify(userDao, Mockito.times(1)).createUser(user);
} |
Effects of Selenium Nanoparticles Combined With Radiotherapy on Lung Cancer Cells
Objective To investigate the effects of selenium nanoparticles (nano-Se) combined with radiotherapy on the proliferation, migration, invasion, and apoptosis of non-small cell lung cancer (NSCLC) A549 and NCI-H23 cells. Methods Nano-Se was synthesized and characterized by transmission electron microscope (TEM), X-ray diffractometer, and Ultraviolet-visible (UV)-Vis Spectroscopy, separately. The uptake of nano-Se by lung cancer cells was detected by flow cytometry. Cell counting kit-8 (CCK-8) method was used to detect the antiproliferative activity of nano-Se combined with radiotherapy. Wound healing tests and transwell assay were used to detect the migration and invasion ability of the cells. Annexin V-fluorescein isothiocyanate (FITC)/Propidium iodide (PI) staining by flow cytometry was used to detect apoptosis. The expression of Cyclin D1 (CCND1), c-Myc, matrix metalloproteinase 2 (MMP2), MMP9, cleaved Caspase-3, and cleaved Caspase-9 were detected by Western blot. Results The average diameter of nano-Se was 24.39 nm and the wavelength of nano-Se increased with the increase of radiation dose under UV-Vis Spectroscopy. The uptake of nano-Se in lung cancer cells was increased with the increase of nano-Se concentration. The nano-Se combined with radiotherapy decreased the proliferation activity of NSCLC cell lines A549 and NCI-H23 in a dose-dependent manner (all P < 0.05). Compared with the Control group, nano-Se combined with radiotherapy could significantly inhibit the migration and invasion of lung cancer cells (all P < 0.05), and the effects of the combination of nano-Se and radiotherapy was better than that of a single application (all P < 0.05). Furthermore, nano-Se combined with radiotherapy could induce apoptosis of lung cancer cells (P < 0.05) and nano-Se combined with radiotherapy could significantly inhibit the expression of proliferation-related proteins CCND1, c-Myc, invasion and migration-related proteins MMP2 and MMP9, but conversely promoted the expression of apoptosis-related proteins cleaved caspase-3 and cleaved caspase-9. Conclusion: This study found that nano-Se combined with radiotherapy plays an anti-cancer role in lung cancer cells by inhibiting cell proliferation, migration, and invasion, as well as inducing apoptosis, suggesting that nano-Se may be used as a radiosensitizer in the clinical treatment of lung cancer, but further research is still needed.
migration, and invasion, as well as inducing apoptosis, suggesting that nano-Se may be used as a radiosensitizer in the clinical treatment of lung cancer, but further research is still needed.
INTRODUCTION
Lung cancer is one of the major cancers in the world. Among different types of lung cancer, non-small cell lung cancer (NSCLC) accounts for approximately 85% of the incidence (Duma et al., 2019), 60% of which are diagnosed as advanced, chemotherapy and radiotherapy are the standard treatment of advanced NSCLC (Herbst et al., 2018). In recent years, radiotherapy and chemotherapy have become a recognized tumor treatment model. Compared with radiotherapy alone and chemotherapy or sequential therapy, combined therapy has a better effect on the continuous control of local tumors and the improvement of the cure rate (Pirker, 2020). However, the adverse reactions of radiotherapy and chemotherapy such as bone marrow suppression, nausea, and vomiting hinder its clinical application, and the 5-year survival rate of NSCLC is still 16.1% (Bagcchi, 2017). Therefore, there is an urgent clinical need to find a safer and more effective treatment method. The development of nanomaterials has greatly improved the diagnosis and treatment of tumors . Traditional anti-tumor drug research often encounters problems such as the lack of specific drug targets and the need for higher doses to achieve higher local concentrations . Nanoparticles (NPs), due to their strong permeability and retention effect, are expected to overcome the shortcomings of traditional anti-tumor drugs and are called new anti-cancer drugs . In recent years, many studies have been done around selenium, which is a trace element, because it plays a critical role in health care, including immune response and cancer prevention . Epidemiological and clinical research results show that selenium can alleviate the hazard of different cancers, for instance, liver cancer, breast cancer, prostate cancer, colon cancer, and lung cancer (Chen et al., 2018). Some synthetic selenium related chemicals, like selenomethionine and methyl selenocysteine, displaying increased anticancer activity with increading doses (Bi et al., 2013;Zeng et al., 2013). As an antitumor drug and an essential trace element, selenium has an effective dose approximate to the toxicity level, which greatly limits its usage in clinical treatments (Bhattacharjee et al., 2014). Nevertheless, more and more research have been performed around selenium nanoparticles (Nano-Se) because of their good bioavailability, high biological activity, and low toxicity (Li et al., 2011). According to reports, the toxicity of nano-level selenium (Se0) is lower than that of selenite (Seþ2 or Seþ4) ions, so Nano-Se is anticipated to substitute other kinds of selenium in nutritional supplements or pharmaceutical dosage forms . Similarly, Nano-Se may also be used as a radiosensitizer to improve the effect of radiotherapy and reduce its side effects. Huang et al. (2013) confirmed in breast cancer, liver cancer and other cells that Nano-Se can trigger the overproduction of intracellular peroxides, thereby activating the p53 and MAPKs pathways, and promoting cell apoptosis. In addition, in animal experiments, they found that Nano se suppressed tumor growth via induction of apoptosis mediated by p53. Jiang et al. (2014) also found similar findings, that is, Nano-Se can cause glioma cytotoxicity by activating a variety of apoptosis signaling pathways, thereby exerting an anti-cancer effect. Given the rare research on the effect of Nano-Se on the function of lung cancer cells, this study intends to treat lung cancer cells through the combination of Nano-Se and radiotherapy to observe the changes in cell proliferation, invasion and migration ability, and the impacts of the above treatments on cell apoptosis, to provide new anti-cancer drugs for the clinical treatment of lung cancer.
Method
Preparation, Characterization and Identification of Nano-Se A 345.9 mg of sodium selenite powder was dissolved in 200 mL of double-distilled water. After fully dissolving, 40 mL of 10 nM sodium selenite solution and 160 mL of 10 mM glutathione solution containing 200 mg of bovine serum albumin was used to prepare 10 mM sodium selenite stock solution. An appropriate amount of 0.1 M sodium hydroxide was added to adjust the pH value of the sodium selenite stock solution to 7.1, nano-Se and oxidized glutathione can be formed immediately, see reference (Gao et al., 2014) for details. Dialysis of the stock solution with double-distilled water for 72 h (double-distilled water is replaced every 6 h) can separate the oxidized glutathione from nano-Se, and then store the resulting nano-Se solution at 4 • C in the refrigerator. A transmission electron microscope (TEM) sample was prepared by dropping a nano-Se suspended particle solution on a carbon-coated copper grid and drying at room temperature (Chen et al., 2015), and a high-resolution TEM (JEOL Ltd., Japan) was used to characterize and observe the synthesized nano-Se and the average particle size was calculated. After counting and measuring more than 100 particles, the average size and particle size distribution of the nano-Se can be determined (Chen et al., 2018). After that, the X-ray diffraction pattern (λ = 0.15419 nm) of the sample was recorded using a Rigaku X-ray diffraction (XRD), and the Ultraviolet-visible (UV)-Vis Spectroscopy (Agilent Technologies, United States) was used to detect the absorbance of nano-Se at 200 to 400 nm under different doses of irradiation in the range. The final concentration of selenium in the aqueous solution was measured using an atomic absorption spectrophotometer (Hitachi, Japan).
Cell Culture
The NSCLC cell lines A549 and NCI-H23 were cultured in DMEM medium containing 10% fetal bovine serum and 1% penicillin-streptomycin. The culture conditions of the incubator were 37 • C and 5% CO 2 .
Detection of Cell Proliferation Activity by CCK-8 Method
Detection of the effects of nano-Se on the proliferation activity of NSCLC cells: NSCLC cell lines A549 and NCI-H23 were seeded in a 96-well plate at a density of 1 × 10 4 and 0.8 × 10 4 cells/well, respectively. After incubating for 1 day, different concentrations of nano-Se (0 (Control), 0.25, 0.5, 1, 2, 5, 10, 15, and 20 µg/mL) were used for treatment for 24 h. Then add 10 µL CCK-8 to each well, and continue to incubate for 2 h in a 37 • C incubator, and then measure the absorbance (OD) at 450 nm with a spectrophotometer. Set up a blank background group (Blank), that is, wells with only DMEM medium as a control to avoid medium infection OD value. Each group has four multiple holes.
Detection of the effect of radiation treatment on the proliferation activity of NSCLC cells: Based on the selection of an appropriate exposure concentration of nano-Se, the NSCLC cell lines A549 and NCI-H23 were firstly divided into 1 × 10 4 and 0.8 × 10 4 cells/well. The cell/well density was seeded in a 96-well plate, cultured for 24 h, and then treated with 1 µg/mL nano-Se for 24 h. Then wash the cells with phosphate-buffered saline (PBS), replace it with a new normal medium, and irradiate 6 MeV-X rays with a linear accelerator. The average dose rate is 200 cGy/min, and the irradiation doses were 0, 2, 4, and 6 Gy. After the irradiation, put the cells back into the incubator and continue culturing for 24 h, and the rest of the detection process is the same as the previous CCK-8 detection method.
The calculation formula for the relative cell proliferation activity is: relative cell proliferation activity (%) = (OD treatment group-OD Blank)/(OD control group-OD Blank) × 100%.
Determination of Nano-Se Uptake of Cells by Flow Cytometry
Since A549 is more sensitive to the toxic reaction of Nano-Se exposure, A549 cells were seeded in a six-well plate at a density of 5 × 10 5 cells/well, and cultured with culture medium containing different concentrations of nano-Se (0, 0.5, and 1 µg/mL) for 24 h. Take gold nano-particles (Gold nano-particles, nano-Au) treated cells as a positive control group (Chang et al., 2017). After the culture, the cells were digested and harvested with trypsin, washed twice with PBS, and then suspended in 1 mL PBS, and tested on flow cytometry to detect the absorption of nanoparticles by cells.
Scratch Test to Detect Cell Migration Ability
A549 and NCI-H23 cells were seeded in a six-well plate and cultured for 24 h to 80-90% confluence. Scribe a straight line with a sterile 200 µL pipette tip perpendicular to the bottom of the plate, wash the fallen cells with PBS, replace the culture medium with fresh medium, and use an inverted microscope connected with a real-time image system to take a picture of the mark. Fresh medium containing 1 µg/mL nano-Se was added to Nano-Se group and nano-Se + Radiation group to culture cells for 24 h, an equal volume of sterilized saline were added to Control group and Radiation group to culture cells for 24 h, then Radiation group and nano-Se + Radiation group received a certain dose of radiation treatment. After the treatment, all the groups were placed in the incubator for 24 h and then photographed again. ImageJ software was used to calculate the relative migration amount of cells according to the scratch gap area (Area) of each group of cells at 0 and 48 h. The formula is: relative cell migration activity (%) = (Area treatment group-0 h-Area treatment group-24 h)/Area treatment group-0 h × 100%.
Determination of Cell Invasion Ability by Transwell
Place the Transwell chamber with 80 µL of matrix gel dropwise into the wells of the 24-well plate, and incubate for 2 h in the cell incubator. After the cells were processed accordingly (see "Scratch test to detect cell migration ability" for specific operations), trypsin-EDTA was used to digest the cells, and 200 µL of suspension containing 1 × 10 5 cells were seeded in the upper chamber of Transwell. At the same time, 750 µL medium containing 10% FBS was added to the lower chamber. After culturing the cells at 37 • C for 48 h, remove the medium, fix the cells with 1 mL of 4% paraformaldehyde at room temperature for 10 min, then remove the fixative, wash the cells with PBS once, and add 1 mL 0.5% Crystal Violet solution to each well, stained at room temperature for 30 min, and rinse the cells with PBS. Finally, the cells that invaded the Transwell chamber were counted with an optical microscope.
Flow Cytometry to Determine the Level of Apoptosis
The treated cells in the six-well plate (see "Scratch test to detect cell migration ability") were trypsinized, centrifuged at 400 × g at 4 • C for 5 min, and 500 µL PBS was added to resuspend the cells to wash and centrifuge to collect the cell pellet. Repeat this step 2. After adding 200 µL of binding buffer to the cells, Annexin V-FITC and PI (10 µL each) were added and mixed gently. After incubating at room temperature for 30 min in the dark, 300 µL of binding buffer was added again, and flow cytometry was immediately performed on the computer. Finally, Flowjo software was used to analyze the results.
Western Blot to Determine Cell Protein Expression
The cells were washed twice with pre-cooled PBS and lysed on ice with RIPA strong lysis buffer containing protease inhibitors. Centrifuged at 12,000 × g at 4 • C for 10 min to take the supernatant and the supernatant was transferred to a new centrifuge tube. Using the BCA method to determine the protein concentration, then add 5× protein loading buffer to mix, and heat at 100 • C for 10 min to denature the protein. Take 20 µg protein sample for SDS-PAGE gel electrophoresis (First use 60 V constant voltage electrophoresis until the loading buffer enters the separation gel, adjust the voltage to 80 V and run until the loading buffer is close to the bottom edge of the gel and turn off the power), and transfer the separated protein to PVDF membrane (0.29 A constant current transfer membrane for 90 min). The membrane was sealed in 5% skimmed milk at room temperature for 2 h, washed with TBST three times, then the corresponding primary antibody was added and incubated overnight at 4 • C. The next day, the primary antibody was removed, the membrane was washed three times with TBST, and HRP-conjugated secondary antibody was used to incubate with the membrane for 1 h at room temperature, and wash the membrane three times with TBST. By dropping the ECL protein luminescent liquid, the protein bands were visualized in the fluorescence imaging system and photographed to record. Finally, ImageJ software was used to perform grayscale analysis of protein bands.
Statistical Analysis
Each experiment in this study was repeated at least three times independently, and the measurement data were expressed as mean ± standard deviation, and SPSS 19.0 was used for statistical analysis. Dunnett-test was used to compare differences between groups, and one-way analysis of variance was used to compare multiple groups. P < 0.05 was regarded as statistically significant.
Characterization and Identification of Nano-Se
In this study, the synthesized nano-Se was first observed by a TEM, and then the size distribution histogram was drawn, as shown in Figures 1A,B, it can be seen that the average size of nano-Se is 24.39 ± 8.61 nm. In addition, we also performed an XRD analysis. As shown in Figure 1C, no obvious diffraction peaks were found, suggesting that nano-Se is relatively pure. Moreover, as we can see, in Figure 1D, nano-Se showed different absorbance at radiation doses of 0, 2, 4, and 6 Gy, suggesting that the increase in radiation dose may increase the concentration of nano-Se.
The Effects of Nano-Se and Its Combination With Radiotherapy on Cell Proliferation Activity
As shown in Figures 2A,B, compared with the Control group, treatment of cells with nano-Se can decrease the proliferation activity of lung cancer cells in a dose-dependent manner (all P < 0.05), and based on nano-Se exposure to cells, after combined radiotherapy, with the increase of radiotherapy dose, the cell proliferation activity gradually decreased (Figures 2C,D, all P < 0.05). Therefore, in subsequent experiments, we chose 1 µg/mL as the exposure concentration of nano-Se and 2 Gy as the radiation dose for radiotherapy.
Absorption of Nano-Se by NSCLC Cells
As shown in Figure 3, compared with the Control group, as the concentration of nano-Se exposed to NSCLC cells increased, the absorption rate of nano-Se by A549 cells also increased.
The Effects of Nano-Se Combined With Radiotherapy on Cell Migration
As shown in Figure 4, compared with the Control group, the combination of nano-Se and radiotherapy can significantly inhibit cell migration (P < 0.05). The results of A549 and NCI-H23 are consistent. In addition, nano-Se and radiotherapy alone also have a certain inhibitory effect on migration (both P < 0.05).
Effect of Nano-Se Combined With Radiotherapy on Cell Invasion Function
As shown in Figure 5, compared with the Control group, the combination of nano-Se and radiotherapy can significantly inhibit cell invasion (P < 0.05), and nano-Se and radiotherapy alone also have a certain inhibitory effect (both P < 0.05).). The results of A549 and NCI-H23 are consistent.
The Effect of Nano-Se Combined With Radiotherapy on Inducing Cell Apoptosis
As shown in Figure 6, compared with the Control group, nano-Se combined with radiotherapy can significantly induce cell apoptosis (P < 0.05). The results of A549 and NCI-H23 are consistent.
The Effects of Nano-Se Combined With Radiotherapy on Cell Proliferation, Invasion, and Migration and Apoptosis-Related Proteins
When detecting the protein expression of lung cancer cells, we chose A549 cells for determination. As shown in Figure 7, Western blot detection of protein expression found that compared with the Control group, nano-Se combined with radiotherapy can significantly inhibit the expression of proliferation-related proteins CCND1, c-myc and invasion and proliferation-related proteins MMP2 and MMP9 (both P < 0.05), on the contrary, it promoted the expression of apoptosis-related proteins cleaved Caspase-3 and cleaved Caspase-9 (both P < 0.05).
DISCUSSION
Lung cancer, especially NSCLC, is one of the most common cancers in the world, and the desire for clinical exploration of effective treatment methods is very urgent.
Radiotherapy has been widely used in the treatment of lung cancer. Although this method can indeed effectively reduce and eliminate cancerous cells, normal tissues close to the sites where were irradiated will certainly be harmfully affected by radiation. Several radiosensitizers have been produced and appliced to cancer treatment, but the most widely used clinical treatment of lung cancer is still chemotherapy (Man et al., 2010). The ideal way to increase the clinical application of radiotherapy is to find a radiosensitizer that exhibits weak cytotoxicity in the absence of radiation and can effectively promote tumor cell radiationinduced cell death. Selenium is known to have membrane stability and is an indispensable trace elements for animals and humans. Although selenium has a toxic effect when it exceeds a certain level, nano-Se has also been shown to be less poison than inorganic selenium and several organic selenium chemicals (Wang H. L. et al., 2007). It is known that the beneficial effects of Se on the treatment of tumors include various mechanisms, such as reducing DNA damage (Jung et al., 2009), antioxidation (Pourkhalili et al., 2012), anti-inflammatory (Miroliaee et al., 2011), enhancing immune response (Ryan-Harshman and Aldoori, 2005), and changing the DNA methylation of tumor suppressor genes state , inducing apoptosis (Zhang et al., 2013) and blocking the transmission of protein signaling pathways (Christensen et al., 2007).
In this research, nano-Se was first synthesized, and then the particle size of nano-Se was observed by TEM. It was observed by UV spectroscopy that radiation treatment would not destroy the structure of nano-Se, but could enhance the cytotoxicity of nano-Se by increasing the concentration of nano-Se. Also, flow cytometry detected that as the concentration of nano-Se increased, the absorption of nano-Se by cells increased. On 25, 0.5, 1, 2, 5, 10, 15, and 20 µg/mL) on the proliferation of NSCLC cells A549 and NCI-H23; (C,D) After 1 µg/mL nano-Se pretreated NSCLC cells A549 and NCI-H23, the effects of different doses of radiation treatment (0 (Control), 2, 4, and 6 Gy) on cell proliferation activity. Compared with the Control group, **P < 0.01, ***P < 0.001; comparison between different concentrations of nano-Se treatment group, ###P < 0.001; comparison between different dose radiation treatment groups, &&P < 0.01, &&&P < 0.001. this basis, this study used the combination of nano-Se and radiotherapy in NSCLC cancer cells and discussed the effect and mechanism of this combined treatment. First, through the CCK-8 experiment, this study confirmed that the effect of nano-Se combined with radiotherapy on the proliferation of NSCLC cells was greater than that of nano-Se exposure treatment alone or irradiation alone, suggesting that nano-Se and radiotherapy have a synergistic effect in inhibiting cell proliferation activity or to promote each other. Metastasis is a major feature of cancer and the main cause of death of approximately 90% of cancer patients. During this process, the migration and invasion functions of cancer cells play an important role, which also leads to serious consequences of tumor metastasis and poor prognosis (Lu et al., 2017). Therefore, in addition to testing the impacts of nano-Se and radiotherapy on cell proliferation, this study also observed the effect of the combination of lung cancer cell migration and invasion. Consistent with expectations, nano-Se alone or radiation treatment can inhibit cell migration and invasion to a certain extent, and the combined effect of the two is more obvious. In addition to studying the inhibitory effect of the combination of the two on the biological behavior of cancer cells, this study also found that nano-Se combined with radiotherapy can induce apoptosis in lung cancer cells through flow cytometry. The above results suggest that nano-Se combined with radiotherapy has a significant anti-cancer effect.
Based on the biological functions of nano-Se combined with radiotherapy on lung cancer cells, this study also explored the mechanism, focusing on detecting the expression of several proteins related to cancer cell proliferation, invasion, metastasis, and apoptosis. It is known that CCND1 is an important cell cycle-related protein, and its main function is to regulate the cell cycle and advance the cell from the G1 phase to the S phase . In tumor cells, CCND1 can accelerate tumor cell division from the G1 phase to the S phase, thereby improving the proliferation ability of tumor cells (Yang et al., 2017); c-Myc is a nuclear protein gene with multiple cell biological functions. It can combine with DNA and chromosomes to regulate cell proliferation (Ericson et al., 2015). Since this study has found that nano-Se combined with radiotherapy can inhibit the proliferation of lung cancer cells through CCK-8 cell proliferation activity experiments, Western blot experiments confirmed that the combination of the two can significantly inhibit the expression levels of CCND1 and c-Myc proteins, further verifying this conclusion. MMPs are a group of zinc-dependent metalloproteinases that regulate a variety of cellular processes, including tumor cell proliferation and metastasis (Egeblad and Werb, 2002). MMP2 and MMP9 are two specific subgroups of MMPs. They have been studied in cancer for many years. Past studies have found that MMP2 and MMP9 were highly expressed in lung cancer and essential for the growth and metastasis of lung tumors (Liu et al., 2019). This study found that the combination of nano-Se and radiotherapy can significantly inhibit the expression of MMP2 and MMP9 proteins by detecting the expression levels of the above two proteins. The results are consistent with the results of Scratch and Transwell. In addition, this study also detected the levels of apoptosis-related classic proteins Caspase-3 and Caspase-9. It is known that Caspase-3 is activated by the proteolytic cleavage of Caspase-9 and is an important apoptosisexecuting Caspase. Caspase signal stimulation and accompanying PARP cleavage are considered to be the main features of the apoptotic cascade (Bi et al., 2018), and their levels also indicate the progress of the apoptotic response. In this study, the levels of Caspase-3 and Caspase-9 were detected and found that the expression of cleaved Caspase-3 and Caspase-9 were increased, suggesting the occurrence of apoptosis. This result is consistent with the study of Huang et al. (2013) and Jiang et al. (2014) that nano-Se can induce apoptosis in cancer cells and exert cytotoxicity. The specific mechanism is shown in Figure 8.
CONCLUSION
In summary, this study found that nano-Se, as a new form of Se, exerted anti-cancer activity including inhibition proliferation, invasion, migration and promotion of apoptosis of NSCLC cells when combined with radiotherapy. This study provides a theoretical basis for in vivo evaluation of the inhibitory effect of nano-Se combined with radiotherapy on lung cancer, but further research is still needed. |
//! Report the reasons collected from the compiler why the specific function
//! needs to use unsafe blocks.
use super::utils::DefPathResolver;
use crate::write_csv;
use corpus_database::tables::Loader;
use std::collections::HashSet;
use std::path::Path;
pub fn query(loader: &Loader, report_path: &Path) {
let def_path_resolver = DefPathResolver::new(loader);
let strings = loader.load_strings();
let function_unsafe_reasons: Vec<_> = loader
.load_function_unsafe_reasons()
.iter()
.map(|(def_path, _index, reason)| (def_path, reason))
.collect::<HashSet<_>>()
.into_iter()
.map(|(def_path, reason)| (def_path_resolver.resolve(*def_path), &strings[*reason]))
.collect();
write_csv!(report_path, function_unsafe_reasons);
}
|
Maneesh Sethi/YouTube; screenshot by Chris Matyszczyk/CNET
One of my favorite exes used to put her hand over my mouth, just before I was about to say something monumentally stupid. (She could guess most of the time.)
It made me more socially productive.
I can therefore entirely sympathize with Maneesh Sethi, a San Francisco blogger who believes that he needs to be less socially networked and more capitalistically productive.
So, as he says on his own Hack The System blog, he went on Craigslist and hired someone who would slap him every time he veered toward Facebook. Yes, slap him in the face.
Sethi, you see, is a blogger who is interested in being more productive in his life. Hiring the slapper seemed to him entirely rational.
He felt he was spending too much time on Facebook and Reddit -- some 6 hours a day, it seems. He had the need to achieve.
Having hired Kara on Craigslist earlier this year -- he says a mere 20 people responded to this posting, which is not the San Francisco I know -- he discovered that this pain-for-gain method worked for him.
He has since repeated it, but told the Huffington Post that it was best when a stranger hit him. Perhaps a stranger doesn't pull her punches.
I wonder, though, whether this is actually an exercise in pain at all.
For some people, being slapped is a pleasure. Ah, you know those people too, do you? Well, here is another video (embedded below) that shows Sethi being slapped repeatedly by random people (mostly women) in Colombia.
During this video he declares: "You know, I can be slapped by women all night long. It doesn't really hurt at all."
One can only conclude, therefore, that the best way to wean yourself away from Facebook is to have something more pleasurable occurring.
I am told that Craigslist is, indeed, always the preeminent place for securing that.
(In the video below, Sethi gets slaphappy at 3:53.) |
def eval_model(self, data_object):
if self.model is None:
self.model = self.load_model(data_object)
logging.info("Evaluating model performance on testing data")
X_train, y_train, X_test, y_test = self._get_data(data_object)
model_predictions = self.model.predict(X_test)
model_probability = self.model.predict_proba(X_test)
model_predictions = model_predictions.astype(int)
model_f1 = f1_score(y_test, model_predictions, labels=None, pos_label=1)
recall = recall_score(y_test, model_predictions, labels=None, pos_label=1)
prec = precision_score(y_test, model_predictions, labels=None, pos_label=1)
accuracy = accuracy_score(y_test, model_predictions)
logging.info(
"positive class fraction: {}".format(float(sum(y_test)) / len(y_test))
)
logging.info(
"positive class predicted fraction: {}".format(
float(sum(model_predictions)) / len(y_test)
)
)
logging.info(
"f1: {}, recall: {}, precision: {}, accuracy: {}".format(
model_f1, recall, prec, accuracy
)
)
roc_auc = self._get_roc_score(y_test, model_probability)
logging.info("AUC: {}".format(roc_auc))
self.scores["auc"] = roc_auc
self.scores["f1"] = model_f1
self.scores["recall"] = recall
self.scores["precision"] = prec
self.scores["positive_class_fraction"] = float(sum(y_test)) / len(y_test)
self.scores["predicted_class_fraction"] = float(sum(model_predictions)) / len(
y_test
)
self.scores["eval_time"] = datetime.datetime.now()
return data_object |
/**
* Checks whether observation is locked out of edits from personal diary.
*
* NOTE! Here are no checks on whether permit is locked or permit partner
* has finished hunting.
*/
public static boolean isLockedOutOfPersonalDiaryEdits(final @Nonnull Observation observation,
final boolean authorOrObserver,
final @Nonnull ObservationSpecVersion specVersion) {
requireNonNull(observation);
requireNonNull(specVersion);
final boolean isLinkedWithHuntingDay = observation.getHuntingDayOfGroup() != null;
if (observation.getObservationCategory().isWithinDeerHunting()) {
return !authorOrObserver
|| !specVersion.supportsCategory()
|| isLinkedWithHuntingDay && !observation.isCreatedLessThanDayAgo();
}
return !authorOrObserver || isLinkedWithHuntingDay;
} |
def sourceNl_to_ints(self, source_nl):
source_nl_clean = source_nl.lower().replace("'", ' ').replace('-', ' ')
source_nl_clean_tok = word_tokenize(source_nl_clean, "english")
source_ints = [int(self.vocab_source[elt]) if elt in self.vocab_source else \
self.OOV_token for elt in source_nl_clean_tok]
source_ints = torch.LongTensor([source_ints]).to(self.device)
return source_ints |
X,N,*P = map(int,open(0).read().split())
if P != []:
P = sorted(list(P),reverse=True)
else:
print(X)
exit()
min_diff = 101
min_val = 101
for i in range(101,-1,-1):
#print(i,min_val,min_val)
if not i in P:
if abs(X-i) <= min_diff and min_val >=i:
min_diff = abs(X-i)
min_val = i
ans = min_val
print(ans) |
n1 = int(input())
n2 = input()
A=0; i=1; B=""
while A<n1:
B += n2[A]
A += i
i += 1
print(B) |
/**
* Definition of Trump
*/
public class PbnTrump
{
public static final int IDLE = -1;
public static final int CLUBS = 0;
public static final int DIAMONDS = 1;
public static final int HEARTS = 2;
public static final int SPADES = 3;
public static final int NOTRUMP = 4;
public static final int NONE = 5;
public static final int NUMBER = 5;
private static final String S_IDLE = "_";
private static final String S_CLUBS = "C";
private static final String S_DIAMONDS = "D";
private static final String S_HEARTS = "H";
private static final String S_SPADES = "S";
private static final String S_NOTRUMP = "NT";
private static final String S_NONE = "";
private int mTrump;
private int TrumpToSuit()
{
int iSuit;
switch ( mTrump )
{
case CLUBS:
iSuit = PbnSuit.CLUBS;
break;
case DIAMONDS:
iSuit = PbnSuit.DIAMONDS;
break;
case HEARTS:
iSuit = PbnSuit.HEARTS;
break;
case SPADES:
iSuit = PbnSuit.SPADES;
break;
default:
iSuit = PbnSuit.NONE;
break;
}
return iSuit;
}
public PbnTrump()
{
mTrump = IDLE;
}
public PbnTrump(
int iTrump )
{
mTrump = iTrump;
}
public PbnTrump(
PbnTrump oTrump )
{
mTrump = oTrump.mTrump;
}
public int Get()
{
return mTrump;
}
public void Set(
int iTrump )
{
mTrump = iTrump;
}
public void Set(
PbnTrump oTrump )
{
mTrump = oTrump.mTrump;
}
public boolean equals(
PbnTrump oTrump )
{
return mTrump == oTrump.mTrump;
}
public boolean Is(
int iTrump )
{
return mTrump == iTrump;
}
public boolean IsTrump(
PbnSuit oSuit )
{
if ( ! IsValid() )
{
return false;
}
PbnSuit lSuit = this.ToSuit();
return oSuit.equals( lSuit );
}
public boolean IsValid()
{
return ( CLUBS <= mTrump ) && ( mTrump <= NOTRUMP );
}
public PbnSuit ToSuit()
{
return new PbnSuit( TrumpToSuit() );
}
public boolean GT(
PbnTrump oTrump )
{
return ( mTrump > oTrump.mTrump );
}
public String toString()
{
String string = S_IDLE;
switch ( mTrump )
{
case CLUBS:
string = S_CLUBS;
break;
case DIAMONDS:
string = S_DIAMONDS;
break;
case HEARTS:
string = S_HEARTS;
break;
case SPADES:
string = S_SPADES;
break;
case NOTRUMP:
string = S_NOTRUMP;
break;
case NONE:
string = S_NONE;
break;
}
return string;
}
} |
Image copyright AP Image caption A Counter-Terrorism Service (CTS) spokesman said its troops had cleared Hit of all gunmen
Iraqi troops have recaptured the strategically important western town of Hit from Islamic State militants after weeks of fighting, officials say.
The military declared that Hit had been "completely liberated" by units of the elite Counter-Terrorism Service (CTS).
Since it began in mid-March, the assault on the town has been the focus of the government's wider campaign to regain control of Anbar province.
Hit sits on a key supply route linking IS-held territory in Iraq and Syria.
Iraqi military officials and the US-led coalition against IS believe that by clearing the town 150km (93 miles) west of Baghdad, they can build on other recent gains in the vast desert of Anbar.
'We will never leave'
CTS spokesman Sabah al-Numani told the AFP news agency that troops took complete control of Hit on Thursday, after clearing it of the last remaining gunmen.
IS militants in the town, between Ramadi and Haditha, put up heavy resistance to the assault. Air strikes by coalition warplanes were being called in by troops late into Wednesday night, CTS commander Gen Abdul Ghani al-Asadi told the Associated Press.
Gen Asadi said that in intercepted radio communications IS fighters were heard saying that "this is our headquarters and we will never leave this area".
More than 20,000 civilians fled Hit after the launch of the operation to retake the town last month, but thousands more were believed to be trapped inside during the last stages of the battle.
The offensive on Hit was reportedly delayed by a two-week sit-in protest in Baghdad by supporters of the powerful Shia cleric Moqtada al-Sadr, as forces had to be pulled from Anbar to protect them.
The protesters demanded that Prime Minister Haider al-Abadi move ahead with a plan to replace ministers appointed on the basis of political affiliation with technocrats in a bid to tackle systemic political patronage that has aided corruption.
Image copyright AP Image caption More than 20,000 civilians fled Hit after the launch of the operation to retake the town
At the end of March, Mr Abadi submitted a list of non-partisan nominees, but it was rejected by the main parties, who put forward their own candidates,
Mr Abadi submitted a second list with their approval on Tuesday, triggering a sit-in in parliament by dozens of MPs, who demanded an opportunity to vote on the original list.
There were chaotic scenes on Wednesday as a brawl broke out during a debate over the reshuffle, and the speaker Salim al-Jabouri formally called for parliament to be dissolved.
On Thursday, a number of MPs held a vote of no-confidence in Mr Jabouri, a leading Sunni Arab politician and ally of the prime minister. But Mr Jabouri said the session lacked the necessary quorum and was marred by "many legal and constitutional errors". |
/**
* Internal extension that registers a {@link ReaderEventListener} to store
* registered {@link ComponentDefinition}s.
*/
private static class ToolingTestApplicationContext extends ClassPathXmlApplicationContext {
private Set<ComponentDefinition> registeredComponents;
public ToolingTestApplicationContext(String path, Class<?> clazz) {
super(path, clazz);
}
@Override
protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
this.registeredComponents = new HashSet<>();
beanDefinitionReader.setEventListener(new StoringReaderEventListener(this.registeredComponents));
beanDefinitionReader.setSourceExtractor(new PassThroughSourceExtractor());
}
public boolean containsComponentDefinition(String name) {
for (ComponentDefinition cd : this.registeredComponents) {
if (cd instanceof CompositeComponentDefinition) {
ComponentDefinition[] innerCds = ((CompositeComponentDefinition) cd).getNestedComponents();
for (ComponentDefinition innerCd : innerCds) {
if (innerCd.getName().equals(name)) {
return true;
}
}
} else {
if (cd.getName().equals(name)) {
return true;
}
}
}
return false;
}
public Iterator<ComponentDefinition> getRegisteredComponents() {
return this.registeredComponents.iterator();
}
} |
<reponame>robertojmm/rmdb
import fs from "fs";
import { settings } from "@/settings";
import i18n from "@/i18n";
import { changeTheme } from "@/themes";
import { changeParser } from "@/parsers";
import { initDB } from "@/database";
function init(): void {
const directories = settings.get("directories");
const appDirectory = directories.main;
if (!fs.existsSync(appDirectory)) {
fs.mkdirSync(appDirectory);
}
const postersDirectory = directories.posters;
if (!fs.existsSync(postersDirectory)) {
fs.mkdirSync(postersDirectory);
}
i18n.locale = settings.get("language");
const actualTheme: string = settings.get("theme");
changeTheme(actualTheme);
const actualParser: string = settings.get("parser");
changeParser(actualParser);
initDB();
}
export default init;
|
import { BaseForm } from './baseform';
import contants from 'contants';
import Axios from 'axios';
export class Payment extends BaseForm {
money;
task;
constructor(...args) {
super(args[0], args[1], args[2])
}
activate(model, nctx) {
super.activate(model, nctx);
this.es.subscribe("next", (task) => {
this.task = task;
});
}
submit() {
this.httpInvoker.post(`${contants.serverUrl}/workflow/tasks/${this.task.id}/complete`, {
taskId: this.task.id,
outputVariables: {
money: this.money
}
}).then((res) => {
this.es.publish("reloadMyTasks");
this.es.publish("completed");
}).catch((res) => {
});
}
}
|
// UpdateWithClient adds Teleport configuration to kubeconfig based on the
// configured TeleportClient.
//
// If `path` is empty, UpdateWithClient will try to guess it based on the
// environment or known defaults.
func UpdateWithClient(path string, tc *client.TeleportClient) error {
clusterAddr := tc.KubeClusterAddr()
clusterName, _ := tc.KubeProxyHostPort()
if tc.SiteName != "" {
clusterName = tc.SiteName
}
creds, err := tc.LocalAgent().GetKey()
if err != nil {
return trace.Wrap(err)
}
return Update(path, Values{
Name: clusterName,
ClusterAddr: clusterAddr,
Credentials: creds,
})
} |
<filename>challenges/the-minion-game.py
# SRC: https://www.hackerrank.com/challenges/the-minion-game/problem
# Functions
def substring_count(string, sub):
count = start = 0
while True:
start = string.find(sub, start) + 1
if start > 0:
count += 1
else:
return count
def get_player_score(string, player, letters):
# Calculate player score as per HR instructions
results = 0
# For each valid player letter
for letter in letters:
# Get the leftmost index of the letter in the string
start = string.index(letter)
# Temp value to calculate points on
_string = string[start:]
# Parse the string letter by letter
while len(_string):
# Add score
results += substring_count(string, _string)
# Drop one letter from right
_string = _string[:-1]
# Reset word to original
_string = string
return player, results
def minion_game(string):
score = []
vowels = ('A', 'E', 'I', 'O', 'U')
# Get valid starting letters for both players
# Stu gets points for words starting with a consonant
# Kev gets points for words starting with a vowel
starters_s = sorted(set([l for l in string if l not in vowels]))
starters_k = sorted(set([l for l in string if l in vowels]))
score.append(get_player_score(string, player='Stuart', letters=starters_s))
score.append(get_player_score(string, player='Kevin', letters=starters_k))
# Check if draw
if len(set([i[1] for i in score])) == 1:
print('Draw')
else:
winner = sorted(score, reverse=True, key=lambda x: x[1])[0]
print(f"{winner[0]} {winner[1]}")
# main()
if __name__ == '__main__':
s = input()
minion_game(s)
|
During the week at the Kennedy Space Center we talked with a trio of friendly astronauts about ....
From a standing start the shuttle reaches Mach 25, 17,500 miles an hour in 8.5 minutes, faster than anyone has ever gone on the 405.
In their explosive teamwork those rockets are generating more than 39 million horsepower. Even from three miles away, it was like looking at a monstrous welding torch as Atlantis cleared the tower, and left the awed viewers feeling the exhaust heat like a warm breeze.
We witnessed the Atlantis launch Friday in the bright Florida sunshine, brightened even further by the 200-foot-long flaming flare of its five muscular rockets lifting the nearly five million pounds of craft and fuel into orbit. (See launch photo and a special Jay Catalano video below)
America's last space shuttle, Atlantis, docked Sunday at the International Space Station where the crew has a full 10-day schedule of work to accomplish on the final visit of the U.S. craft.
...what the space experience is like from a personal perspective --and. Scroll down to Related for our previous reports.
Here's our report from inside the space experience:
NASA scientists said one important human lesson learned from the 135 shuttle flights is to give astronauts time off even in the cloistered quarters of space, a day off for reading, relaxing or live emailing with family.
It can take nearly three hours to dress for a space walk, longer even than a columnist's wife takes for an earthbound event. What do they do during a six or eight-hour space walk about personal needs? They wear a diaper. Do they get thirsty? Yes, there's a pressure straw on the right side of the helmet.
What about itchy noses? Yes, they happen. At the astronauts' request, NASA installed a little pad on the left they can rub their face against to scratch. Since they can't look down inside the suit, spacewalkers wear a mirror on their wrist to read a clock and instruments off their chest.
Spacewalkers are usually so focused on their assignments, practiced often in the giant pool at Houston's Johnson Space Center, they don't have much time to sightsee. But they can't help noticing the frequent sunrises and sunsets that occur every 45 minutes at their speeds.
Their custom-made spacesuits must change gears just as often, for the more than 300-degree difference between keeping them warm during the night flight portions and cooling them during the daytime above the atmosphere. Wheelock says in space the twinkling stars don't look that much different than from Earth. However, there are millions more.
Wheelock, an Army test pilot who spent six months aboard the space station, said you are not so much wearing the oversized spacesuits like clothing as you are floating within them.
He describes one creepy experience during a spacewalk. His assignment was to stow gear in the cargo bay. His feet were buckled onto the orbiter arm and he began a slow journey up and over. At the end of the long, gangly arm he could only look straight ahead.
For the longest time he lost sight of Earth and the orbiter. "I was staring off into the utter blackness of deep scary space," Wheelock recalled. "And you think, 'Now, that's a very large place.'"
He knew he was safe, but found himself kicking his heels back against the locked space boots frequently just to doublecheck.
For a long time the space station, scheduled for use through 2020, had only simple windows offering straight-out views. Now it has some arranged like a cupola, offering maybe a 160-degree view. One sleep period Wheelock was tucking himself into his vertical sleeping bag like a bat, when he decided to take a quick peek out the cupola for a few minutes.
So busy are the working space inhabitants that they're rarely aware of where they are at any one time, just as earthlings don't track the station's location. Wheelock spotted the familiar shape of Australia below. Then came the vast Pacific with a few dots of islands, northern Canada and then Africa where scores of lightning storms flashed like natural strobes throughout the cloud cover below. He couldn't wait to see what was coming next.
Later, Wheelock checked the time on his watch: He'd been watching Earth for two hours and circled the globe twice. As corny as it sounds, he said that experience made him wonder why humans don't get along better on what from space seems to be a very tiny place in a very big universe.
The consensus was a launch in the Russian Soyuz craft, now the only way for U.S. astronauts to go into space, was smoother than the shuttle. But the return -- Russian capsules descend by parachute to land on, well, land -- is something else. Wheelock sought advice from an American colleague before his Soyuz return. And the text reply contained only two words: "Hang on."
Wheelock said he did. It was two or three loud explosions followed by "the loudest biggest car crash you can imagine."
Back on Earth Wheelock said he felt as if he was floating for six weeks. U.S. astronauts are forbidden from driving for the same time period to ensure return of equilibrium. Even months after his return, Wheelock's dreams often involve floating.
Still, members of the diminshed American astronaut corps, now about half the size of the peak 135, say they would make the dangerous trip in a heartbeat.
"I'd stow away in Atlantis' toilet if I thought I could get away with it," said Antonelli. The American is learning Russian to enhance his longshot chances of being picked for future launches which will be under Russian command. President Obama canceled the scheduled next generation of crew-carrying U.S. rocket.
Robert Crippen, who flew, among others, the very first shuttle mission with John Young, told the....
.... NASA Tweetup that he'd sign up to return to space if they'd let him. He said, "It's the nature of the United States to press forward and explore," but he finds NASA's future plans "very fuzzy."
The pioneer added, "It's sad from where I sit to see our space shuttle come to an end and I hope we get our act together as a country to return to low-earth orbit, the moon, Mars, somewhere."
Antonelli offered running commentary of NASA TV's live feed of the crew-boarding procedure at the 195-foot level of the orbiter through the White Room, so-called because it is white. "See, that phone there," Antonelli said, "that's your last phone on Earth. It's for the crew. They didn't phone me. Guess they thought their family was more important for some reason."
He pointed out White Room crew members handing their nametags to the boarding astronauts for a free ride into space. "It's the crew's salute to the last guys they see, who buckle them and seal the hatch."
Then, Panelli highlighted another important astronaut procedure in preparation for launching into space at 25 times the speed of sound. "See that corner?" Antonelli asked, pointing to the giant TV screen. "Around there is the last toilet on Earth."
RELATED:
Behind the scenes of a shuttle launch
Atlantis is up and the space shuttle program is up in smoke
Where each U.S. space shuttle is scheduled to live in retirement
-- Andrew Malcolm
Don't forget to follow The Ticket via Twitter alerts of each new Ticket item. Or click this: @latimestot. Our Facebook Like page is over here. We're also available on Kindle. Use the ReTweet buttons above to share any item with family and friends.
Photos: Paolo Nespoli / ESA / NASA (Endeavour docked at the International Space Station, May 30, 2011; Dick Clark / NASA (Atlantis launch aerial view); Andrew Malcolm (screengrab from NASA TV); Jean Louis Santini / AFP / Getty Images (At the 195-foot level, the ramp to the White Room, last fresh air for boarding astronauts; Bill Ingalls / NASA (Launch controllers watch the last Atlantis ascent July 8 from a control room three miles away).
Video courtesy of our new Twitter pal, Jay Catalano; more of his photos here. |
Process of becoming a mother for Iranian surrogacy‐commissioning mothers: A grounded theory study
AIM
Little knowledge is available about the experiences of the commissioning mothers during the process of surrogacy; thus, the present study was conducted in order to explore and analyze this process.
METHODS
This study was conducted in a referral institute in Tehran with a qualitative approach and using grounded theory methodology. The data were collected through 39 unstructured, in-depth interviews that were conducted with 15 gestational commissioning mothers, two of their husbands, four surrogates, and five of the personnel at centers for assisted reproduction (some participants were interviewed more than once). Sampling started purposively and then continued theoretically.
RESULTS
The analysis revealed the main concern of these mothers to be the feeling of "insecurity about becoming a mother" and their predominant strategy for dealing with it to be "seeking security about becoming a mother," which emerged as a core concept. The consequences of the mothers' adopted strategies and the effects of the intervening factors included "reaching a state of relative peace," "a continuing threat to one's identity," and "mental and physical exhaustion."
CONCLUSION
Identifying the demands of this group of mothers can help medical personnel, particularly nurses, adopt better plans for the future and to optimize the care they provide to these patients. |
<reponame>AlbertiPot/CTNAS
import torch
class MovingAverageMetric(object):
def __init__(self, alpha=0.9):
self.alpha = alpha
self.reset()
def reset(self,) -> None:
self._value = 0
def update(self, value) -> None:
if torch.is_tensor(value):
v = value.item()
elif isinstance(value, (int, float)):
v = value
else:
raise ValueError("'value' should be int, float or pytorch scalar tensor, but found {}"
.format(type(value)))
if self._value is None:
self._value = v
else:
self._value = self.alpha*self._value+(1-self.alpha)*v
def compute(self) -> float:
return self._value
|
def name_to_layer(self, name, idx):
if name not in self.function_mapping:
raise ValueError('name %s not exists in function mapping' % name)
layer = self.function_mapping[name]
cls, args = layer['cls'], layer['args']
args['name'] = name + '_id_%d' % idx
return cls(**args) |
def iterdir(self, path: PurePath) -> Iterator[str]:
for child in self.resolve(path).iterdir():
child = child.relative_to(self._root)
yield child.name |
What's the right way to go around Green Lake?
“What’s the right way to go around Green Lake?” Isaac Chirino of Shoreline asked KUOW’s Local Wonder. Boy, people REALLY care about this one. People like Carolyn Frost. In the early 1990s, she and a friend walked the Seattle lake’s 2.8-mile path every morning. But there were these aggressive runners, according to Frost, and they would yell, “TRAIL!” forcing her and her friend out of the way. Read blog posts about Green Lake and you’ll find similar gripes. This shouldn’t surprise anyone who has spent time in Seattle. We are a city that loves its rules – we wear our helmets, we wait at crosswalks, we rarely honk our horns. We are, after all, a city that had garbage inspectors for a while.
Sponsor
But online comment threads also include complaints about Green Lake know-it-alls, who seem to revel in schooling the rest of us. Frost was one of these marmish types. She was a working mom of three who didn’t have much extra time, but she was so frustrated by the Green Lake scene that she started taking photographs of people she believed were going the wrong way. “We’re not just some lunatics,” Frost told me by phone. “We just could not understand why people did not follow the rules at Green Lake.” Photos as proof, she called the parks department for a meeting. But officials there dismissed her. That ticked her off. “When you call your government and you get absolutely nothing back from them, not even the courtesy, ‘We’re glad you brought this problem to our attention,’ you start wondering,” Frost said.
Sponsor
Frost became convinced – still is, in fact – of a government conspiracy. A pause to note that that these walkers and runners were not going the wrong way. Feet may go either direction in the inner lane; wheels must go counterclockwise in the outer lane. But signage in the early 1990s was confusing. The arrow for cyclists and roller-bladers pointed up; the arrow for feet pointed down. Frost and her friend interpreted that to mean that feet could only move clockwise. She became so frustrated that she targeted “the runners and their friends.” Robin Hennes was among them. Then 34, Hennes walked to work every morning by way of Green Lake.
Sponsor
“They would say, ‘Wrong way,’ then, ‘Wrong way, lady,’” Hennes recalled. “Then it got kinda snarly, and it would be, ‘Can’t read, stupid lady. What’s the matter with you? You can’t find a man? No sex in your life?’” Seattle nice, they were not. “They would do odd things like pop out of shrubbery and say, ‘There she is!’” Hennes said. “And then they started taking my picture every day.” Frost admitted to taking those photos. (She said she still has them at her Puyallup home, for her children to discover after she’s gone.) But she vehemently denies ever jumping out of the bushes.
Sponsor
Hennes continued, “Then they would shake a fistful of keys and me and then they started blasting me with a whistle.” That whistle, Hennes said, once threw her so off balance that she fell over. Frost sounded proud of the whistle when we spoke. “Everybody should carry a bear whistle,” she said with a chuckle. Hennes learned of others being harassed and before long she and five others – including an 80-year-old woman named Margaret Anderson – went to court for a restraining order. According to the court record, Frost and her friend were banned from the lake for three months.
Sponsor |
<filename>lib/targets/legacy/index.ts
import { TsGeneratorPlugin, TFileDesc, TContext, getRelativeModulePath } from "ts-generator";
import { join, dirname } from "path";
import { codegen, getRuntime } from "./generation";
import { extractAbi } from "../../parser/abiParser";
import { getFilename } from "../shared";
export interface ITypechainCfg {
outDir?: string;
}
export class TypechainLegacy extends TsGeneratorPlugin {
name = "Typechain-legacy";
private readonly outDirAbs?: string;
private runtimePathAbs?: string;
constructor(ctx: TContext<ITypechainCfg>) {
super(ctx);
const { cwd, rawConfig } = ctx;
if (rawConfig.outDir) {
this.outDirAbs = join(cwd, rawConfig.outDir);
this.runtimePathAbs = buildOutputRuntimePath(this.outDirAbs);
}
}
transformFile(file: TFileDesc): TFileDesc | void {
const fileDirPath = dirname(file.path);
if (!this.runtimePathAbs) {
this.runtimePathAbs = buildOutputRuntimePath(fileDirPath);
}
const outDir = this.outDirAbs || fileDirPath;
const fileName = getFilename(file.path);
const outputFilePath = join(outDir, `${fileName}.ts`);
const relativeRuntimePath = getRelativeModulePath(outputFilePath, this.runtimePathAbs);
const abi = extractAbi(file.contents);
if (abi.length === 0) {
return;
}
const wrapperContents = codegen(abi, { fileName, relativeRuntimePath });
return {
path: outputFilePath,
contents: wrapperContents,
};
}
afterRun(): TFileDesc | void {
if (this.runtimePathAbs) {
return {
path: this.runtimePathAbs,
contents: getRuntime(),
};
}
}
}
function buildOutputRuntimePath(dirPath: string): string {
return join(dirPath, "typechain-runtime.ts");
}
|
//This is the word break method
public static void wordBreak(String str, String ans, HashSet<String> dict){
if(str.length() == 0){
System.out.println(ans);
return;
}
for(int i = 0; i < str.length(); i++){
String left = str.substring(0, i+1);
if(dict.contains(left)){
String right = str.substring(i+1);
wordBreak(right, ans = left+" ", dict);
}
}
} |
<filename>src/js/lib/histogramInterval.test.ts
import brim from "../brim"
import histogramInterval from "./histogramInterval"
import {DateTuple} from "./TimeWindow"
const start = new Date()
test("returns the proper format", () => {
const end = brim
.time(start)
.add(5, "minutes")
.toDate()
const timeWindow: DateTuple = [start, end]
expect(histogramInterval(timeWindow)).toEqual({
number: 1,
unit: "second",
roundingUnit: "second"
})
})
|
//
// resolve the image from the given tile set
//
func resolveImage(tiles map[int]tileDef) []string {
used := 0
image := []string{}
leftTile := findFirstCorner(tiles)
fmt.Println(leftTile.id)
currentTile := leftTile
imagePos := 0
for used < len(tiles) {
for {
fmt.Printf(" %d ", currentTile.id)
for pos, line := range currentTile.data {
if len(image) <= imagePos+pos {
image = append(image, strings.TrimSpace(line))
} else {
image[imagePos+pos] = image[imagePos+pos] + " " + strings.TrimSpace(line)
}
}
used++
if currentTile.rightTileID > 0 {
lastID := currentTile.id
lastBorders := currentTile.right
currentTile = tiles[currentTile.rightTileID]
switch lastID {
case currentTile.rightTileID :
if currentTile.right[1] == lastBorders[0] {
currentTile = turnRightTile(currentTile)
currentTile = turnRightTile(currentTile)
} else {
currentTile = flipTile(currentTile)
}
case currentTile.topTileID :
currentTile = turnLeftTile(currentTile)
case currentTile.bottomTileID :
currentTile = turnRightTile(currentTile)
}
} else {
break
}
}
fmt.Println()
imagePos += len(image)
if leftTile.bottomTileID > 0 {
lastID := currentTile.id
lastBorders := currentTile.bottom
leftTile = tiles[leftTile.bottomTileID]
switch lastID {
case leftTile.bottomTileID :
if leftTile.bottom[1] == lastBorders[0] {
leftTile = turnRightTile(leftTile)
leftTile = turnRightTile(leftTile)
} else {
leftTile = flipTile(leftTile)
}
case leftTile.topTileID :
leftTile = turnLeftTile(leftTile)
case currentTile.bottomTileID :
leftTile = turnRightTile(leftTile)
}
currentTile = leftTile
}
}
for _, line := range image {
fmt.Println(line)
}
return image
} |
This is the Top Ten Bleeding Cool Bestseller List, as compiled by a number of comic stores from their sales on Wednesday and Thursday. It measures what are known as the “Wednesday Warriors”, those who can’t wait to the weekend to get this week’s comics. We salute you, and the keenness you bring to your passion.
Marvel had a lot of Civil War II tie-in comics this week. But unlike the Civil War crossovers from a decade ago, not one of them entered the top ten. Instead, this week’s Bestseller chart was dominated by DC Rebirth, including the likes of Hellblazer over and above all the Marvel superhero titles. Only the Star Wars titles made it in.
Also, for the first time, Darth Vader beat Star Wars…
1. Batman #3
2. Justice League #1
3. Superman #3
4. Darth Vader #23
5. Star Wars #21
6. Batgirl and the Birds of Prey Rebirth #1
7. Green Arrow #3
8. Hellblazer Rebirth #1
9. Aquaman #3
10. Green Lanterns #3
Thanks to the following retailers,
Who had this to say,
Fantastic week for sales with 4 books passing the century mark and the others performing better than expected. Always nice when the invoice is almost cleared for the week on day one. Rick and Morty,Invader Zim and just about anything cartoon related was flying out of the store this week. The rest of the back-issue market was pretty much keys due to SDCC this week which was to be expected. DC is still riding high with the Rebirth kick. I just hope DC has a follow up. Meaning when the new 52 started there was a lot of readers but that readership bleeded off. This time hopefully there is a year end shocker or something to keep people interested and excited. Darth Vader is slipping since it will be ending in a few months. Marvel is really slipping because one of the bad things about re launches is people wait till the actual re launch to try a series. No one wants to try something that is ending. So now we have months of people holding off on Marvel material other than Civil War. DC shipped eight Rebirth books this week, and DC took the top eight positions in our store’s sales. No Marvel superhero books made the top ten–the two Star Wars books made the bottom of the list. Never in our store’s history have so many customers disliked what Marvel was doing–but they are becoming the regular target of reader scorn. Marvel, it’s time to forget Marvel Now and try to give readers a Marvel Rebirth, getting back to the core basics of the characters that readers love! Strong interest in Silver Age Shazam, Superman, Batman, and Justice League. By now i sound like a broken record because DC Rebirth once again destroyed all competition. The only comic that was not a DC book that made it to our top ten was I Hate Fairyland. I was even surprised that last week’s Hal Jordan rebirth clobbered Deadpool and the Merc’s #1. Reducing their line, upping the frequency of the best sellers and lowering their price point has been an absolute success for DC. Marvel please adopt this model sooner than later. Wow, once again DC Rebirth continues to do wonders are our store! DC hasn’t had four books in our top ten for quite sometime, and even though Marvel has a few more books on our top ten than DC, the talk about the shop it definitely in DC’s favor! Bryan Lee O’Malley’s Snotgirl also had some great sales this week as well.
About Rich Johnston Chief writer and founder of Bleeding Cool. Father of two. Comic book clairvoyant. Political cartoonist.
(Last Updated )
Related Posts
None found |
Psychological management of individual performance.
About the Editor About the Contributors Series Preface Preface Part 1: Performance: Concept, Theory, and Predictors Performance Concepts and Performance Theory (Sabine Sonnentag and Michael Frese) 2. Ability and Non-ability Predictors of Job Performance (Ruth Kanfer and Tracy M Kantrowitz) 3. PRACTICE CHAPTER--debis Career Development Center: Personality Scales within a Process-Oriented Development Instrument for Management High Potentials (Jurgen Deller et al) 4. Work Design and Individual Work Performance: Research Findings and an Agenda for Future Inquiry (Sharon K Parker and Nick Turner) 5. PRACTICE CHAPTER--Organizational Design and Organizational Development as a Precondition for Good Job Design and High Job Performance (Oliver Strohm) Part 2: Assessing Performance 6. Appraisal: An Individual Psychological Perspective (Clive Fletcher) 7. PRACTICE CHAPTER--Performance Appraisal (Gesa Drewes and Bernd Runde) 8. Analysis of Performance Potential (Daniela Lohaus and Martin Kleinmann) 9. PRACTICE CHAPTER--Assessing Potential and Future Performance (Wieby Altink and Helma Verhagen) Part 3 Enhancing Performance 10. The High Performance Cycle: Standing the Test of Time (Gary P Latham et al) 11. PRACTICE CHAPTER--Enhancing Performance through Goal-Setting and Feedback Interventions (Jen A Algera et al) 12. Enhancing Performance through Training (Beryl Hesketh and Karolina Ivancic) 13. PRACTICE CHAPTER--Enhancing Performance through Training (Brigitte Winkler) 14. Enhancing Performance through Mentoring (Terri A Scandura and Betti A Hamilton) 15. PRACTICE CHAPTER --Mentoring for World-Class Performance (James G Clawson and Douglas S Newburg) 16. Enhancing Performance through Pay and Reward Systems (Henk Thierry) 17. PRACTICE CHAPTER--Performance Measurement and Pay for Performance (Harrie F J M Tuijl et al) 18. Managing Individual Performance: A Strategic Perspective (Susan E Jackson and Randall S Schuler) 19. PRACTICE CHAPTER--Performance Improvement through Human Resource Management (Sabine Remdisch) Part 4 Ensuring Performance in a Wider Context 20. Performance, Well-being and Self-Regulation (Sabine Sonnentag) 21. PRACTICE CHAPTER--Well-being, Stress Managment and Performance: From Analysis to Intervention (Rendel D de Jong) 22. Integrating the Linkages between Organizational Culture and Individual Outcomes at Work (Paul Tesluk et al) 23. PRACTICE CHAPTER--Organizational Culture: A Case Study (Jaap J van Muijen) Author Index Subject Index |
/**
* Iniciar propiedades.
* @param prop nombre del fichero.
*/
private void iniciarPropiedades(final String prop) {
try {
this.configProperties = new Properties();
this.configProperties.load(new FileInputStream(prop));
} catch (IOException ex) {
logger.error(ex);
}
} |
<reponame>CASMarkusHimmel/kata-csvreader-java<filename>src/main/java/de/cas/mse/exercise/csv/CsvHeader.java
package de.cas.mse.exercise.csv;
import java.util.List;
import de.cas.mse.exercise.csv.ui.CsvUi;
public class CsvHeader {
private final List<CsvColumn> columns;
public CsvHeader(List<CsvColumn> columns) {
this.columns = columns;
}
public void addToUi(CsvUi ui) {
for (CsvColumn column : columns) {
column.addToUi(ui);
}
}
}
|
Conceptual design and multidisciplinary optimization of in-plane morphing wing structures
In this paper, the topology optimization methodology for the synthesis of distributed actuation system with specific applications to the morphing air vehicle is discussed. The main emphasis is placed on the topology optimization problem formulations and the development of computational modeling concepts. For demonstration purposes, the inplane morphing wing model is presented. The analysis model is developed to meet several important criteria: It must allow large rigid-body displacements, as well as variation in planform area, with minimum strain on structural members while retaining acceptable numerical stability for finite element analysis. Preliminary work has indicated that addressed modeling concept meets the criteria and may be suitable for the purpose. Topology optimization is performed on the ground structure based on this modeling concept with design variables that control the system configuration. In other words, states of each element in the model are design variables and they are to be determined through optimization process. In effect, the optimization process assigns morphing members as 'soft' elements, non-morphing load-bearing members as 'stiff' elements, and non-existent members as 'voids.' In addition, the optimization process determines the location and relative force intensities of distributed actuators, which is represented computationally as equal and opposite nodal forces with soft axial stiffness. Several different optimization problem formulations are investigated to understand their potential benefits in solution quality, as well as meaningfulness of formulation itself. Sample in-plane morphing problems are solved to demonstrate the potential capability of the methodology introduced in this paper. |
/**
* Representation of the result of loading a GamesBackup.
* @author nolan
*
*/
public class LoadGamesBackupResult {
private String filename;
private int numFound;
private int numDuplicates;
private List<Game> loadedGames;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getNumFound() {
return numFound;
}
public void setNumFound(int numFound) {
this.numFound = numFound;
}
public List<Game> getLoadedGames() {
return loadedGames;
}
public void setLoadedGames(List<Game> loadedGames) {
this.loadedGames = loadedGames;
}
public int getNumDuplicates() {
return numDuplicates;
}
public void setNumDuplicates(int numDuplicates) {
this.numDuplicates = numDuplicates;
}
} |
def fname_callback(option, op_str, value, parser):
flist = []
for arg in parser.rargs:
if arg[0] is "-":
break
else:
flist.append(arg)
setattr(parser.values, option.dest, flist) |
def ham(s1, s2):
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
mm=0
sup=0
for el1, el2 in zip(s1, s2):
if el1=='-' and el2=='-':
continue
sup +=1
if el1 != el2:
mm +=1
return mm*1.0/sup |
def add_user(self, name: str) -> None:
connection, cursor = self.create_connection()
qrc = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)
qrc.add_data(name)
qrc.make(fit=True)
image = qrc.make_image()
image.save(
"./qr/" + sha3_512(name.encode("ascii", "replace")).hexdigest() +
".png")
cursor.execute("INSERT INTO users (name) VALUES (:name)",
{"name": name})
connection.commit()
self.database_lock.release()
self.database_updated_event.set() |
<reponame>thiagosouzalink/my_codes-exercices-book-curso_intensivo_de_python<filename>Capitulo_10/exercise10_8/exercise10_8.py
"""
10.8 – Gatos e cachorros: Crie dois arquivos, cats.txt e dogs.txt. Armazene pelo
menos três nomes de gatos no primeiro arquivo e três nomes de cachorro no
segundo arquivo. Escreva um programa que tente ler esses arquivos e mostre o
conteúdo do arquivo na tela. Coloque seu código em um bloco try-except
para capturar o erro FileNotFound e apresente uma mensagem simpática caso
o arquivo não esteja presente. Mova um dos arquivos para um local diferente
de seu sistema e garanta que o código no bloco except seja executado de
forma apropriada.
"""
file_cats = 'cats.txt'
file_dogs = 'dogs.txt'
try:
with open(file_cats) as file_object:
names_cats = file_object.readlines()
except FileNotFoundError:
print(f'Desculpe, o arquivo {file_cats} não foi encontrado.')
else:
print('\nOs nomes dos gatos são:')
for cat in names_cats:
print(cat.strip())
print()
try:
with open(file_dogs) as file_object:
names_dogs = file_object.readlines()
except FileNotFoundError:
print(f'Desculpe, o arquivo {file_dogs} não foi encontrado.')
else:
print('Os nomes dos cachorros são:')
for dog in names_dogs:
print(dog.strip())
print() |
def step(self):
if self.__finished:
return
if self.__connector.getPresence() and not self.__connector.isLocked():
self.__connector.lock()
elif self.__encoder.getValue() > REPLICA_DECOUPLING_ANGLE:
self.__enable_statuette_decoupling = True
elif self.__encoder.getValue(
) <= STATUETTE_DECOUPLING_ANGLE and self.__connector.isLocked(
) and self.__enable_statuette_decoupling:
self.__connector.unlock()
self.__finished = True |
package org.qfox.jestful.client.cache.impl.http;
import org.qfox.jestful.client.cache.impl.http.annotation.CacheControl;
import org.qfox.jestful.client.cache.impl.http.annotation.CacheExtension;
import org.qfox.jestful.commons.StringKit;
import org.qfox.jestful.commons.collection.CaseInsensitiveMap;
import org.qfox.jestful.core.*;
import java.util.Map;
public class HttpCacheConstantDirector implements Actor {
@Override
public Object react(Action action) throws Exception {
final Resource r = action.getResource();
final Mapping m = action.getMapping();
final Class<CacheControl> c = CacheControl.class;
final CacheControl directive = m.isAnnotationPresent(c) ? m.getAnnotation(c) : r.isAnnotationPresent(c) ? r.getAnnotation(c) : null;
if (directive == null) return action.execute();
final Map<String, String> map = new CaseInsensitiveMap<String, String>();
if (directive.noCache()) map.put("no-cache", "");
if (directive.noStore()) map.put("no-store", "");
if (directive.maxAge() >= 0) map.put("max-age", String.valueOf(directive.maxAge()));
if (directive.maxStale() >= 0) map.put("max-stale", directive.maxStale() == 0 ? "" : String.valueOf(directive.maxStale()));
if (directive.minFresh() >= 0) map.put("min-fresh", String.valueOf(directive.minFresh()));
if (directive.noTransform()) map.put("no-transform", "");
if (directive.onlyIfCached()) map.put("only-if-cached", "");
final CacheExtension[] extensions = directive.cacheExtensions();
for (CacheExtension extension : extensions) {
final String key = extension.key();
final String value = extension.value();
if (StringKit.isBlank(key) && StringKit.isBlank(value)) continue;
if (StringKit.isBlank(key)) map.put(value.trim(), "");
else map.put(key.trim(), extension.quoted() ? "\"" + value.trim() + "\"" : value.trim());
}
final StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (sb.length() > 0) sb.append(", ");
final String key = entry.getKey();
final String value = entry.getValue();
sb.append(key);
if (StringKit.isBlank(value)) continue;
sb.append("=").append(value);
}
final Request request = action.getRequest();
request.setRequestHeader("Cache-Control", sb.toString());
return action.execute();
}
}
|
def image_summary(name: str,
data: tf.Tensor,
fps=25,
step: int = None,
max_outputs=3):
rank = data.shape.ndims
assert rank >= 3
if rank > 5:
data = merge_video_time_dimensions(data)
if rank == 3:
data = tf.expand_dims(data, axis=-1)
rank = 4
if rank == 4:
return tf.summary.image(name, data, step=step, max_outputs=max_outputs)
else:
return gif_summary(name, data, fps, step, max_outputs) |
/**
* Try out manually some performance measures.
*/
public class TryPerformanceMeasure {
private JSONObject response;
public static void main(final String args[]) throws Exception {
// increase vehicles
// String requestFile = "src/test/resources/metrics/vehicles/req_v68_b1.json";
// String requestFile = "src/test/resources/metrics/vehicles/req_v137_b1.json";
// String requestFile = "src/test/resources/metrics/vehicles/req_v205_b1.json";
// String requestFile = "src/test/resources/metrics/vehicles/req_v274_b1.json";
// increase bookings
// String requestFile = "src/test/resources/metrics/bookings/req_v1_b34.json";
// String requestFile = "src/test/resources/metrics/bookings/req_v1_b68.json";
// String requestFile = "src/test/resources/metrics/bookings/req_v1_b102.json";
// String requestFile = "src/test/resources/metrics/bookings/req_v1_b137.json";
// mixed
String requestFile = "src/test/resources/metrics/req_v1_b1.json";
// String requestFile = "src/test/resources/metrics/req_v34_b120.json";
// String requestFile = "src/test/resources/metrics/req_v68_b103.json";
// String requestFile = "src/test/resources/metrics/req_v136_b69.json";
// String requestFile = "src/test/resources/metrics/req_v205_b103.json";
TryPerformanceMeasure tryOut = new TryPerformanceMeasure();
try {
tryOut.jsprit(requestFile);
} catch (RouteOptimizationException exception) {
String errorResponse = new ErrorResponse(exception).create();
System.out.println(errorResponse);
throw exception;
}
}
public void jsprit(String requestFile) throws Exception {
// given
Path fileName = Path.of(requestFile);
String msg = Files.readString(fileName);
JSONObject routeRequest = new JSONObject(msg);
// when
RouteProcessing routeProcessing = new RouteProcessingWithMetrics();
routeProcessing.calculate(routeRequest);
StatusResponse statusResponse = routeProcessing.getStatusResponse();
response = statusResponse.status;
// then
JSONObject metrics = response.getJSONObject("data").getJSONObject("metrics");
System.out.println(metrics);
String metricFilename = fileName.toString().replace(".json", "_metric.json");
writeJsonFile(metrics, metricFilename);
}
private void writeJsonFile(JSONObject request, String filename) throws IOException {
Path filepath = Paths.get(filename);
Files.write(filepath, request.toString().getBytes());
}
} |
My friend was physically assaulted for wearing a Trump hat at a Purim party in Washington, D.C. I watched it happen. A guy walked over from behind and flipped his cap off because it said “Trump” on the back of it. “You voted for Trump!” he yelled.
I was dying of laughter because I knew my friend is a very liberal Democrat who was only trolling. But as he turned around to try to respectfully explain he was wearing the hat as his costume, his (probably intoxicated) assaulter began taking jabs at his chest. The guy was livid. The rabbi who was there had to step in between them and assure them that they can wear whatever hat they liked on Purim, regardless of their politics.
I, on the other hand, was dressed up as a Women’s March attendee. That was also a joke, as anybody who knows me knows I am far from sympathetic to the radical Women’s March agenda.
Nevertheless, I received a lot of love for my ‘pussy’ hat, which several people assumed was worn in seriousness. It was somewhat funny to watch and upsetting at the same time. I realized how much some people hate my politics.
“I love your hat,” a girl told me emphatically, then turned to my friend and told him she hoped he wasn’t wearing his hat seriously because Donald Trump hates Jews and wants to kill all of us. “I was gonna ask you, how are you Jewish?” she said.
I know I am likely upsetting my liberal friend with this post. He didn’t want this story publicized as a talking point for conservatives, and that is understandable. But I will not let a story like this go unreported, because it affects me personally.
It affects me when I watch Jews being told they can’t support a Republican president because of identity politics, and it affects me when I watch violence against conservatives pushed under the rug in the name of ‘social justice.’ I would hope any truthful person would do the same if the roles were reversed.
Latest Videos |
<filename>core/service/data/notify.ts<gh_stars>1-10
import axios from '@/utils/axios'
import { Request } from '@/interface/request'
import { Notify } from '@/interface/request/notify'
/** 获取公告 */
export const getNotic = () => axios.send<Request.Result<Notify.Notic>>(axios.api.notify.notic)
export const getFriendLink = () =>
axios.send<Request.ResultList<Notify.FriendLink>>(axios.api.notify.friend.get)
|
<reponame>datmaAtmanEuler/VietGoal2
export class Content {
Id:number = 0;
Title:string = '';
Content:string = '';
}
|
from seamless.core import context, cell, StructuredCell
ctx = context(toplevel=True)
ctx.data = cell("mixed")
ctx.sc = StructuredCell(
data=ctx.data
)
data = ctx.sc.handle
data.set(20)
print(data)
ctx.compute()
print(data.data, ctx.data.value)
data.set({})
data.a = "test"
data.b = 12
data.b.set(5)
data.c = {"d": {}}
data.c.d.e = 12.0
print(data)
ctx.compute()
print(data.data, ctx.data.value)
|
/**
* Filter XAttrs from a list of existing XAttrs. Removes matched XAttrs from
* toFilter and puts them into filtered. Upon completion,
* toFilter contains the filter XAttrs that were not found, while
* fitleredXAttrs contains the XAttrs that were found.
*
* @param existingXAttrs Existing XAttrs to be filtered
* @param toFilter XAttrs to filter from the existing XAttrs
* @param filtered Return parameter, XAttrs that were filtered
* @return List of XAttrs that does not contain filtered XAttrs
*/
@VisibleForTesting
List<XAttr> filterINodeXAttrs(final List<XAttr> existingXAttrs,
final List<XAttr> toFilter, final List<XAttr> filtered)
throws AccessControlException {
if (existingXAttrs == null || existingXAttrs.isEmpty() ||
toFilter == null || toFilter.isEmpty()) {
return existingXAttrs;
}
List<XAttr> newXAttrs =
Lists.newArrayListWithCapacity(existingXAttrs.size());
for (XAttr a : existingXAttrs) {
boolean add = true;
for (ListIterator<XAttr> it = toFilter.listIterator(); it.hasNext()
;) {
XAttr filter = it.next();
Preconditions.checkArgument(!KEYID_XATTR.equalsIgnoreValue(filter),
"The encryption zone xattr should never be deleted.");
if (UNREADABLE_BY_SUPERUSER_XATTR.equalsIgnoreValue(filter)) {
throw new AccessControlException("The xattr '" +
SECURITY_XATTR_UNREADABLE_BY_SUPERUSER + "' can not be deleted.");
}
if (a.equalsIgnoreValue(filter)) {
add = false;
it.remove();
filtered.add(filter);
break;
}
}
if (add) {
newXAttrs.add(a);
}
}
return newXAttrs;
} |
def _get_from_cache(self, sector, scale, eft, basis):
try:
return self._cache[eft][scale][basis][sector]
except KeyError:
return None |
<reponame>sbbnethub/sbbnethub
import { countBy } from "./index";
export = countBy;
|
// askForString asks for a string once, using the default if the
// anser is empty. Errors are only returned on I/O errors
func (s *Action) askForString(ctx context.Context, text, def string) (string, error) {
if ctxutil.IsAlwaysYes(ctx) {
return def, nil
}
select {
case <-ctx.Done():
return def, errors.New("user aborted")
default:
}
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s [%s]: ", text, def)
input, err := reader.ReadString('\n')
if err != nil {
return "", errors.Wrapf(err, "failed to read user input")
}
input = strings.TrimSpace(input)
if input == "" {
input = def
}
return input, nil
} |
def pairtree_path(filehash, level=2):
parts = [filehash[(i*2):(i*2)+2] for i,l in enumerate(range(level))]
parts.append(filehash)
return os.sep.join(parts) |
//Stop the timer 1.
#ifndef TM1_STOP_H
#define TM1_STOP_H
#ifdef __cplusplus
extern "C" {
#endif
#include <IO.h>
extern void tm1_stop(void);
#ifdef __cplusplus
}
#endif
#endif
|
def accept_damage(self, damage: Damage):
pass |
<reponame>Medium-One/s5d9-diagnostics-intelligence-with-wifi-and-ota
/***********************************************************************************************************************
* Copyright [2015] Renesas Electronics Corporation and/or its licensors. All Rights Reserved.
*
* The contents of this file (the "contents") are proprietary and confidential to Renesas Electronics Corporation
* and/or its licensors ("Renesas") and subject to statutory and contractual protections.
*
* Unless otherwise expressly agreed in writing between Renesas and you: 1) you may not use, copy, modify, distribute,
* display, or perform the contents; 2) you may not use any name or mark of Renesas for advertising or publicity
* purposes or in connection with your use of the contents; 3) RENESAS MAKES NO WARRANTY OR REPRESENTATIONS ABOUT THE
* SUITABILITY OF THE CONTENTS FOR ANY PURPOSE; THE CONTENTS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
* NON-INFRINGEMENT; AND 4) RENESAS SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING DAMAGES RESULTING FROM LOSS OF USE, DATA, OR PROJECTS, WHETHER IN AN ACTION OF CONTRACT OR TORT, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE CONTENTS. Third-party contents included in this file may
* be subject to different terms.
**********************************************************************************************************************/
#include "r_qspi.h"
#include "../synergy/ssp/src/driver/r_qspi/r_qspi_private.h"
#include "../synergy/ssp/src/driver/r_qspi/r_qspi_private_api.h"
#include <r_qspi_subsector_erase.h>
ssp_err_t R_QSPI_SubSectorErase (void * p_api_ctrl, uint8_t * p_device_address)
{
uint32_t chip_address = (uint32_t) p_device_address - BSP_PRV_QSPI_DEVICE_PHYSICAL_ADDRESS;
qspi_instance_ctrl_t * p_ctrl = (qspi_instance_ctrl_t *) p_api_ctrl;
#if QSPI_CFG_PARAM_CHECKING_ENABLE
SSP_ASSERT(p_ctrl);
SSP_ASSERT(p_device_address);
#endif
/* Send command to enable writing */
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, QSPI_COMMAND_WRITE_ENABLE);
/* Close the SPI bus cycle */
HW_QSPI_DIRECT_COMMUNICATION_ENTER(p_ctrl->p_reg);
if (4 == p_ctrl->num_address_bytes)
{
/* Send command to erase */
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, QSPI_COMMAND_4BYTE_SECTOR_ERASE);
/* Send command to write data */
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, (uint8_t)(chip_address >> 24));
}
else
{
/* Send command to erase */
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, QSPI_COMMAND_4BYTE_SUBSECTOR_ERASE);
}
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, (uint8_t)(chip_address >> 16));
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, (uint8_t)(chip_address >> 8));
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, (uint8_t)(chip_address));
/* Close the SPI bus cycle */
HW_QSPI_DIRECT_COMMUNICATION_ENTER(p_ctrl->p_reg);
/* Send command to disable writing */
HW_QSPI_BYTE_WRITE(p_ctrl->p_reg, QSPI_COMMAND_WRITE_DISABLE);
/* Close the SPI bus cycle */
HW_QSPI_DIRECT_COMMUNICATION_ENTER(p_ctrl->p_reg);
return SSP_SUCCESS;
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11
// UNSUPPORTED: libcpp-has-no-localization
// <experimental/iterator>
//
// template <class _Delim, class _CharT = char, class _Traits = char_traits<_CharT>>
// class ostream_joiner;
//
// ostream_joiner & operator++(int) noexcept
// returns *this;
#include <experimental/iterator>
#include <iostream>
#include <cassert>
#include "test_macros.h"
namespace exper = std::experimental;
template <class Delim, class CharT, class Traits>
void test ( exper::ostream_joiner<Delim, CharT, Traits> &oj ) {
static_assert((noexcept(oj++)), "" );
exper::ostream_joiner<Delim, CharT, Traits> &ret = oj++;
assert( &ret == &oj );
}
int main(int, char**) {
{ exper::ostream_joiner<char> oj(std::cout, '8'); test(oj); }
{ exper::ostream_joiner<std::string> oj(std::cout, std::string("9")); test(oj); }
#ifndef TEST_HAS_NO_WIDE_CHARACTERS
{ exper::ostream_joiner<std::wstring> oj(std::cout, std::wstring(L"10")); test(oj); }
#endif
{ exper::ostream_joiner<int> oj(std::cout, 11); test(oj); }
#ifndef TEST_HAS_NO_WIDE_CHARACTERS
{ exper::ostream_joiner<char, wchar_t> oj(std::wcout, '8'); test(oj); }
{ exper::ostream_joiner<std::string, wchar_t> oj(std::wcout, std::string("9")); test(oj); }
{ exper::ostream_joiner<std::wstring, wchar_t> oj(std::wcout, std::wstring(L"10")); test(oj); }
{ exper::ostream_joiner<int, wchar_t> oj(std::wcout, 11); test(oj); }
#endif
return 0;
}
|
/**
* DB instance a shard in storage
* Stores each of the key with multiple suffixes
*/
public class MultiMapRecordDb {
private Logger logger = LogManager.getLogger(MultiMapRecordDb.class);
RocksDB db;
String dbPath;
//ReentrantLock writeLock = new ReentrantLock();
final int instanceId;
final boolean isReadOnly;
/** Init DB */
public MultiMapRecordDb(final String dbDir, final int instanceId){
this.instanceId = instanceId;
this.dbPath = dbDir;
this.isReadOnly = false;
initDb();
}
/** Init with option to turn on readonly */
public MultiMapRecordDb(final String dbDir, final int instanceId, final boolean isReadOnly){
this.instanceId = instanceId;
this.dbPath = dbDir;
this.isReadOnly = false;
initDb();
}
public synchronized void initDb(){
logger.info("init {} instance {}" , dbPath , instanceId);
File instanceDataDir = new File(dbPath+ "\\"+instanceId);
if (!instanceDataDir.exists()){
instanceDataDir.mkdir();
}
dbPath = instanceDataDir.getAbsolutePath();
Options options = new Options()
.setCreateIfMissing(true)
.setAllowMmapReads(true)
.setAllowMmapWrites(true)
.setCompressionType(CompressionType.ZSTD_COMPRESSION)
.setEnablePipelinedWrite(true);
try {
if (!isReadOnly) {
db = RocksDB.open(options,
dbPath);
}else{
db = RocksDB.openReadOnly(options,
dbPath);
}
} catch (Exception e) {
logger.error("Error in init of DB instance {} {}",instanceId, dbPath);
e.printStackTrace();
}
}
public void close(){
logger.info("compact & close {}",instanceId);
try {
if (!isReadOnly){
db.compactRange();
}
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void addRecord(final String k, final String v){
final String suffixedK = k+":"+ UUID.randomUUID().toString().replace("-","");
try {
addRecord(suffixedK.getBytes(StandardCharsets.UTF_8),v.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void addRecord(final byte [] k, final byte[] v){
try{
db.put(k,v);
}catch (Exception e){
logger.error("error in adding record {} {}", String.valueOf(k),e);
}
}
public byte [] fetchRecord(final byte[] k){
try{
return db.get(k);
}catch (Exception e){
logger.error("exception in getting record {},{}",String.valueOf(k),e);
}
return null;
}
public synchronized void updateRecord(final String k , final String v){
try{
updateRecord(k.getBytes(StandardCharsets.UTF_8),v.getBytes(StandardCharsets.UTF_8));
}catch (Exception e){
logger.error("error in updating record {} instance {} {}",k,instanceId,e);
}
}
public synchronized void updateRecord(final byte [] k, final byte [] v){
try{
db.merge(k,v);
}catch (Exception e){
logger.error("error in updating record {} instance {} {}",k,instanceId,e);
}
}
public Set<byte[]> getRecord(final String k){
Preconditions.checkArgument(k!=null,"Key cannot be null");
try{
return getRecord(k.getBytes(StandardCharsets.UTF_8));
}catch (Exception e){
logger.error("error in fetching record {} instance {} {}",k,instanceId,e);
e.printStackTrace();
}
return null;
}
public Set<byte[]> getRecord(final byte [] k){
Preconditions.checkArgument(k!=null,"Key cannot be null");
try{
return fetchRecordsBulk(k);
}catch (Exception e){
// e.printStackTrace();
logger.error("error in fetching record {} instance {} {}",k,instanceId,e);
}
return null;
}
public Set<byte[]> fetchRecordsBulk(final String k){
Preconditions.checkArgument(k!=null,"Key cannot be null");
return fetchRecordsBulk(k);
}
public Set<byte[]> fetchRecordsBulk(final byte [] k){
RocksIterator iterator = db.newIterator();
String kStr = String.valueOf(k);
Set<byte[]> byteArrColl = new HashSet<>();
iterator.seek(k);
try{
byte [] karr = iterator.key();
byte [] varr = iterator.value();
String key = new String(karr);
String [] keyParts = key.split(":");
do {
if (!iterator.isValid()){
break;
}
System.out.println("process " + kStr + " " + k);
if (!keyParts[0].equalsIgnoreCase(kStr)) {
System.out.println("keys are diff " + key + " " + keyParts[0]);
break;
}
byteArrColl.add(varr);
iterator.next();
} while (true);
return byteArrColl;
}catch (Exception e){
logger.error("Exception in fetching records for {} ",String.valueOf(k),e);
}
return null;
}
} |
def process_file(contents, filename, filedate, years, row_count="max"):
if years:
read_cols = years + ['id']
else:
read_cols = "all"
f = filename[0]
split = f.split('_')
try:
if 'zip' in filename[0]:
zip_file = None
for content, name, date in zip(contents, filename, filedate):
content_type, content_string = content.split(',')
content_decoded = base64.b64decode(content_string)
zip_str = io.BytesIO(content_decoded)
zip_file = ZipFile(zip_str, 'r')
filename = zip_file.namelist()[0]
with zip_file.open(filename) as csvfile:
if row_count == "max":
if read_cols == "all":
xanthos_data = pd.read_csv(csvfile, encoding='utf8', sep=",")
else:
xanthos_data = pd.read_csv(csvfile, encoding='utf8', sep=",", usecols=read_cols)
else:
if read_cols == "all":
xanthos_data = pd.read_csv(csvfile, encoding='utf8', sep=",", nrows=row_count)
else:
xanthos_data = pd.read_csv(csvfile, encoding='utf8', sep=",", usecols=read_cols,
nrows=row_count)
elif 'csv' in filename[0]:
content_type, content_string = contents[0].split(',')
decoded = base64.b64decode(content_string)
if row_count == "max":
if read_cols == "all":
xanthos_data = pd.read_csv(io.StringIO(decoded.decode('utf-8')), error_bad_lines=False,
warn_bad_lines=True)
else:
xanthos_data = pd.read_csv(io.StringIO(decoded.decode('utf-8')), usecols=read_cols,
error_bad_lines=False, warn_bad_lines=True)
else:
if read_cols == "all":
xanthos_data = pd.read_csv(io.StringIO(decoded.decode('utf-8')), nrows=row_count,
error_bad_lines=False, warn_bad_lines=True)
else:
xanthos_data = pd.read_csv(io.StringIO(decoded.decode('utf-8')), nrows=row_count, usecols=read_cols,
error_bad_lines=False, warn_bad_lines=True)
except Exception as e:
print(e)
return None
return [xanthos_data, split] |
<reponame>demosdemon/libmusicbrainz-objc
//
// @file MBRelease.h
// @author <NAME>
// @date Jun 7 2010
// @copyright
// 2010 <NAME> <<EMAIL>> \n
// 2012 <NAME> <<EMAIL>> \n
// This program is made available under the terms of the MIT License.
//
// @brief Release entity
#import "MBRateAndTaggableEntity.h"
@class MBTextRepresentation, MBArtistCredit, MBReleaseGroup, MBList;
/// Represents a `<release/>` element
@interface MBRelease : MBRateAndTaggableEntity
/// Title of the release
@property (nonatomic, readonly) NSString *Title;
/// Status of the release
@property (nonatomic, readonly) NSString *Status;
/// Quality of the release data
@property (nonatomic, readonly) NSString *Quality;
/// Disambiguation comment for the release
@property (nonatomic, readonly) NSString *Disambiguation;
/// Packaging for this release
@property (nonatomic, readonly) NSString *Packaging;
/// Text Representation for this release
@property (nonatomic, readonly) MBTextRepresentation *TextRepresentation;
/// Artist Credit for this release
@property (nonatomic, readonly) MBArtistCredit *ArtistCredit;
/// Release Group that this release belongs to
@property (nonatomic, readonly) MBReleaseGroup *ReleaseGroup;
/// Date of release.
///
/// Matches the regular expression `[0-9]{4}(-[0-9]{2}){0,2}` or empty.
@property (nonatomic, readonly) NSString *Date;
/// ISO-3166 Country Code for this release
///
/// Matches regular expression `[A-Z]{2}` or empty
@property (nonatomic, readonly) NSString *Country;
/// Barcode for the release
@property (nonatomic, readonly) NSString *Barcode;
/// Amazon ASIN for the release
@property (nonatomic, readonly) NSString *Asin;
/// MBList with MBLabelInfo objects
@property (nonatomic, readonly) MBList *LabelInfoList;
/// MBList with MBMedium objects
@property (nonatomic, readonly) MBList *MediumList;
/// MBList with MBRelation objects
@property (nonatomic, readonly) MBList *RelationList;
/// MBList with MBCollection objects
@property (nonatomic, readonly) MBList *CollectionList;
@end
|
def floor_height(self):
return self.chunk.terrain[self.pos.as_tuple()] |
// ReadTable is a convenience function to quickly and easily read a parquet file
// into an arrow table.
//
// The schema of the arrow table is generated based on the schema of the parquet file,
// including nested columns/lists/etc. in the same fashion as the FromParquetSchema
// function. This just encapsulates the logic of creating a separate file.Reader and
// pqarrow.FileReader to make a single easy function when you just want to construct
// a table from the entire parquet file rather than reading it piecemeal.
func ReadTable(ctx context.Context, r parquet.ReaderAtSeeker, props *parquet.ReaderProperties, arrProps ArrowReadProperties, mem memory.Allocator) (arrow.Table, error) {
pf, err := file.NewParquetReader(r, file.WithReadProps(props))
if err != nil {
return nil, err
}
reader, err := NewFileReader(pf, arrProps, mem)
if err != nil {
return nil, err
}
return reader.ReadTable(ctx)
} |
S=input()
T=input()
slist=list(S)
tlist=list(T)
l=len(slist)
res=0
for i in range(0,l):
if(slist[i]!=tlist[i]):
res+=1
print(res) |
<reponame>pelderson/knooppuntnet
import {NgModule} from "@angular/core";
import {RouterModule, Routes} from "@angular/router";
import {Util} from "../components/shared/util";
import {ReplicationStatusPageComponent} from "./status/replication-status-page.component";
import {StatusPageComponent} from "./status/status-page.component";
import {StatusSidebarComponent} from "./status/status-sidebar.component";
import {SystemStatusPageComponent} from "./status/system-status-page.component";
const routes: Routes = [
Util.routePath("", StatusPageComponent, StatusSidebarComponent),
Util.routePath("replication", ReplicationStatusPageComponent, StatusSidebarComponent),
Util.routePath("replication/:period", ReplicationStatusPageComponent, StatusSidebarComponent),
Util.routePath("replication/:period/:year", ReplicationStatusPageComponent, StatusSidebarComponent),
Util.routePath("replication/:period/:year/:monthOrWeek", ReplicationStatusPageComponent, StatusSidebarComponent),
Util.routePath("replication/:period/:year/:month/:day", ReplicationStatusPageComponent, StatusSidebarComponent),
Util.routePath("replication/:period/:year/:month/:day/:hour", ReplicationStatusPageComponent, StatusSidebarComponent),
Util.routePath("system", SystemStatusPageComponent, StatusSidebarComponent),
Util.routePath("system/:period", SystemStatusPageComponent, StatusSidebarComponent),
Util.routePath("system/:period/:year", SystemStatusPageComponent, StatusSidebarComponent),
Util.routePath("system/:period/:year/:monthOrWeek", SystemStatusPageComponent, StatusSidebarComponent),
Util.routePath("system/:period/:year/:month/:day", SystemStatusPageComponent, StatusSidebarComponent),
Util.routePath("system/:period/:year/:month/:day/:hour", SystemStatusPageComponent, StatusSidebarComponent),
];
@NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [
RouterModule
]
})
export class StatusRoutingModule {
}
|
/**
* Configurator class red data from different json file like advancementRewards.json and store in advancementRewards Map<String, Double> object
* we will now compare value in database with the values that the configurator class has read
* and update the value to the database if value changed
*/
private void updateDatabase() {
updateAdvancementReward();
updateEntityReward();
updateBlockMinedReward();
} |
Before becoming Delhi Chief Minister Arvind Kejriwal had promised free water upto 20,000 litres for every household. (Photo: PTI)
Arvind Kejriwal's Aam Aadmi Party stormed to power in 2015 decimating the Congress and pushing the BJP to the margins with his promise of free water, cheaper electricity and corruption-free government.
Delhi Chief Minister Arvind Kejriwal lists free water to lakhs of households in the city as one of his achievements. But at a time when he sacked his Water Resource Minister Kapil Mishra - who has put Arvind Kejriwal in the dock with corruption allegations, a family in the northwest Delhi has got a water bill of Rs 8,642.
Madhav Sharan Shukla, a resident of Shalimar Bagh, was surprised when he found a bill delivered to him from the Delhi Jal Board of nearly Rs 9,000. "Wasn't drinking water supposed to be free under Arvind Kejriwal government," asks Shukla.
'WHAT HAPPENED TO WATER SWARAJYA'
"Arvind Kejriwal told us that they would bring water swarajya in Delhi. We supported him for this. What happened to the promise of water swarajya," asked Shukla.
In 2015, the AAP promised to bring Water Swarajya in Delhi saying that they "will provide Water as a Right" to every household in the city.
Sudha, Shukla's wife' said, "We have been using the same quantity of water. Our water usage has not changed. We have got such an inflated bill for the first time. The bills were never so high during Sheila Dikshit government."
"The Delhi Jal Board officials say that this is the combined bill for the period (of one year)," Madhav Shukla added.
The water bill - dated March 28 - that was delivered to Shukla read 'current period charges' and contains arrear of Rs 10,109.54 and after making some 'adjustment', the payable amount has been billed at Rs 8,642.
First water bill delivered to Shukla family. (Photo: India Today) First water bill delivered to Shukla family. (Photo: India Today)
DJB 'RECTIFIES BILL' AFTER COMPLAINT
Nervous after seeing the bill amount Shukla made a few rounds to the Delhi Jal Board office at Ashok Vihar - the regional centre for the area. Shukla got to speak to some of the officials registering his complaint.
"I asked the DJB officials as to how they calculated my water bill. They told me that my meter was not functional, so standard bill has been sent to me," Shukla said adding, "But, none of the DJB men, who came to take down the meter reading ever complained of non-functional water meter. And, how all of a sudden they come to know that it was not working for two years?"
Meanwhile, Shukla was isistent and kept visiting the Delhi Jal Board office. He was later told that his bill was being revived as 'erroneous' copy of the same was delivered to him.
Shukla got another water bill dated May 1 with payable amount of Rs 3,553 without making any 'adjustment'.
After complaints, the DJB issued another bill to Shukla family. (Photo: India Today) After complaints, the DJB issued another bill to Shukla family. (Photo: India Today)
The new bill reads 'current period charges' for April 20, 2016 to April 17, 2017 against January 29, 2017 to February 19, 2017.
Shukla family is still not convinced with the calculations of the DJB officials. Sudha Shukla insists that the 'water usage' has not changed.
Previous payment history shows Shukla family paying a maximum bill of Rs 300 for June-August 2015. The last water bill paid by Shukla family for February-April 2016 was of Rs 130.
The family is planning to raise the issue in Janata Darbar of Arvind Kejriwal.
Madhav Sharan Shukla complains of receing inflated water bills from the DJB and plans to take the matter to Delhi CM Arvind Kejriwal in Janata Darbar. (Photo: India Today) Madhav Sharan Shukla complains of receing inflated water bills from the DJB and plans to take the matter to Delhi CM Arvind Kejriwal in Janata Darbar. (Photo: India Today)
WHAT AAP MANIFESTO 2015 SAID
In its manifesto for the Delhi Assembly election in 2015, the AAP promised -
It will provide universal access to clean drinking water to all its citizens of Delhi at an affordable price.The DJB Act will be amended to make clean drinking water a right of people.Free Lifeline Water: AAP will ensure free lifeline water of upto 20 kiloliter to every household with DJB's metered water connection.
Incidentally, presenting the AAP government's budget in March, Delhi Deputy Chief Minister Mansih Sisodia said that the Delhi Jal Board's revenue went up by Rs 178 crore despite providing free water to over 12.5 lakh consumers. Shukla family is certainly not one of those.
ALSO READ |
AAP offers free water to Delhi residents, but mohalla clinics running dry
Delhi may face water shortage for a day as canal in Haryana closes for repair
ALSO WATCH | 45-YEAR-OLD DIES OF THIRST |
private static boolean addToZip(String addFileFromThisDir, File addThis, ZipOutputStream zos) {
if (addThis.isDirectory()) return false;
String entryPath;
String addThisPath = addThis.getAbsolutePath();
if (!addThisPath.startsWith(addFileFromThisDir)) {
System.out.println("MiscUtils.addToZip(..) -- BAJ!!");
return false;
} else {
entryPath = addThisPath.substring(addFileFromThisDir.length() + 1);
}
try {
zos.putNextEntry(new ZipEntry(entryPath));
FileInputStream input = new FileInputStream(addThis);
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
|
/**
* Utility to set DistCp options.
*/
public final class DistCPOptionsUtil {
private static final String TDE_ENCRYPTION_ENABLED = "tdeEncryptionEnabled";
private DistCPOptionsUtil() {}
public static DistCpOptions getDistCpOptions(CommandLine cmd,
List<Path> sourcePaths,
Path targetPath,
boolean isSnapshot,
Configuration conf) throws FalconException, IOException {
DistCpOptions distcpOptions = new DistCpOptions(sourcePaths, targetPath);
distcpOptions.setBlocking(true);
distcpOptions.setMaxMaps(Integer.parseInt(cmd.getOptionValue("maxMaps")));
distcpOptions.setMapBandwidth(Integer.parseInt(cmd.getOptionValue("mapBandwidth")));
String tdeEncryptionEnabled = cmd.getOptionValue(TDE_ENCRYPTION_ENABLED);
if (StringUtils.isNotBlank(tdeEncryptionEnabled) && tdeEncryptionEnabled.equalsIgnoreCase(Boolean.TRUE.toString())) {
distcpOptions.setSyncFolder(true);
distcpOptions.setSkipCRC(true);
} else {
if (!isSnapshot) {
String overwrite = cmd.getOptionValue(ReplicationDistCpOption.DISTCP_OPTION_OVERWRITE.getName());
if (StringUtils.isNotEmpty(overwrite) && overwrite.equalsIgnoreCase(Boolean.TRUE.toString())) {
distcpOptions.setOverwrite(Boolean.parseBoolean(overwrite));
} else {
distcpOptions.setSyncFolder(true);
}
}
String skipChecksum = cmd.getOptionValue(ReplicationDistCpOption.DISTCP_OPTION_SKIP_CHECKSUM.getName());
if (StringUtils.isNotEmpty(skipChecksum)) {
distcpOptions.setSkipCRC(Boolean.parseBoolean(skipChecksum));
}
}
if (isSnapshot) {
// Settings needed for Snapshot distCp.
distcpOptions.setSyncFolder(true);
distcpOptions.setDeleteMissing(true);
} else {
// Removing deleted files by default - FALCON-1844
String removeDeletedFiles = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_REMOVE_DELETED_FILES.getName(), "true");
boolean deleteMissing = Boolean.parseBoolean(removeDeletedFiles);
distcpOptions.setDeleteMissing(deleteMissing);
if (deleteMissing) {
// DistCP will fail with InvalidInputException if deleteMissing is set to true and
// if targetPath does not exist. Create targetPath to avoid failures.
FileSystem fs = HadoopClientFactory.get().createProxiedFileSystem(targetPath.toUri(), conf);
if (!fs.exists(targetPath)) {
fs.mkdirs(targetPath);
}
}
}
String ignoreErrors = cmd.getOptionValue(ReplicationDistCpOption.DISTCP_OPTION_IGNORE_ERRORS.getName());
if (StringUtils.isNotBlank(ignoreErrors)) {
distcpOptions.setIgnoreFailures(Boolean.parseBoolean(ignoreErrors));
}
String preserveBlockSize = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_BLOCK_SIZE.getName());
if (StringUtils.isNotBlank(preserveBlockSize) && Boolean.parseBoolean(preserveBlockSize)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.BLOCKSIZE);
}
String preserveReplicationCount = cmd.getOptionValue(ReplicationDistCpOption
.DISTCP_OPTION_PRESERVE_REPLICATION_NUMBER.getName());
if (StringUtils.isNotBlank(preserveReplicationCount) && Boolean.parseBoolean(preserveReplicationCount)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.REPLICATION);
}
String preservePermission = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_PERMISSIONS.getName());
if (StringUtils.isNotBlank(preservePermission) && Boolean.parseBoolean(preservePermission)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.PERMISSION);
}
String preserveUser = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_USER.getName());
if (StringUtils.isNotBlank(preserveUser) && Boolean.parseBoolean(preserveUser)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.USER);
}
String preserveGroup = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_GROUP.getName());
if (StringUtils.isNotBlank(preserveGroup) && Boolean.parseBoolean(preserveGroup)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.GROUP);
}
String preserveChecksumType = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_CHECKSUM_TYPE.getName());
if (StringUtils.isNotBlank(preserveChecksumType) && Boolean.parseBoolean(preserveChecksumType)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.CHECKSUMTYPE);
}
String preserveAcl = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_ACL.getName());
if (StringUtils.isNotBlank(preserveAcl) && Boolean.parseBoolean(preserveAcl)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.ACL);
}
String preserveXattr = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_XATTR.getName());
if (StringUtils.isNotBlank(preserveXattr) && Boolean.parseBoolean(preserveXattr)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.XATTR);
}
String preserveTimes = cmd.getOptionValue(
ReplicationDistCpOption.DISTCP_OPTION_PRESERVE_TIMES.getName());
if (StringUtils.isNotBlank(preserveTimes) && Boolean.parseBoolean(preserveTimes)) {
distcpOptions.preserve(DistCpOptions.FileAttribute.TIMES);
}
return distcpOptions;
}
} |
// CheckPasswordAndIssueKey() checks whether the username/password combo
// checks out. If so, it will generate (and return) a new key associated with
// that username. Returns an empty string and appropriate error if the
// username/password combo is bad.
//
func CheckPasswordAndIssueKey(uname, pwd string) (string, error) {
ok, err := CheckPassword(uname, pwd)
if !ok {
return "", err
}
kstr := generate_key()
kmu.Lock()
keys[kstr] = key{ uname: uname, until: time.Now().Add(key_lifetime) }
kdirty = true
kmu.Unlock()
return kstr, nil
} |
Tunable thulium-doped mode-locked fiber laser with watt-level average power.
We demonstrate a wavelength-tunable, sub-200 fs, and watt-level thulium-doped ultrafast fiber oscillator with a fundamental frequency repetition rate of 509.7 MHz. The wavelength can be tuned between 1918.5 nm and 2031 nm by adjusting the intra-cavity waveplates. When the wavelength is tuned to below 2000 nm, the average output power exceeds 1 W. The oscillator provides a maximum average power of 1.314 W (corresponding to a pulse energy of 2.58 nJ) and a highest peak power of 12.5 kW at 1940 nm. Such a high-power, tunable 2-µm mode-locked fiber laser is an ideal light source candidate for a variety of applications, such as frequency metrology, molecular spectroscopy, and ultrafast pump-probe spectroscopy. |
def gauss(self, full_reduce:bool=False, x:Any=None, y:Any=None, blocksize:int=6, pivot_cols:List[int]=[]) -> int:
rows = self.rows()
cols = self.cols()
pivot_row = 0
for sec in range(math.ceil(cols / blocksize)):
i0 = sec * blocksize
i1 = min(cols, (sec+1) * blocksize)
chunks: Dict[Tuple[Z2,...],int] = dict()
for r in range(pivot_row, rows):
t = tuple(self.data[r][i0:i1])
if not any(t): continue
if t in chunks:
self.row_add(chunks[t], r)
if x is not None: x.row_add(chunks[t], r)
if y is not None: y.col_add(r, chunks[t])
else:
chunks[t] = r
p = i0
while p < i1:
for r0 in range(pivot_row, rows):
if self.data[r0][p] != 0:
if r0 != pivot_row:
self.row_add(r0, pivot_row)
if x is not None: x.row_add(r0, pivot_row)
if y is not None: y.col_add(pivot_row, r0)
for r1 in range(pivot_row+1, rows):
if pivot_row != r1 and self.data[r1][p] != 0:
self.row_add(pivot_row, r1)
if x is not None: x.row_add(pivot_row, r1)
if y is not None: y.col_add(r1, pivot_row)
pivot_cols.append(p)
pivot_row += 1
break
p += 1
rank = pivot_row
if full_reduce:
pivot_row -= 1
pivot_cols1 = pivot_cols.copy()
for sec in range(math.ceil(cols / blocksize) - 1, -1, -1):
i0 = sec * blocksize
i1 = min(cols, (sec+1) * blocksize)
chunks = dict()
for r in range(pivot_row, -1, -1):
t = tuple(self.data[r][i0:i1])
if not any(t): continue
if t in chunks:
self.row_add(chunks[t], r)
if x is not None: x.row_add(chunks[t], r)
if y is not None: y.col_add(r, chunks[t])
else:
chunks[t] = r
while len(pivot_cols1) != 0 and i0 <= pivot_cols1[-1] < i1:
pcol = pivot_cols1.pop()
for r in range(0, pivot_row):
if self.data[r][pcol] != 0:
self.row_add(pivot_row, r)
if x is not None: x.row_add(pivot_row, r)
if y is not None: y.col_add(r, pivot_row)
pivot_row -= 1
return rank |
// Adjacent3DActives tries to find the actives adjacent to this position
func (p *Program) Adjacent3DActives(x, y, z int) int {
actives := 0
for i := x - 1; i <= x+1; i++ {
for j := y - 1; j <= y+1; j++ {
for k := z - 1; k <= z+1; k++ {
if (i >= 0 && i < len(p.Map3D)) && (j >= 0 && j < len(p.Map3D[i])) && (k >= 0 && k < len(p.Map3D[i][j])) {
if (i != x || j != y || k != z) && p.Map3D[i][j][k] == ACTIVE {
actives++
}
}
}
}
}
return actives
} |
The State of Texas has spent nearly $650,000 in taxpayer money underwriting state efforts to roll back abortion access over the past two years, according to public records obtained by Rewire .
The State of Texas has spent nearly $650,000 in taxpayer money underwriting state efforts to roll back abortion access over the past two years, according to public records obtained by Rewire.
Gavel via Shutterstock
The State of Texas has spent nearly $650,000 in taxpayer money underwriting state efforts to roll back abortion access over the past two years, according to public records obtained by Rewire.
That’s the amount of money that the Texas Office of the Attorney General (OAG) spent litigating three controversial state laws in 2012 and 2013, according to a breakdown of staff salary and travel expenses provided by the OAG. The breakdown includes a separate item simply called “abortion topic related,” which cost taxpayers just over $100,000 in the same period of time.
The total—$648,340.13, to be precise—represents another hefty taxpayer contribution to some states’ push against abortion access.
Abortion litigation has reportedly cost the taxpayers of Kansas $913,000; Idaho’s coffers have been emptied to the tune of $811,000; and North Dakota has now spent more than $200,000 defending laws intended to limit access to abortion, according to records that state provided to Rewire.
Get the facts, direct to your inbox. Subscribe to our daily or weekly digest. SUBSCRIBE
While taxpayers are footing the bill for these cases, many of the laws flow from groups whose political outlook is usually fiscally, as well as socially, conservative.
For instance, of the bills accrued by Texas, $120,000 arose from defending HB 2—the law that led to state Sen. Wendy Davis’ famous filibuster last summer—and which has since led to the shuttering of more than a quarter of Texas clinics that provide abortions, amongst other services, according to the Texas Policy Evaluation Project.
Portions of that law are based on model bills produced by Americans United for Life (AUL) according to Kristi Hamrick, an AUL spokesperson.
Hamrick said that several parts of the Texas law—the provisions relating to medical abortions, some definitions within the act, and other requirements relating to physician conduct—were based on AUL’s model bills.
“AUL provides model legislation to anyone who asks for it—media, legislators, etc,” Hamrick wrote in an email to Rewire. “AUL is very careful in determining whether legislation, as passed, is based on AUL’s models, depending on the content of the language.”
AUL says its strategy is to help state lawmakers pass deliberately unconstitutional laws, that directly conflict with the U.S. Supreme Court’s decision in Roe v. Wade. AUL hopes to provoke a constitutional challenge that will land before the Supreme Court, opening up the possibility that Roe will be overturned.
While AUL is tied to right-wing, free-market groups that typically decry public spending, its legal strategy is premised on the use of public subsidies, in the form of taxpayer dollars that states must spend to defend these deliberately unconstitutional laws.
Hamrick did not answer questions relating to AUL’s reliance on taxpayer funds to underwrite its legal strategy.
In the case of HB 2, legal challenges have already reached state and federal court, and may reach the U.S. Supreme Court. That, of course, would result in additional costs for taxpayers.
The total tally of how much taxpayers in all states have already spent defending anti-choice laws is unknown, but what’s clear is that the figure is likely to climb, with more states expected to consider new restrictions on abortion access this legislative session, and a profusion of litigation already underway. |
/*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.2 $
|
| Classes:
| SoBaseList
|
| Author(s) : <NAME>
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include <stdlib.h>
#include <Inventor/SoLists.h>
#include <Inventor/SoPath.h>
#include <Inventor/SoPickedPoint.h>
#include <Inventor/details/SoDetail.h>
#include <Inventor/misc/SoBase.h>
////////////////////////////////////////////////////////////////////////
//
// Description:
// Default constructor.
//
// Use: public
SoBaseList::SoBaseList() : SbPList()
//
////////////////////////////////////////////////////////////////////////
{
// By default, this adds references to things in the list when
// they are added
addRefs = TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Constructor that takes initial approximate size (number of items
// in list).
//
// Use: public
SoBaseList::SoBaseList(int size) : SbPList(size)
//
////////////////////////////////////////////////////////////////////////
{
// By default, this adds references to things in the list when
// they are added
addRefs = TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Constructor that takes another list to copy values from.
//
// Use: public
SoBaseList::SoBaseList(const SoBaseList &l)
//
////////////////////////////////////////////////////////////////////////
{
// By default, this adds references to things in the list when
// they are added
addRefs = TRUE;
copy(l);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Add a pointer to the end of the list
//
// Use: public
void
SoBaseList::append(SoBase * ptr) // pointer to append
//
////////////////////////////////////////////////////////////////////////
{
SbPList::append((void *) ptr);
if (addRefs && ptr)
ptr->ref();
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Insert given pointer into list before pointer with given index
//
// Use: public
void
SoBaseList::insert(SoBase *ptr, // pointer to insert
int addBefore) // index to add before
//
////////////////////////////////////////////////////////////////////////
{
if (addRefs && ptr)
ptr->ref();
SbPList::insert((void *) ptr, addBefore);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Remove pointer with given index
//
// Use: public
void
SoBaseList::remove(int which) // index of pointer to remove
//
////////////////////////////////////////////////////////////////////////
{
if (addRefs && (*this)[which])
(*this)[which]->unref();
SbPList::remove(which);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Remove all pointers from one with given index on, inclusive
//
// Use: public
void
SoBaseList::truncate(int start) // first index to remove
//
////////////////////////////////////////////////////////////////////////
{
int i;
if (addRefs) {
for ( i = start; i < getLength(); i++) {
if ( (*this)[i] ) {
(*this)[i]->unref();
}
}
}
SbPList::truncate(start);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Copy a list, keeping all reference counts correct
//
// Use: public
void
SoBaseList::copy(const SoBaseList &bList) // list to copy from
//
////////////////////////////////////////////////////////////////////////
{
int i;
truncate(0);
if (addRefs) {
for (i = 0; i < bList.getLength(); i++) {
if ( bList[i] ) {
bList[i]->ref();
}
}
}
SbPList::copy(bList);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Set an element of a list
//
// Use: public
void
SoBaseList::set(int i, // index to set
SoBase *ptr) // new pointer value
//
////////////////////////////////////////////////////////////////////////
{
if (addRefs) {
if ( ptr ) {
ptr->ref() ;
}
if ( (*this)[i] ) {
(*this)[i]->unref();
}
}
(*(const SbPList *) this) [i] = (void *) ptr;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Looks in the SoPathList for a path that matches a given one, using the
// == operator. If it is found, return that index, otherwise retun -1
//
// Use: public
int
SoPathList::findPath(const SoPath &path)
//
////////////////////////////////////////////////////////////////////////
{
int i;
SoPath *testPath;
for(i = 0; i < getLength(); i++) {
testPath = (*this)[i];
if (*testPath == path)
return i;
}
return -1; // not found
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Sorts path list in place based on (1) increasing address of head
// node, then (2) increasing indices of children.
//
// Use: public
void
SoPathList::sort()
//
////////////////////////////////////////////////////////////////////////
{
SoPath **paths = new SoPath *[getLength()];
int i;
// Use qsort to do the work
for (i = 0; i < getLength(); i++) {
paths[i] = (*this)[i];
paths[i]->ref();
}
qsort(paths, getLength(), sizeof(SoPath *), comparePaths);
// Move the paths back into this list
for (i = 0; i < getLength(); i++)
set(i, paths[i]);
// Get rid of the array
for (i = 0; i < getLength(); i++)
paths[i]->unref();
delete [] paths;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Given a sorted list, removes any path that (1) is a duplicate,
// or (2) goes through a node that is the tail of another path.
//
// Use: public
void
SoPathList::uniquify()
//
////////////////////////////////////////////////////////////////////////
{
int i, lastSame;
const SoPath *p1;
const SoPath *p2;
// Remove duplicates from the end to minimize array shuffling
for (i = getLength() - 2; i >= 0; i--) {
// Use the SoPath::findFork() method to determine the last
// node that is on a common chain for both paths. Since the
// paths are sorted, we can just check if this node is at the
// end of the first path. If it is, the second one is a
// duplicate and can be removed.
p1 = (*this)[i];
p2 = (*this)[i + 1];
lastSame = p1->findFork(p2);
if (lastSame == p1->getLength() - 1)
remove(i + 1);
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Comparison method for path list sorting.
//
// Use: private
int
SoPathList::comparePaths(const void *p1Ptr, const void *p2Ptr)
//
////////////////////////////////////////////////////////////////////////
{
const SoPath *p1, *p2;
p1 = * (const SoPath * const *) p1Ptr;
p2 = * (const SoPath * const *) p2Ptr;
// Most likely, the head nodes will be the same, so test this first
if (p1->getHead() == p2->getHead()) {
// Test indices in order. A missing child comes before an
// existing child
int depth;
for (depth = 1; depth < p1->getLength(); depth++) {
if (depth >= p2->getLength())
return 1;
if (p1->getIndex(depth) < p2->getIndex(depth))
return -1;
if (p1->getIndex(depth) > p2->getIndex(depth))
return 1;
}
// If we get here, then the paths are the same up to the end
// of path 1. If path2 is longer, then it comes after
if (p2->getLength() > p1->getLength())
return -1;
// Exact same paths
return 0;
}
else if (p1->getHead() < p2->getHead())
return -1;
else
return 1;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Add a typeId to the end of the list
//
// Use: public
void
SoTypeList::append(SoType typeId) // typeId to append
//
////////////////////////////////////////////////////////////////////////
{
// we have to do some hackage to cast an SoType into a void *...
void *hackage = (void*)(unsigned long)(*(int32_t *)&typeId);
SbPList::append(hackage);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Returns index of given typeId in list, or -1 if not found.
//
// Use: public
int
SoTypeList::find(SoType typeId) const
//
////////////////////////////////////////////////////////////////////////
{
// we have to do some hackage to cast an SoType into a void *...
void *hackage = (void*)(unsigned long)(*(int32_t *)&typeId);
return SbPList::find(hackage);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Insert given typeId into list before typeId with given index
//
// Use: public
void
SoTypeList::insert(SoType typeId, // typeId to insert
int addBefore) // index to add before
//
////////////////////////////////////////////////////////////////////////
{
// we have to do some hackage to cast an SoType into a void *...
void *hackage = (void*)(unsigned long)(*(int32_t *)&typeId);
SbPList::insert(hackage, addBefore);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Access an element of a list
//
// Use: public
SoType
SoTypeList::operator [](int i) const
//
////////////////////////////////////////////////////////////////////////
{
// we have to do some hackage to cast our void * back to an SoType...
int32_t hackage = (long)(* (const SbPList *) this)[i];
return *(SoType*)&hackage;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Set an element of a list
//
// Use: public
void
SoTypeList::set(int i, // index to set
SoType typeId) // new typeId value
//
////////////////////////////////////////////////////////////////////////
{
// we have to do some hackage to cast an SoType into a void *...
void *hackage = (void*)(unsigned long)(*(int32_t *)&typeId);
(*(const SbPList *) this) [i] = hackage;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Copy constructor.
//
// Use: public
SoDetailList::SoDetailList(const SoDetailList &l) : SbPList(l)
{
// We need to copy the details, since we delete them when we
// truncate the list
for (int i = 0; i < getLength(); i++)
(* (const SbPList *) this)[i] = (void *) (*this)[i]->copy();
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Delete all details on the list from one with given index on,
// inclusive.
//
// Use: public
void
SoDetailList::truncate(int start)
//
////////////////////////////////////////////////////////////////////////
{
int i;
for ( i = start; i < getLength(); i++) {
if ( (*this)[i] ) {
delete (*this)[i];
}
}
SbPList::truncate(start);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Copies list, making copy instances of each detail in list.
//
// Use: public
void
SoDetailList::copy(const SoDetailList &l)
//
////////////////////////////////////////////////////////////////////////
{
truncate(0);
int num = l.getLength();
for (int i = 0; i < num; i ++) {
SoDetail* detail = l[i];
if (detail)
append(detail->copy());
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Sets an element of a list, deleting old entry.
//
// Use: public
void
SoDetailList::set(int i, SoDetail *detail)
//
////////////////////////////////////////////////////////////////////////
{
if ((*this)[i] != NULL)
delete (*this)[i];
(* (const SbPList *) this)[i] = (void *) detail;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Copy constructor.
//
// Use: public
SoPickedPointList::SoPickedPointList(const SoPickedPointList &l) : SbPList(l)
{
// We need to copy the pickedPoints, since we delete them when we
// truncate the list
for (int i = 0; i < getLength(); i++)
(* (const SbPList *) this)[i] = (void *) (*this)[i]->copy();
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Delete all pickedPoints on the list from one with given index on,
// inclusive.
//
// Use: public
void
SoPickedPointList::truncate(int start)
//
////////////////////////////////////////////////////////////////////////
{
int i;
for (i = start; i < getLength(); i++)
if ((*this)[i] != NULL)
delete (*this)[i];
SbPList::truncate(start);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Sets an element of a list, deleting old entry.
//
// Use: public
void
SoPickedPointList::set(int i, SoPickedPoint *pickedPoint)
//
////////////////////////////////////////////////////////////////////////
{
if ((*this)[i] != NULL)
delete (*this)[i];
(* (const SbPList *) this)[i] = (void *) pickedPoint;
}
|
<reponame>mrwangzhanwei/cloud-brideg<filename>cloud-bridge-common/src/main/java/com/cloud_bridge/conf/ConfigFactory.java
package com.cloud_bridge.conf;
/**
* @author 王战伟
* @email <EMAIL>
* @date 2020/3/25 10:03
*/
public interface ConfigFactory {
String filaPath="config.properties";
ServerConfig getConfig(String filePath);
}
|
export * from './tsconfig';
export * from './compiler_host';
export * from './diagnostics';
export * from './file_cache';
export * from './worker';
export * from './manifest';
|
The Chinese Room: Visualization and Interaction to Understand and Correct Ambiguous Machine Translation
We present The Chinese Room, a visualization interface that allows users to explore and interact with a multitude of linguistic resources in order to decode and correct poor machine translations. The target users of The Chinese Room are not bilingual and are not familiar with machine translation technologies. We investigate the ability of our system to assist such users in decoding and correcting faulty machine translations. We found that by collaborating with our application, end‐users can overcome many difficult translation errors and disambiguate translated passages that were otherwise baffling. We also examine the utility of our system to machine translation researchers. Anecdotal evidence suggests that The Chinese Room can help such researchers develop better machine translation systems. |
/**
* Moves the view
* @param deltaX delta
*/
public void move(float deltaX) {
swipeListView.onMove(downPosition, deltaX);
if (swipeCurrentAction == SwipeListView.SWIPE_ACTION_DISMISS) {
setTranslationX(parentView, deltaX);
setAlpha(parentView, Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / viewWidth)));
} else {
setTranslationX(frontView, deltaX);
}
} |
Perugia, Italy (CNN) -- An Italian jury has found American student Amanda Knox and her Italian boyfriend Raffaele Sollecito guilty in the stabbing death of British exchange student Meredith Kercher.
Knox was sentenced to 26 years in prison and Sollecito was sentenced to 25 years.
Both were convicted on all charges except theft and together must pay 5 million euros ($7.4 million) to the victim's family. In addition, Knox must pay 40,000 euros ($60,000) to a man whom she falsely accused of the killing.
Knox, wearing a lime jacket, her hair in a single braid, began to sob -- her sniffles and sobs punctuating the otherwise silent courtroom -- as the judge read the verdict quietly, without expression.
Few of the eight jurors looked at her. Six of the jurors were wearing red, white and green sashes -- the colors of Italy's flag.
Sollecito's stepmother cried out her stepson's name twice as he and Knox were led from the court.
Curt Knox, Amanda Knox's father, walked the four blocks from the courtroom to his hotel staring stonily ahead, holding his two tearful daughters by the hand.
He said nothing as they strode through the streets of the medieval town except "Move," when journalists got in his way.
"We are extremely disappointed in the verdict rendered today against our daughter," Knox's family said in a statement.
"While we always knew this was a possibility, we find it difficult to accept this verdict when we know that she is innocent, and that the prosecution has failed to explain why there is no evidence of Amanda in the room where Meredith was so horribly and tragically murdered.
"It appears clear to us that the attacks on Amanda's character in much of the media and by the prosecution had a significant impact on the judges and jurors and apparently overshadowed the lack of evidence in the prosecution's case against her."
Knox and Sollecito will appeal the verdicts, attorneys said.
After the verdict, Knox's lawyer, Carlo Della Vedova said his client was upset, but strong.
He would not speculate on the reason for the verdict.
"We have to see the motivation," he said, referring to legal paperwork the judge must file within 90 days to explain the jury's reasoning.
Her family was disappointed, but not surprised, by the verdict, Knox's aunt Janet Huff told CNN.com
"It was terrible, it was gut-wrenching just to hear them say it," said Huff, speaking from her Seattle, Washington, home.
"And to see the people outside the courtroom applauding -- that just made me sick that people can be that callous and cold."
Knox and Sollecito were charged with murder and sexual violence in the November 2007 stabbing death of Meredith Kercher. Knox and Kercher, both studying abroad, were roommates. A third suspect was found guilty in a separate trial.
Prosecutors argued Seattle, Washington, native Amanda Knox was a resentful American so angry with her British roommate that she exacted revenge during a twisted sex misadventure at their home two years ago.
They said Knox directed Sollecito and another man infatuated with her, Rudy Guede, to hold Kercher down as Knox played with a knife before slashing Kercher's throat.
Defense lawyers argued that Guede, who was convicted in a separate fast-track trial and is currently appealing his conviction, was the sole killer. On Thursday, Knox took the stand for a third time in the Perugia courtroom, telling jurors that she is not a "killer" who stabbed her former roommate.
"They say that I am calm. I am not calm," Knox said in Italian. "I fear to lose myself, to have the mask of the killer forced upon me. I fear to be defined as someone I am not."
Prosecutors touted an airtight case.
See the evidence that convicted Knox
They argued DNA on Kercher's bra clasp belonged to Sollecito. And the alleged murder weapon, a 6 ½-inch kitchen knife taken from Sollecito's home, had the DNA of Knox on the handle and Kercher on the blade, prosecutors said.
During the trial, the defense sought to cast doubt on the knife evidence, arguing it doesn't match the wounds on Kercher's body.
And they said the bra clasp with Sollecito's DNA on it was left at the crime scene for weeks and is so contaminated that the evidence can't be considered credible.
Knox's family has argued she has been the victim of character assassination.
Members of Kercher's family have declined repeated CNN requests for comment.
Prosecutor Giuliano Mignini accused the defense of "lynching" the Italian police who worked on the case.
Knox and Sollecito have been jailed for more than two years. The trial began in January in Perugia, a university town about 115 miles (185 kilometers) north of Rome.
CNN's Paula Newton in Italy contributed to this report. |
<gh_stars>0
package com.wstro.dao;
import com.wstro.entity.SsqBet;
import com.wstro.util.BaseDao;
public interface SsqBetDao extends BaseDao<SsqBet> {
}
|
/**
* Evaluate the script.
*
* @param execName the name that will be passed to BSF for this script execution.
* @return the result of the evaluation
* @exception BuildException if something goes wrong executing the script.
*/
@Override
public Object evaluateScript(String execName) throws BuildException {
checkLanguage();
ClassLoader origLoader = replaceContextLoader();
try {
BSFManager m = createManager();
declareBeans(m);
if (engine == null) {
return m.eval(getLanguage(), execName, 0, 0, getScript());
}
return engine.eval(execName, 0, 0, getScript());
} catch (BSFException be) {
throw getBuildException(be);
} finally {
restoreContextLoader(origLoader);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.