content
stringlengths
7
2.61M
// Create inputs for first inference of subgraph. Status T5EncoderSubgraph::CreateInitialFeeds( const Tensor& encoder_input_ids, const std::vector<const OrtValue*>& implicit_inputs, int num_beams, int pad_token_id, int start_token_id, std::vector<OrtValue>& feeds, const BeamSearchDeviceHelper::CreateEncoderInputsFunc& create_encoder_inputs_func, const BeamSearchDeviceHelper::AddToFeedsFunc& add_to_feeds_func, IAllocatorUniquePtr<char>& buffer, OrtValue& expanded_decoder_input_ids) { ORT_ENFORCE(session_state_ != nullptr, "Setup must be called before CreateInitialFeeds"); feeds.reserve(static_cast<size_t>(num_subgraph_inputs) + static_cast<size_t>(num_implicit_inputs)); AllocatorPtr cpu_allocator = session_state_->GetAllocator(encoder_input_ids.Location()); OrtValue expanded_encoder_input_ids; OrtValue expanded_encoder_attention_mask; ORT_RETURN_IF_ERROR(create_encoder_inputs_func(&encoder_input_ids, num_beams, pad_token_id, start_token_id, cpu_allocator, expanded_encoder_input_ids, expanded_encoder_attention_mask, expanded_decoder_input_ids)); const IExecutionProvider* provider = GetProvider(); ORT_RETURN_IF_ERROR(add_to_feeds_func( provider, {expanded_encoder_input_ids, expanded_encoder_attention_mask, expanded_decoder_input_ids}, feeds, buffer)); for (const auto* entry : implicit_inputs) { feeds.push_back(*entry); } return Status::OK(); }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIBHDFS_JNI_HELPER_H #define LIBHDFS_JNI_HELPER_H #include <jni.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <errno.h> #define PATH_SEPARATOR ':' /** Denote the method we want to invoke as STATIC or INSTANCE */ typedef enum { STATIC, INSTANCE } MethType; /** * Create a new malloc'ed C string from a Java string. * * @param env The JNI environment * @param jstr The Java string * @param out (out param) the malloc'ed C string * * @return NULL on success; the exception otherwise */ jthrowable newCStr(JNIEnv *env, jstring jstr, char **out); /** * Create a new Java string from a C string. * * @param env The JNI environment * @param str The C string * @param out (out param) the java string * * @return NULL on success; the exception otherwise */ jthrowable newJavaStr(JNIEnv *env, const char *str, jstring *out); /** * Helper function to destroy a local reference of java.lang.Object * @param env: The JNIEnv pointer. * @param jFile: The local reference of java.lang.Object object * @return None. */ void destroyLocalReference(JNIEnv *env, jobject jObject); /** invokeMethod: Invoke a Static or Instance method. * className: Name of the class where the method can be found * methName: Name of the method * methSignature: the signature of the method "(arg-types)ret-type" * methType: The type of the method (STATIC or INSTANCE) * instObj: Required if the methType is INSTANCE. The object to invoke the method on. * env: The JNIEnv pointer * retval: The pointer to a union type which will contain the result of the method invocation, e.g. if the method returns an Object, retval will be set to that, if the method returns boolean, retval will be set to the value (JNI_TRUE or JNI_FALSE), etc. * exc: If the methods throws any exception, this will contain the reference * Arguments (the method arguments) must be passed after methSignature * RETURNS: -1 on error and 0 on success. If -1 is returned, exc will have a valid exception reference, and the result stored at retval is undefined. */ jthrowable invokeMethod(JNIEnv *env, jvalue *retval, MethType methType, jobject instObj, const char *className, const char *methName, const char *methSignature, ...); jthrowable constructNewObjectOfClass(JNIEnv *env, jobject *out, const char *className, const char *ctorSignature, ...); jthrowable methodIdFromClass(const char *className, const char *methName, const char *methSignature, MethType methType, JNIEnv *env, jmethodID *out); jthrowable globalClassReference(const char *className, JNIEnv *env, jclass *out); /** classNameOfObject: Get an object's class name. * @param jobj: The object. * @param env: The JNIEnv pointer. * @param name: (out param) On success, will contain a string containing the * class name. This string must be freed by the caller. * @return NULL on success, or the exception */ jthrowable classNameOfObject(jobject jobj, JNIEnv *env, char **name); /** getJNIEnv: A helper function to get the JNIEnv* for the given thread. * If no JVM exists, then one will be created. JVM command line arguments * are obtained from the LIBHDFS_OPTS environment variable. * @param: None. * @return The JNIEnv* corresponding to the thread. * */ JNIEnv* getJNIEnv(void); /** * Figure out if a Java object is an instance of a particular class. * * @param env The Java environment. * @param obj The object to check. * @param name The class name to check. * * @return -1 if we failed to find the referenced class name. * 0 if the object is not of the given class. * 1 if the object is of the given class. */ int javaObjectIsOfClass(JNIEnv *env, jobject obj, const char *name); /** * Set a value in a configuration object. * * @param env The JNI environment * @param jConfiguration The configuration object to modify * @param key The key to modify * @param value The value to set the key to * * @return NULL on success; exception otherwise */ jthrowable hadoopConfSetStr(JNIEnv *env, jobject jConfiguration, const char *key, const char *value); /** * Fetch an instance of an Enum. * * @param env The JNI environment. * @param className The enum class name. * @param valueName The name of the enum value * @param out (out param) on success, a local reference to an * instance of the enum object. (Since Java enums are * singletones, this is also the only instance.) * * @return NULL on success; exception otherwise */ jthrowable fetchEnumInstance(JNIEnv *env, const char *className, const char *valueName, jobject *out); #endif /*LIBHDFS_JNI_HELPER_H*/ /** * vim: ts=4: sw=4: et: */
def chan_to_energy(dic): A = dic["Energy coefficients"] ch = dic["Channels"] energy = A[0] + A[1] * ch + A[2] * ch * ch + A[3] * ch * ch * ch out_dic = {"Energy": energy} return out_dic
<filename>pkg/outputs/elasticsearch/config.go /* * Copyright 2019-2020 by <NAME> * https://www.fibratus.io * 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 elasticsearch import ( "github.com/rabbitstack/fibratus/pkg/outputs" "github.com/spf13/pflag" "time" ) const ( esEnabled = "output.elasticsearch.enabled" esServers = "output.elasticsearch.servers" esTimeout = "output.elasticsearch.timeout" esFlushPeriod = "output.elasticsearch.flush-period" esHealthcheck = "output.elasticsearch.healthcheck" esBulkWorkers = "output.elasticsearch.bulk-workers" esHealthcheckInterval = "output.elasticsearch.healthcheck-interval" esHealthcheckTimeout = "output.elasticsearch.healthcheck-timeout" esUsername = "output.elasticsearch.username" esPassword = "<PASSWORD>" esSniff = "output.elasticsearch.sniff" esTraceLog = "output.elasticsearch.trace-log" esIndexName = "output.elasticsearch.index-name" esTemplateName = "output.elasticsearch.template-name" esTemplateConfig = "output.elasticsearch.template-config" esGzipCompression = "output.elasticsearch.gzip-compression" ) // Config contains the options for tweaking the output behaviour. type Config struct { outputs.TLSConfig // Enabled determines whether ES output is enabled. Enabled bool `mapstructure:"enabled"` // Servers contains a comma separated list of Elasticsearch instances that comprise the cluster. Servers []string `mapstructure:"servers"` // Timeout specifies the connection timeout. Timeout time.Duration `mapstructure:"timeout"` // FlushPeriod specifies when to flush the bulk at the end of the given interval. FlushPeriod time.Duration `mapstructure:"flush-period"` // BulkWorkers represents the number of workers that commit docs to Elasticserach. BulkWorkers int `mapstructure:"bulk-workers"` // Healthcheck enables/disables nodes health checking. Healthcheck bool `mapstructure:"healthcheck"` // HealthCheckInterval specifies the interval for checking if the Elasticsearch nodes are available. HealthCheckInterval time.Duration `mapstructure:"healthcheck-interval"` // HealthCheckTimeout sets the timeout for periodic health checks. HealthCheckTimeout time.Duration `mapstructure:"healthcheck-timeout"` // Username is the user name for the basic HTTP authentication. Username string `mapstructure:"username"` // Password is the password for the basic HTTP authentication. Password string `mapstructure:"password"` // Sniff enables the discovery of all Elasticsearch nodes in the cluster. This avoids populating the list of available Elasticsearch nodes. Sniff bool `mapstructure:"sniff"` // TraceLog determines if the Elasticsearch trace log is enabled. Useful for troubleshooting. TraceLog bool `mapstructure:"tracelog"` // IndexName represents the target index for kernel events. It allows time specifiers to create indices per time frame. IndexName string `mapstructure:"index-name"` // TemplateName specifies the name of the index template. TemplateName string `mapstructure:"template-name"` // TemplateConfig contains the full JSON body of the index template. TemplateConfig string `mapstructure:"template-config"` // GzipCompression specifies if gzip compression is enabled. GzipCompression bool `mapstructure:"gzip-compression"` } // AddFlags registers persistent flags. func AddFlags(flags *pflag.FlagSet) { flags.Bool(esEnabled, false, "Determines whether ES output is enabled") flags.StringSlice(esServers, []string{"http://127.0.0.1:9200"}, "Contains a comma separated list of Elasticsearch instances that comprise the cluster") flags.Duration(esTimeout, time.Second*5, "Specifies the output connection timeout") flags.Duration(esFlushPeriod, time.Second, "Specifies when to flush the bulk at the end of the given interval") flags.Int(esBulkWorkers, 1, "Represents the number of workers that commit docs to Elasticsearch") flags.Bool(esHealthcheck, true, "Enables/disables nodes health checking") flags.Duration(esHealthcheckInterval, time.Second*10, "Specifies the interval for checking if the Elasticsearch nodes are available") flags.Duration(esHealthcheckTimeout, time.Second*5, "Specifies the timeout for periodic health checks") flags.String(esUsername, "", "Identifies the user name for the basic HTTP authentication") flags.String(esPassword, "", "Specifies the password for the basic HTTP authentication") flags.Bool(esSniff, false, "Enables the discovery of all Elasticsearch nodes in the cluster. This avoids populating the list of available Elasticsearch nodes") flags.Bool(esTraceLog, false, "Determines if the Elasticsearch trace log is enabled. Useful for troubleshooting") flags.String(esTemplateName, "fibratus", "Specifies the name of the index template") flags.String(esIndexName, "fibratus", "Represents the target index for kernel events. It allows time specifiers to create indices per time frame") flags.String(esTemplateConfig, "", "Contains the full JSON body of the index template") flags.Bool(esGzipCompression, false, "Specifies if gzip compression is enabled") }
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/quic/congestion_control/cube_root.h" #include "base/logging.h" namespace { // Find last bit in a 64-bit word. int FindMostSignificantBit(uint64 x) { if (!x) { return 0; } int r = 0; if (x & 0xffffffff00000000ull) { x >>= 32; r += 32; } if (x & 0xffff0000u) { x >>= 16; r += 16; } if (x & 0xff00u) { x >>= 8; r += 8; } if (x & 0xf0u) { x >>= 4; r += 4; } if (x & 0xcu) { x >>= 2; r += 2; } if (x & 0x02u) { x >>= 1; r++; } if (x & 0x01u) { r++; } return r; } // 6 bits table [0..63] const uint32 cube_root_table[] = { 0, 54, 54, 54, 118, 118, 118, 118, 123, 129, 134, 138, 143, 147, 151, 156, 157, 161, 164, 168, 170, 173, 176, 179, 181, 185, 187, 190, 192, 194, 197, 199, 200, 202, 204, 206, 209, 211, 213, 215, 217, 219, 221, 222, 224, 225, 227, 229, 231, 232, 234, 236, 237, 239, 240, 242, 244, 245, 246, 248, 250, 251, 252, 254 }; } // namespace namespace net { // Calculate the cube root using a table lookup followed by one Newton-Raphson // iteration. uint32 CubeRoot::Root(uint64 a) { uint32 msb = FindMostSignificantBit(a); DCHECK_LE(msb, 64u); if (msb < 7) { // MSB in our table. return ((cube_root_table[static_cast<uint32>(a)]) + 31) >> 6; } // MSB 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ... // cubic_shift 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, ... uint32 cubic_shift = (msb - 4); cubic_shift = ((cubic_shift * 342) >> 10); // Div by 3, biased high. // 4 to 6 bits accuracy depending on MSB. uint32 down_shifted_to_6bit = (a >> (cubic_shift * 3)); uint64 root = ((cube_root_table[down_shifted_to_6bit] + 10) << cubic_shift) >> 6; // Make one Newton-Raphson iteration. // Since x has an error (inaccuracy due to the use of fix point) we get a // more accurate result by doing x * (x - 1) instead of x * x. root = 2 * root + (a / (root * (root - 1))); root = ((root * 341) >> 10); // Div by 3, biased low. return static_cast<uint32>(root); } } // namespace net
package com.dnb.services.customproduct; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for GlobalAssets complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="GlobalAssets"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CurrentAssets" type="{http://services.dnb.com/CustomProductServiceV2.0}GlobalCurrentAssets" minOccurs="0"/> * &lt;element name="TotalCurrentAssetsAmount" type="{http://services.dnb.com/CustomProductServiceV2.0}FinancialAmountType" minOccurs="0"/> * &lt;element name="FixedAssets" type="{http://services.dnb.com/CustomProductServiceV2.0}GlobalLongTermAssets" minOccurs="0"/> * &lt;element name="TotalFixedAssetsAmount" type="{http://services.dnb.com/CustomProductServiceV2.0}FinancialAmountType" minOccurs="0"/> * &lt;element name="OtherAssetsAmount" type="{http://services.dnb.com/CustomProductServiceV2.0}FinancialAmountType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GlobalAssets", namespace = "http://services.dnb.com/CustomProductServiceV2.0", propOrder = { "currentAssets", "totalCurrentAssetsAmount", "fixedAssets", "totalFixedAssetsAmount", "otherAssetsAmount" }) public class GlobalAssets { @XmlElement(name = "CurrentAssets") protected GlobalCurrentAssets currentAssets; @XmlElement(name = "TotalCurrentAssetsAmount") protected FinancialAmountType totalCurrentAssetsAmount; @XmlElement(name = "FixedAssets") protected GlobalLongTermAssets fixedAssets; @XmlElement(name = "TotalFixedAssetsAmount") protected FinancialAmountType totalFixedAssetsAmount; @XmlElement(name = "OtherAssetsAmount") protected FinancialAmountType otherAssetsAmount; /** * Gets the value of the currentAssets property. * * @return * possible object is * {@link GlobalCurrentAssets } * */ public GlobalCurrentAssets getCurrentAssets() { return currentAssets; } /** * Sets the value of the currentAssets property. * * @param value * allowed object is * {@link GlobalCurrentAssets } * */ public void setCurrentAssets(GlobalCurrentAssets value) { this.currentAssets = value; } /** * Gets the value of the totalCurrentAssetsAmount property. * * @return * possible object is * {@link FinancialAmountType } * */ public FinancialAmountType getTotalCurrentAssetsAmount() { return totalCurrentAssetsAmount; } /** * Sets the value of the totalCurrentAssetsAmount property. * * @param value * allowed object is * {@link FinancialAmountType } * */ public void setTotalCurrentAssetsAmount(FinancialAmountType value) { this.totalCurrentAssetsAmount = value; } /** * Gets the value of the fixedAssets property. * * @return * possible object is * {@link GlobalLongTermAssets } * */ public GlobalLongTermAssets getFixedAssets() { return fixedAssets; } /** * Sets the value of the fixedAssets property. * * @param value * allowed object is * {@link GlobalLongTermAssets } * */ public void setFixedAssets(GlobalLongTermAssets value) { this.fixedAssets = value; } /** * Gets the value of the totalFixedAssetsAmount property. * * @return * possible object is * {@link FinancialAmountType } * */ public FinancialAmountType getTotalFixedAssetsAmount() { return totalFixedAssetsAmount; } /** * Sets the value of the totalFixedAssetsAmount property. * * @param value * allowed object is * {@link FinancialAmountType } * */ public void setTotalFixedAssetsAmount(FinancialAmountType value) { this.totalFixedAssetsAmount = value; } /** * Gets the value of the otherAssetsAmount property. * * @return * possible object is * {@link FinancialAmountType } * */ public FinancialAmountType getOtherAssetsAmount() { return otherAssetsAmount; } /** * Sets the value of the otherAssetsAmount property. * * @param value * allowed object is * {@link FinancialAmountType } * */ public void setOtherAssetsAmount(FinancialAmountType value) { this.otherAssetsAmount = value; } }
© Used with permission of / © Rogers Media Inc. 2016. Photo, Mike Kalasnik/Flickr. When I first heard that wrestler Hulk Hogan was suing the website Gawker for $100 million in damages for posting video clips from a sex tape, I dismissed it as pure silliness. After all, Hogan, the loudmouth, mustachioed 1980s WWE champ, makes for an easy punch line. And he isn’t exactly a sympathetic character — for instance, he’s been known to make racial slurs. But, on closer look, the trial raises important questions about privacy and consent, in the celebrity world and beyond. In a nutshell: In 2012, Gawker Media posted portions of a secretly-recorded tape from 2006 or 2007 that showed Hogan having consensual sex with Heather Clem. She’s the former wife of Hogan’s then-best friend Todd Clem, a shock radio DJ who filmed the encounter without Hogan’s knowledge or consent. Hogan (whose legal name is Terry Bollea) is suing Gawker Media for $100 million arguing that his privacy has been violated. Gawker’s defense is that Hogan had publicly talked about his sex life and the existence of the tape, including on Howard Stern’s radio show, which meant it wasn’t a secret. Gawker also says that the exposure is just the reality of life in the digital age, and that Hogan’s public persona and fame made the footage newsworthy. “You have to own up to it and do it with as much grace as you can. Just don’t fight it,” was the advice Gawker founder Nick Denton offered to public figures who might have secrets leaked online. Related: Ashley Madison’s cheaters deserve privacy, too When it comes to uncovering material that is scandalous or controversial, “newsworthiness” is loosely defined. That’s as it should be, to protect journalists from being censored when they expose the hypocrisies and secrets of powerful people, like, say, a big city mayor who smokes crack. It’s harder to make the “news value” argument, though, when the person being exposed is famous but not particularly powerful and their secret is not about anything illegal or corrupt. Hogan’s case reminds me of the 2014 hack of iCloud accounts of several female celebrities including Jennifer Lawrence and Gabrielle Union, and the subsequent leak of their private, nude photos. In a Vanity Fair interview, Lawrence called it “a sex crime” and “a sexual violation.” At the time, many blamed those women for the breach: if they didn’t want those pictures made public, they shouldn’t have taken them in the first place. That sounds an awful lot like Gawker’s case for posting Hogan’s sex tape — once a celebrity opens the door to their private life, they shouldn’t expect it to ever be closed again. Related: How are witnesses prepped in sexual assault trials? The idea that past private actions imply consent to future public exposure is a dangerous one — not just for celebrities. We’ve seen this play out in rape trials and harassment cases, where women are shamed for their sexual histories, or in revenge porn, where intimate photos are shared to humiliate ex-lovers. We’ve also seen how traumatic it can be to be exposed online without consent in the case of sports journalist Erin Andrews, the victim of a stalker who posted nude photos of her on websites. In a recent trial, Andrews revealed that her bosses at ESPN added to her trauma by insisting that she do an interview about the incident, even after she told them she wanted to put it all behind her. Hulk Hogan seems an unlikely ally to these women and certainly an unlikely champion for the rights of victims of sexual harassment and abuse. But that’s exactly why we need to take his case seriously. He should be able to decide how much of himself he wishes to expose and when he wants to expose it. As cartoonish and outrageous as Hogan may be, his right to privacy is no joke. More columns by Rachel Giese: When it comes to women in media, let’s #AskHerMore Kesha’s court battle and the power dynamics of pop music There’s value in live-tweeting Jian Ghomeshi’s trial
<reponame>simonrose121/slidinghome<filename>modules/soundengine/source/IwSoundSpec.cpp /* * This file is part of the Marmalade SDK Code Samples. * * (C) 2001-2012 Marmalade. All Rights Reserved. * * This source code is intended only as a supplement to the Marmalade SDK. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ /* * Sound description. */ #include "IwSoundSpec.h" #include "IwResManager.h" #include "s3eSound.h" #include "IwSound.h" #include "IwSoundData.h" #include "IwSoundGroup.h" #include "IwSoundInst.h" #include "IwSoundParams.h" #include "IwSoundPCM.h" #include "IwSoundADPCM.h" #include "IwDebug.h" #include "IwRandom.h" // Forward Declarations //----------------------------------------------------------------------------- // CIwSoundSpec callbacks //----------------------------------------------------------------------------- int _IwSoundSpec_EndSampleCB(s3eSoundEndSampleInfo* esInfo, void* userData) { IW_CALLSTACK("_IwSoundSpec_EndSampleCB") if (esInfo->m_RepsRemaining) return 1; // End sound CIwSoundInst* pInst = (CIwSoundInst*)userData; pInst->m_Flags |= CIwSoundInst::COMPLETE_F; return 0; } //----------------------------------------------------------------------------- // CIwSoundSpec //----------------------------------------------------------------------------- IW_CLASS_FACTORY(CIwSoundSpec); IW_MANAGED_IMPLEMENT(CIwSoundSpec) CIwSoundSpec::CIwSoundSpec() { IW_CALLSTACK("CIwSoundSpec::CIwSoundSpec") m_Data = NULL; m_VolMin = IW_GEOM_ONE; m_VolMax = IW_GEOM_ONE; m_PanMin = 0; m_PanMax = 0; m_PitchMin = IW_GEOM_ONE; m_PitchMax = IW_GEOM_ONE; m_Group = NULL; m_Flags = 0; } //----------------------------------------------------------------------------- CIwSoundSpec::~CIwSoundSpec() { IW_CALLSTACK("CIwSoundSpec::~CIwSoundSpec"); if (IwGetSoundManager()) IwGetSoundManager()->StopSoundSpec(this); } //----------------------------------------------------------------------------- void CIwSoundSpec::Serialise() { IW_CALLSTACK("CIwSoundSpec::Serialise") CIwManaged::Serialise(); IwSerialiseUInt16(m_Flags); IwSerialiseInt16(m_VolMin); IwSerialiseInt16(m_VolMax); IwSerialiseInt16(m_PanMin); IwSerialiseInt16(m_PanMax); IwSerialiseInt16(m_PitchMin); IwSerialiseInt16(m_PitchMax); // To be resolved: IwSerialiseManagedHash(&m_Data); IwSerialiseManagedHash(&m_Group); } //----------------------------------------------------------------------------- void CIwSoundSpec::Resolve() { IW_CALLSTACK("CIwSoundSpec::Resolve") CIwManaged::Resolve(); IwResolveManagedHash(&m_Data, IW_SOUND_RESTYPE_DATA); IwResolveManagedHash(&m_Group, IW_SOUND_RESTYPE_GROUP); } //----------------------------------------------------------------------------- CIwSoundInst* CIwSoundSpec::Play(const CIwSoundParams* pParams) { IW_CALLSTACK("CIwSoundSpec::Play") // Get free inst - Fail if not available CIwSoundInst* pInst = IwGetSoundManager()->GetFreeInst(); if (!pInst) return NULL; // Fail if no free channel int32 chanID = IwGetSoundManager()->GetFreeChannel(pInst, m_Data->m_Format); if (chanID < 0) { IwGetSoundManager()->SetFreeInst(pInst); return NULL; } IwTrace(SOUND, ("Playing %s %p", DebugGetName(), m_Data->m_Samples)); // Get specified or identity modifying params if (!pParams) pParams = IwGetSoundManager()->GetParamsIdentity(); // Get specified or identity group CIwSoundGroup* pGroup = NULL; if (m_Group) { pGroup = m_Group; if (pGroup->GetMaxPolyphony()) { if (pGroup->GetMaxPolyphony() == pGroup->GetCurrPolyphony()) { // ! I have changed the default behaviour here from killing // ! the oldest instance to just preventing any new sounds // ! being played. This is because there are multithreading // ! issues to consider, which aren't trivial. The current // ! KillOldestInst isn't strictly correct, as the polyphony // ! gets decremented twice - once in our thread, once in // ! the sound thread. Also, because of the delayed stop, // ! if many instances are fired off at once, the fixed // ! buffer can overflow if (pGroup->GetFlags() & CIwSoundGroup::KILL_OLDEST_F) { // Kill oldest instance pGroup->KillOldestInst(true); } else { // Sorry, we're at our limit IwGetSoundManager()->SetFreeInst(pInst); return NULL; } } } // Increase curr polyphony pGroup->m_CurrPolyphony++; } else { pGroup = (CIwSoundGroup*)IwGetSoundManager()->GetGroupIdentity(); } pInst->m_Count = 0; // Get vol/pan/pitch to store with inst iwsfixed vol = (m_VolMin == m_VolMax) ? m_VolMin : (iwsfixed)IwRandMinMax(m_VolMin, m_VolMax); iwsfixed pan = (m_PanMin == m_PanMax) ? m_PanMin : (iwsfixed)IwRandMinMax(m_PanMin, m_PanMax); iwsfixed pitch = (m_PitchMin == m_PitchMax) ? m_PitchMin : (iwsfixed)IwRandMinMax(m_PitchMin, m_PitchMax); // Write to inst pInst->m_Spec = this; pInst->m_Vol = (iwsfixed)IW_FIXED_MUL(vol, pParams->m_Vol); pInst->m_Pan = (iwsfixed)MAX(-IW_GEOM_ONE, MIN(IW_GEOM_ONE, pan + pParams->m_Pan)); pInst->m_Pitch = (iwsfixed)IW_FIXED_MUL(pitch, pParams->m_Pitch); pInst->m_ChanID = (uint16)chanID; pInst->m_EndSampleCB = NULL; // Get final vol/pan/pitch vol = (iwsfixed)IW_FIXED_MUL(pInst->m_Vol, IW_FIXED_MUL(IwGetSoundManager()->GetMasterVol(), pGroup->m_Vol)); pan = (iwsfixed)MAX(-IW_GEOM_ONE, MIN(IW_GEOM_ONE, pan + IwGetSoundManager()->GetMasterPan() + pGroup->m_Pan)); pitch = (iwsfixed)IW_FIXED_MUL(pitch, IW_FIXED_MUL(IwGetSoundManager()->GetMasterPitch(), pGroup->m_Pitch)); bool looped = IsLooped(); if (IwGetSoundManager()->IsActive() == false) return pInst; s3eSoundChannelRegister(chanID, S3E_CHANNEL_END_SAMPLE, (s3eCallback)_IwSoundSpec_EndSampleCB, pInst); // Set volume // s3eSoundChannelSetInt(chanID, S3E_CHANNEL_VOLUME, vol << 4); // PROPOSED FIX TO #379 s3eSoundChannelSetInt(chanID, S3E_CHANNEL_VOLUME, MIN(S3E_SOUND_MAX_VOLUME, vol >> 4)); // convert from .12 to .8 format // TODO: SET PAN // Set pitch int32 pp = IW_FIXED_MUL(pitch, pInst->GetSpec()->GetData()->m_RecPitch); s3eSoundChannelSetInt(chanID, S3E_CHANNEL_RATE, pp); // Play sound according to sample formatzzscz switch (m_Data->m_Format) { case PCM_8BIT_MONO: { CIwArray<int8> samples; m_Data->GetData(samples); s3eSoundChannelPlay(chanID, (int16*) samples.begin(), (int16*) samples.end()-(int16*)samples.begin(), (looped ? -1 : 1), 0); } break; case PCM_16BIT_MONO: { // Get an array containing the data CIwArray<int16> samples; m_Data->GetData(samples); s3eSoundChannelPlay(chanID, (int16*)samples.begin(), (int16*)samples.end()-(int16*)samples.begin(), (looped ? -1 : 1), 0); } break; case ADPCM_MONO: { CIwArray<int16> samples; m_Data->GetData(samples); s3eSoundChannelSetInt(chanID, S3E_CHANNEL_USERVAR, (intptr_t)m_Data); s3eSoundChannelPlay(chanID, (int16*)samples.begin(), (int16*)samples.end()-(int16*)samples.begin(), (looped ? -1 : 1), 0); } break; } // Set callbacks return pInst; } //----------------------------------------------------------------------------- bool CIwSoundSpec::ParseAttribute(CIwTextParserITX* pParser, const char* pAttrName) { IW_CALLSTACK("CIwSoundSpec::ParseAttribute") #ifndef IW_DEBUG IwAssertMsg(SOUND, false, ("Project not built with IW_DEBUG")); return false; #else if (!strcmp(pAttrName, "data")) { // Locate CIwSoundData resource char line[80]; pParser->ReadString(line, 80); m_Data = (CIwSoundData*)IwGetResManager()->GetResNamed(line, IW_SOUND_RESTYPE_DATA); IwAssertMsg(SOUND, m_Data, ("Could not find CIwSoundData named %s", line)); } else if (!strcmp(pAttrName, "vol")) { iwfixed v; pParser->ReadFixed(&v); m_VolMin = m_VolMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "volMin")) { iwfixed v; pParser->ReadFixed(&v); m_VolMin = (iwsfixed)v; } else if (!strcmp(pAttrName, "volMax")) { iwfixed v; pParser->ReadFixed(&v); m_VolMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "pitch")) { iwfixed v; pParser->ReadFixed(&v); m_PitchMin = m_PitchMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "pitchMin")) { iwfixed v; pParser->ReadFixed(&v); m_PitchMin = (iwsfixed)v; } else if (!strcmp(pAttrName, "pitchMax")) { iwfixed v; pParser->ReadFixed(&v); m_PitchMax = (iwsfixed)v; } else if (!strcmp(pAttrName, "loop")) { bool b; pParser->ReadBool(&b); if (b == true) m_Flags |= LOOPED_F; else m_Flags &= ~LOOPED_F; } else if (!strcmp(pAttrName, "group")) { // Locate CIwSoundGroup resource char line[80]; pParser->ReadString(line, 80); CIwSoundGroup* pGroup = IwSafeCast<CIwSoundGroup*> (IwGetResManager()->GetResNamed(line, IW_SOUND_RESTYPE_GROUP)); IwAssertMsgTrap(SOUND, pGroup, ("Could not find CIwSoundGroup named %s", line), return true); SetGroup(pGroup); } else return CIwManaged::ParseAttribute(pParser, pAttrName); #endif return true; } //----------------------------------------------------------------------------- void CIwSoundSpec::ParseClose(CIwTextParserITX* pParser) { IW_CALLSTACK("CIwSoundSpec::ParseClose") #ifndef IW_DEBUG IwAssertMsg(SOUND, false, ("Project not built with IW_DEBUG")); #else // There must be a current resource group IwAssertMsgTrap(SOUND, IwGetResManager()->GetCurrentGroup(), ("No current resource group - don't know what to do with created object"), return); // Add to current resource group IwGetResManager()->GetCurrentGroup()->AddRes(IW_SOUND_RESTYPE_SPEC, this); #endif } //----------------------------------------------------------------------------- void CIwSoundSpec::Trace() { // Output header info #ifdef IW_DEBUG IwTrace(SOUND, ("\"%s\"", DebugGetName())); #endif IwTrace(SOUND, ("Hash: %u Vol: %d->%d Pitch: %d->%d Pan: %d->%d", m_Hash, m_VolMin, m_VolMax, m_PitchMin, m_PitchMax, m_PanMin, m_PanMax)); // Output an ascii graph representing the sample const int32 cColumns = 80; // Width of graph const int32 cRows = 32; // Height of graph // Symbols used to draw the graph - Should look something like this: // .:'| // |||| // -------- // |||| // ':!| // This gives us four units per row of the graph. const char cSymbolsPos[] = { ' ', '.', ':', '\'', '|' }; const char cSymbolsNeg[] = { '|', '!', ':', '\'', ' ' }; char lineBuffer[cColumns + 1]; // Allow space for terminator uint32 sampleSize = m_Data->m_SampleCount; int16 heightUnit; // Sample value represented by each quarter row. CIwArray<int16> samples16; CIwArray<int8> samples8; switch (m_Data->m_Format) { case PCM_8BIT_MONO: heightUnit = 0x100 / (cRows * 4); m_Data->GetData(samples8); IwTrace(SOUND, ("Format: PCM 8-bit mono")); break; case PCM_16BIT_MONO: heightUnit = 0x10000 / (cRows * 4); m_Data->GetData(samples16); IwTrace(SOUND, ("Format: PCM 16-bit mono")); break; default: // Unsupported format IwTrace(SOUND, ("Format: Unsupported")); return; } // Draw the graph for (int32 y = cRows / 2 - 1; y >= (-cRows / 2); y--) // Counting cRows { int16 sampleMin = (int16)(y * 4); const char* symbols = (y >= 0) ? cSymbolsPos : cSymbolsNeg; int32 x = 0; for (x = 0; x < cColumns; x++) { int16 sampleUnits; if (m_Data->m_Format == PCM_16BIT_MONO) sampleUnits = samples16[(x * sampleSize) / cColumns] / heightUnit; else sampleUnits = samples8[(x * sampleSize) / cColumns] / heightUnit; int16 remainder = sampleUnits - sampleMin; if (sampleMin >= sampleUnits) remainder = 0; else if (remainder > 4) remainder = 4; lineBuffer[x] = symbols[remainder]; } // Start and terminate string and output lineBuffer[x] = '\0'; #ifdef IW_USE_TRACING int16 axisVal = (y >= 0) ? (sampleMin + 4) * heightUnit : sampleMin * heightUnit; IwTrace(SOUND, ("%6d %s", axisVal, lineBuffer)); #endif if (y == 0) { // axis line memset(lineBuffer, '-', cColumns); lineBuffer[0] = '0'; lineBuffer[cColumns] = '\0'; IwTrace(SOUND, ("%6d %s", 0, lineBuffer)); } } }
A quad bike rider was caught on dashcam footage flying round a corner on two wheels before smashing into the car that was recording him. Jessica Billingham, 21, who was left shocked but uninjured, claims the man then fled without exchanging details. The crash happened in Dudley, West Midlands, as Ms Billingham and her boyfriend Tommy Butters, 20, were heading to the shops. Ms Billingham, from Bobbington, Staffordshire, says she called police from the scene but claims no officers turned up. She added: 'The car has been written off. I reported this at the police station this morning to be told that police do not have to stop for road traffic accidents. 'Police also said that without a registration they could not investigate the quad bike. To say I'm disappointed in our police would be an understatement. 'I am however extremely grateful to the wonderful people who assisted my daughter and waited with her until her dad reached her. The shocking footage shows the man speeding around the corner and into the oncoming lane. Another person on a quad bike can be seen behind him. The first rider tries to turn the quad bike but ends up on two wheels and, realising the bike is out of control, braces for impact. The dash cam captures the quad bike smashing into Ms Billingham's car bonnet. Ms Billingham said of her and her boyfriend: 'We were both just shaken up but just glad that we're both okay as it could have been a lot worse. 'I'm really grateful to the people who stopped to see we were okay and one lady waited with me until my dad managed to get to me which was really nice of her. 'There were two quad bikes, the one who crashed into me originally said to pull my car round off the main road and we'll exchange details and get it sorted. 'He told me that his brakes weren't working on his quad bike. But then when moving my car he ran off and didn't come back. He was very quick to disappear and he either took the bike with him or the other quad bike rider helped him. 'I was shocked that the police drove past after myself and other drivers tried to flag them down but can understand that they may have been on the way to another call. 'But I was disappointed that when we reported it the following morning that they weren't even interested in seeing the footage or looking into it further without the registration. 'That's why it was uploaded on social media and many people have reported that they often drive around there in the road and have nearly caused accidents and have been a nuisance. 'I'm not criticising the police as I know they're understaffed and don't have enough support but I feel this is more than just a road traffic accident.
/** * Created by kristianss27 on 10/27/16. */ public class ViewHolder2 extends RecyclerView.ViewHolder implements View.OnClickListener { public ImageView ivUserImg; public TextView tvUserName; public TextView tvTweetText; private Context context; private List<Tweet> articles; public ViewHolder2(View v, Context context, List<Tweet> articles){ super(v); ivUserImg = (ImageView) v.findViewById(R.id.ivUserImg); tvUserName = (TextView) v.findViewById(R.id.tvUserName); tvTweetText = (TextView) v.findViewById(R.id.tvTweetText); // Store the context this.context = context; this.articles = articles; // Attach a click listener to the entire row view itemView.setOnClickListener(this); } @Override public void onClick(View v) { /*int position = getAdapterPosition(); // gets item position if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it Article article = articles.get(position); // We can access the data within the views Intent intent = new Intent(context, ArticleActivity.class); intent.putExtra("article", Parcels.wrap(article)); v.getContext().startActivity(intent); //Toast.makeText(context, article.getHeadline(), Toast.LENGTH_SHORT).show(); }*/ } }
We at DICE are committed to improving the overall Battlefield 4 multiplayer experience for our players. Some issues, commonly referenced in conjunction to “netcode” are preventing Battlefield 4 from performing optimally for everyone, and with this post we would like to explain what we are doing to address these problems. Fixing the commonly nicknamed “netcode issues” – problems ranging between faulty networking latency compensation and glitches in the gameplay simulation itself – is one of the top priorities for DICE. We’d like to take a moment to discuss how we are addressing these issues, as this is a very hot topic for many of our fans. We are working on fixing glitches in your immediate interactions with the game world: the way you move and shoot, the feedback when you’re hit, and the way other players’ actions are shown on your screen. The game receives updates from the game server and displays these to the player using a system called latency compensation – this system makes sure players move around naturally on your screen when network updates arrive. We have found and fixed several issues with latency compensation, and thereby decreased the impressions of “one hit kills” in the game. We have also fixed several issues that could lead to rubber banding, and we are working on fixing several more. Below you’ll find a detailed list of the issues we are focusing on, or have already adjusted in-game. We hope this gives you more insight into the “netcode” issues and we will continue to keep you updated on top issues. What we are Fixing or Investigating Rubber banding We have made several server optimizations that have decreased rubber banding for some players. To further address the issue, there are upcoming fixes for packet loss and a customize screen bug, both connected to the rubber banding issue. Furthermore, we will continue to collect data to pinpoint exactly when and why rubber banding is occurring. Kill camera delay / Player death sync On some occasions, the kill camera would trigger before the game client displayed the last portion of damage being dealt, giving players the impression that they died too early. There were also issues with blood effects, damage indicators, and the health bar in the HUD being out of sync. A fix for this will be included in the next game update. Tickrate Players have been asking whether the tickrate – how often the server will update the game world – in Battlefield 4 will be higher in the future. Though we haven’t got any immediate plans to increase the tickrate at this moment, we are exploring the possibilities of raising the tickrate on specific servers. No registered damage We are aware of the bug where players have been firing at their opponent and not doing damage. In the February 13 game update for PC, we added a piece of code that enables us to specifically track instances where this would occur. We are currently looking at when this issue is triggered, and what causes it. The data that we receive will help us to further improve the firefights in the future. Instant death while sprinting At certain occasions while walking or sprinting, a player could get catapulted at high speed which would cause death if any object was standing in the way. This was caused by a mathematical error in the character physics code, and we have a fix prepared for an upcoming patch. Various Items In addition to these items, there are also fixes coming for issues with Levolution being out of sync, shots appearing to be fired in the wrong direction, and vehicles outside the infantry area not taking damage when fired at. Also, we have introduced new in-game icons that will help you, and us, to troubleshoot network related problems that could cause an inconsistent multiplayer experience. Network Troubleshooting Icons With the January 30-31 game updates, we’ve introduced two new icons to the Battlefield 4 HUD (head-up display). These were added to the game as a way for us, and the players, to more easily troubleshoot common network-related issues that may have negative effects on the multiplayer experience. The first icon, seen at the top in the shape of a clock, indicates that your connection to the server is lagging. There can be several reasons for this. For example, it could mean that someone else is using your connection while you are playing, but it could also mean that there is a network problem that occurred somewhere between you and the server. The effect of such lag is that it will take a bit longer for you to see what is happening in the game world. If this icon is frequently blinking, you might want to try a different server or see if you can decrease the load on your Internet connection. The second icon, at the bottom, shows four squares that indicate packet loss. When you see this icon, your connection to the server is experiencing lost packets, which means that information is failing to reach its destination, either when your game client sends it to the server or when the server sends the information to you. Please keep in mind that packets always get lost on the Internet and that you should not be alarmed if you’re seeing this icon blinking once or twice. If you have a large amount of packet loss and see the icon often, you will probably experience game “hiccups” sometimes – action will stop for a moment, then speed ahead to catch up. What we have Fixed Kill card shows 0 health Kill card sometimes incorrectly displays 0 health, despite the enemy being alive. This could happen when a portion of damage dealt was rejected by the server, since the bullets that caused it were fired after the point of death for the firing player – the kill card would show the health as predicted by your game client, rather than the health confirmed by the server. An improvement that decreased the rate at which this happens went live for PC on Feb 13, and will be included in the next game update for all the platforms. Broken collision We have fixed instances of broken collision that made it impossible for players to shoot past broken objects, such as the collapsed chimney on Zavod 311. Crosshair disappearing, resulting in hit markers disappearing In firefights, players on PC could experience their crosshair disappearing, resulting in hit markers also disappearing. This would happen when certain gadgets were deployed by other players. A fix for this is now live. Hit impact sounds Impact sounds did not match the number of bullet impacts, causing players to feel that they died too quickly. An improvement to this went live for PC on February 13, and will be included in the next update for all the other platforms. The cooldown time for letting bullet hits trigger the sound has been decreased considerably, so players will now hear every bullet that hits them. Headshot icon We have re-introduced the headshot icon to help players understand when they get killed by a headshot, something that usually results in an instant death. The headshot icon went live in the January 30-31 game update for all platforms. We want to assure you that we are constantly investigating, or already in the process of updating, all these items and several more that you’ve had concerns with – and that we will continue to do so with your help. Please continue to send us your feedback, and thank you for your continued support. Remember to visit the Battlefield 4 Control Room regularly for all intel on game updates.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.springframework.data.rest.webmvc; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.Field; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.rest.core.invoke.RepositoryInvoker; import org.springframework.data.rest.core.mapping.ResourceMetadata; import static org.springframework.data.rest.webmvc.RepositoryEntityController.BASE_MAPPING; import org.springframework.data.rest.webmvc.jsonfilterannotations.SerializeOnePropertiesFilter; import org.springframework.data.rest.webmvc.jsonfilterannotations.SerializeOnePropertiesFilters; import org.springframework.data.rest.webmvc.support.BackendId; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author luis */ public class JsonRepositoryEntityController extends AbstractRepositoryRestController { public JsonRepositoryEntityController(PagedResourcesAssembler<Object> pagedResourcesAssembler) { super(pagedResourcesAssembler); } public class CustomIntrospector extends JacksonAnnotationIntrospector { @Override public Object findFilterId(Annotated a) { // Let's default to current behavior if annotation is found: Object id = super.findFilterId(a); // but use simple class name if not if (id == null) { int beginIndex = a.getName().lastIndexOf('.') + 1; id = a.getName().substring(beginIndex); } return id; } } public void processOutput( ResourceMetadata resourceMetadata, Object domainObj, OutputStream outputStream ) throws IOException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Class resourceMetaDataClass = resourceMetadata.getClass(); Field field = resourceMetaDataClass.getDeclaredField("repositoryInterface"); field.setAccessible(true); RepositoryMetadata repositoryMetadata = (RepositoryMetadata) field.get(resourceMetadata); field.setAccessible(false); SerializeOnePropertiesFilters ann = repositoryMetadata.getRepositoryInterface().getAnnotation(SerializeOnePropertiesFilters.class); SimpleFilterProvider filterProvider = new SimpleFilterProvider().setDefaultFilter(SimpleBeanPropertyFilter.filterOutAllExcept("")); if (ann != null) { for (SerializeOnePropertiesFilter serializeOnePropertiesFilter : ann.value()) { String className = serializeOnePropertiesFilter.className(); String[] exclude = serializeOnePropertiesFilter.exclude(); String[] include = serializeOnePropertiesFilter.include(); if (exclude.length > 0) { filterProvider.addFilter(className, SimpleBeanPropertyFilter.serializeAllExcept(exclude)); } else if (include.length > 0) { filterProvider.addFilter(className, SimpleBeanPropertyFilter.filterOutAllExcept(include)); } else { filterProvider.addFilter(className, SimpleBeanPropertyFilter.serializeAllExcept("")); } } } new ObjectMapper() .setAnnotationIntrospector(new CustomIntrospector()) .writerWithDefaultPrettyPrinter() .with(filterProvider) .writeValue(outputStream, domainObj); } /** * <code>GET /{repository}/{id}</code> - Returns a single entity. * * @param resourceInformation * @param id * @param output * @return * @throws HttpRequestMethodNotSupportedException * @throws com.fasterxml.jackson.core.JsonProcessingException * @throws java.lang.NoSuchFieldException * @throws java.lang.IllegalAccessException */ @RequestMapping(value = BASE_MAPPING + "/{id}", method = RequestMethod.GET, produces = "application/json") public ResponseEntity getItemResourceJson( RootResourceInformation resourceInformation, @BackendId Serializable id, OutputStream output ) throws HttpRequestMethodNotSupportedException, JsonProcessingException, IOException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { resourceInformation.verifySupportedMethod(HttpMethod.GET, ResourceType.ITEM); RepositoryInvoker repoMethodInvoker = resourceInformation.getInvoker(); Object domainObj = repoMethodInvoker.invokeFindOne(id); if (domainObj == null) { return new ResponseEntity(HttpStatus.NOT_FOUND); } processOutput(resourceInformation.getResourceMetadata(), domainObj, output); return new ResponseEntity(HttpStatus.OK); } }
<reponame>bkarasu95/compact-launcher-api<filename>src/server/database/repositories/ProgramImageRepository.ts import axios, { AxiosResponse } from 'axios' import { ProgramImageDocument } from '../../models/program.model' import AbstractRepository from './AbstractRepository' import fs from 'fs' import path from 'path' import { fileSystem } from '../../config/filesystem' export default class ProgramImageRepository extends AbstractRepository<ProgramImageDocument> { transferToLocal = async (programImage: ProgramImageDocument): Promise<ProgramImageDocument> => { if (programImage.isLocal) { return programImage } let axiosRes: AxiosResponse try { axiosRes = await axios.get(programImage.path, { responseType: 'stream', // download the file }) } catch (e) { return programImage } // detect the file type let extension: string = axiosRes.headers['Content-Type'] ?? axiosRes.headers['content-type'] // TODO think about there, we need better detection const splittedExtension: string[] = extension.split('/') extension = splittedExtension[splittedExtension.length - 1] let filePath = path.join(fileSystem.imagesPath, programImage._id.toHexString()) + `.${extension}` const writer = fs.createWriteStream(filePath) await axiosRes.data.pipe(writer) programImage.path = filePath.replace(fileSystem.imagesPath, fileSystem.assetUrl).replace('\\', '/') // make url compability programImage.isLocal = true programImage.save() return programImage } }
Maybe it's time for political candidates to rethink the emphasis on fundraising. Voters seem not to be impressed by the campaign advertisements and strategists that money buys. In Tuesday's election in Stamford, the mayoral candidate who raised significantly more money lost. In September's Democratic primary, the mayoral candidate who raised significantly more money lost. And remember Tom Foley, the Greenwich private equity manager who spent $11 million on his 2010 campaign and is not governor? How about Linda McMahon, onetime maven of Stamford's World Wrestling Entertainment, who spent $50 million in 2010 and $50 million more in 2012 and still is not a member of the U.S. Senate? With the money they raised, candidates purchased countless TV ads, radio ads, online ads, print ads, mailers, billboards and lawn signs, and paid the salaries of strategists and other campaign workers who set up appearances and websites, emailed voters and researched opponents. But voters didn't buy in. The Republican candidate in Stamford's mayoral race, Michael Fedele, raised $459,000, which was $145,000 more than the winner, Democrat David Martin, who raised $314,000. The discrepancy was similar in the Democratic Party primary on Sept. 10, when Martin went up against state Rep. William Tong of the 147th District. With the backing of Gov. Dannel Malloy, former Stamford mayor, Tong raised $312,000. Martin at the time had $166,000. Both of Martin's victories were squeakers. He won the primary by just 197 votes, and he took Tuesday's election by only 569 votes. But if you look at the races as fund-raising contests, they were anything but squeakers. Tong out-raised Martin by 88 percent in the primary, and Fedele had 47 percent more money to spend than Martin in the general election. Yet Tong and Fedele lost. After the primary, Tong said he couldn't pinpoint a reason for his loss. His campaign manager, Josh Fedeli, said low voter turnout, 27 percent, hurt. The Martin campaign cited his 30 years of experience in Stamford government and the backing of the city's Democratic establishment as factors in his primary win. After Tuesday's election, Fedele said his race "could have been a lot different if it was just head to head," meaning two candidates. But, with the addition of unaffiliated candidates Kathleen Murphy and John Zito, the race had four candidates. Murphy and Zito together drew 6.1 percent of the total, or 1,281 votes. A good number of those might have gone to Fedele. Democratic City Committee Chairman John Mallozzi said the spoiler effect likely worked in Martin's favor. But he attributed Martin's victory to hard work -- "fighting for votes one at a time." Notice that, in evaluating why they may have won or lost, no one cited how Fedele spent $47.37 for each vote he got and Martin spent $30.61 in the mayoral contest. Instead, they cited voter turnout, experience, party endorsement, spoilers and hard work as factors in their wins or losses. And yet the hunt for campaign donations is on. In anticipation of next year's run for the governor's seat, politicians of both parties are going full tilt, taking advantage of a controversial campaign finance loophole that lets them accept money from special-interest groups. A recent examination of federal campaign finance reports by Hearst Connecticut Newspapers showed bipartisan collection of donations from trash haulers, electricity companies, pharmaceutical conglomerates and others -- a list that includes contractors that do business with the state and lobbyists who haunt the halls of Hartford on behalf of their clients. Under the law, state contractors cannot give to state party committees but may give to federal committees. State Republicans allege that Malloy broke that rule during a recent fund-raising swing through California. Republicans last month filed a complaint with the State Elections Enforcement Commission alleging that Malloy, who is up for re-election next year but has not yet announced his candidacy, solicited donations from an executive whose company does business with the state. Malloy and Connecticut Democrats said they abide by the rules for state and federal contributions and did not do anything Republicans don't do. In the meantime, four Republicans interested in becoming governor are chasing campaign donations. As of the Sept. 30 filing, state Sen. John McKinney of Fairfield, state Sen. Toni Boucher of Wilton and Foley each raised about $30,000, and Danbury Mayor Mark Boughton raised nearly $15,000. McKinney, the only one who officially declared his candidacy, has said his campaign actually has $90,000. Foley recently agreed to pay the State Elections Enforcement Commission a $16,000 fine for registering his Political Action Committee in another state. In Connecticut, a fund-raising frenzy is in full swing. In Stamford, the 2013 mayoral race was the most expensive in city history. The candidates spent a total of $1.1 million trying to get your vote. In all the scrambling for contributions that will purchase commercials, advertisements, billboards and the expertise of campaign managers, candidates may not notice that voters aren't quite buying it.
In-flight refueling (or air-to-air refueling) is an important method for extending the range of aircraft traveling long distances over areas having no feasible landing or refueling points. Although in-flight refueling is a relatively common operation, especially for military aircraft, precise positioning of a second aircraft (the receiver aircraft, for example) with respect to a first aircraft (the tanker aircraft, for example) is required in order to provide a safe engagement of the first aircraft with the second aircraft for the dispensing of fuel. In-flight refueling operations often take place during low-light conditions, including operations at night and during inclement weather, such that it may be advantageous to illuminate the in-flight refueling operation by, for instance, providing lighting installed on the first aircraft to illuminate the second aircraft as it approaches the first aircraft for in-flight refueling. Such illumination may aid, for instance a refueling system operator onboard the first aircraft, in visualizing the second aircraft as it approaches for an in-flight refueling operation. There are currently two primary systems for in-flight refueling. One system is the boom refueling system. The boom refueling system typically comprises a rigid boom extended from a refueling aircraft. At one end of the boom is a refueling nozzle and adjacent the refueling nozzle are airfoils, which are controlled by a refueling system operator such as, for instance, a boom operator, on the refueling aircraft. The airfoils provide maneuverability of the boom with respect to an aircraft that is to be refueled. For the aircraft that is to be refueled, the second aircraft, the operator of the second aircraft must maneuver the second aircraft to within an in-flight refueling position, below and aft of the first aircraft. Upon maneuvering into the in-flight refueling position, the boom operator controls the airfoils to position and mate the boom into a refueling connection on the second aircraft. Another type of refueling system is the probe and drogue system. In the probe and drogue system, a refueling hose having a drogue disposed on one end is trailed behind first aircraft (the tanker aircraft). The second aircraft has a probe that is flown by its operator into the drogue. As the drogue typically moves away from the second aircraft as it approaches, great skill and maneuvering ability is required by the operator of the second aircraft to mate the probe with the drogue. It is preferable, in the probe and drogue system, for the second aircraft to approach and enter the in-flight refueling position relative to the first aircraft as in the boom system, except in this case, the operator of the second aircraft is also responsible for “flying” the second aircraft's probe directly into the trailing drogue, because the drogue lacks the control surfaces that are provided on the refueling boom. The refueling system operator may be responsible, however, for extending the drogue to a trailing position that is within a suitable range of the second aircraft, such that the operator of the second aircraft may safely mate the probe with the drogue. For both types of in-flight refueling systems, the refueling system operator of the first aircraft may, in some cases (such as in remote airborne refueling operator (RARO) systems), be positioned remotely from the refueling equipment (including boom equipment and drogue equipment) such that the refueling system operator may view the in-flight refueling operation remotely via, for instance, a camera positioned to capture an image of the in-flight refueling operation and direct the image to a display that may be visible to the refueling system operator. In such RARO systems, for in-flight refueling operations often take place during low-light conditions, including operations at night and during inclement weather, it may be advantageous to illuminate the in-flight refueling operation by, for instance, providing lighting installed on the first aircraft to illuminate the second aircraft as it approaches the first aircraft for in-flight refueling such that the RARO camera may be capable of capturing images of the in-flight refueling operation. Illuminating systems have been disclosed for illuminating in-flight refueling operations, including those involving a RARO system such that the refueling system operator may remotely view the in-flight refueling operation. However, in the disclosed illuminating systems, the lighting units used are tungsten filament lamps that produce emissions including large amounts of light in the visible wavelengths such that the illuminating system may hamper the vision of an operator of the second aircraft as it approaches the first aircraft for an in-flight refueling operation. Also, the visible light emissions produced by the tungsten filament lamps are not covert, and may be visible to hostile observers and/or aircraft. In addition, the tungsten filament lamps also have a relatively short useful life of only 200-300 hours and a large electrical power requirement. The tungsten filament lamps also produce a large amount of heat and may require diffusing and filtered optics that result may result in the lamps' emissions having a non-uniform illumination field. Therefore, there exists a need for an illuminating system that provides eye-safe and covert illumination that is adapted to uniformly illuminate, for instance, an area to rear and aft of a first aircraft that may contain an in-flight refueling position. There also exists a need for an illumination system and device that produces eye-safe, covert emissions to provide illumination to an in-flight refueling position but that does not require a large electrical power supply or generate a large amount of excess heat. There also exists a need for an illuminating system that comprises component parts that are reliable, durable, and suitable for carriage by a first aircraft configured to conduct in-flight refueling operations.
Small Heath Leadership Academy is seeking to appoint a well-motivated and proactive Teacher of MFL. We are looking for an outstanding teacher; someone with high expectations, a love of the subject, able to inspire and enjoy the challenges of the role. You will need to be a team player; you will go the extra mile to support our students and want to continually develop the team. You will demonstrate high standards of delivery in a consistent manner, be committed to improving achievement across all key stages and will be able to inspire both staff and students. You will be passionate about learning, well-motivated, dynamic and able to engage young people. Enthusiasm, a winning personality, and an imaginative approach to the delivery of the curriculum area and attention to detail are essential. Work in partnership with the Principal, Senior Leadership Team, staff, students and parents in generating the ethos and values which underpin the school enriched by mutual care and respect extending into the local community. Liaise with the business support team in all matters concerning administration, health and safety and external agencies. Establish a partnership with parents to involve them in their child’s learning of the subject. Take responsibility for promoting and safeguarding the welfare of the children and young people in school. The school is part of Star Academies Trust, one the UKs leading education providers. Through our mission of educational excellence, character development and service to communities, we aim to fulfil our vision of nurturing today’s young people and inspiring tomorrow’s leaders. We welcome enquiries from everyone and value diversity in our workforce. For an informal and confidential discussion, for an informal and confidential discussion, please contact Dan Hennessy on 0121 464 7997. Small Heath Leadership Academy is committed to safeguarding and promoting the welfare of children. This post is subject to satisfactory clearances including; references, Enhanced DBS disclosure, health clearance and proof of eligibility to work in the UK in accordance with the Asylum and Immigration Act 1996.
// Write all unique parameter values to the given output stream @Override public void writeFields(OutputStream os) throws IOException { os.write(ByteUtils.convertToBytes(location.x)); os.write(ByteUtils.convertToBytes(location.y)); os.write(ByteUtils.convertToBytes(location.z)); }
import { IAuthenticationResult } from '../types'; import OnCheckSession from './OnCheckSession'; import { Auth } from 'aws-amplify'; /** * Start the change password flow with AWS Cognito, followed by the {@link OnConfirmPassword} * @param input See {@link ICognitoUserVariables} * @returns See {@link IAuthenticationResult} */ export const OnForgotPassword = async ( username: string ): Promise<IAuthenticationResult> => { try { const result = await Auth.forgotPassword(username); return OnCheckSession(result); } catch (error) { // if (__DEV__) console.log(error); return OnCheckSession(error); } }; export default OnForgotPassword;
def max_pool_backward_naive(dout, cache): dx = None dA = dout (A_prev, hparameters) = cache pool_height = hparameters["pool_height"] pool_width = hparameters["pool_width"] stride = hparameters["stride"] (m, n_C_prev, n_H_prev, n_W_prev) = A_prev.shape m, n_C, n_H, n_W = dA.shape dA_prev = np.zeros(A_prev.shape) for i in range(m): a_prev = A_prev[i,:,:,:] for c in range(n_C): for h in range(n_H): for w in range(n_W): vert_start = h * stride vert_end = vert_start + pool_height horiz_start = w * stride horiz_end = horiz_start + pool_width a_prev_slice = a_prev[c,vert_start: vert_end, horiz_start: horiz_end] mask = create_mask_from_window(a_prev_slice) dA_prev[i, c, vert_start:vert_end, horiz_start:horiz_end] += np.multiply(mask, dA[i, c, h, w]) dx = dA_prev return dx
Trees hanging over the floodwaters scratched at the bus, and branches got caught in its two front mirrors. The vehicle finally came to a stop amid some trees. Around that time, emergency responders rescued the driver and the 12-year-old boy inside the bus with him, the Austin American-Statesman reports. Nathan DeYoung, the 57-year-old school bus driver, was arrested on charges of endangering a child and not obeying warning signs following the incident, online jail records said. DeYoung was booked at the Williamson County Jail on $10,000 bond, but was release the next day. A Leander Independent School District spokesperson said DeYoung had worked for the district since August, but has since been fired, according to Patch. The middle school student who was in the bus called his mother “in hysterics” just before 8:30 a.m. that morning, the mother, Ashley Ringstaff, wrote in a Facebook post. The bus had been en route to Stiles Middle School, Hill Country News reports. Ringstaff said that the boy is “exhausted and resting” but wasn’t hurt during the ordeal. She also thanked Leander and county rescuers for getting the boy home safe. Police agreed with Ringstaff in a statement that accompanied the dash camera video, which was posted on Facebook on Friday. “Just two feet of water can carry away most vehicles,” Leander police wrote, advising motorists to turn around instead of risking drowning by fording into unknown waters.
. Acoustics measurements in the Service module of the International space station were performed at the workplaces with the vehicle and life support systems and equipment in operational status, and at the crew sleeping sites. Analysis of the measuring results revealed violation of the noise limits across the whole module. Measures were taken to abate noise at the place of origin and along the propagation path in order to prevent its negative effects on crew health.
# #8-6 # def city_country(city, country): # print(f"{city.title()}, {country.title()}") # city_country('des moines', 'usa') # city_country('paris', 'france') #8-7 def make_album(artist, album, songs = None): if songs: album_info = { 'artist name': artist, 'album name': album, 'songs': songs } else: album_info = { 'artist name': artist, 'album name': album, } print(album_info) make_album('led zeppelin', 'album 1', songs = 20) #8-8
Molecular Mapping of QTLs Associated with Lodging Resistance in Dry Direct-Seeded Rice (Oryza sativa L.) Dry direct-seeded rice (DSR) is an alternative crop establishment method with less water and labor requirement through mechanization. It provides better opportunities for a second crop during the cropping season and therefore, a feasible alternative system to transplanted lowland rice. However, lodging is one of the major constraints in attaining high yield in DSR. Identification of QTLs for lodging resistance and their subsequent use in improving varieties under DSR will be an efficient breeding strategy to address the problem. In order to map the QTLs associated with lodging resistance, a set of 253 BC3F4 lines derived from a backcross between Swarna and Moroberekan were evaluated in two consecutive years. A total of 12 QTLs associated with lodging resistance traits were mapped on chromosomes 1, 2, 6, and 7 using 193 polymorphic SNP markers. Two major and consistent effect QTLs, namely qCD1.1 (with R2 of 10%) and qCS1.1 (with R2 of 14%) on chromosome 1 with id1003559 being the peak SNP marker (flanking markers; id1001973-id1006772) were identified as a common genomic region associated with important lodging resistance traits. In silico analysis revealed the presence of Gibberellic Acid 3 beta-hydroxylase along with 34 other putative candidate genes in the marker interval region of id1001973-id1006772. The positive alleles for culm length, culm diameter, and culm strength were contributed by the upland adaptive parent Moroberekan. Our results identified significant positive correlation between lodging related traits (culm length diameter and strength) and grain yield under DSR, indicating the role of lodging resistant traits in grain yield improvement under DSR. Deployment of the identified alleles influencing the culm strength and culm diameter in marker assisted introgression program may facilitate the lodging resistance under DSR. INTRODUCTION Lodging in cereal crops is the result of the combined effects of the plants morphological traits and adverse weather conditions such as heavy winds and rains. Reduced crop yields, quality deterioration, and minimized harvesting efficiency are significantly associated with lodging. In recent years, due to limited water supply and escalating labor costs, direct-seeded rice (DSR) has become a major alternative among farmers in tropical countries (). However, the large-scale cultivation of DSR is also prone to lodging, along with other problems such as uncontrolled weeds, yield reductions, and poor nutrient uptake (Nguyen and Ferrero, 2006). Moreover, lodging has been found to be more severe in DSR than in transplanted rice (). Three types of lodging exist in cereal crops, namely: root lodging, stem bending, and stem breakage. Dry DSR is most susceptible to root lodging due to its shallow rooting system (;). Lowland rice is generally affected by the bending type of lodging due to the bending pressure of the upper internodes during strong winds and rains. Stem breakage occurs in the lower internodes of culms having a thin diameter and weak tensile strength (). Lodging resistance is a complex trait and influenced by many interacting agro-morphological traits. Different techniques have been used to measure the lodging effects in various crops, the most common of which is pushing the resistance of the lower part of the plant (;;). The short stature of plants has earlier been the main target in improving the lodging resistance and harvest index of rice Peng and Khush, 2003). However, statements cannot be generalized as the susceptibility of rice plant to lodging varies among cultivars with short plant height (). Reducing the plant's height also reduces its photosynthetic capacity and leads to a decrease in total biomass production, thus, restricting the plant's potential for further yield increase (;;). The dwarfing gene (sd 1 ) associated with short plant height has been used to show the negative pleiotropic effects on culm morphology in rice (). Therefore, moderate plant height, large stem diameter, thick stem walls, and high lignin deposition have been recommended as the corrected preferential traits for the improvement of lodging resistance under DSR (). Considering the current yield constraints under DSR conditions due to lodging, the identification of quantitative trait loci (QTLs) and candidate genes will increase our understanding of the regulatory mechanism of lodging resistance and will help breeders to improve lodging resistance under this system. A number of QTL mapping studies for culm length, strength, and thickness related to lodging resistance have been carried Abbreviations: DSR, Direct seeded rice; CL, Culm length; CD, Culm diameter; CS, Culm strength; SNP, Single nucleotide polymorphism; CIM, Composite Interval Mapping; PCA, Principal component analysis; SAS, Statistical Analysis System. out using different rice segregating populations (Kashiwagi and Ishimaru, 2004;;;;;). By keeping all these points in mind, the present study aimed to identify the genomic regions associated with lodging resistance, examine the correlations of lodging resistance traits with grain yield, and look into the possible candidate genes within the identified genetic regions. Plant Materials and Field Experiments The field experiments were conducted during the wet seasons (WS) of 2014 and 2015 at the International Rice Research Institute -South Asia Hub (IRRI-SAH), ICRISAT, Hyderabad, India (78 16 longitude, 17 32 latitude with 540 m above the sea level). The experimental material consisted of a set of 253 lines derived from a backcross mapping population of Swarna * 3/Moroberekan (). Genomic regions associated with early vigor and direct seeded rice related traits have been reported in same background in our previous study (). The field trials were laid out in alphalattice design in two replications in the year 2014 and in augmented RCBD in the year 2015. Seeds were direct seeded in leveled, unpuddled soil under aerobic conditions by dibbling at a depth of 3 cm. Single row plot of 4 m were planted with row spacing of 20 cm. The pre-emergence herbicide Pendimethalin @1.5 ml/l was applied within 2 days after seeding (DAS) at surface moisture level. Manual weeding was followed regularly with 2 sprays of the post-emergence spray bispyribac-sodium (Nominee Gold) at 2 ml/l. The appropriate dosages of fertilizers and nutrients were administered during the critical stages of growth as recommended under the DSR system (;). The trials were irrigated once in a week throughout the cropping period. The tensiometers were installed across the field at 30 cm soil depth to measure soil moisture levels. Measurement of Culm Strength and Other Traits At fully ripened stage, a prostrate tester (Daiki Rika Kogyou Co., Tokyo, Japan) was set perpendicular to the middle of the plant from 20 to 25 cm above the ground and the plant was pushed at an angle of 45 to measure the pushing resistance (Kashiwagi and Ishimaru, 2004). Culm strength (CS) was then estimated using the following formula (): No. of tillers The culm strength was averaged over three plants for each line of the mapping population. Culm diameter (CD) in mm was measured using a sliding vernier caliper in the field from the same three plants at a height of 30 cm above ground level. Culm length (CL) in cm was measured as plant height minus panicle length (). The other morphological traits viz., days to 50% flowering, plant height (cm), tiller number, panicle length (cm), and grain yield (kg ha −1 ) were recorded in both the years of 2014 and 2015. Days to 50% flowering (DTF) was recorded as when 50% of the panicles across the plot have emerged. At maturity plant height (cm) of three randomly chosen plants per plot was measured from ground level to the tip of the highest panicle and then averaged for analysis. The grain were harvested from each plot at physiological maturity, dried to moisture content ∼14%, and then weighed to calculate the grain yield in kg ha −1. Tiller numbers were counted manually and panicle length was measured using a centimeter scale. Statistical Analysis Genotype means for each trial were estimated in the first stage analysis using the REML option of Proc Mixed (), taking lines as fixed and replicates and blocks as random. In the second stage, a mixed model is fitted to the genotypeenvironment table of means and the weights estimated in the first stage (;Mhring and Piepho, 2009). The weights are the reciprocal of the variance of genotype means. The experimental error of each genotype-year combination is weighted by the variance of mean of the particular year. The mixed model is Where ij is the adjusted mean of the ith genotype in the jth environment, j is the main effect of the jth environment, g i is the main effect of the ith genotype and ij is the interaction of the ith genotype with the jth environment. Note that ij subsumes residual error of the adjusted mean. The residual variance is set to unity. Year-wise correlations of lodging-associated traits with yield and other morphological traits such as days to 50% flowering, plant height (cm), tiller number, panicle length (cm), with grain yield (kg ha −1 ) were calculated using SAS PROC CORR (SAS Institute, 1992). Construction of Linkage Map and QTL Identification for Lodging Resistance in Rice A total of 193 polymorphic SNPs were used to construct the linkage map by covering all 12 chromosomes spanning 1,525 cM with an average interval of 7.86 cM () Phenotypic data on lodging associated traits were subject to QTL analysis to identify the genetic regions using QGene ver 4.3.10 (Joehanes and Nelson, 2008). The stepwise cofactor selection and default values were used for setting the CIM procedure in QGene. The genome scan interval was set to 1 cM and Window size was set at 10 cM. A LOD (logarithm of odds) score of 2.5 with 1,000 permutations was used for confirming the presence of a putative QTL. The QTLs responsible for phenotypic variance of more than 10% were considered as major-effect QTLs. The putative candidate genes for lodging-associated traits were identified based on the available literature and on the RAP database (http://rapdb.dna.affrc.go. jp/). Phenotypic Evaluations of Culm Traits with Lodging Resistance Three culm traits associated with lodging resistance and other morphological traits such as plant height, days to 50% flowering, number of tillers, panicle length and grain yield were investigated. Analysis of variance revealed significant difference (p < 0.01) between the two parents (Swarna and Moroberekan) in all traits measured in both years. The overall progeny means for lodging-related traits were: culm length (59 ± 10.9 cm), culm diameter (1.65 ± 0.20 mm), and culm strength (28 ± 7.7 g/stem) with Moroberekan on the higher side in both years ( Table 1). No transgressive segregant with a thicker diameter and higher culm strength than Moroberekan was observed. The phenotypic distribution of lodging-associated traits (CL, CD, and CS) was nearly normal in year 2014, while in 2015, CD and CS were skewed toward the Swarna (Figure 1). The culm strength of the progenies was classified from infirmness to good strength (good strength ≥ 40.1 gram/stem, medium 20.1∼40 gram/stem, infirmness ≤ 20 gram/stem) on the basis of instrument reading (prostrate tester) and visual observation of plant lodging tendency correlated with the stem strength reading. A two-stage analysis was used as the experimental design varied between the 2 years. The analysis indicated significant genotype year interaction for grain yield, culm length and culm strength ( Table 2). However the trial variance was 0 in the case of culm strength, culm length and grain yield and the genotype year interaction was 0 in the case of culm diameter. The differences between genotypes were non-significant in the case of culm diameter. The best entries for grain yield, culm length and culm strength performing across the years are shown in Supplementary Table 1. Phenotypic Correlation between Culm Strength and Other Related Traits In both years, yield exhibited a moderate positive significant correlation with culm diameter and culm length however; it had a weak positive correlation with culm strength (Table 3). At the same time, culm strength and culm diameter were positively and significantly correlated (r = 0.682, p < 0.01 and r = 0.722, p < 0.01 in year 2014 and 2015, respectively). Earlier reports on various cereals including rice (;;), wheat (;;) and barley () have reported significant associations of lodging resistance with culm diameter and the wall thickness of basal internodes. These findings indicate that increasing the culm diameter can improve the resistance of cereals to lodging and subsequently increase yields. It was also observed that the lines with yields greater than 5,000 kg ha −1 possessed intermediate culm length (59-70 cm) in 2014 and moderate to large culm length (51-90 cm) in 2015. The high yielding lines also possessed moderate measurements for culm length, strength, and diameter ( Table 4). QTL Detection The introduction of the semi-dwarfing genes rht 1 in wheat () and sd 1 in rice () improved lodging resistance and increased yield significantly. However, to further improve yield, an increase of 10-20 cm in the height of the presently cultivated semi-dwarf rice varieties has been suggested as a viable alternative (). Therefore, identifying QTLs related to culm traits, together with increased plant height, is needed for improving lodging resistance and yield (). In the present study, 12 QTLs controlling culm length, culm diameter, and culm strength were detected over four different chromosomes in the backcross population of Swarna * 3/Moroberekan (Figure 2, Table 5). Chromosome 1 harbored the maximum number of QTLs for lodging-associated traits. A total of three culm length QTLs (LOD>3.0) were detected on chromosomes 1, 2, and 7 (qCL 1.1, qCL 2.1, and qCL 7.1 ) over the 2 years. The allele for higher culm length for qCL 2.1 was from the taller parent Moroberekan while the semi-dwarf parent Swarna contributed favorable alleles to the other two loci (qCL 1.1 and qCL 7.1 ). The explained phenotypic variance ranges from 11 to 26.0%. Previously, Mu et al. identified six additive QTLs associated with culm length on chromosomes 2, 3, 4, 5, and 6 with a phenotypic variation of 39% collectively. Matsubara et al. mapped four QTLs for culm length on chromosome 1, 2, 5, and 6. In present study, the QTL qCL 1.1 identified at physical position of 36.1 Mbp on chromosome 1 with 26% of phenotypic variance was 4 Mbp closer from large effect QTL for culm length (with R 2 of 73%) reported by Matsubara et al.. Three QTLs that affected culm diameter were detected on chromosomes 1 (qCD 1.1 ), 2 (qCD 2.1 ), and 7 (qCD 7.1 ) with phenotypic variance explained by 10-14%. The alleles for culm diameter (qCD 1.1, qCD 2.1, and qCD 7.1 ) were contributed by Moroberekan. The QTL qCD 1.1 was consistent in both 2014 and 2015 with a phenotypic variance of 14 and 10%, respectively. Many researchers have detected QTLs for higher culm diameter on chromosome 1 at physical interval of 6Mbp-11 Mbp using various mapping populations (Kashiwagi and Ishimaru, 2004;;). The culm diameter was reported to have positive effects on the section modulus (SM) and bending moment at breaking (M), leading to lodging resistance without any yield loss (). Keller et al. identified two QTLs for culm thickness associated with lodging resistance in a population between wheat and spelt. The previous reports and present findings demonstrate the role of culm diameter in enhancing lodging resistance in rice. Six QTLs (qCS 1.1, qCS 2.1, qCS 2.2, qCS 2.3, qCS 6.1, and qCS 6.2 ) for culm strength were detected on three chromosomes in the present study. The QTLs with positive effect for culm strength were contributed by the Moroberekan parent. Previously, a number of QTLs viz., prl5, SCM1, SCM2, SCM3, and SCM4 were reported for culm strength (Kashiwagi and Ishimaru, 2004;;). However, some of the identified QTLs region was quite large for its utilization in marker-assisted selection; fine mapping, sequencing and allele mining of the identified regions could be useful in further deployment. The QTL qCS 1.1 identified in present study was reproducible in both 2014 and 2015 with a phenotypic variance of 23 and 14%, respectively and located on chromosome 1. Mu et al. also reported QTL for culm strength on same chromosome in marker interval of RM5-RM302. The QTLs qCS 6.1 and qCS 6.2 were identified on chromosome 6 with phenotypic variance of 11 and 8%, respectively. The QTL qCS 6.2 for culm strength identified in the present study was in agreement with earlier reported QTL STRONG CULM2 (SCM2) at physical position of 27 Mbp (). The detailed analysis of SCM2 through positional cloning and sequencing reveals that the gene is similar to APO1 favorably leads to increase in the spikelet number and enhanced culm strength by increasing the cell proliferation rate (). The QTL-hotspot for early vigor, early uniform emergence (qEV 6.1, qEUE 6.1 ) in interval of 11.7-27.6 cM under DSR conditions reported by Singh et al. was located near to QTL for culm strength (qCS 6.1 ) identified in present study at position of 26.2 cM. The observed direct relationship among the seedling establishment and lodging resistant traits in term of co-location of genetic regions could be an important landmark for various desirable traits under DSR conditions. Co-localization of QTLs In this study, the stable and consistent effect QTL region between id1001973-id1006772 markers reported to be associated with the traits culm diameter and culm strength indicating the pleiotropic effect of the identified genomic region or linkage of loci controlling both the traits. Current finding in the present study are in agreement with the previous report of lodging resistant traits in rice (Kashiwagi and Ishimaru, 2004;). The identified shared loci can be fine mapped and cloned to resolve the underlying gene functions constituting the QTL region (Eshed and Zamir, 1995;;). Though the genetic distance of this co-localized region is of considerable length (47.5-72.3 cM), it may provide an important clue for future efforts to explore the region by fine mapping to better understand the mechanism of this complex trait. Identification of Putative Candidate Genes The genomic regions within the consistent QTL for culm diameter (qCD 1.1 ) and culm strength (qCS 1.1 ) were analyzed in silico for the presence of possible candidate genes previously reported for lodging resistance. A total of 35 putative genes were found within the stable QTL region identified for culmassociated traits ( Table 6). Many genes within the QTL were responsible for phytohormones synthesis, hypothetical and expressed protein, heat shock protein, transcriptional factors, and precursors for various biochemical and metabolic pathways. Among them, a putative candidate gene Gibberellic Acid (GA) 3 beta-hydroxylase with single copy 4003659-4004946 bp was identified. This gene is the final precursor in the biosynthetic pathway of the plant hormone Gibberellin (). Another report highlighted the effect of the plant hormone GA on lodging resistance in rice and on increased total biomass signifying the positive impact of overexpression of GA on lodging resistance due to increased culm diameter and lignin deposition. GA was also found to increase biomass yield. A few other findings reported that higher lignin content is responsible for improved varietal resistance to the bending type of lodging (Ookawa and Ishihara, 1993;). Recently, Ookawa et al. also discussed the effect of high GA level results in enlargement of culm diameter by increasing the number of parenchymatous cells in the culm. Further studies needed to confirm the positive regulation of GA on culm thickness in the genomic region on chromosome 1. Such candidate genes need to be further characterized to be used as potential targets for marker-assisted breeding for strong/thick culm providing lodging resistance in rice. The QTL for culm strength (qCS 6.2 ) identified in the present study was also explained by by identifying candidate gene SCM2 within the marker interval of RM 20546-RM 20562 at physical location of 27 Mbp. This gene was found to be responsible for the physical strength of the culm and for the increase in spikelet number because of pleiotropic gene action. This finding points to the authenticity of the QTL hot spot region for lodging resistance genes and will be an important landmark in future breeding programs for improved lodging resistance in rice. CONCLUSION Culm diameter and culm strength are potential target traits for breeding rice varieties with enhanced lodging resistance under DSR conditions. The stable and consistent genetic region within the marker interval of id1001973-id1006772 could be an important source of alleles responsible for enhancing lodging resistance in rice. The polymorphic SNP markers in these QTL regions may be utilized for future marker-assisted breeding programs. Functional validation of the candidate gene SCM2 as well as genes for GA biosynthesis with precursors of various metabolic pathways associated with culm QTLs (qCS 6.2, qCS 1.1, and qCD 1.1 ) will be a valuable future step to clearly understand the mechanism of lodging resistance. AUTHOR CONTRIBUTIONS SY was involved in conducting the experiment, recording observations and drafting the article; US, SN, CV, and PR helped in experimental work and contributed to the manuscript modification; KR, NS was involved in experimental analysis, interpretation of data and revising the manuscript; AK was involved in the design of the experiment and in the critical revision of the manuscript. All authors approved the final version of the manuscript.
<reponame>so11y/vitest<filename>packages/vitest/src/reporters/renderers/listRenderer.ts import { createLogUpdate } from 'log-update' import c from 'picocolors' import cliTruncate from 'cli-truncate' import stripAnsi from 'strip-ansi' import type { Task } from '../../types' import { getTests } from '../../utils' import { F_RIGHT } from './figures' import { getCols, getStateSymbol } from './utils' export interface ListRendererOptions { renderSucceed?: boolean } const DURATION_LONG = 300 const MAX_HEIGHT = 20 const outputMap = new WeakMap<Task, string>() function formatFilepath(path: string) { const lastSlash = Math.max(path.lastIndexOf('/') + 1, 0) const basename = path.slice(lastSlash) let firstDot = basename.indexOf('.') if (firstDot < 0) firstDot = basename.length firstDot += lastSlash return c.dim(path.slice(0, lastSlash)) + path.slice(lastSlash, firstDot) + c.dim(path.slice(firstDot)) } export function renderTree(tasks: Task[], options: ListRendererOptions, level = 0) { let output: string[] = [] for (const task of tasks) { let suffix = '' const prefix = ` ${getStateSymbol(task)} ` if (task.mode === 'skip' || task.mode === 'todo') suffix += ` ${c.dim('[skipped]')}` if (task.type === 'suite') suffix += c.dim(` (${getTests(task).length})`) if (task.result?.end) { const duration = task.result.end - task.result.start if (duration > DURATION_LONG) suffix += c.yellow(` ${Math.round(duration)}${c.dim('ms')}`) } let name = task.name if (level === 0) name = formatFilepath(name) output.push(' '.repeat(level) + prefix + name + suffix) if ((task.result?.state !== 'pass') && outputMap.get(task) != null) { let data: string | undefined = outputMap.get(task) if (typeof data === 'string') { data = stripAnsi(data.trim().split('\n').filter(Boolean).pop()!) if (data === '') data = undefined } if (data != null) { const out = `${' '.repeat(level)}${F_RIGHT} ${data}` output.push(` ${c.gray(cliTruncate(out, getCols(-3)))}`) } } if (task.type === 'suite' && task.tasks.length > 0) { if ((task.result?.state === 'fail' || task.result?.state === 'run' || options.renderSucceed)) output = output.concat(renderTree(task.tasks, options, level + 1)) } } // TODO: moving windows return output.slice(0, MAX_HEIGHT).join('\n') } export const createListRenderer = (_tasks: Task[], options: ListRendererOptions = {}) => { let tasks = _tasks let timer: any const stdout = process.stdout const log = createLogUpdate(stdout) function update() { log(renderTree(tasks, options)) } return { start() { if (timer) return this timer = setInterval(update, 200) return this }, update(_tasks: Task[]) { tasks = _tasks update() return this }, async stop() { if (timer) { clearInterval(timer) timer = undefined } log.clear() stdout.write(`${renderTree(tasks, options)}\n`) return this }, clear() { log.clear() }, } }
def to_json(self, value, app, use_security): if value is None: rval = '' else: rval = util.smart_str(value) return rval
One to Rule Them All: a General Randomized Algorithm for Buffer Management with Bounded Delay We give a memoryless scale-invariant randomized algorithm for the Buffer Management with Bounded Delay problem that is e/(e-1)-competitive against an adaptive adversary, together with better performance guarantees for many restricted variants, including the s-bounded instances. In particular, our algorithm attains the optimum competitive ratio of 4/3 on 2-bounded instances. Both the algorithm and its analysis are applicable to a more general problem, called Collecting Items, in which only the relative order between packets' deadlines is known. Our algorithm is the optimal randomized memoryless algorithm against adaptive adversary for that problem in a strong sense. While some of provided upper bounds were already known, in general, they were attained by several different algorithms. Introduction In this paper, we consider the problem of buffer management with bounded delay, introduced by Kesselman et al.. This problem models the behavior of a single network switch responsible for scheduling packet transmissions along an outgoing link as follows. We assume that time is divided into unit-length steps. At the beginning of a time step, any number of packets may arrive at a switch and be stored in its buffer. Each packet has a positive weight, corresponding to the packets priority, and a deadline, which specifies the latest time when the packet can be transmitted. Only one packet from the buffer can be transmitted in a single step. A packet is removed from the buffer upon transmission or expiration, i.e., reaching its deadline. The goal is to maximize the gain, defined as the total weight of the packets transmitted. We note that buffer management with bounded delay is equivalent to a scheduling problem in which packets are represented as jobs of unit length, with given release times, deadlines and weights; release times and deadlines are restricted to integer values. In this setting, the goal is to maximize the total weight of jobs completed before their respective deadlines. As the process of managing packet queue is inherently a real-time task, we model it as an online problem. This means that the algorithm, when deciding which packets to transmit, has to base its decision solely on the packets which have already arrived at a switch, without the knowledge of the future. Competitive Analysis To measure the performance of an online algorithm, we use the standard notion of competitive analysis, which, roughly speaking, compares the gain of the algorithm to the gain of the optimal solution on the same instance. For any algorithm Alg, we denote its gain on instance I by G Alg (I). The optimal offline algorithm is denoted by Opt. We say that a deterministic algorithm Alg is R-competitive if on any instance I it holds that G Alg (I) ≥ 1 R G Opt (I). When analyzing the performance of an online algorithm Alg, we view the process as a game between Alg and an adversary. The adversary controls what packets are injected into the buffer and chooses which of them to send. The goal is then to show that the adversary's gain is at most R times Alg's gain. If the algorithm is randomized, we consider its expected gain, E, where the expectation is taken over all possible random choices made by Alg. However, in the randomized case, the power of the adversary has to be further specified. Following Ben-David et al., we distinguish between an oblivious and an adaptive-online adversary, which from now on we will call adaptive, for short. An oblivious adversary has to construct the whole instance in advance. This instance may depend on Alg but not on the random bits used by Alg during the computation. The expected gain of Alg is compared to the gain of the optimal offline solution on I. In contrast, in case of an adaptive adversary, the choice of packets to be injected into the buffer may depend on the algorithm's behavior up to the given time step. This adversary must also provide an answering entity Adv, which creates a solution in parallel to Alg. This solution may not be changed afterwards. We say that Alg is R-competitive against an adaptive adversary if for any adaptively created instance I and any answering algorithm Adv, it holds that. We note that Adv is (wlog) deterministic, but as Alg is randomized, so is the instance I. In the literature on online algorithms, the definition of the competitive ratio sometimes allows an additive constant, i.e., a deterministic algorithm is then called R-competitive if there exists a constant ≥ 0 such that for any instance I it holds that G Alg (I) ≥ 1 R G Opt (I) −. An analogous definition applies to the randomized case. For our algorithm Mix-R the bound holds for = 0, which is the best possible. Basic Definitions We denote a packet with weight w and relative deadline d by (w, d), where the relative deadline of a packet is, at any time, the number of steps after which it expires. The packet's absolute deadline, on the other hand, is the exact point in time at which the packet expires. a packet that is in the buffer, i.e., has already been released and has neither expired nor been transmitted by an algorithm, is called pending for the algorithm. The lifespan of a packet is its relative deadline value upon injection, or in other words the difference between its absolute deadline and release time. The goal is to maximize the weighted throughput, i.e., the total weight of transmitted packets. We assume that time is slotted in the following way. We distinguish between points in time and time intervals, called steps. In step t, corresponding to the interval (t, t + 1), Adv and the algorithm choose, independently, a packet from their buffers and transmit it. The packet transmitted by the algorithm (Adv) is immediately removed from the buffer and no longer pending. Afterwards, at time t + 1, the relative deadlines of all remaining packets are decremented by 1, and the packets whose relative deadlines reach 0 expire and are removed from both Adv's and the algorithm's buffers. Next, the adversary injects any set of packets. At this point, we proceed to step t + 1. To no surprise, all known algorithms are scale-invariant, which means that they make the same decisions if all the weights of packets in an instance are scaled by a positive constant. a class of further restricted algorithms is of special interest for their simplicity. An algorithm is memoryless if in every step its decision depends only on the set of packets pending at that step. An algorithm that is both memoryless and scale-invariant is called memoryless scale-invariant. Previous and Related Work, Restricted Variants The currently best, 1.828-competitive, deterministic algorithm for general instances was given by Englert and Westermann. Their algorithm is scaleinvariant, but it is not memoryless. However, in the same article Englert and Westermann provide another, 1.893-competitive, deterministic algorithm that is memoryless scale-invariant. The best known randomized algorithm is the 1.582competitive memoryless scale-invariant RMix, proposed by Chin et al.. For reasons explained in Section 2.1 the original analysis by Chin et al. is only applicable in the oblivious adversary model. However, a refined analysis shows that the algorithm remains 1.582-competitive in the adaptive adversary model. Consider a (memoryless scale-invariant) greedy algorithm that always transmits the heaviest pending packet. It is not hard to observe that it is 2-competitive, and actually no better than that. But for a few years no better deterministic algorithm for the general case was known. This naturally led to a study of many restricted variants. Below we present some of them, together with known results. The most relevant bounds known are summarized in Table 1. Note that the majority of algorithms are memoryless scale-invariant. For a general overview of techniques and results on buffer management, see the surveys by Azar, Epstein and Van Stee and Goldwasser. Uniform Sequences An instance is s-uniform if the lifespan of each packet is exactly s. Such instances have been considered for two reasons. Firstly, there is a certain connection between them and the FIFO model of buffer management, also considered by Kesselmann et al.. Secondly, the 2-uniform instances are among the most elementary restrictions that do not make the problem trivial. However, analyzing these sequences is not easy: while a simple deterministic 1.414-competitive algorithm for 2-uniform instances is known to be optimal among memoryless scale-invariant algorithms, for unrestricted algorithms a sophisticated analysis shows the optimum competitive ratio is 1.377. Bounded Sequences An instance is s-bounded if the lifespan of each packet is at most s; therefore every s-uniform instances is also s-bounded. This class of in- stances is important, because the strongest lower bounds on the competitive ratio known for the problem employ 2-bounded instances. These are ≈ 1.618 for deterministic algorithms, 1.25 for randomized algorithms in the oblivious adversary model, and 4/3 in the adaptive adversary model. For 2bounded instances algorithms matching these bounds are known. A competitive deterministic algorithm is also known for 3-bounded instances, but in general the best algorithms for s-bounded instances are only known to be 2 − 2/s + o(1/s)-competitive. Similarly Ordered Sequences An instance is similarly ordered or has agreeable deadlines if for every two packets i and j their spanning intervals are not properly contained in one another, i.e., if r i < r j implies d i ≤ d j. Note that every 2-bounded instance is similarly ordered, as is every s-uniform instance, for any s. An optimal deterministic -competitive algorithm and a randomized 4/3-competitive algorithm for the oblivious adversary model are known. With the exception of 3-bounded instances, this is the most general class of instances for which a -competitive deterministic algorithm is known. Other restrictions Among other possible restrictions, let us mention one for which our algorithm provides some bounds. Motivated by certain transmission protocols, which usually specify only several priorities for packets, one might bound the number of different packet weights. In fact, Kesselmann et al. considered deterministic algorithms for instances with only two distinct packet weights. Our Contribution We consider randomized algorithms against an adaptive adversary, motivated by the following observation. In reality, traffic through a switch is not at all independent of the packet scheduling algorithm. For example, lost packets are typically resent, and throughput through a node affects the choice of routes for data streams in a network. These phenomena can be captured by the adaptive adversary model but not by the oblivious one. The adaptive adversary model is also of its own theoretical interest and has been studied in numerous other settings. The main contribution of this paper is a simple memoryless scale-invariant algorithm Mix-R, which may be viewed as RMix, proposed by Chin et al., with a different probability distribution over pending packets. The competitive ratio of Mix-R is at most e/(e − 1) on the one hand, but on the other it is provably better than that for many restricted variants of the problem. Some of the upper bounds we provide were known before (cf. Table 1), but in general they were achieved by several different algorithms. Specifically, where N is the maximum, over steps, number of packets that have positive probability of transmission in the step. Note that 1/ 1 − (1 − 1 N ) N tends to e/(e − 1) from below. The number N can be bounded a priori in certain restricted variants of the problem, thus giving better bounds for them, as we discuss in detail in Section 2.4. For now let us mention that N ≤ s in s-bounded instances and instances with at most s different packet weights. The particular upper bound of 4/3 that we obtain for 2-bounded instances is tight in the adaptive adversary model. As is the case with RMix, both Mix-R and its analysis rely only on the relative order between the packets' deadlines. Therefore our upper bound(s) apply to the Collecting Items problem. In fact, Mix-R is the optimum randomized memoryless algorithm for that problem in a strong sense, cf. Appendix A. Analysis technique In our analysis, we follow the paradigm of modifying the adversary's buffer, introduced by Li et al.. Namely, we assume that in each step the algorithm and the adversary have precisely the same pending packets in their buffers. Once they both transmit a packet, we modify the adversary's buffer judiciously to make it identical with that of the algorithm. This amortized analysis technique leads to a streamlined and intuitive proof. When modifying the buffer, we may have to let the adversary transmit another packet, inject an extra packet to his buffer, or upgrade one of the packets in its buffer by increasing its weight or deadline. We will ensure that these changes will be advantageous to the adversary in the following sense: for any adversary strategy Adv, starting with the current step and buffer content, there is an adversary strategy Adv that continues computation with the modified buffer, such that the total gain of Adv from the current step on (inclusive), on any instance, is at least as large as that of Adv. To prove R-competitiveness, we show that in each step the expected amortized gain of the adversary is at most R times the expected gain of the algorithm, where the former is the total weight of the packets that Adv eventually transmitted in this step. Both expected values are taken over random choices of the algorithm. We are going to assume that Adv never transmits a packet a if there is another pending packet b such that transmitting b is always advantageous to Adv. Formally, we introduce a dominance relation among the pending packets and assume that Adv never transmits a dominated packet. We say that a packet a = (w a, d a ) is dominated by a packet b = (w b, d b ) at time t if at time t both a and b are pending, w a ≤ w b and d a ≥ d b. If one of these inequalities is strict, we say that a is strictly dominated by b. We say that packet a is (strictly) dominated whenever there exists a packet b that (strictly) dominates it. Then the following fact can be shown by a standard exchange argument. Proof. Adv can be transformed into Adv iteratively: take the minimum t 0 such that Adv first violates the second property in step t 0, and transform Adv into an algorithm Adv with gain no smaller than that of Adv, which satisfies the second property up to step t 0, possibly violating it in further steps. Let t 0 be the first step in which the second property is violated. Let y = (w, d) be the packet transmitted by Adv and x = (w, d ) be the packet that dominates y; then w ≥ w and d ≤ d. Let Adv transmit the same packets as Adv up to step t 0 − 1, but in step t 0 let it transmit x, and in the remaining steps let it try to transmit the same packets as Adv. It is impossible in one case only: when Adv transmits x in some step t. But then d ≥ d > t, so let Adv transmit y, still pending at t. Clearly, the gain of Adv is at least as large as the gain of Adv. Let us stress that Fact 1 holds for the adaptive adversary model. Now we give an example of another simplifying assumption, often assumed in the oblivious adversary model, which seems to break down in the adaptive adversary model. In the oblivious adversary model the instance is fixed in advance by the adversary, so Adv may precompute the optimum schedule to the instance and follow it. Moreover, by standard exchange argument for the fixed set of packets to be transmitted, Adv may always send the packet with the smallest deadline from that set-this is usually called the earliest deadline first (EDF) property or order. This assumption not only simplifies analyses of algorithms but is often crucial for them to yields desired bounds. In the adaptive adversary model, however, the following phenomenon occurs: as the instance I is randomized, Adv does not know for sure which packets it will transmit in the future. Consequently, deprived of that knowledge, it cannot ensure any specific order of packet transmissions. The Algorithm We describe the algorithm's behavior in a single step. We introduce the packet h 0 to shorten Mix-R's pseudocode by making it possible to set the value of p 1 in the first iteration of the loop. The packet itself is chosen in such a way that p 0 = 0, to make it clear that it is not considered for transmission (unless h 0 = h 1 ). The while loop itself could be terminated as soon as r = 0, because afterwards Mix-R does not assign positive probability to any packet. However, letting it construct the whole sequence h 1, h 2,... h m such that H m = ∅ simplifies our analysis. Before proceeding with the analysis, we note a few facts about Mix-R. Furthermore, every pending packet is dominated by one of h 1,..., h m. Fact 3. The numbers p 1, p 2,..., p m form a probability distribution such that Furthermore, the bound is tight for i < n, while p i = 0 for i > n, i.e., Theorem 4. Mix-R is 1/ 1 − (1 − 1 N ) N -competitive against an adaptive adversary, where N is the maximum, over steps, number of packets that are assigned positive probability in a step. Proof. For a given step, we describe the changes to Adv's scheduling decisions and modifications to its buffer that make it the same as Mix-R's buffer. Then, to prove our claim, we will show that where n is the number of packets assigned positive probability in the step. The theorem follows by summation over all steps. Recall that, by Fact 1, Adv (wlog) sends a packet that is not strictly dominated. By Fact 2, the packets h 1, h 2,... h m dominate all pending packets, so the one sent by Adv, say p is (wlog) one of h 1, h 2,... h m : if p is dominated by h i, but not strictly dominated, then p has the same weight and deadline as h i. We begin by describing modifications to Adv's buffer and estimate Adv's amortized gain. To this end we need to fix the packet sent by Mix-R, so let us assume it is h f = (w f, d f ). Assume that Adv transmits a packet h z = (w z, d z ). We will denote the adversary's amortized gain given the latter assumption by G (z) Adv. We consider two cases. and Mix-R transmit their packets, we replace h f in the buffer of Adv by a copy of h z. This way their buffers remain the same afterwards, and the change is advantageous to Adv: this is essentially an upgrade of the packet h f in its buffer, as both d f ≤ d z and w f ≤ w z hold. Case 2: d f > d z. After both Adv and Mix-R transmit their packets, we let Adv additionally transmit h f, and we inject a copy of h z into its buffer, both of which are clearly advantageous to Adv. This makes the buffers of Adv and Mix-R identical afterwards. We start by proving, the bound on the adversary's expected amortized gain. Note that Adv always gains w z, and if d z < d f (z > f ), it additionally gains w f. Thus, when Adv transmits h z, its expected amortized gain is As the adversary's expected amortized gain satisfies The equality in follows trivially from. To see that the inequality in holds as well, observe that, by, for all j < m, where the inequality follows from. Now we turn to, the bound on the expected gain of Mix-R in a single step. Obviously, By, p i w i = w i − w i+1 for all i < n. Also, p n = 1 − i<n p i, by Fact 3. Making corresponding substitutions in yields As implies w i = w i−1 (1 − p i−1 ) for all i ≤ n, we can express w n as Substituting for w n in, we obtain Note that and therefore the inequality between arithmetic and geometric means yields Plugging into yields which proves, and together with, the whole theorem. Rationale behind the probability distribution Recall that the upper bound on the competitive ratio of Mix-R is irrespective of the choice of p 1,..., p m. The particular probability distribution used in Mix-R is chosen to (heuristically) minimize above ratio by maximizing E , while keeping satisfied, i.e., keeping The first goal is trivially achieved by setting p 1 ← 1. This however makes Adv > w 1 for all z > 1. Therefore, some of the probability mass is transferred to p 2, p 3,... in the following way. To keep E as large as possible, p 2 is greedily set to its maximum, if there is any unassigned probability left, p 3 is set to its maximum, and so on. As E G Adv cannot be equalized, they are only smaller than w 1. The lower bound for the Collecting Items problem, presented in Appendix A, proves that this heuristic does minimize. Implications for Restricted Variants We have already mentioned that for s-bounded instances or those with at most s different packet weights, N ≤ m ≤ s in Theorem 4, which trivially follows from Fact 2. Thus for either kind of instances Mix-R is 1/ 1 − (1 − 1 s ) scompetitive. In particular, on 2-bounded instances Mix-R coincides with the previously known optimal 4/3-competitive algorithm Rand for the adaptive adversary model. Sometimes it may be possible to give more sophisticated bounds on N, and consequently on the competitive ratio for particular variant of the problem, as we now explain. The reason for considering only the packets h 0, h 1,..., h m is clear: by Fact 1 and Fact 2, Adv (wlog) transmits one of them. Therefore, Mix-R tries to mimic Adv's behavior by adopting a probability distribution over these packets (recall that in the analysis the packets pending for Mix-R and Adv are exactly the same) that keeps the maximum, over Adv's choices, expected amortized gain of Adv and its own expected gain as close as possible (cf. Section 2.3). Now, if for whatever reason we know that Adv is going to transmit a packet from some set S, then H 0 can be initialized to S rather than all pending packets, and Theorem 4 will still hold. And as the upper bound guaranteed by Theorem 4 depends on N, it might improve if the cardinality of S is small. While it seems unlikely that bounds for any restricted variant other than s-bounded instances or instances with at most s different packet weights can be obtained this way, there is one interesting example that shows it is possible. For similarly ordered instances (aka instances with agreeable deadlines) and oblivious adversary one can always find such set S of cardinality at most 2 ; while not explicitly stated, this fact was proved before by Li et al.. Roughly, the set S contains the earliest-deadline and the heaviest packet from any optimal provisional schedule. The latter is the optimal schedule under the assumption that no further packets are ever injected, and as such can be found in any step. Conclusion and Open Problems While Mix-R is very simple to analyze, it subsumes almost all previously known randomized algorithms for packet scheduling and provides new bounds for several restricted variants of the problem. One notable exception is the optimum algorithm against oblivious adversary for 2-bounded instances. This exposes that the strength of our analysis, i.e., applicability to adaptive adversary model, is most likely a weakness at the same time. The strongest lower bounds on competitive ratio for oblivious and adaptive adversary differ. And as both are tight for 2-bounded instances, it seems impossible to obtain an upper bound smaller than 4/3 on the competitive ratio of Mix-R for any non-trivial restriction of the problem in the oblivious adversary model. In both the algorithm and its analysis it is the respective order of packets' deadlines rather than their exact values that matter. Therefore, our results are also applicable to the Collecting Items problem, briefly described in Section 1.3. As mentioned in Section 1.4, Mix-R is the optimum randomized memoryless algorithm for Collecting Items, cf. Appendix A. Therefore, to beat either the general bound of e/(e − 1), or any of the 1/ 1 − (1 − 1 s ) s bounds for s-bounded instances for buffer management with bounded delay, one either needs to consider algorithms that are not memoryless scale-invariant, or better utilize the knowledge of exact deadlines-in the analysis at least, if not in the algorithm itself. Last but not least, let us remark again that Mix-R and its analysis might automatically provide better bounds for further restricted variants of the problem, provided that some insight allows to confine the adversary's choice of packets for transmission in a step, while knowing which packets are pending for it-one such example is the algorithm for similarly ordered instances (aka instances with agreeable deadlines), as we discussed in Section 2.4. A Lower Bound for Collecting Items In this section, for completeness, we evoke the lower bound on the Collecting Items problem. As the proof is omitted in the original article due to space constraints, and the original theorem statement therein is not parametrized by N, we restate the theorem. Theorem 5 (Theorem 6.3 of ). For every randomized memoryless algorithm for the Collecting Items problem, there is an adaptive adversary's strategy using at most N different packet weights such that the algorithm's competitive ratio against the strategy is at least 1/ 1 − (1 − 1 N ) N, and at every step the algorithm has at most N packets in its queue. Below we present the original proof from. Proof. Fix some online memoryless randomized algorithm A, and consider the following scheme. Let a > 1 be a constant, which we specify later, and let n = N − 1 At the beginning, the adversary inserts items a 0, a 1,..., a n into the queue, in this order. (To simplify notation, in this proof we identify items with their weights.) In our construction we maintain the invariant that in each step, the list of items pending for A is equal to a 0, a 1,..., a n. Since A is memoryless, in each step it uses the same probability distribution (q j ) n j=0, where q j is the probability of collecting item a j. Moreover, n i=0 q i = 1, as without loss of generality the algorithm always makes a move. We consider n+1 strategies for an adversary, numbered 0, 1,..., n. The k-th strategy is as follows: in each step collect a k, delete items a 0, a 1,..., a k, and then issue new copies of these items. Additionally, if A collected a j for some j > k, then the adversary issues a new copy of a j as well. This way, in each step exactly one copy of each a j is pending for A, while the adversary accumulates in its pending set copies of the items a j, for j > k, that were collected by A. This step is repeated T ≫ n times, and after the last step both the adversary and the algorithm collect all their pending items. Since T ≫ n, we only need to focus on the expected amortized profits (defined below) in a single step. We look at the gains of A and the adversary in a single step. If the adversary chooses strategy k, then it gains a k. Additionally, at the end it collects the item collected by the algorithm if this item is greater than a k. Thus, its amortized expected gain in a single step is a k + i>k q i a i. The expected gain of A is i q i a i. For any probability distribution (q j ) n j=0 of the algorithm, the adversary chooses a strategy k which maximizes the competitive ratio. Thus, the competitive ratio of A is is at least for any coefficients v 0,..., v n ≥ 0 such that k v k = 1. Let M = a n+1 −n(a−1). For k = 0, 1,..., n, we choose v k = 1 M a n−k (a − 1), if k < n, 1 M (a − n(a − 1), ) if k = n. The choice of these values may seem somewhat mysterious, but it's in fact quite simple-it is obtained by considering A's distributions where q j = 1 for some j (and thus when A is deterministic), assuming that the resulting lower bounds on the right-hand side of are equal, and solving the resulting system of equations. For these values of v k we obtain M R M v k a k + M v n a n + n j=0 q j a j k<j M v k = n(a − 1)a n + a n + n j=0 q j (a j − 1)a n+1 = a n+1 + a n+1 n j=0 q j a j − a n+1 n j=0 q j = a n+1 + a n+1 n j=0 q j a j − a n+1 = a n+1 n j=0 q j a j. Therefore, R ≥ a n+1 /M. This bound is maximized for a = 1 + 1/n, in which case we get
<filename>blades/seafile/daemon/processors/sendcommit-v3-new-proc.c /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ #include "common.h" #define DEBUG_FLAG SEAFILE_DEBUG_TRANSFER #include "log.h" #include <fcntl.h> #include <ccnet.h> #include "net.h" #include "utils.h" #include "seafile-session.h" #include "sendcommit-v3-new-proc.h" #include "processors/objecttx-common.h" #include "vc-common.h" /* seafile-recvcommit-v3 INIT ---------------------> 200 OK INIT <--------------------- Object SEND_OBJ -----------------------> Ack or Bad Object <--------------------- ... End -----------------------> */ enum { INIT, SEND_OBJECT }; typedef struct { char remote_id[41]; char last_uploaded_id[41]; GList *id_list; gboolean visited_last_uploaded; gboolean compute_success; } SeafileSendcommitProcPriv; #define GET_PRIV(o) \ (G_TYPE_INSTANCE_GET_PRIVATE ((o), SEAFILE_TYPE_SENDCOMMIT_V3_NEW_PROC, SeafileSendcommitProcPriv)) #define USE_PRIV \ SeafileSendcommitProcPriv *priv = GET_PRIV(processor); static int send_commit_start (CcnetProcessor *processor, int argc, char **argv); static void handle_response (CcnetProcessor *processor, char *code, char *code_msg, char *content, int clen); G_DEFINE_TYPE (SeafileSendcommitV3NewProc, seafile_sendcommit_v3_new_proc, CCNET_TYPE_PROCESSOR) static void release_resource (CcnetProcessor *processor) { USE_PRIV; if (priv->id_list != NULL) string_list_free (priv->id_list); CCNET_PROCESSOR_CLASS (seafile_sendcommit_v3_new_proc_parent_class)->release_resource (processor); } static void seafile_sendcommit_v3_new_proc_class_init (SeafileSendcommitV3NewProcClass *klass) { CcnetProcessorClass *proc_class = CCNET_PROCESSOR_CLASS (klass); proc_class->name = "sendcommit-v3-new-proc"; proc_class->start = send_commit_start; proc_class->handle_response = handle_response; proc_class->release_resource = release_resource; g_type_class_add_private (klass, sizeof (SeafileSendcommitProcPriv)); } static void seafile_sendcommit_v3_new_proc_init (SeafileSendcommitV3NewProc *processor) { } static int send_commit_start (CcnetProcessor *processor, int argc, char **argv) { USE_PRIV; GString *buf; TransferTask *task = ((SeafileSendcommitV3NewProc *)processor)->tx_task; memcpy (priv->remote_id, task->remote_head, 41); /* fs_roots can be non-NULL if transfer is resumed from NET_DOWN. */ if (task->fs_roots != NULL) object_list_free (task->fs_roots); task->fs_roots = object_list_new (); if (task->commits != NULL) object_list_free (task->commits); task->commits = object_list_new (); buf = g_string_new (NULL); g_string_printf (buf, "remote %s seafile-recvcommit-v3 %s %s", processor->peer_id, task->to_branch, task->session_token); ccnet_processor_send_request (processor, buf->str); g_string_free (buf, TRUE); return 0; } static void send_commit (CcnetProcessor *processor, const char *object_id) { TransferTask *task = ((SeafileSendcommitV3NewProc *)processor)->tx_task; char *data; int len; ObjectPack *pack = NULL; int pack_size; if (seaf_obj_store_read_obj (seaf->commit_mgr->obj_store, task->repo_id, task->repo_version, object_id, (void**)&data, &len) < 0) { g_warning ("Failed to read commit %s.\n", object_id); goto fail; } pack_size = sizeof(ObjectPack) + len; pack = malloc (pack_size); memcpy (pack->id, object_id, 41); memcpy (pack->object, data, len); ccnet_processor_send_update (processor, SC_OBJECT, SS_OBJECT, (char *)pack, pack_size); seaf_debug ("Send commit %.8s.\n", object_id); g_free (data); free (pack); return; fail: ccnet_processor_send_update (processor, SC_NOT_FOUND, SS_NOT_FOUND, object_id, 41); ccnet_processor_done (processor, FALSE); } static void send_one_commit (CcnetProcessor *processor) { USE_PRIV; char *commit_id; if (!priv->id_list) { ccnet_processor_send_update (processor, SC_END, SS_END, NULL, 0); ccnet_processor_done (processor, TRUE); return; } commit_id = priv->id_list->data; priv->id_list = g_list_delete_link (priv->id_list, priv->id_list); send_commit (processor, commit_id); g_free (commit_id); } static gboolean collect_upload_commit_ids (SeafCommit *commit, void *data, gboolean *stop) { CcnetProcessor *processor = data; TransferTask *task = ((SeafileSendcommitV3NewProc *)processor)->tx_task; USE_PRIV; if (strcmp (priv->last_uploaded_id, commit->commit_id) == 0) { priv->visited_last_uploaded = TRUE; *stop = TRUE; return TRUE; } if (priv->remote_id[0] != 0 && strcmp (priv->remote_id, commit->commit_id) == 0) { *stop = TRUE; return TRUE; } if (commit->parent_id && !seaf_commit_manager_commit_exists (seaf->commit_mgr, commit->repo_id, commit->version, commit->parent_id)) { *stop = TRUE; return TRUE; } if (commit->second_parent_id && !seaf_commit_manager_commit_exists (seaf->commit_mgr, commit->repo_id, commit->version, commit->second_parent_id)) { *stop = TRUE; return TRUE; } priv->id_list = g_list_prepend (priv->id_list, g_strdup(commit->commit_id)); /* We don't need to send the contents under an empty dir. */ if (strcmp (commit->root_id, EMPTY_SHA1) != 0) object_list_insert (task->fs_roots, commit->root_id); object_list_insert (task->commits, commit->commit_id); return TRUE; } static void * compute_upload_commits_thread (void *vdata) { CcnetProcessor *processor = vdata; SeafileSendcommitV3NewProc *proc = (SeafileSendcommitV3NewProc *)processor; TransferTask *task = proc->tx_task; USE_PRIV; gboolean ret; ret = seaf_commit_manager_traverse_commit_tree_truncated (seaf->commit_mgr, task->repo_id, task->repo_version, task->head, collect_upload_commit_ids, processor, FALSE); if (!ret) { priv->compute_success = FALSE; return vdata; } /* We have to make sure all commits that need to be uploaded are found locally. * If we have traversed up to the last uploaded commit, we've traversed all * needed commits. */ if (!priv->visited_last_uploaded) { seaf_warning ("Not all commit objects need to be uploaded exist locally.\n"); priv->compute_success = FALSE; return vdata; } priv->compute_success = TRUE; return vdata; } static void compute_upload_commits_done (void *vdata) { CcnetProcessor *processor = vdata; USE_PRIV; if (!priv->compute_success) { ccnet_processor_send_update (processor, SC_NOT_FOUND, SS_NOT_FOUND, NULL, 0); ccnet_processor_done (processor, FALSE); return; } send_one_commit (processor); } static void send_commits (CcnetProcessor *processor, const char *head) { SeafileSendcommitV3NewProc *proc = (SeafileSendcommitV3NewProc *)processor; USE_PRIV; char *last_uploaded; last_uploaded = seaf_repo_manager_get_repo_property (seaf->repo_mgr, proc->tx_task->repo_id, REPO_LOCAL_HEAD); if (!last_uploaded || strlen(last_uploaded) != 40) { seaf_warning ("Last uploaded commit id is not found in db or invalid.\n"); ccnet_processor_send_update (processor, SC_SHUTDOWN, SS_SHUTDOWN, NULL, 0); ccnet_processor_done (processor, FALSE); return; } memcpy (priv->last_uploaded_id, last_uploaded, 40); g_free (last_uploaded); ccnet_processor_thread_create (processor, seaf->job_mgr, compute_upload_commits_thread, compute_upload_commits_done, processor); } static void handle_response (CcnetProcessor *processor, char *code, char *code_msg, char *content, int clen) { SeafileSendcommitV3NewProc *proc = (SeafileSendcommitV3NewProc *)processor; TransferTask *task = proc->tx_task; if (task->state != TASK_STATE_NORMAL) { ccnet_processor_done (processor, TRUE); return; } switch (processor->state) { case INIT: if (memcmp (code, SC_OK, 3) == 0) { processor->state = SEND_OBJECT; send_commits (processor, task->head); return; } break; case SEND_OBJECT: if (memcmp (code, SC_ACK, 3) == 0) { send_one_commit (processor); return; } break; default: g_return_if_reached (); } g_warning ("Bad response: %s %s.\n", code, code_msg); if (memcmp (code, SC_ACCESS_DENIED, 3) == 0) transfer_task_set_error (task, TASK_ERR_ACCESS_DENIED); ccnet_processor_done (processor, FALSE); }
package cli func getFlagName(f Flag) (result string, ok bool) { if v := flagValue(f).FieldByName("Name"); v.IsValid() { return v.Interface().(string), true } return } func getFlagAliases(f Flag) (result []string, ok bool) { if v := flagValue(f).FieldByName("Aliases"); v.IsValid() { return v.Interface().([]string), true } return } func getFlagEnvVars(f Flag) (result []string, ok bool) { if v := flagValue(f).FieldByName("EnvVars"); v.IsValid() { return v.Interface().([]string), true } return } func getFlagUsage(f Flag) (result string, ok bool) { if v := flagValue(f).FieldByName("Usage"); v.IsValid() { return v.Interface().(string), true } return } func getFlagDefaultText(f Flag) (result string, ok bool) { if v := flagValue(f).FieldByName("DefaultText"); v.IsValid() { return v.Interface().(string), true } return } func getFlagFilePath(f Flag) (result string, ok bool) { if v := flagValue(f).FieldByName("FilePath"); v.IsValid() { return v.Interface().(string), true } return } func getFlagRequired(f Flag) (result bool, ok bool) { if v := flagValue(f).FieldByName("Required"); v.IsValid() { return v.Interface().(bool), true } return } func getFlagHidden(f Flag) (result bool, ok bool) { if v := flagValue(f).FieldByName("Hidden"); v.IsValid() { return v.Interface().(bool), true } return } func getFlagTakesFile(f Flag) (result bool, ok bool) { if v := flagValue(f).FieldByName("TakesFile"); v.IsValid() { return v.Interface().(bool), true } return } func getFlagSkipAltSrc(f Flag) (result bool, ok bool) { if v := flagValue(f).FieldByName("SkipAltSrc"); v.IsValid() { return v.Interface().(bool), true } return } func getFlagValue(f Flag) (result interface{}, ok bool) { if v := flagValue(f).FieldByName("Value"); v.IsValid() { return v.Interface(), true } return } func getFlagValuePtr(f Flag) (result interface{}, ok bool) { if v := flagValue(f).FieldByName("Value"); v.IsValid() { return v.Addr().Interface(), true } return } func getFlagDestination(f Flag) (result interface{}, ok bool) { if v := flagValue(f).FieldByName("Destination"); v.IsValid() { return v.Interface(), true } return }
/* * Copyright (c) 2007, Technische Universitaet Berlin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the Technische Universitaet Berlin nor the names * of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @author Philipp Huppertz <[email protected]> */ #include "sfpacket.h" #include <cstring> SFPacket::SFPacket(int pType, int pSeqno) { length = 0; seqno = pSeqno; type = pType; } // copy constructor SFPacket::SFPacket(const SFPacket &pPacket) { length = pPacket.getLength(); type = pPacket.getType(); seqno = pPacket.getSeqno(); setPayload(pPacket.getPayload(), length); } SFPacket::~SFPacket() { // if (buffer) delete[] buffer; } const char* SFPacket::getPayload() const { if(((type == SF_PACKET_ACK) || (type == SF_PACKET_NO_ACK))) { return buffer + 1; } else { return NULL; } } int SFPacket::getLength() const { return length; } int SFPacket::getType() const { return type; } int SFPacket::getSeqno() const { return seqno; } bool SFPacket::setPayload(const char* pBuffer, uint8_t pLength) { if ((pLength > 0) && (pLength < cMaxPacketLength) && ((type == SF_PACKET_ACK) || (type == SF_PACKET_NO_ACK))) { length = pLength; memcpy(buffer + 1, pBuffer, pLength); return true; } DEBUG("SFPACKET::setPayload : wrong packet length = " << static_cast<int>(pLength) << " or type = " << type) return false; } void SFPacket::setSeqno(int pSeqno) { seqno = pSeqno; } void SFPacket::setType(int pType) { type = pType; } int const SFPacket::getMaxPayloadLength() { return cMaxPacketLength; } /* == operator */ bool SFPacket::operator==(SFPacket const& pPacket) { bool retval=false; if((pPacket.getType() == type) && (pPacket.getLength() == length) && (pPacket.getSeqno() == seqno)) { if((type == SF_PACKET_ACK) || (type == SF_PACKET_NO_ACK)) { retval = (memcmp(pPacket.getPayload(), getPayload(), length) == 0); } } return retval; } /* return the length that shall be transmitted via TCP */ int SFPacket::getTcpLength() const { return length + 1; } /* return the payload of the TCP packet */ const char* SFPacket::getTcpPayload() { char l = length; buffer[0] = l; return buffer; }
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; string basepath = "/home/shincurry/Dropbox/Paper/animeloop/Resources/lens_switch/"; string videopath = basepath + "lens_switch_example_.mkv"; //string videopath = "/home/shincurry/Downloads/[LoliHouse] Kimi no Na wa [BDRip 1920x1080 AVC-yuv420p8 AAC PGS(chs,eng,jpn)].mkv"; int main(int argc, char** argv) { VideoCapture capture(videopath); if (!capture.isOpened()) { cout << "No camera or video input!\n" << endl; return -1; } int total_frames = capture.get(CV_CAP_PROP_FRAME_COUNT); Mat prevframe, nextframe, differframe; int i = 0; ofstream file(basepath + "framediff.txt"); capture.read(prevframe); cvtColor(prevframe, prevframe, CV_RGB2GRAY); while (capture.read(nextframe)) { cvtColor(nextframe, nextframe, CV_RGB2GRAY); //帧差法 absdiff(nextframe, prevframe, differframe); // imshow("Prev Frame", prevframe); // imshow("Next Frame", nextframe); // imshow("Differ Frame", differframe); int count = 0; int total = differframe.rows * differframe.cols; for (int row = 0; row < differframe.rows; ++row) { for (int col = 0; col < differframe.cols; ++col) { if (differframe.at<uchar>(row, col) > 10) { count++; } } } double rate = (total != 0) ? double(count) / total : 0; if (rate > 0.85) { // cvWaitKey(); cout << "len switched. " << i << endl; } if (file.is_open()) { file << rate << endl; } char c = waitKey(33); if (c == 27) break; prevframe = nextframe; i++; } // file.close(); return 0; }
import { AktivBruker, AktivEnhet, Saksbehandler } from './domain'; import { erLocalhost, finnMiljoStreng } from './utils/url-utils'; import { UseFetchHook } from './hooks/use-fetch'; export enum ContextApiType { NY_AKTIV_ENHET = 'NY_AKTIV_ENHET', NY_AKTIV_BRUKER = 'NY_AKTIV_BRUKER' } async function doFetch(url: string, options?: RequestInit): Promise<Response> { return await fetch(url, { ...options, credentials: 'include' }); } async function getJson<T>(url: string, options?: RequestInit): Promise<T> { try { const resp = await doFetch(url, options); return await resp.json(); } catch (e) { return Promise.reject(e); } } async function postJson<T>(url: string, body: T, options?: RequestInit): Promise<T> { try { await doFetch(url, { ...options, method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); return body; } catch (e) { return Promise.reject(e); } } export const modiacontextholderUrl = (() => { if (erLocalhost()) { return '/modiacontextholder/api'; } return `https://app${finnMiljoStreng()}.adeo.no/modiacontextholder/api`; })(); export async function oppdaterAktivBruker(fnr: string | null | undefined) { return await postJson(`${modiacontextholderUrl}/context`, { verdi: fnr, eventType: ContextApiType.NY_AKTIV_BRUKER }); } export async function oppdaterAktivEnhet(enhet: string | null | undefined) { return await postJson(`${modiacontextholderUrl}/context`, { verdi: enhet, eventType: ContextApiType.NY_AKTIV_ENHET }); } export async function nullstillAktivBruker() { return await fetch(AKTIV_BRUKER_URL, { method: 'DELETE', credentials: 'include' }); } export const AKTIV_ENHET_URL = `${modiacontextholderUrl}/context/aktivenhet`; export const AKTIV_BRUKER_URL = `${modiacontextholderUrl}/context/aktivbruker`; export const SAKSBEHANDLER_URL = `${modiacontextholderUrl}/decorator`; export async function hentAktivBruker(): Promise<AktivBruker> { return await getJson<AktivBruker>(AKTIV_BRUKER_URL); } export async function hentAktivEnhet(): Promise<AktivEnhet> { return await getJson<AktivEnhet>(AKTIV_ENHET_URL); } export function getWebSocketUrl(saksbehandler: UseFetchHook<Saksbehandler>) { if (process.env.NODE_ENV === 'development') { return 'ws://localhost:2999/hereIsWS'; } return saksbehandler.data .map((saksbehandler) => saksbehandler.ident) .map( (ident) => `wss://veilederflatehendelser${finnMiljoStreng()}.adeo.no/modiaeventdistribution/ws/${ident}` ) .withDefault(undefined); }
Mainstream liberals, and in particular Democrats, have been known to cozy up to radical language and symbols just as their value, and with it the political fortunes of those who parrot and exploit them, begins to rise. The last few years are crowded with examples. I’m thinking here of liberals’ oafish performance as champions of social justice. You see it most strikingly in the warm embrace of intersectionality and Black Lives Matter (both of which emerged from the black feminist tradition). That each has exploded in popularity in recent years isn’t itself the problem. The problem is that in the hands of many a liberal politician and pundit, they’ve been rapidly evacuated of substance. Substance that otherwise includes a set of short and long-term political commitments aimed at improving black life. Anyone who claims to value those lives should feel an awful rage at the outcome. After all, rhetorical admiration for black people without a full-throated embrace of policies that stand to improve the actual lives of black people may buoy the fortunes of the speaker, but it’s a pretty shitty deal for…black people. What’s cool is that it doesn’t have to be this way. Take healthcare. Judged by the misery it inflicts on black people, few systems should be as easily slated for decimation as America’s employer-provided system. In its place, the admirers of black life should get behind Medicare-for-All pronto. Employer-Provided Insurance Disproportionately Screws Black People As the healthcare debate raged in early 2009, Glenn Beck stormed from microphone to microphone, thundering that the ACA was just the opening salvo in Obama’s stealth war of reparations: “The health care bill is reparations. It’s the beginning of reparations.” Tucked in between Beck’s aggressive lunacy was a kernel of truth. Any leftward lurch on healthcare disproportionately impacts black people because black people are disproportionately uninsured. The reasons why are not mysterious. America’s system of private, employer-provided care creates massive cracks for people to fall through. If having a job is the main bridge over that yawning gap then, by definition, those without a job will often find themselves falling into the abyss. And given the powerful role racism plays in the American labor market, it’s no surprise that black people are overrepresented among the fallen. Consider that the United States, as a deliberate feature of monetary policy, maintains about a 4% unemployment rate. This alone is damning evidence against an employment-based model. Then note, highlight, and carve deep into memory that black unemployment consistently doubles white unemployment, that the same is true of black poverty, and that the median white family is worth more than 33 times the median black family. The outcome is about what you’d expect: higher uninsured rates among black people. And a higher likelihood of experiencing all the horror that comes with―needless financial and physical ruin chief among them. There’s more. Consider the fact that jobs are impermanent things, with tens of millions of people sliding in and out of employment every year. It’s easy to see what’s wrong with building such an unreliable bridge to healthcare. Even if you snag a job that provides coverage, the threat of having your insurance clawed away haunts you at every turn. Now recall the structurally high unemployment rate of black people. The horror of all this should, by now, be painfully obvious. For all people, and black people especially, employer-provided coverage is the flimsiest of all possible bridges to stand on in the first place. All of which illuminates a terrifying and unsurprising fact of American life: black people suffer the absurd cruelty of our healthcare system in a way that few others do. These design flaws are deeply harmful, often fatal, and always avoidable. The solution is as obvious as the cruelty: guaranteed coverage for everyone. Obamacare Only Partially Closed the Gap Although our employer-provided system throws people into the abyss just as they enter life’s most uncertain chapters, popular single-payer programs like Medicare and Medicaid have been there to pull many of them back. There’s no doubt that Obamacare’s greatest triumph was its expansion of Medicaid, which extended that good socialized medicine to millions of America’s uninsured. There are several important lessons here, but I’ll rattle off just a couple. For one, it’s a solid reminder why public health care tends to be more popular than market-based alternatives. A system of guaranteed, quality, and easily navigable coverage will tend to be vastly preferable to one where decisions about who deserves to live or die depend on the compassion of the job market. But it’s also been a lesson in how barbarism preserves itself. The current state-federal hodgepodge means that conservative states can more effectively sabotage healthcare. In their desperate crusade against Obamacare, 19 states have refused to take up the Medicaid expansion. The majority of those states are also where the majority of black people live: the American south. It must be said that anything short of a full-blown Medicare for All style system has made peace with this grim possibility. Conclusion The bottom line is this: in a country that relies overwhelmingly on employers to deliver healthcare to its people, the unemployed and underemployed will always be at risk of falling into the country’s sprawling and ruthless healthcare abyss. And in the United States, where black people sit at the bottom of most things economic, the absence of universally guaranteed coverage will always mean more misery piled atop black lives. Lives that have only recently become fashionable to hail as worth more than the unsleeping cruelty their country has inflicted on them. And lives those same newfound admirers can’t possibly give a damn about while trashing the sort of policies capable of preventing their economic and physical ruin.
Depression: schism in contemporary psychiatry. The author decribes an experience in his own family involving the initial unsuccessful treatment of a depressed patient. The patient failed to respond to psychotherapeutic and drug treatment on an outpatient basis and in three hospitals; in a fourth hospital he improved dramatically after a series of ECT treatments and remained without depressive symptoms. The author stresses the importance of psychiatrists keeping an open mind about various treatment approaches.
BLUF Domain Function Does Not Require a Metastable Radical Intermediate State BLUF (blue light using flavin) domain proteins are an important family of blue light-sensing proteins which control a wide variety of functions in cells. The primary light-activated step in the BLUF domain is not yet established. A number of experimental and theoretical studies points to a role for photoinduced electron transfer (PET) between a highly conserved tyrosine and the flavin chromophore to form a radical intermediate state. Here we investigate the role of PET in three different BLUF proteins, using ultrafast broadband transient infrared spectroscopy. We characterize and identify infrared active marker modes for excited and ground state species and use them to record photochemical dynamics in the proteins. We also generate mutants which unambiguously show PET and, through isotope labeling of the protein and the chromophore, are able to assign modes characteristic of both flavin and protein radical states. We find that these radical intermediates are not observed in two of the three BLUF domains studied, casting doubt on the importance of the formation of a population of radical intermediates in the BLUF photocycle. Further, unnatural amino acid mutagenesis is used to replace the conserved tyrosine with fluorotyrosines, thus modifying the driving force for the proposed electron transfer reaction; the rate changes observed are also not consistent with a PET mechanism. Thus, while intermediates of PET reactions can be observed in BLUF proteins they are not correlated with photoactivity, suggesting that radical intermediates are not central to their operation. Alternative nonradical pathways including a ketoenol tautomerization induced by electronic excitation of the flavin ring are considered. ■ INTRODUCTION Light-sensing proteins mediate the response of living systems to light. In the most widely studied examples, rhodopsins, phytochromes, and photoactive yellow protein, the primary process involves an excited state isomerization reaction. 1,2 Relatively recently a range of blue-light-sensing flavoproteins have been discovered and shown to be widespread, occurring in animals, plants, fungi, and bacteria. 3−5 Three separate classes have now been identified: photolyase/cryptochromes; lightoxygen-voltage (LOV) domain proteins; blue light sensing using FAD (BLUF) domain proteins. In each case the chromophore is a flavin (isoalloxazine) ring which is planar in its oxidized form and thus not able to exert a mechanical force on the surrounding protein. Consequently the mechanism of operation of these photoactive flavoproteins is a topic of intense experimental and theoretical investigation. 6,7 In the DNA repair enzyme, photolyase, a change in oxidation state of the flavin is observed, while in the LOV domain a reaction of the triplet state of the flavin with an adjacent cysteine is the primary mechanism. 8−11 The BLUF domain is a versatile unit involved in phototaxis in Synechocystis, 12,13 biofilm formation in Acinetobacter baumannii, 14 and gene expression in Rhodobacter sphaeroides, 15,16 processes which are controlled by the BLUF proteins PixD (Slr1694) and BlsA and activation of photopigment and PUC A protein (AppA), respectively. In addition to this importance in nature some applications for flavoproteins have been proposed. For example, the role of the BLUF domain in light-induced regulation of gene expression makes it a candidate for exploitation in the emerging field of optogenetics, 17 while the use of photoactive flavoproteins as sources of genetically expressed singlet oxygen has been proposed. 18,19 Despite this interest and importance, the primary mechanism operating in the BLUF domain is as yet unresolved, and forms the topic of the present paper. Conversion of the dark-adapted state of BLUF proteins to the signaling state under blue (∼450 nm) light leads to a redshift in the ground state absorption of the flavin ring by 10−15 nm, with the flavin remaining in its fully oxidized form in both states. 20,21 The light-adapted state thus formed relaxes back to the dark state in the absence of irradiation in a time which is dependent on the particular BLUF domain protein: 30 min for AppA, 9 min in BlsA, but much faster (<10 s) in PixD. AppA is the best characterized of all BLUF domain proteins. 22 −24 In the photosynthetic organism it acts as an antirepressor, responsible for light-activated control of the expression of genes involved in the biosynthesis of the photosynthetic apparatus. It comprises an N-terminal BLUF domain and a C-terminal domain which binds the repressor molecule PpsR in the dark. Irradiation with blue light causes dissociation of the AppA:PpsR complex. The structure of the BLUF domain (AppA BLUF ) has been studied by X-ray, NMR, and QM/MM and purely classical calculations. 22,23,25−31 An Xray structure is shown in Figure 1, and the existence of an intricate H-bonding network involving the flavin ring and residues Y21, Q63, W104, and M106 is apparent. Currently, Xray structures disagree on the orientation of Q63 and W104, but both NMR and QM/MM calculations suggest that Q63 is mobile and flips between light and dark states, leading to modified H-bonded interactions between Q63, Y21, and the flavin ring. 25,32,33 A change in H-bonding between protein and the flavin on light activation ( Figure 1) is supported by light minus dark IR difference measurements and Raman spectroscopy, where a red-shift is observed in the transition associated with the C4O stretch mode of the flavin ring. 21,34,35 In agreement with the structure and spectroscopy, sitedirected mutagenesis shows that the residues Y21 and Q63 are essential for the light-activated function. 37,38 When these residues are mutated, the red-shift in the flavin absorption characteristic of a photoactive state is not observed. On the other hand W104 can be exchanged in AppA, and the red-shift is retained, but the light-to-dark recovery rate is dramatically enhanced (for example when Trp is replaced by Ala there is an 80-fold increase in the recovery rate), and biological activity is abolished. 39 We have shown elsewhere in femtosecond to millisecond IR spectroscopy that this mutation shortcircuits the structure change in AppA, thereby abolishing in vivo activity. 40 The originally proposed and most widely accepted model for the primary process in BLUF domains is electron transfer from a highly conserved tyrosine residue (Y21 in AppA) to the photoexcited flavin ring, Y21−FAD* → Y21 + −FAD −. This assignment is based on two important observations: the formation of a radical like spectrum in ultrafast transient electronic spectroscopy of PixD and the observation of complex multiexponential kinetics in the decay of the transient electronic spectrum. 38,41−46 Such multiexponential kinetics could be consistent with sequential formation of FAD − and FADH on a subnanosecond time scale. 45 However, in AppA no radical state was observed either by ultrafast electronic or transient infrared spectroscopy. 47,48 The electron transfer reaction was inferred by analogy with the PixD result and through analysis of the complex kinetics, which persist in AppA. An alternative proposal was presented, based on transient IR spectroscopy of AppA and its mutants, that photoexcitation of the flavin ring initiates a prompt change in the H-bonding environment without a change in oxidation state, which is sufficient to initiate structural change through a tautomerization in the Q63 residue. 48,49 Quite recently two other BLUF domain proteins (BlsA and BlrB) were investigated by ultrafast electronic and vibrational spectroscopy, respectively; again, no radical spectrum was detected, although complex kinetics were observed. 50,51 These results raise the key question of whether formation of a radical intermediate is critical to the operation of the BLUF domain. For example, a number of recent theoretical approaches to modeling the mechanism of signaling state formation in BLUF proteins assume formation of an electron transfer intermediate. 26,52−54 Here we resolve this question by studying three dark-adapted BLUF domains, AppA BLUF, PixD, and BlsA with 100 fs temporal resolution transient infrared (TRIR) spectroscopy with 4 cm −1 spectral resolution. These data are compared with TRIR of AppA BLUF mutants and model flavins which unambiguously display the spectra of radical intermediates. 55−57 In this way marker bands for neutral and radical states are identified. These assignments are confirmed by isotope substitution. We then track the presence or absence of radical states in the three BLUF domains in their dark-adapted states. Finally, to further probe the role of photoinduced electron transfer we modulate the redox potential of the tyrosine residue in AppA BLUF, suggested to act as the electron donor, 45,54 using unnatural amino acid substitution. 58 This comprehensive study allows us to describe the role of radical intermediate states in the BLUF photocycle. Such intermediates are observed in a number of proteins, but their presence is not correlated with photoactivity. Thus, an alternative mechanism for BLUF domain function is proposed. ■ EXPERIMENTAL METHODS Transient Spectroscopy. The transient infrared spectrometer is based on the ULTRA apparatus described in detail elsewhere 59 with additional details given in the Supporting Information (SI). Key features are the stability and 10 kHz repetition rate which permit the acquisition of transient IR difference (TRIR) spectra with 100 fs time resolution and a signal-to-noise which allow the detection of transient changes in optical density as small as 10 OD. Such high signal-tonoise supports detailed global analysis procedures described in the SI. Materials and Protein Preparation. Methods for the preparation of AppA, the uniformly 13 C-labeled AppA and the AppA mutants have been presented elsewhere. 49 Additional details are provided in SI. Synthesis of 2-fluorotyrosine (2-FTyr) and 3-fluorotyrosine (3-FTyr) was performed as described by Stubbe, 60,61 and additional details are provided in SI. Redox Potentials. The formal potentials at physiological pH of Tyr, 2-FTyr, and 3-FTyr were recorded using an Autolab PGStat302N computer-controlled potentiostat (Metrohm) in pH 7.0 phosphate buffer using square wave voltammetry. A three-electrode cell was used comprising a 3 mm glassy carbon working electrode, a Pt counter electrode (99.99% Goodfellow), and a saturated calomel reference electrode (Radiometer). The applied potential was modulated in square-waveform with the following parameters: pulse amplitude 25 mV, frequency 12.5 Hz, step potential 2 mV. Scanning in an oxidative direction revealed a single oxidation peak for each amino acid derivative. The oxidation of the amine moiety in each species is electrochemically irreversible, therefore the formal potential is found simply by subtracting the pulse amplitude from the observed peak potential. 62 Note that, as the oxidation process involves concomitant proton and electron transfer, at physiological pH the formal potentials used herein differ from standard potential literature values (which by definition refer to the standard potential at pH 1.0) by ∼−55 mV/pH unit. Data analysis was performed using the on-board potentiostat software Nova v 1.10. ■ RESULTS AND DISCUSSION Transient IR Spectroscopy of AppA. Figure 2A shows the experimentally measured TRIR difference spectra for the dark-adapted state of the AppA BLUF domain (dAppA BLUF ) evolving between 1 ps and 1 ns after excitation at 450 nm. These are similar to spectra presented earlier, 48 but experimental developments yield spectra with greatly improved signal-to-noise over a wider spectral range, which encompasses a number of newly observed modes. From a comparison with the TRIR of FMN in buffer solution ( Figure 2B) it is evident that on the nanosecond time scale the dAppA BLUF spectrum is dominated by flavin ring localized vibrational modes, with negative (bleach) peaks arising from depletion of the electronic ground state and positive peaks appearing during the excitation pulse arising from excited state modes. Detailed assignments based on DFT calculations and isotopic substitutions have been presented elsewhere. 55,56,63−65 Essentially the two highestfrequency bleach modes (1701 and 1653 cm −1 ) arise from a coupled pair of carbonyl stretch/N3H wag modes, while the narrow bleaches at 1584 (weak) and 1548 cm −1 (strong) are flavin ring modes. The complex line shape between 1600 and 1653 cm −1 contains contributions from both the excited electronic state of the flavin ring and protein modes perturbed by electronic excitation. The assignment of modes to the protein has been confirmed by studies of the fully 13 C-labeled dAppA (SI, Figure S1) and described elsewhere. 49 An important result in Figure 2A is the observation of a pair of broad transient absorptions at 1380 and 1415 cm −1. These are assigned to the singlet excited state of the flavin ring, because they are clearly also present in the TRIR of FMN in solution 65 ( Figure 2B). Thus, the 1380 cm −1 transient and intense 1548 cm −1 bleach intensities can be taken as marker modes, indicating the population of the excited state and ground state, respectively, of FAD in dAppA BLUF. In line with this assignment these bands appear within the excitation pulse, and their temporal evolution is simply a decrease in amplitude without any spectral shift ( Figure 2C). The temporal evolution of the spectra in Figure 2A is in other respects rather featureless; despite the marked improvement in signal-to-noise compared to earlier data, there is no evidence for the formation of intermediate species with distinct vibrational spectra on the subnanosecond time scale. Essentially the spectra in Figure 2A appear within the excitation pulse and mainly relax back to the electronic ground state. In contrast to this relatively simple spectroscopy the relaxation kinetics are complex and can only be fit with a sum of at least two exponential decay terms (Table 1). This should not be taken as necessarily indicating two distinct states, but rather a minimum numerical representation of multiexponential kinetics. Such complex kinetics may indicate an inhomogeneous ground state distribution, with different decay kinetics for different conformations of the protein around the flavin ring. In at least one case (the 1690 cm −1 shoulder on the 1701 cm −1 bleach, Figure 2A) spectrally distinct states are observed to have different ground state recovery lifetimes. The faster recovery of the 1690 cm −1 bleach is particularly noteworthy because it correlates with the faster ground state recovery of the lightadapted state (lAppA BLUF ), which has a red-shifted C4O carbonyl mode (see SI Figure S2). This may indicate the existence of a fraction of the light state structure even in the dark-adapted protein. In Figure 2C the kinetics associated with the flavin ring ground and excited state marker modes of dAppA BLUF at 1380 and 1548 cm −1 are compared. The kinetics are of opposite sign but otherwise cannot be distinguished from one another, aside Comparison of the excited state decay (1380 cm −1 ) and ground state recovery (1548 cm −1 ) dynamics of dAppA BLUF. The 1548 cm −1 data have been inverted and normalized for the comparison. The difference at long time reflects the fact that the excited singlet state relaxes completely but the ground state is not completely repopulated due to population of long-lived state; this is modeled by a constant offset for the analysis in Table 1. from the constant offset in the ground state recovery (1548 cm −1 ), which is associated with microsecond relaxation dynamics. 40 This offset is also evident in independent global analysis ( Figure S3 in SI). The corresponding two exponential fits are the same within the fitting error (Table 1). Such close agreement of excited state decay and ground state recovery is inconsistent with a sequential kinetics model in which the excited state is quenched to form a distinct intermediate state which then relaxes on a longer time scale to form the lightadapted state. In that case the 1380 cm −1 excited state transient would relax faster than the 1548 cm −1 ground state recovers. Thus, there is no evidence in these data for the existence of distinct intermediates in the subnanosecond kinetics of dAppA BLUF. That the dynamics are nonsingle exponential most likely reflects a distribution of ground state structures in the protein (for which there is some evidence in Figure 2A and some calculations 33 ). The quality of the data in Figure 2A is sufficient to conduct a global kinetic analysis. To make meaningful comparisons between all samples studied (see below) we restricted modeling to two simple cases, first the construction of decay-associated spectra (DAS) with two decaying and one nondecaying (final) state and second evolution-associated spectra (EAS) using a single intermediate scheme, A→B→C. Both schemes fit the data adequately and equally well. Thus, to distinguish between them it is critical to have additional criteria, in particular a distinct spectrum that can be associated with any intermediate state. More complex models with additional intermediates or decaying states yield a slight improvement in the quality of the fit, but no new physical insight. The results are shown in SI ( Figure S3). The DAS show minor 30 ps and major 485 ps decaying components plus a final spectrum. This aligns closely with the biexponential kinetics of the marker modes (Table 1, Figure 2C); it is significant that the 30 ps DAS is similar to the transient spectrum of lAppA BLUF ( Figure S2 in SI). For the EAS the initial and intermediate states have essentially the same spectra. Thus, global analysis also does not support the formation of an intermediate state. Both models yield essentially the same 'final' spectrum, and its microsecond kinetics (responsible for the offset in Figure 2C) have been described elsewhere. 40 To summarize, for dAppA BLUF no bands are found in the TRIR spectra which can be assigned specifically to formation of a radical (or any other) intermediate state in the photocycle. Further, the kinetics do not point to population of a distinct intermediate state. There is evidence for an inhomogeneous ground state distribution giving rise to complex kinetics, which may include structures similar to the light-activated state, lAppA BLUF. Observation of Radical States in dAppA BLUF Mutants. To investigate the role of radical states in the primary photochemistry of dAppA BLUF the Y21W mutant was studied by TRIR and transient absorption. This protein is photoinactive, 39 with no red shift in the spectrum of the dark-adapted state on irradiation. However, electron transfer quenching of the flavin excited state is expected to be significantly faster in Y21W than in dAppA BLUF because the driving force for charge separation is larger (more negative) by ∼300 mV when Tyr is replaced by Trp. 66 It was reported by Bonetti et al. 38 that the equivalent Y8W substitution in PixD opened up a new radical. Analysis of TRIR data for Y21W will require marker modes for possible radical states. We have previously reported vibrational mode assignments for FAD − and FADH ground states, and assigned transitions at 1528 cm −1 and 1626 cm −1 to the ground state of the radical (radical spectra are presented in SI Figure S4). 64 These radical marker modes complement those identified above for the neutral reactants. Although the 1626 cm −1 region in dAppA BLUF is crowded due to contributions from both protein and flavin, the 1528 cm −1 region is not and does not show the growth of an absorption which could be assigned to formation of FAD − ( Figure 2A); thus, there is no positive evidence for a radical state in the wildtype protein. The TRIR spectra for Y21W dAppA BLUF are shown in Figure 3A. That a new reaction pathway has been introduced is immediately apparent from the spectra ( Figure 3A) and kinetics ( Figure 3B). There are transient absorptions at 1521 and 1637 cm −1 that are absent in wild-type dAppA BLUF. Both peaks show true intermediate kinetics, increasing in amplitude as a function of time after excitation, reaching a maximum at around 10 ps, and decaying on a slower time scale ( Figure 3B). The 1521 cm −1 transient is assigned to formation of a flavin radical by photoexcited electron transfer from Trp21, while the intense 1637 cm −1 peak may have contributions from FAD − and/or the Trp + radical cation. Along with the formation of these new transient states, a time-dependent bleach is expected, as some ground state species must be consumed in the reaction. Such consumption kinetics are seen in the increasingly negative bleach at 1626 cm −1 ( Figure 3A). Thus, the spectra and kinetics of Y21W are consistent with a sequential electron transfer reaction, W21− FAD* → W21 + −FAD − → W21−FAD The sequential nature of the kinetics is supported by comparison of the FAD* decay (1380 cm −1 ) which should reflect the primary electron transfer rate, and FAD ground state recovery (1548 cm −1 ), which will also depend on the rate of charge recombination (Table 1, Figure 3C). The FAD excited state decays more rapidly than the ground state recovers, in line with the formation of an intermediate state but in contrast to the behavior of dAppA BLUF ( Figure 2C, Table 1). As for wild-type dAppA BLUF the kinetics of Y21W are nonsingle exponential (Table 1) even for the decay of FAD*. This again probably reflects a distribution of ground state structures in Y21W. Further proof that an electron transfer reaction occurs in Y21W was obtained from transient visible absorption spectroscopy (SI Figure S5) In that case the Trp radical cation spectrum of Y21W is shown to rise and decay with the same kinetics as the 1640 cm −1 mode. To confirm these assignments of protein and flavin modes in the TRIR spectra of Y21W, the fully 13 C-labeled protein U 13 C− Y21W was studied ( Figure 4). As expected, the main bleach modes associated with the flavin ring (1548, 1585 cm −1 ) occur at essentially the same frequency as in dAppA BLUF, although the highest-frequency carbonyl bleach unexpectedly shifts down from 1701 to 1696 cm −1. This shift suggests a contribution from an instantaneous bleach of a protein mode underlying the C4O flavin bleach in Y21W. At this frequency the most probable assignment of the protein bleach is to a change in either oscillator strength or frequency of a carbonyl mode in an amino acid side chain H-bonded to the flavin. Such instantaneous bleach modes were previously reported in the photoinactive mutant Q63E. 49 The 13 C substitution leads to major changes in the 1580−1680 cm −1 region, with the intense transient peak at 1637 cm −1 shifting to 1600 cm −1 and the associated bleach shifting from 1626 cm −1 to become a minimum at 1585 cm −1 (strongly overlapped with the flavin ring mode). The downshift of this pair on isotopic substitution confirms that they arise from vibrational modes of the electron donor, the W21 residue; thus both donor and acceptor states are observed simultaneously by TRIR. Unfortunately, there is only limited data on the IR spectra of Trp radicals or the radical cation, making further assignment to specific vibrational modes difficult. 67 The final major effect of 13 C exchange is an increase in the amplitude of the 1661 cm −1 bleach compared to that of Y21W. This bleach is assigned in dAppA BLUF to the lowerfrequency flavin carbonyl mode, C2O, 55,56 and the apparently stronger bleach in fact arises from the downshift of the absorption of the radical product mode which partially obscures this transient in Y21W. Importantly, the transient species growing in at 1521 cm −1 does not shift on 13 C labeling, consistent with its assignment to formation of the flavin radical anion on the picosecond time scale (Figure 4). The absence of this feature from the spectra of wild-type dAppA BLUF (Figure 2A Figures 3A,4). The 1485 cm −1 mode in Y21W is unshifted on 13 C substitution, and thus, is assigned to the flavin radical (which aligns with a feature seen in the glucose oxidase radical spectrum 64 ). The 1447 cm −1 transient which appears only in U 13 C−Y21W must arise from a mode of the Trp radical cation, shifted down from a position underlying the 1480−1520 cm −1 region in the Y21W. The observation of a clear rising component in the TRIR data invites application of the sequential kinetic model in global analysis; the resulting EAS for Y21W and U 13 C−Y21W are shown in Figure 5. The spectra correlate with the discussion of the raw data above and add some new details. The band at 1701 cm −1 shifts, weakens, and broadens on 13 C substitution, showing that the protein bleach mode underlying the C4O carbonyl has shifted down to fill in the feature at 1690 cm −1. As discussed above, this is associated with a carbonyl mode in a protein residue, instantaneously perturbed on excitation of the flavin ring. Further assignment will require specific isotope editing of residues H-bonded to the flavin. The intense pair of modes assigned to the Trp → Trp + reaction are downshifted by isotope substitution, as expected. In U 13 C−Y21W this pair is overlapped with features at ∼1610 and 1580 cm −1 which do not themselves shift on isotopic exchange and can thus be assigned as flavin modes. In addition to the previously noted rising feature of FAD − at 1521 cm −1 (which does not shift on isotope exchange) new features associated with the radical intermediate are also resolved in the global analysis at 1485 cm −1 (FAD − ) and 1447 (Trp + ). Finally it is significant that the final EAS for Y21W and U 13 C−Y21W ( Figure 5) are very close to the baseline. The long-lived perturbation to the protein structure seen in dAppA BLUF is absent in Y21W, consistent with the latter being a photoinactive protein. Thus, these data on Y21W show that photoinduced electron transfer reactions can be observed in BLUF domain proteins by TRIR and that there are a number of characteristic marker bands for radical intermediates states of both electron donor and acceptor. The absence of these modes from the dAppA BLUF spectrum argues against the formation of a significant population of radical intermediate states during its photocycle. TRIR of BLUF Domains PixD and BlsA. In Figure 6 the evolution of the TRIR spectra for two further BLUF domain proteins, PixD and BlsA, are shown. The ultrafast dynamics of PixD have been studied in detail by Kennis and co-workers through transient electronic spectroscopy. 38,45 They observed radical states in PixD. The photocycle of the recently characterized BlsA BLUF protein has been described by us. 50 Comparison of the TRIR spectra immediately shows distinct differences between them ( Figure 6). The most remarkable observation is the clear growth of the flavin radical in PixD on the tens of picoseconds time scale at 1528 cm −1 ( Figure 6A). In contrast to PixD, but in common with dAppA BLUF (Figure 2A), no such radical state is observed for BlsA ( Figure 6C). The results of the biexponential analysis of PixD at 1380 and 1548 cm −1 marker modes are included in Table 1. As expected for a sequential electron transfer reaction, the excited state decays more rapidly than the ground state is repopulated, although the difference is not as large as in Y21W AppA BLUF, consistent with the larger driving force in the latter. For BlsA the same marker modes show no difference in the excited state decay and ground state recovery kinetics, as was also found for dAppA BLUF (Table 1, Figure 2C). A further significant difference is that PixD has overall faster kinetics than BlsA and dAppA BLUF, as already noted by Gauden et al. 45 Thus, these observations confirm not only the importance of the electron transfer reaction in PixD but also that the observation of radical intermediate states is the exception rather than the rule for the four BLUF domains studied by ultrafast spectroscopy (BlrB also did not show the radical transient 51 ). Evidently different BLUF domains exhibit different excited state chemistry. An important question is the identity of the electron donor in PixD, usually assumed to be the adjacent tyrosine, Y8. No modes are observed in Figure 6A which can be clearly associated with a radical cation (a bleach does develop at 1630 cm −1, but this is not sufficient to assign the electron donor to Y8 as the flavin ring has modes in this range). To compare with Y21W the corresponding Y8W mutant of PixD was prepared. The effect of mutation is to dramatically accelerate the quenching of FAD* and also to increase the rate of ground state recovery ( Table 1). The EAS recovered for the TRIR data for PixD ( Figure 6A) and Y8W (SI Figure S6) are shown in Figure 7. Again, the most striking feature is the appearance in Y8W of the differential line shape 1625/1634 cm −1, obscuring the lower-frequency carbonyl bleach of the flavin ring. This agrees closely with observations in the Y21W AppA BLUF ( Figure 3a, 5), consistent with a Trp electron donor. However, no strong rise time is associated with this pair in Y8W, which we ascribe to the fact that the electron transfer reaction is too fast ( Table 1) for the rise to be resolved from the multiple contributions to the signal at this wavenumber. The absence of this characteristic pair of modes in PixD is therefore consistent with a Tyr electron donor rather than the more remote W91 residue, which also aligns with the considerably slower overall kinetics compared with those of Y8W. Finally the different final EAS for PixD and Y8W, with only the former showing residual features at 1700 and 1625 cm −1, indicate a long-lived perturbation of the protein structure characteristic of the photoactive form. 40 Modulating the Driving Force for Electron Transfer. One possible explanation for the failure to observe a radical spectrum in dAppA BLUF, BlsA and BlrB is that the rate of charge separation is small, and that of charge recombination is large, such that no radical population builds up. Charge separation as the rate-determining step would also be consistent with the identical kinetics observed for excited state decay and ground state recovery ( Figure 2C, Table 1). To probe this possibility the Tyr21 residue in dAppA BLUF was replaced with two unnatural amino acids, tyrosine fluorinated at positions 2 and 3 (labeled 2FY21 and 3FY21, respectively). This substitution is expected to give a minimum perturbation to the structure, leaving the surrounding residues unchanged. 58,60 However, it will have the effect of modulating the free energy driving the electron transfer reaction, G 0, due to the different redox potential of the three tyrosines. This will modify the ratedetermining charge separation step even in the case of slow charge separation and fast recombination. The other factor which will be altered by the Tyr/FTyr exchange is the Hbonding environment, through the pK a of the acidic proton. These parameters are listed in Table 2, where the formal potentials for the fluorinated tyrosine electron donors at physiological pH are reported for the first time. As can be seen, the effect of fluorine substitution alters the potential, but the position of the fluorine substituent has no significant effect. The locations and shape of the TRIR spectra for the 2FY21 and 3FY21 are very similar to those for dAppA BLUF (SI, Figure S7). This is consistent with a minimal perturbation to the Hbond environment around the flavin ring on exchange for the native Tyr. However, there is a distinct effect on the kinetics with both relaxation times recovered from the biexponential analysis becoming significantly longer for the FTyr proteins (Table 3). However, as was observed for dAppA BLUF, there is no difference between the excited state decay and ground state recovery kinetics, again requiring no significant population of an intermediate state. For the analysis of these data we turn to the classical Marcus expression for the rate constant of an electron transfer reaction: 68 Figure 7. Evolution-associated spectra for PixD and Y8W PixD. The kinetic scheme is A→B→C and the sequence of the EAS is black→ red→blue. a The redox potentials were measured at pH 7 (protonated form, data shown in Figure S7 in SI) but converted to standard (pH 1), assuming a reversible system. b The free energies were calculated according to eqs 2) and (3 assuming E(F/F − ) = −0.33 V and 2.5 eV for E S 1 the onset of the S 0 →S 1 transition and the unknown electrostatic factor has been assumed negligible. In 1 V el is the electronic coupling parameter between donor and acceptor and,, the reorganization energy, both of which depend in quite complex ways on the details of the local structure and environment, while is also a function of the redox potentials. 69−71 The other parameters have their usual meaning. This equation defines the Marcus curve, a parabola with maximum at −G 0 = separating the normal and Marcus inverted regions (Figure 8). The driving force for the forward electron transfer (charge separation, CS) reaction is given by: 70 the E(i) are the redox potentials of the respective couples, i, E S1 the 0−0 energy (in eV)of the electronic transition in FAD and G an electrostatic term, typically less than 0.1 eV. The corresponding expression for charge recombination (CR) is Thus, by varying the redox potential of the tyrosine the G 0 for CR and CS steps will be modified ( Figure 8A); the calculated G 0 are given in Table 2, where the corresponding data for Trp are included for reference to theY21W data. These data may be compared with the sequential scheme which adequately fits all data sets, where X is W or Y and the rate coefficients are now identified with electron transfer. For this scheme the decay of the FAD excited state will be faster than the recovery of the ground state if k CS > k CR. This is indeed the case whenever the radical intermediates are observed (Y21W, PixD, Y8W), as shown by the kinetics associated with their respective marker modes in Table 1, Figures 3C, and 6B. However, for dAppA BLUF, BlsA, and the two FTyr mutants, the excited state decay and ground state recovery kinetics overlap. This can only happen in the case that k CS < k CR, in which case the slow decay of FAD* by electron transfer determines the rate of ground state recovery, and the population of the intermediate will be negligible. For this to be the case requires k CS to decrease substantially between for example PixD and dAppA BLUF, with little change or an acceleration in k CR ; this would indicate high sensitivity of electron transfer in the BLUF domain to the structure around the flavin ring. In all cases the driving force for charge recombination is greater than for charge separation ( Table 2). In that case, k CS < k CR requires that the electron transfer is in the normal rather than the Marcus inverted region ( Figure 8). However, a consequence of being in the normal region is that an increase in driving force, such as is observed when Tyr is exchanged for FTyr, is predicted to result in an increased rate of charge separation ( Figure 8B). What is in fact observed is a decrease in that rate (a longer excited state decay, Table 3). Thus, the changes in kinetics observed when FTyr replaces Tyr21 in dAppA BLUF are not consistent with a simple excited state electron transfer quenching mechanism. This observation is consistent with the lack of any measurable population of radical intermediate states (Figure 2A). This conclusion applies also to BlsA and (on the basis of the optical spectroscopy 44 ) BlrB, but not to PixD, where a radical intermediate is clearly observed, as already reported. 38,43 Significantly, fluorotyrosine substitution was also used in PixD, and an increase in the excited state decay time was also reported, although the redox potentials were not available at that time. 43 The most straightforward interpretation of these data is that in AppA (and by extension BlsA and BlrB) charge separation to form a radical intermediate is not the primary step in the BLUF domain photocycle. This is a conclusion which has important implications for theoretical modeling of the BLUF domain. Further, the conclusion does not depend on the choice of, which has the effect of shifting the Marcus curve, and therefore the inverted region, to smaller G for a smaller ; this increases k CS, but does not alter the effect of making G more negative (Table 2), which is a predicted acceleration in k CS. This is true until k CS falls within the inverted region (for < 0.9 eV), but in that case k CS > k CR, which is not observed. Thus, the fluorotyrosine data support the conclusion that at least k CR ≫ k CS, and any radical state must have only a fleeting existence and not act as a metastable intermediate about which structural reorganization occurs. The observation of electron transfer reactions in PixD (and in Y21W and Y8W) may arise because the driving forces are quite different from those in Table 1, indicative of specific medium effects on the redox potentials and the relative geometry of donor and acceptor (which will modify V el ). Such changes could have the effect of placing the charge recombination in the inverted region, decreasing the rate of charge recombination, allowing observation of the intermediate ( Figure 8B). Such effects on electron transfer reactions in protein are intrinsically interesting but not obviously associated with BLUF domain function. set to 1.8 eV such that the maximum value for the rate constant is set to match the fastest observed decay time of 2 ps (in Y8W). The G 0 for charge separation and recombination are marked for dAppA BLUF and 2FY21. As G 0 becomes more negative in the normal region, the charge separation rate constant is expected to increase. A Nonradical Intermediate Pathway for the Primary Step in BLUF Domain Proteins. In the absence of unambiguous experimental evidence for radical intermediates in the primary photochemistry of dAppA BLUF (and at least two other BLUF proteins), it is necessary to propose an alternative pathway to the altered H-bond structure and red-shifted absorption known to be associated with photoactive BLUF domains. Both we and Domratcheva and co-workers previously considered the possibility of photoinduced tautomerization being sufficient to modify the structure of the key residue Q63. 29,48 In our model the electronic ground state supports equilibrium between the dominant keto and minor enol forms of Q63. 48,49 The present kinetic and spectroscopic data ( Figure 2) and recent calculations 33 suggest that a distribution of ground state structures exists, which may correspond with a distribution in the position of the keto−enol equilibrium. Upon electronic excitation of the flavin ring, the strength of the Hbonds formed between it and the surrounding amino acid residues (Y21, Q63, N45, W104) may be modified by changes in electron density in the flavin ring. It is proposed that this is sufficient to drive the position of the equilibrium to the enol form. The resulting rearrangement in the H-bond environment in the excited state occurs on a subpicosecond time scale. Ultrafast changes in the environment of the chromophore consistent with an excitation-induced change in H-bond structure have been observed in TRIR measurements and may be consistent with the tautomerization (Figure 2 and S1). 48,49 In the future TRIR measurements on isotope-labeled AppA will be undertaken to test this assignment, targeting Q63 and other residues involved in the H-bond structure around the flavin (Figure 1). Electronic relaxation of the reorganized structure back to the ground state leaves the flavin in an altered H-bond environment, one which is not directly accessible from the dark ground electronic state. This unstable form of the ground state can either relax back to the original ground state (the dominant pathway judged from the kinetic data) or populate the red-shifted state, for example through isomerization of the enol form of Q63 and subsequent H-bond reorganization. Although no radical intermediates were detected for dAppA BLUF or BlsA, and modulation of the driving force for electron transfer did not support a charge separation reaction, we cannot absolutely rule out a role for the electron transfer reaction coordinate. It is plausible that motion along the reactive coordinate leading to electron transfer results in excited state quenching, with the ultrafast charge recombination placing the BLUF domain in the unstable neutral ground state configuration, as proposed above. The precise pathway for the reorganization of this configuration may be revealed by the kind of QM/MM calculations that have begun to appear. 33,52,54 However, such calculations must be informed by the knowledge that radical intermediate states are, at most, a fleeting entity; thus, alternative pathways should be considered. ■ CONCLUSION The primary processes in the BLUF domain have been investigated by ultrafast TRIR spectroscopy. Marker modes were identified for the flavin excited and ground electronic states and for the flavin radical anion. High signal-to-noise 100 fs time resolution studies of the transient spectra and kinetics of dAppA BLUF did not reveal the formation of any new states which could be assigned to a radical (or any other) intermediate. Radical intermediates were however readily observed in the photoinactive Y21W mutant of dAppA BLUF, and the kinetics of the photoinduced electron transfer were characterized. Radical intermediates have subsequently been observed in a number of other photoinactive states of AppA BLUF (unpublished data), but there is no correlation between the observation of photoactivity and formation of a significant population of radical intermediates. The possibility that the population of radical intermediates was kinetically limited was tested by assuming that electron transfer does occur and modifying the thermodynamic driving force through unnatural amino acid substitution. Those data were also not consistent with photoinduced electron transfer being the primary process in dAppA BLUF. Thus, the present data for dAppA BLUF are in contradiction to the widely accepted mechanism for BLUF domain function, photoinduced electron transfer between Tyr21 and FAD* leading to a radical intermediate. The TRIR measurements were extended to the BLUF domain proteins PixD and BlsA. Radical formation was observed in PixD in good agreement with earlier observations. 45 However, no radical intermediates were found in BlsA, and a similar null result was recently reported in a fourth BLUF domain, BlrB. 51 These data suggest that the Y21-to-flavin electron transfer is a sensitive function of BLUF domain structure. However, although electron transfer intermediates are observed in PixD and in other photoinactive mutants of dAppA BLUF (and in its light-adapted form, unpublished data) there is no correlation between the rate of electron transfer and photoactivity. Consequently we considered alternative pathways to signaling state formation in the BLUF domain. It was proposed that electronic excitation is itself sufficient to induce H-bond reorganization in the flavin environment. This could arise through the modified electronic structure of the flavin excited state. There is existing experimental evidence for such a coupling between electronic excitation and changes in protein structure. 49 It was suggested that this change in H-bonding is sufficient to perturb the position of keto−enol tautomerization in the key Q63 residue, 29,48 and that this is the primary event which leads to the subsequent structural reorganization and ultimately to formation of the signaling state. * S Supporting Information Further experimental methods along with additional TRIR spectra and electrochemistry data. This material is available free of charge via the Internet at http://pubs.acs.org.
ANALYSIS OF PARENTAL AWARENESS OF TOILET TRAINING SUCCESS IN CHILDREN AGED 1-3 YEARS Background : The low success of toilet training in the community influenced the many mothers who do not train their children for chapters and bak in their place, as well as a lack of motivation from parents. The purpose of this study is the influence of parental awareness levels on the success of toilet training in children aged 1-3 years. Method : The design of this study is observational with a cross sectional approach. The population is all parents of years using simple random sampling techniques obtained a sample of 33 respondents. Independent variables of parental awareness level and dependent variables of toilet training success, with the Mann Whitney test. Result : The results showed that most of the respondents had a lesser level of awareness, which was 23 respondents (69.7%). And most respondents have the ability to toilet training late, which is 23 respondents (69.7%) Analysis : The results of the analysis obtained p-value 0.000 smaller than = 0.05, then p ≤ so that H1 is accepted which means there is an influence on the level of parental awareness on the success of toilet training in children aged 1-3 years in The Village of Parakan Trenggalek. Conclution : The level of parental awareness is able to increase the success of toilet training in children, because with the awareness of parents, parents want to motivate and train their children toilet training early on. INTRODUCTION Toilet training is an effort in training children to control BAK (Urination) and Defecation (Defecation) this ability must be carried out from an early age in the hope that the child is trained in controlling BAK (Urination) and DEFECATION (Defecation) at a predetermined place, and the child can reach the stage ofndirianism at this age (Rejeki., et al, 2019). This toilet training is taught to children ranging in age from 24 to 36 months of age. This age is the right time to be taught toilet training (Jacob., et al, 2016). According to WHO states that 58% of parents succeed in training toilet training when the child is 18 to 36 months old. And 42% of parents train toilet training when the child is more than 36 months old, so children have not succeeded in running toilet training when they are 3 years old. According to data from the Ministry of Health of the Republic of Indonesia in Indonesia, it is estimated that the number of children aged 1-3 years is 21,628,363 people. According to the national Household Health Survey (SKRT), it is estimated that the number of toddlers who have difficulty controlling BAK (Urination) and Defecation (Defecation) at the age of up to pre-school reaches 75 million children. Children who successfully run toileting 25% and 75% fail to run toileting. Pthere are children of preschool age (4-5 years) children who successfully run toileting 40% and 60% fail to run toileting (Kameliawati. F., et al, 2020). Based on research in East Java province in 2020 as many as 36.67% of toddler age (18-36 months) who were fully cared for by their mothers succeeded in learning toilet training, while at the age of toddlers (18-36 months) who were taken care of were not fully cared for by their mothers, 63.33% of them were unsuccessful in learning toilet training. Trenggalek Regency in 2020 obtained children who received good instrumental support with good toileting skills, namely 35.7%; for good instrumental support with sufficient toileting ability, namely 50.0% for instrumental support both with less toileting ability by 14.3%. Based on the results of a preliminary study conducted by researchers in July 2021 in Parakan Trenggalek Village to 10 parents of children aged 1-3 years, it was found that 7 respondents (70%) said that their children still have the habit of urinating (BAK) and defecating (DEFECATION) in any place sometimes by wearing diapers because mothers rarely provide motivation or train about toilet training. Meanwhile, 3 respondents (30%) said their children still have the habit of wearing diapers at night because parents are lazy to take their children to the bathroom while urinating. The success of toilet training conducted by mothers or babysitters is influenced by several factors, namely the factor of parents' knowledge of toilet training 69%, the factor of parental education towards toilet training 54%, and the factor of using diapers in children is still high at 78.3%. Where from the results of the study it was obtained that the percentage of respondents who behaved negatively was more who did not have toilet training. This is because mothers who are negative towards toilet training are not motivated to do toilet training because mothers think using pampers is more effective and instant. There are several factors that can trigger the failure of toilet training including lack of family knowledge, family readiness and the readinessof children or mothers to teach the correct toilet training (Harahap. M., et al, 2021). If the family is looking for information about teaching the correct toilet training to the child, then the family will be ready or able to teach toilet training appropriately, properly and correctly. On the other hand, if the family does not want to find information about teaching toilet training correctly, it will have bad consequences on children, one of which is that children can be emotional and arbitrary in daily activities. The role of the family is very important for the child to teach the correct use of the toilet. METHODS The design of this study is observational. This research is a quantitative research. The approach method used in this study is cross sectional. This study was conducted where all variables were taken only once. The population in this study was all parents of children aged 1-3 years in Parakan Trenggalek Village as many as 132 people, using probability sampling techniques with simple random sampling obtained a sample of 33 respondents. It was then tested using the Mann Whitney Rank Test = 0.05. An independent variable in this study is the Level of Parental Awareness. While the dependent variable is the Success of Toilet Training. The measuring instrument in this study used a questionnaire. Based on table 5. it is known that most respondents never got information about toilet training, which was 23 respondents (69.7%). Based on table 7. it is known that most respondents have a lack of awareness, which is 23 respondents (69.7%).,000 b p value = 0.000 < (0.05), so that H0 is rejected and H1 is accepted which means that there is an influence on the level of parental awareness on the success of toilet training in children aged 1-3 years in Parakan Trenggalek Village. A. Parental Awareness Level In Toilet Training Based on the results of the study, it is known that most of the respondents in Parakan Trenggalek Village have a level of awareness that is less than 23 (69.7%). A person's lack of awareness level will result in wrong knowledge, attitudes and actions as well. Consciousness is defined as a condition of being awake or able to understand as precisely as possible. Secondly, consciousness is defined as all the ideas, feelings, opinions, and so on that a person or group of people have. In addition, consciousness is defined as a person's understanding or knowledge of himself and his existence (Viendyasari. M, 2019). According to researchers the formation of consciousness can occur due to the presence of ideas, feelings, opinions that a person or group of people have. In addition, awareness also occurs because of a person's understanding or knowledge of himself and his existence. The factor affecting the level of consciousness is the age of the parents. The results showed that most of the 23 respondents (69.7%) aged 20-35 years had a low level of awareness of 16 respondents (48.5%). According to (Yasin. Z., et al, 2019) with the increase of age a person will experience changes in physical and psychological aspects and this change occurs due to the maturation of organ function, in the psychological and mental aspects of a person's thinking nerves become more mature and mature so as to affect a person's attitude in carrying out actions. According to researchers, age will affect a person's actions or attitudes, where the older a person is, the more mature knowledge will be in carrying out actions. Another factor that affects the level of awareness is education, the results showed that most of the respondents were 19 (57.6%) junior high school educated. According to (Hernanta. R., et al, 2017) the lower a person's education, the more difficult it is to receive information and in the end there is less knowledge because knowledge greatly affects a person's attitude in an action. In addition, a person's level of education will affect the mindset in the development of the information obtained and affect the respondent's consciousness so that the level of awareness becomes less. If a person has a low level of education it will hinder the improvement of one's consciousness. According to researchers the level of consciousness is closely related to education. Education affects the knowledge of a person's attitudes and actions so that the knowledge and insight gained is still low, where a person with low education will be less and less knowledgeable to determine good behavior. The next factor that affects the level of awareness is having or never getting information about toilet training. From the results of the study, it showed that most of the respondents, a total of 23 (69.7%) had never received information about toilet training. According to (Wahyu. R., et al, 2014) obtaining information can accelerate a person to acquire new knowledge. By providing information, it will increase people's knowledge, then knowledge will cause awareness and will eventually cause people to behave or have appropriate attitudes and actions because it is based on their own situation and not thoughts. Information is a form of stimulus that affects a person, both directly from the environment and indirectly. According to researchers, a person's knowledge can be influenced by whether or not the person is informed, the more a person gets information the more knowledge is gained. B. Success of Toilet Training in Children Aged 1-3 Years Based on the results of the study, it is known that almost all of the respondents in Parakan Trenggalek Village, a total of 23 (69.7%) have children in the category of not having succeeded in practicing toilet training. According to (Ernawati. D, 2021) In doing urination and defecation exercises in children requires preparation both physically, psychologically and intellectually, through these preparations it is hoped that children will be able to control defecation or urination on their own. And family support can also help increase the success of children's toilet training. According to researchers, the success in toilet training can be known from parents' knowledge and children's readiness. That apart from the knowledge of parents, the readiness of children in terms of physicality affects the teaching of toilet training. If in terms of physique, the child is not ready to do toilet training, then parents must be patient until their child is fully prepared to do toilet training. And the success of toilet training is also influenced by family support. Not only the parents, but also other family members. Because family support plays a fairly good role in the success of children's toilet training. Another factor that affects the success of toilet training is the age of the parents. Based on the results of the study showed that most of the respondents were 23 (69.7%) aged 20-35 years. According to (Yasin. Z., et al, 2019) with the increase of age a person will experience changes in physical and psychological aspects and this change occurs due to the maturation of organ function, in the psychological and mental aspects of a person's thinking nerves become more mature and mature so as to affect a person's attitude in carrying out actions. According to researchers, age will affect a person's actions or attitudes, where the older a person is, the more mature knowledge will be in carrying out actions. Another factor that affects the success of toilet training is the age of the child. Based on the results of the study showed that most of the respondents a total of 23 (69.7%) had children aged 13-24 months. According to (Sari., et al, 2020), toilet training is carried out on children aged 15-18 months, because the system is sufficiently developed and can already recognize signs from their bladder and abdomen. Children are also required to be able to control the muscles that open and close their bladder and anus. At the age stage of 18-36 months, the ability of the urethral sphincter to control the cravings and the ani sphincter to control the desire for defecation begins to develop. According to researchers, children's age will affect the success of toilet training, where the older the child is, the physical, psychological and intellectual readiness will mature. Because in reality what happens in the field of children after 1-2 years, they are still in the process of getting to know and practicing toilet training. They will start successful toilet training at the age of more than 2 years. Another factor that affects the success of toilet training is parental education, based on the results of research, most of the respondents of 19 (57.6%) have a junior high school education. According to (Hernanta. R., et al, 2017) the lower a person's education, the more difficult it is to receive information and in the end there is less knowledge because knowledge greatly affects a person's attitude in an action. In addition, a person's level of education will affect the mindset in the development of the information obtained and affect the respondent's consciousness so that the level of awareness becomes less. If a person has a low level of education it will hinder the improvement of one's consciousness. According to researchers, the level of education of parents also determines success. The level of education affects the mother's knowledge of the application of toilet training, if the mother's education is low, it will affect the knowledge of the application of toilet training so that it affects how to train early the application of toilet training. The next factor that affects the success of toilet training is having or never getting information about toilet training. Based on the results of the study, it showed that most of the respondents, a total of 23 (69.7%) never received information about toilet training. According to (Wahyu. R., et al, 2014) obtaining information can accelerate a person to acquire new knowledge. By providing information, it will increase people's knowledge, then knowledge will cause awareness and will eventually cause people to behave or have appropriate attitudes and actions because it is based on their own situation and not thoughts. Information is a form of stimulus that affects a person, both directly from the environment and indirectly. According to researchers, a person's knowledge can be influenced by whether or not the person is informed, the more a person gets information the more knowledge is gained. C. Effect of Parental Awareness Level on The Success of Toilet Training In Children Aged 1-3 Years Results from table 16. it is known that most of the respondents had a lack of awareness level of 23 (69.7%), of which 23 (69.7%) had children with the category of not having a problem l doing their toilet training. Hypothesis testing about the influence of parents' level of awareness on the success of toilet training in children aged 1-3 years in Parakan Trenggalek Village using the Mann-Whitney Test. The calculation results of the Mann-Whitney Test test obtained a probability value (p-value) of 0.000 less than (alpha) = 0.05. Based on these criteria, it shows that the null hypothesis is rejected and statistically there is an influence between the level of parental awareness on the success of toilet training in children aged 1-3 years significantly. A person's lack of awareness level will result in wrong knowledge, attitudes and actions as well. Consciousness is defined as a condition of being awake or able to understand as precisely as possible. Secondly, consciousness is defined as all the ideas, feelings, opinions, and so on that a person or group of people have. In addition, consciousness is defined as a person's understanding or knowledge ofhimself and his existence (Viendyasari. M, 2019). Parents' awareness of training and motivating their children can help increase the success of toilet training. If the child applies toilet training properly and successfully, the child also receives the benefits of the toilet training. One of the developments that children have to go through is toilet training. The success of toilet training depends on the child and family, mother or father. Toilet training is an important aspect in the development of children during the toddler age and mustreceive parental attention in urination and defecation. One of the efforts made by parents to improve the readiness of toilet training in children is to use good parenting andminimize the use of diapers (Mail. A., et al, 2018) According to researchers the formation of consciousness can occur due to the presence of ideas, feelings, opinions that a person or group of people have. In addition, awareness also occurs because of a person's understanding or knowledge of himself and his existence. The formation of increased awareness of parents in toilet training will be followed by the formation, change and ability of children in conducting toilet training. Thisis based on table 16. where most of the respondents had a lack of awareness about toilet training, namely 23 respondents (69.7%) where 23 respondents had not succeeded in toilet training. The benefits obtained by parents by introducing children to get used to the bathroom when tubs and defecation are that children can be independent, children can control when they want to urinate or defecate, not wet the bed anymore. This can be done by means of natural exercises that can create a child's independence. The method or stage of introducing toilet training can be in a simple way and is easy for children to understand. CONCLUSION Based on the results of the study, several conclusions can be formulated according to thetu juan of the study, namely the level of awareness of parents about toilet training in Parakan Trenggalek Village, most of the respondents had a lack of awareness level, namely a total of 23 respondents (69.7%). And the success of toilet training in children aged 1-3 years in Parakan Trenggalek Village, most of the respondents had children with the category of not succeeding in toilet training, namely a total of 23 respondents (69.7%). So that there is avariable level of parental awareness of the success of toilet training in children aged 1-3 years in Parakan Trenggalek Village. ACKNOWLEDGMENTS We would like to thank the Parakan Trenggalek Village for allowed to do research in there.
Coupling Quantification of Pulverization with Galvanostatic Cycling of Bulk Film Alloy-Type Anodes Alloy-type anodes, such as metallic antimony, demonstrate promise as alternative electrode materials for lithium-ion battery systems due to their high theoretical capacity of 660 mAh/g. However, antimony undergoes anisotropic volume expansion and multiple crystallographic phase transformations upon lithiation and delithiation, which often leads to fracture. This fracture can result in loss of electrical contact and poor cycling stability. These pulverization phenomena are often observed, primarily during delithiation, but are not quantified in terms of physical bulk material lost. To quantify the mass, size, volume, and density of pulverized regions in a bulk antimony film in a lithium system, we have developed a cell that enables the use of optical microscopy to capture videos of lithiation and delithiation. Using ImageJ and MATLAB® scripts developed for analysis, we have begun to quantify the amount of material lost as a function of deposition parameters.
package com.cart.shoppingapp.model; import android.os.Parcel; import android.os.Parcelable; import androidx.room.Ignore; import io.reactivex.annotations.NonNull; public class Product implements Parcelable { @NonNull private int id; @NonNull private String name; @NonNull private String caterogy; @NonNull private String price; @NonNull private String oldPrice; @NonNull private int stock; public Product(int id, String name, String caterogy, String price, String oldPrice, int stock) { this.id = id; this.name = name; this.caterogy = caterogy; this.price = price; this.oldPrice = oldPrice; this.stock = stock; } @Ignore public Product(Product product) { this.id = product.id; this.name = product.name; this.caterogy = product.caterogy; this.price = product.price; this.oldPrice = product.oldPrice; this.stock = product.stock; } protected Product(Parcel in) { id = in.readInt(); name = in.readString(); caterogy = in.readString(); price = in.readString(); oldPrice = in.readString(); stock = in.readInt(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCaterogy() { return caterogy; } public void setCaterogy(String caterogy) { this.caterogy = caterogy; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getOldPrice() { return oldPrice; } public void setOldPrice(String oldPrice) { this.oldPrice = oldPrice; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public static final Creator<Product> CREATOR = new Creator<Product>() { @Override public Product createFromParcel(Parcel in) { return new Product(in); } @Override public Product[] newArray(int size) { return new Product[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(id); parcel.writeString(name); parcel.writeString(caterogy); parcel.writeString(price); parcel.writeString(oldPrice); parcel.writeInt(stock); } }
Q: Was Pericles the only famous loss from the plague in Athens? Reading about the Plague of Athens in The Peloponnesian War by Thucydides, I was struck by this question. The plague killed an estimated 75,000 to 100,000 people in a city full of famous people, but I can only cite Pericles as a loss, along his wife and their two sons, Paralus and Xanthippus, and according to Plutarch, his sister too. Did any other known people die during that plague? By famous or known I mean someone whose name has been recorded with at least some deeds or profession. It may be a philosopher, an artist, a politician or a general, or someone related. This means that Myrtis is discarded. I already checked Wikipedia category 430 BC deaths onwards until 426 BC, with no results. A: I think the answer is that, failing the discovery of a new primary source, we will never know. Considering the sheer human cost of the Plague of Athens, its footprint in ancient literature does seem somewhat shallow (although who knows which texts have been lost over the centuries). For instance, one might consider the Plague and its effects on the people and society of ancient Athens and Attica to have been an example worthy of politico-philosophical discussion, but Plato mentions plague just once and even there not the Plague of Athens specifically: '... once she even put off the plague for ten years by telling the Athenians what sacrifices to make.' (Symposium, 201d) He also mentions the recent death of Pericles (Gorgias 503e), but not its cause. One should note though that Plato doesn't mention other momentous contemporary events, e.g. the Sicilian Expedition. You may wish to take a look at 'The Plague of Thebes, a Historical Epidemic in Sophocles’ Oedipus Rex'. However, we can of course speculate. For instance, it is conceivable that Herodotus died of the Plague (Wikipedia). The following people also died around the time of Plague (Wikipedia): Ion of Chios Protagoras Stesimbrotos of Thasos (Anaxagoras, who spent much of his life in Athens, died c. 428 but in Lampsacus in the Troad and thus could not have died of the Plague of Athens.) My methodology for searching through the works of Plato: I used the index of Plato: Complete Works edited by John M. Cooper (Hackett, 1997) to look for references to plague, Pericles and Sicily. I didn't check the works of other philosophers or ancient writers, although some (quick) online searches didn't turn up anything.
#ifndef CX_STACK_H #define CX_STACK_H #include "cixl/vec.h" struct cx; struct cx_type; struct cx_stack { struct cx *cx; struct cx_vec imp; unsigned int nrefs; }; struct cx_stack *cx_stack_new(struct cx *cx); struct cx_stack *cx_stack_ref(struct cx_stack *stack); void cx_stack_deref(struct cx_stack *stack); void cx_stack_dump(struct cx_vec *imp, FILE *out); struct cx_iter *cx_stack_iter_new(struct cx_stack *stack, ssize_t start, size_t end, int delta); struct cx_type *cx_init_stack_type(struct cx_lib *lib); #endif
#pragma once #include "Core/Common.h" #include "Core/ComponentArray.h" #include "Core/InterfaceTypes.h" namespace ScarletInterface { class ComponentManager { public: template<typename T> void RegisterComponent() { const char* typeName = typeid(T).name(); std::cout << "Registered: " << typeName << ", ID: " << (int)m_NextComponentType << std::endl; m_ComponentTypes.insert({ String(typeName), m_NextComponentType }); m_ComponentArrays.insert({ String(typeName), CreateRef<ComponentArray<T>>() }); m_NextComponentType++; } template<typename T> bool HasRegisterComponent() { const char* typeName = typeid(T).name(); return m_ComponentTypes.find(String(typeName)) != m_ComponentTypes.end(); } template<typename T> InterfaceComponent GetComponentType() { const char* typeName = typeid(T).name(); return m_ComponentTypes[String(typeName)]; } template<typename T> void AddComponent(const Interface& _Interface, T _Component) { this->GetComponentArray<T>()->InsertData(_Interface, _Component); } template<typename T> void RemoveComponent(const Interface& _Interface) { this->GetComponentArray<T>()->RemoveData(_Interface); } template<typename T> T& GetComponent(const Interface& _Interface) { return this->GetComponentArray<T>()->GetData(_Interface); } template<typename T> bool HasComponent(const Interface& _Interface) { return this->GetComponentArray<T>()->HasData(_Interface); } void DestroyInterface(const Interface& _Interface) { for (auto const& pair : m_ComponentArrays) { auto const& component = pair.second; component->DestroyInterface(_Interface); } } private: UnorderedMap<String, InterfaceComponent> m_ComponentTypes = {}; UnorderedMap<String, Ref<IComponentArray>> m_ComponentArrays = {}; InterfaceComponent m_NextComponentType = {}; template<typename T> Ref<ComponentArray<T>> GetComponentArray() { const char* typeName = typeid(T).name(); return std::static_pointer_cast<ComponentArray<T>>(m_ComponentArrays[String(typeName)]); } public: static Ref<ComponentManager> Create() { return CreateRef<ComponentManager>(); } }; }
<filename>trainer/trainer.py import numpy as np import torch from torchvision.utils import make_grid from base import BaseTrainer from utils import inf_loop, MetricTracker from cg_manipulation.cg_utils import optical_flow_to_motion from torchvision.utils import save_image class Trainer(BaseTrainer): """ Trainer class """ def __init__(self, model, criterion, metric_ftns, optimizer, config, device, data_loader, valid_data_loader=None, lr_scheduler=None, len_epoch=None): super().__init__(model, criterion, metric_ftns, optimizer, config) self.config = config self.device = device self.data_loader = data_loader if len_epoch is None: # epoch-based training self.len_epoch = len(self.data_loader) else: # iteration-based training self.data_loader = inf_loop(data_loader) self.len_epoch = len_epoch self.valid_data_loader = valid_data_loader self.do_validation = self.valid_data_loader is not None self.lr_scheduler = lr_scheduler self.log_step = int(np.sqrt(data_loader.batch_size)) self.train_metrics = MetricTracker('loss', *[m.__name__ for m in self.metric_ftns], writer=self.writer) self.valid_metrics = MetricTracker('loss', *[m.__name__ for m in self.metric_ftns], writer=self.writer) def _train_epoch(self, epoch): """ Training logic for an epoch :param epoch: Integer, current training epoch. :return: A log that contains average loss and metric in this epoch. """ self.model.train() self.train_metrics.reset() for batch_idx, (img_view_0, img_view_1, img_view_2, img_view_3, img_view_4, img_depth_0, img_depth_1, img_depth_2, img_depth_3, img_depth_4, img_motion_0, img_motion_1, img_motion_2, img_motion_3, img_motion_4, img_view_truth) in enumerate(self.data_loader): # data, target = data.to(self.device), target.to(self.device) truth = img_view_truth.to(self.device) view_0, depth_0, flow_0 = img_view_0.to(self.device), img_depth_0.to(self.device), img_motion_0.to(self.device) view_1, depth_1, flow_1 = img_view_1.to(self.device), img_depth_1.to(self.device), img_motion_1.to(self.device) view_2, depth_2, flow_2 = img_view_2.to(self.device), img_depth_2.to(self.device), img_motion_2.to(self.device) view_3, depth_3, flow_3 = img_view_3.to(self.device), img_depth_3.to(self.device), img_motion_3.to(self.device) view_4, depth_4, flow_4 = img_view_4.to(self.device), img_depth_4.to(self.device), img_motion_4.to(self.device) with torch.no_grad(): flow_0 = optical_flow_to_motion(flow_0, 5.37) flow_1 = optical_flow_to_motion(flow_1, 5.37) flow_2 = optical_flow_to_motion(flow_2, 5.37) flow_3 = optical_flow_to_motion(flow_3, 5.37) flow_4 = optical_flow_to_motion(flow_4, 5.37) self.optimizer.zero_grad() output = self.model(view_0, depth_0, flow_0, view_1, depth_1, flow_1, view_2, depth_2, flow_2, view_3, depth_3, flow_3, view_4, depth_4, flow_4) loss = self.criterion(output, truth, 0.1) loss.backward() self.optimizer.step() with torch.no_grad(): for i in range(0,1): save_image(output[i], "./data/Test/" + str(batch_idx * 1 + i) + "res.png") save_image(img_view_0[i], "./data/Test/" + str(batch_idx * 1 + i) + "origin.png") save_image(img_view_truth[i], "./data/Test/" + str(batch_idx * 1 + i) + "gtruth.png") self.writer.set_step((epoch - 1) * self.len_epoch + batch_idx) self.train_metrics.update('loss', loss.item()) for met in self.metric_ftns: self.train_metrics.update(met.__name__, loss) if batch_idx % self.log_step == 0: self.logger.debug('Train Epoch: {} {} Loss: {:.6f}'.format( epoch, self._progress(batch_idx), loss.item())) self.writer.add_image('input', make_grid(view_0.cpu(), nrow=8, normalize=True)) if batch_idx == self.len_epoch: break log = self.train_metrics.result() if self.do_validation: val_log = self._valid_epoch(epoch) log.update(**{'val_'+k : v for k, v in val_log.items()}) if self.lr_scheduler is not None: self.lr_scheduler.step() return log def _valid_epoch(self, epoch): """ Validate after training an epoch :param epoch: Integer, current training epoch. :return: A log that contains information about validation """ self.model.eval() self.valid_metrics.reset() with torch.no_grad(): for batch_idx, (img_view_0, img_view_1, img_view_2, img_view_3, img_view_4, \ img_depth_0, img_depth_1, img_depth_2, img_depth_3, img_depth_4, \ img_motion_0, img_motion_1, img_motion_2, img_motion_3, img_motion_4, img_view_truth) \ in enumerate(self.valid_data_loader): # data, target = data.to(self.device), target.to(self.device) truth = img_view_truth.to(self.device) view_0, depth_0, flow_0 = img_view_0.to(self.device), img_depth_0.to(self.device), img_motion_0.to(self.device) view_1, depth_1, flow_1 = img_view_1.to(self.device), img_depth_1.to(self.device), img_motion_1.to(self.device) view_2, depth_2, flow_2 = img_view_2.to(self.device), img_depth_2.to(self.device), img_motion_2.to(self.device) view_3, depth_3, flow_3 = img_view_3.to(self.device), img_depth_3.to(self.device), img_motion_3.to(self.device) view_4, depth_4, flow_4 = img_view_4.to(self.device), img_depth_4.to(self.device), img_motion_4.to(self.device) flow_0 = optical_flow_to_motion(flow_0, 5.37) flow_1 = optical_flow_to_motion(flow_1, 5.37) flow_2 = optical_flow_to_motion(flow_2, 5.37) flow_3 = optical_flow_to_motion(flow_3, 5.37) flow_4 = optical_flow_to_motion(flow_4, 5.37) output = self.model(view_0, depth_0, flow_0, view_1, depth_1, flow_1, view_2, depth_2, flow_2, view_3, depth_3, flow_3, view_4, depth_4, flow_4) loss = self.criterion(output, truth, 0.1) self.writer.set_step((epoch - 1) * len(self.valid_data_loader) + batch_idx, 'valid') self.valid_metrics.update('loss', loss.item()) for met in self.metric_ftns: self.valid_metrics.update(met.__name__, loss) self.writer.add_image('input', make_grid(view_0.cpu(), nrow=8, normalize=True)) # add histogram of model parameters to the tensorboard for name, p in self.model.named_parameters(): self.writer.add_histogram(name, p, bins='auto') return self.valid_metrics.result() def _progress(self, batch_idx): base = '[{}/{} ({:.0f}%)]' if hasattr(self.data_loader, 'n_samples'): current = batch_idx * self.data_loader.batch_size total = self.data_loader.n_samples else: current = batch_idx total = self.len_epoch return base.format(current, total, 100.0 * current / total)
/** * This runnable will send one upsert message per second using StandardObjectPublisher * * @author kanej * */ static private class SendOneMessagePerSec implements Runnable { private long counter = 0; private long max_counter = Long.MAX_VALUE; public SendOneMessagePerSec() {} public SendOneMessagePerSec(long max_counter) { this.max_counter = max_counter; } public void run() { while(true) { StandardMessageOnUpsert message = new StandardMessageOnUpsert(new Kind("one-per-sec-test"),new ObjectId(++counter)); StandardObjectPublisher.publishObject(EXAMPLE_TOPIC, message); try { Thread.currentThread().sleep(1000); } catch(Exception e) { e.printStackTrace(); } if ( counter > max_counter ) break; } boolean shutdown_result = StandardObjectPublisher.shutdown(); System.out.println("Shutdown publisher result = "+shutdown_result); } }
The effect of public funding on research output: the New Zealand Marsden Fund ABSTRACT We estimate the impact of the NZ Marsden Fund on research success, by comparing the subsequent performance of funded and unfunded researchers. We control for selection bias using the Marsden panel rankings. We find that funding is associated with a 6%15% increase in publications and an 11%22% increase in citation-weighted papers for research teams. We attempt to pin down the dynamic structure of this effect by looking at the research trajectories of individual researchers, but this model yields inconsistent results. We find no systematic evidence that Marsden panel rankings are predictive of subsequent success.
def system_has_access_control(username, security_marking): data_hash = hashlib.sha224('{0!s}'.format(security_marking).encode('utf-8')).hexdigest() key = 'system_has_access_control-{0!s}-{1!s}'.format(username, data_hash) data = cache.get(key) if data is not None: return data else: results = get_system_access_control_plugin().has_access(username, security_marking) cache.set(key, results, timeout=settings.GLOBAL_SECONDS_TO_CACHE_DATA) return results
CNN Poll: 88% say Rep. Stark should not apologize David Edwards and Muriel Kane Published: Friday October 19, 2007 del.icio.us Print This Email This CNN is reporting that 88% of those voting in their Friday morning online poll say there is no reason Rep. Pete Stark (D-CA) should apologize for remarks blasting President Bush on the floor of the House of Representatives. In the course of debate on expanding SCHIP funding, Stark told Congressional Republicans (video, story), "You don't have money to fund the war or children. But you're going to spend it to blow up innocent people, if we could get enough kids to grow old enough for you to send to Iraq to get their head's blow off for the president's amusement." House Minority Leader Rep. John Boehner quickly issued a statement demanding a retraction and apology, in which he said, "Our troops in Iraq are fighting against al-Qaeda and other radical jihadists hellbent on killing the people we are sent here to represent. Congressman Stark’s statement dishonors not only the Commander-in-Chief, but the thousands of courageous men and women of America’s armed forces who believe in their mission and are putting their lives on the line for our freedom and security." There has predictably been support for Stark on the left, along with endorsements of Boehner's outrage on the right. A thread at the liberal Democratic Underground site asked members to "DU this CNN poll!" but also expressed amusement that the sentiment in favor of Stark was already running at 87% to 13%. One commenter suggested that "the poll has been Freeped, it was 89% before, now it's 87%," to which another replied "amazing what consitutes freeping these daze." "Freeping" is a reference to the practice initiated at the conservative Free Republic message board some years ago of sending members to overwhelm online polls with indications of support for right-wing policies and politicians. Liberal sites like Democratic Underground and Daily Kos then began countering this strategy with similar exhortations of their own. The lopsided result of the CNN poll is striking, especially since the mainstream consensus seems to be that even if Stark was just shooting his mouth off, as he has many times in the past, he may have crossed a line of bad taste in suggesting that the president actively enjoys seeing American soldiers' heads blown off. For example, when Keith Olbermann indicated on his program that he felt there was "something refreshing about his at least refusal to back down," guest Jonathan Alter responded that Stark's comments were "silly and counterproductive, and the best thing for him to do would be to apologize and move on." MSNBC's "First Read" blog eneumerated Stark's history of inflammatory remarks: "On another occasion he publicly questioned the provenance of J.C. Watts' offspring, comments that so enraged the former Oklahoma quarterback that he angrily marched up to Stark on the House floor and had to be restrained from beating the living daylights out of the 70-something liberal. Also, during a gun control debate some years back, Stark suggested that opponents of gun control were phallically challenged. And not too long ago, he called a GOP opponent on the Ways and Means committee a 'fruitcake' during committee proceedings." The following video is from CNN's American Morning, broadcast on October 19, 2007. Advertisements Want a gift card? Participate in a presidential frontrunner survey!
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LENGTH_LONGEST_STRICT_BITONIC_SUBSEQUENCE{ static int f_gold ( int arr [ ] , int n ) { HashMap < Integer , Integer > inc = new HashMap < Integer , Integer > ( ) ; HashMap < Integer , Integer > dcr = new HashMap < Integer , Integer > ( ) ; int len_inc [ ] = new int [ n ] ; int len_dcr [ ] = new int [ n ] ; int longLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int len = 0 ; if ( inc . containsKey ( arr [ i ] - 1 ) ) len = inc . get ( arr [ i ] - 1 ) ; len_inc [ i ] = len + 1 ; inc . put ( arr [ i ] , len_inc [ i ] ) ; } for ( int i = n - 1 ; i >= 0 ; i -- ) { int len = 0 ; if ( dcr . containsKey ( arr [ i ] - 1 ) ) len = dcr . get ( arr [ i ] - 1 ) ; len_dcr [ i ] = len + 1 ; dcr . put ( arr [ i ] , len_dcr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) if ( longLen < ( len_inc [ i ] + len_dcr [ i ] - 1 ) ) longLen = len_inc [ i ] + len_dcr [ i ] - 1 ; return longLen ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{78}); param0.add(new int[]{-6,-18,-48,58,-54,76,80,-56,86,58,-86,-86,-88,32,12,58,58,-16,86,-24,84,86,36,18,30,-32,-4,-36,-72,-4,42,94}); param0.add(new int[]{0,1}); param0.add(new int[]{92,26,72,8,66,28,34,61,28}); param0.add(new int[]{-86,-82,-76,-68,-66,-64,-62,-56,-48,-42,-38,-30,-22,-18,-10,-10,-4,-2,4,28,42,44,50,50,56,58,60,76,82,86,86,98}); param0.add(new int[]{0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,1,0,0,0,0,1,0}); param0.add(new int[]{3,4,8,9,12,13,16,19,23,25,29,31,34,36,38,41,42,47,49,50,51,51,58,63,66,70,73,74,75,75,75,76,76,80,82,83,83,84,86,89,90,91,91,95,96}); param0.add(new int[]{4,-76,60,48,-14,72}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{66,80,79,72,1,67,20,67,32,40,22,64,58,67,10,21,37,49}); List<Integer> param1 = new ArrayList<>(); param1.add(0); param1.add(18); param1.add(1); param1.add(5); param1.add(25); param1.add(17); param1.add(44); param1.add(3); param1.add(17); param1.add(15); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
Superconducting Bandpass Modulator With 2.23-GHz Center Frequency and 42.6-GHz Sampling Rate This paper presents a superconducting bandpass modulator for direct analog-to-digital conversion of radio frequency signals in the gigahertz range. The design, based on a 2.23-GHz microstrip resonator and a single flux quantum comparator, exploits several advantages of superconducting electronics: the high quality factor of resonators, the fast switching speed of the Josephson junction, natural quantization of voltage pulses, and high circuit sensitivity. The modulator test chip includes an integrated acquisition memory for capturing output data at sampling rates up to 45 GHz. The small size (256 b) of the acquisition memory limits the frequency resolution of spectra based on standard fast Fourier transforms. Output spectra with enhanced resolution are obtained with a segmented correlation method. At a 42.6-GHz sampling rate, the measured SNR is 49 dB over a 20.8-MHz bandwidth, and a full-scale (FS) input is 17.4 dBm. At a 40.2-GHz sampling rate, the measured in-band noise is 57 dBFS over a 19.6-MHz bandwidth. The modulator test chip contains 4065 Josephson junctions and dissipates 1.9 mW at = 4.2 K.
<gh_stars>1-10 /******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2001 * * by the XIPHOPHORUS Company http://www.xiph.org/ * * * ******************************************************************** function: key psychoacoustic settings for 44.1/48kHz last mod: $Id: psych_44.h,v 1.7 2001/12/22 09:40:40 xiphmont Exp $ ********************************************************************/ /* preecho trigger settings *****************************************/ static vorbis_info_psy_global _psy_global_44[3]={ {8, /* lines per eighth octave */ /*{990.f,990.f,990.f,990.f}, {-990.f,-990.f,-990.f,-990.f}, -90.f, {0.f,0.f,0.f,0.f}, {-0.f,-0.f,-0.f,-0.f}, -90.f,*/ {30.f,30.f,30.f,34.f}, {-990.f,-990.f,-990.f,-990.f}, -90.f, -6.f, 0, }, {8, /* lines per eighth octave */ /*{990.f,990.f,990.f,990.f}, {-990.f,-990.f,-990.f,-990.f}, -90.f,*/ {26.f,26.f,26.f,30.f}, {-90.f,-90.f,-90.f,-90.f}, -90.f, -6.f, 0, }, {8, /* lines per eighth octave */ {26.f,26.f,26.f,30.f}, {-26.f,-26.f,-26.f,-30.f}, -90.f, -6.f, 0, } }; /* noise compander lookups * low, mid, high quality ****************/ static float _psy_compand_44_short[3][NOISE_COMPAND_LEVELS]={ /* sub-mode Z */ { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, /* 7dB */ 8.f, 9.f,10.f,11.f,12.f,13.f,14.f, 15.f, /* 15dB */ 16.f,17.f,18.f,19.f,20.f,21.f,22.f, 23.f, /* 23dB */ 24.f,25.f,26.f,27.f,28.f,29.f,30.f, 31.f, /* 31dB */ 32.f,33.f,34.f,35.f,36.f,37.f,38.f, 39.f, /* 39dB */ }, /* mode_Z nominal */ { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 6.f, /* 7dB */ 7.f, 7.f, 7.f, 7.f, 6.f, 6.f, 6.f, 7.f, /* 15dB */ 7.f, 8.f, 9.f,10.f,11.f,12.f,13.f, 14.f, /* 23dB */ 15.f,16.f,17.f,17.f,17.f,18.f,18.f, 19.f, /* 31dB */ 19.f,19.f,20.f,21.f,22.f,23.f,24.f, 25.f, /* 39dB */ }, /* mode A */ { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 5.f, 5.f, /* 7dB */ 6.f, 6.f, 6.f, 5.f, 4.f, 4.f, 4.f, 4.f, /* 15dB */ 4.f, 4.f, 5.f, 5.f, 5.f, 6.f, 6.f, 6.f, /* 23dB */ 7.f, 7.f, 7.f, 8.f, 8.f, 8.f, 9.f, 10.f, /* 31dB */ 11.f,12.f,13.f,14.f,15.f,16.f,17.f, 18.f, /* 39dB */ } }; static float _psy_compand_44[3][NOISE_COMPAND_LEVELS]={ /* sub-mode Z */ { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, /* 7dB */ 8.f, 9.f,10.f,11.f,12.f,13.f,14.f, 15.f, /* 15dB */ 16.f,17.f,18.f,19.f,20.f,21.f,22.f, 23.f, /* 23dB */ 24.f,25.f,26.f,27.f,28.f,29.f,30.f, 31.f, /* 31dB */ 32.f,33.f,34.f,35.f,36.f,37.f,38.f, 39.f, /* 39dB */ }, /* mode_Z nominal */ { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, /* 7dB */ 8.f, 9.f,10.f,11.f,12.f,12.f,13.f, 13.f, /* 15dB */ 13.f,14.f,14.f,14.f,15.f,15.f,15.f, 15.f, /* 23dB */ 16.f,16.f,17.f,17.f,17.f,18.f,18.f, 19.f, /* 31dB */ 19.f,19.f,20.f,21.f,22.f,23.f,24.f, 25.f, /* 39dB */ }, /* mode A */ { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, /* 7dB */ 8.f, 8.f, 7.f, 6.f, 5.f, 4.f, 4.f, 4.f, /* 15dB */ 4.f, 4.f, 5.f, 5.f, 5.f, 6.f, 6.f, 6.f, /* 23dB */ 7.f, 7.f, 7.f, 8.f, 8.f, 8.f, 9.f, 10.f, /* 31dB */ 11.f,12.f,13.f,14.f,15.f,16.f,17.f, 18.f, /* 39dB */ } }; /* tonal masking curve level adjustments *************************/ static vp_adjblock _vp_tonemask_adj_longblock[6]={ /* adjust for mode zero */ {{ { 10, 10, 5, }, /*63*/ { 10, 10, 5, }, { 10, 10, 5, }, /* 125 */ { 10, 10, 5, }, { 10, 10, 5, }, /* 250 */ { 10, 10, 5, }, { 10, 10, 5, }, /* 500 */ { 10, 10, 5, }, { 10, 10, 5, }, /* 1000 */ { 10, 10, 5, }, { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, /* 2000 */ { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, /* 4000 */ { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, /* 8000 */ { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, { 16, 16, 14, 12, 12, 15, 15, 15, 15, 15, 10}, /* 16000 */ }}, /* adjust for mode two */ {{ { 10, 10, 5, }, /*63*/ { 10, 10, 5, }, { 10, 10, 5, }, /* 125 */ { 10, 10, 5, }, { 10, 10, 5, }, /* 250 */ { 10, 10, 5, }, { 10, 10, 5, }, /* 500 */ { 10, 10, 5, }, { 10, 10, 5, }, /* 1000 */ { 10, 10, 5, }, { 0, }, /* 2000 */ { 0, }, { 10, 5, 5, }, /* 4000 */ { 10, 10, 5, }, { 10, 10, 7, 5, }, /* 8000 */ { 10, 10, 7, 7, 5, 5, 10, 10, 10, 5, }, { 16, 16, 14, 8, 8, 8, 10, 10, 10, 5, }, /* 16000 */ }}, /* adjust for mode four */ {{ { 10, 5, 5, }, /*63*/ { 10, 5, 5, }, { 10, 5, 5, }, /* 125 */ { 10, 5, 5, }, { 10, 5, 5, }, /* 250 */ { 10, 5, 5, }, { 10, 5, 5, }, /* 500 */ { 10, 5, 5, }, { 10, 5, 5, }, /* 1000 */ { 10, 5, 5, }, { 0, }, /* 2000 */ { 0, }, { 0, }, /* 4000 */ { 10, 5, 5, }, { 10, 10, 7, 5, }, /* 8000 */ { 10, 10, 7, 5, 5, 5, 10, 10, 10, 5, }, { 16, 16, 14, 8, 8, 8, 10, 10, 10, 5, }, /* 16000 */ }}, /* adjust for mode six */ {{ { 10, 5, 5, }, /*63*/ { 10, 5, 5, }, { 10, 5, 5, }, /* 125 */ { 10, 5, 5, }, { 10, 5, 5, }, /* 250 */ { 10, 5, 5, }, { 10, 5, 5, }, /* 500 */ { 10, 5, 5, }, { 10, 5, 5, }, /* 1000 */ { 10, 5, 5, }, { 0, }, /* 2000 */ { 0, }, { 0, }, /* 4000 */ { 10, 5, 5, }, { 10, 10, 7, 5, }, /* 8000 */ { 10, 10, 7, 5, 5, 5, 5, 5, 5, }, { 12, 10, 10, 5, 5, 5, 5, 5, 5, }, /* 16000 */ }}, /* adjust for mode eight */ {{ { 0, }, /*63*/ { 0, }, { 0, }, /* 125 */ { 0, }, { 0, }, /* 250 */ { 0, }, { 0, }, /* 500 */ { 0, }, { 0, }, /* 1000 */ { 0, }, { 0, }, /* 2000 */ { 0, }, { 0, }, /* 4000 */ { 0, }, { 0, }, /* 8000 */ { 0, }, { 5, 5, 5, 5, 5, 5, 5, }, /* 16000 */ }}, /* adjust for mode ten */ {{ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*63*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*125*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*250*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*500*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*1000*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*2000*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*4000*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*8000*/ { 0, 0, 0, -5,-10,-10,-10,-15,-15,-15,-15}, { 0, 0, 0, 0, 0, -5, -5,-10,-15,-15,-15}, /*16000*/ }}, }; static vp_adjblock _vp_tonemask_adj_otherblock[6]={ /* adjust for mode zero */ {{ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, /*63*/ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, /*125*/ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, /*250*/ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, { 5, 5, 5, 0, -5, -5, -5, -5, -5, -5, -5}, /*500*/ { 5, 5, 5, 0, -5, -5, -5, -5, -5, -5, -5}, { 5, 5, 5, }, /*1000*/ { 5, 5, 5, }, { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, /*2000*/ { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, /*4000*/ { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, /*8000*/ { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, { 16, 16, 14, 12, 12, 15, 15, 15, 15, 15, 10}, /*16000*/ }}, /* adjust for mode two */ {{ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, /*63*/ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, /*125*/ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, /*250*/ { 0, 0, 0, 0,-10,-10,-10,-10,-10,-10,-10}, { 5, 5, 5, 0, -5, -5, -5, -5, -5, -5, -5}, /*500*/ { 5, 5, 5, 0, -5, -5, -5, -5, -5, -5, -5}, { 10, 10, 5, }, /* 1000 */ { 10, 10, 5, }, { 0, }, /* 2000 */ { 0, }, { 0, }, /* 4000 */ { 10, 5, 5, }, { 10, 10, 7, 5, }, /* 8000 */ { 10, 10, 7, 7, 5, 5, 10, 10, 10, 5, }, { 16, 16, 14, 8, 8, 8, 10, 10, 10, 5, }, /* 16000 */ }}, /* adjust for mode four */ {{ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*63*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*125*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*250*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*500*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 5, 5, 5, }, /* 1000 */ { 5, 5, 5, }, { 0, }, /* 2000 */ { 0, }, { 0, }, /* 4000 */ { 10, 5, 5, }, { 10, 10, 7, 5, }, /* 8000 */ { 10, 10, 7, 5, 5, 5, 10, 10, 10, 5, }, { 16, 16, 14, 8, 8, 8, 10, 10, 10, 5, }, /* 16000 */ }}, /* adjust for mode six */ {{ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*63*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*125*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*250*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*500*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 5, 5, 5, }, /* 1000 */ { 5, 5, 5, }, { 0, }, /* 2000 */ { 0, }, { 0, }, /* 4000 */ { 10, 5, 5, }, { 10, 10, 7, 5, }, /* 8000 */ { 10, 10, 7, 5, 5, 5, 5, 5, 5, }, { 12, 10, 10, 5, 5, 5, 5, 5, 5, }, /* 16000 */ }}, /* adjust for mode eight */ {{ {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, /*63*/ {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, /*125*/ {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, /*250*/ {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, /*500*/ {-10,-10,-10,-15,-15,-15,-15,-20,-20,-20,-20}, { 0,-10,-10,-15,-15,-15,-15,-15,-15,-15,-15}, { 0,-10,-10,-15,-15,-15,-15,-15,-15,-15,-15}, { 0, }, /* 2000 */ { 0, }, { 0, }, /* 4000 */ { 0, }, { 0, }, /* 8000 */ { 0, }, { 5, 5, 5, 5, 5, 5, 5, }, /* 16000 */ }}, /* adjust for mode ten */ {{ { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, /*63*/ { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, /*125*/ { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, /*250*/ { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, /*500*/ { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, /*1000*/ { 0, 0, 0, -5,-15,-20,-20,-20,-20,-20,-20}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*2000*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*4000*/ { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, { 0, 0, 0, -5,-15,-15,-15,-15,-15,-15,-15}, /*8000*/ { 0, 0, 0, -5,-10,-10,-10,-15,-15,-15,-15}, { 0, 0, 0, 0, 0, -5, -5,-10,-15,-15,-15}, /*16000*/ }}, }; static vp_adjblock _vp_peakguard[6]={ /* zero */ {{ {-14,-16,-18,-19,-24,-24,-24,-24,-24,-24,-24},/*63*/ {-14,-16,-18,-19,-24,-24,-24,-24,-24,-24,-24}, {-14,-16,-18,-19,-24,-24,-24,-24,-24,-24,-24},/*125*/ {-14,-16,-18,-19,-24,-24,-24,-24,-24,-24,-24}, {-14,-16,-18,-19,-24,-24,-24,-24,-24,-24,-24},/*250*/ {-14,-16,-18,-19,-24,-24,-24,-24,-24,-24,-24}, {-10,-10,-10,-10,-16,-16,-18,-20,-22,-24,-24},/*500*/ {-10,-10,-10,-10,-14,-14,-16,-20,-22,-24,-24}, {-10,-10,-10,-10,-14,-14,-16,-20,-22,-24,-24},/*1000*/ {-10,-10,-10,-10,-14,-14,-16,-20,-22,-24,-24}, {-10,-10,-10,-10,-14,-14,-16,-20,-22,-24,-24},/*2000*/ {-10,-10,-10,-12,-16,-16,-16,-20,-22,-24,-24}, {-10,-10,-10,-12,-16,-16,-16,-20,-22,-24,-24},/*4000*/ {-10,-10,-10,-12,-12,-14,-16,-18,-22,-24,-24}, {-10,-10,-10,-10,-10,-14,-16,-18,-22,-24,-24},/*8000*/ {-10,-10,-10,-10,-10,-14,-16,-18,-22,-24,-24}, {-10,-10,-10,-10,-10,-12,-16,-18,-22,-24,-24},/*16000*/ }}, /* two */ {{ {-14,-20,-20,-20,-26,-30,-30,-30,-30,-30,-30},/*63*/ {-14,-20,-20,-20,-26,-30,-30,-30,-30,-30,-30}, {-14,-20,-20,-20,-26,-30,-30,-30,-30,-30,-30},/*125*/ {-14,-20,-20,-20,-26,-30,-30,-30,-30,-30,-30}, {-14,-20,-20,-20,-26,-30,-30,-30,-30,-30,-30},/*250*/ {-14,-20,-20,-20,-26,-30,-30,-30,-30,-30,-30}, {-14,-20,-20,-20,-26,-30,-30,-30,-30,-30,-30},/*500*/ {-10,-10,-10,-10,-14,-14,-14,-20,-26,-30,-30}, {-10,-10,-10,-10,-14,-14,-14,-20,-22,-30,-30},/*1000*/ {-10,-10,-10,-10,-14,-14,-16,-20,-22,-30,-30}, {-10,-10,-10,-10,-14,-14,-16,-20,-22,-30,-30},/*2000*/ {-10,-10,-10,-10,-14,-14,-16,-20,-22,-30,-30}, {-10,-10,-10,-10,-14,-14,-16,-20,-22,-30,-30},/*4000*/ {-10,-10,-10,-10,-10,-11,-12,-13,-22,-30,-30}, {-10,-10,-10,-10,-10,-11,-12,-13,-22,-30,-30},/*8000*/ {-10,-10,-10,-10,-10,-10,-10,-11,-22,-30,-30}, {-10,-10,-10,-10,-10,-10,-10,-10,-20,-30,-30},/*16000*/ }}, /* four */ {{ {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40},/*63*/ {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40}, {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40},/*125*/ {-14,-20,-20,-20,-20,-20,-20,-30,-32,-32,-40}, {-14,-20,-20,-20,-20,-20,-20,-30,-32,-32,-40},/*250*/ {-14,-20,-20,-20,-20,-20,-20,-24,-32,-32,-40}, {-14,-20,-20,-20,-20,-20,-20,-24,-32,-32,-40},/*500*/ {-10,-10,-10,-10,-14,-16,-20,-24,-26,-32,-40}, {-10,-10,-10,-10,-14,-16,-20,-24,-22,-32,-40},/*1000*/ {-10,-10,-10,-10,-14,-16,-20,-24,-22,-32,-40}, {-10,-10,-10,-10,-14,-16,-20,-24,-22,-32,-40},/*2000*/ {-10,-10,-10,-10,-14,-16,-20,-24,-22,-32,-40}, {-10,-10,-10,-10,-14,-14,-16,-20,-22,-32,-40},/*4000*/ {-10,-10,-10,-10,-10,-11,-12,-13,-22,-32,-40}, {-10,-10,-10,-10,-10,-11,-12,-13,-22,-32,-40},/*8000*/ {-10,-10,-10,-10,-10,-10,-10,-11,-22,-32,-40}, {-10,-10,-10,-10,-10,-10,-10,-10,-20,-32,-40},/*16000*/ }}, /* six */ {{ {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40},/*63*/ {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40}, {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40},/*125*/ {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40}, {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40},/*250*/ {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40}, {-14,-20,-20,-20,-26,-32,-32,-32,-32,-32,-40},/*500*/ {-14,-14,-14,-16,-20,-22,-24,-24,-28,-32,-40}, {-14,-14,-14,-16,-20,-22,-24,-24,-28,-32,-40},/*1000*/ {-14,-14,-14,-16,-20,-22,-24,-24,-28,-32,-40}, {-14,-14,-16,-20,-24,-26,-26,-28,-30,-32,-40},/*2000*/ {-14,-14,-16,-20,-24,-26,-26,-28,-30,-32,-40}, {-14,-14,-16,-20,-24,-26,-26,-28,-30,-32,-40},/*4000*/ {-14,-14,-14,-20,-22,-22,-24,-24,-26,-32,-40}, {-14,-14,-14,-18,-20,-20,-24,-24,-24,-32,-40},/*8000*/ {-14,-14,-14,-18,-20,-20,-24,-24,-24,-32,-40}, {-14,-14,-14,-18,-20,-20,-22,-24,-24,-32,-40},/*16000*/ }}, /* eight */ {{ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*63*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*88*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*125*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*170*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*250*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*350*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*500*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*700*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*1000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*1400*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*2000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*2800*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*4000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*5600*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*8000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*11500*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-40,-40},/*16600*/ }}, /* ten */ {{ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*63*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*88*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*125*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*170*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*250*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*350*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*500*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*700*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*1000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*1400*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*2000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*2800*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*4000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*5600*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*8000*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*11500*/ {-14,-20,-24,-26,-32,-34,-36,-38,-40,-44,-46},/*16600*/ }} }; static int _psy_noisebias_long[11][17]={ /*63 125 250 500 1k 2k 4k 8k 16k*/ {-20,-20,-18,-18,-18,-16,-14, -8, -6, -2, 0, 2, 3, 3, 4, 4, 10}, {-20,-20,-20,-20,-20,-20,-20,-10, -6, -2, -2, -2, 1, 1, 2, 2, 4}, {-20,-20,-20,-20,-20,-20,-20,-10, -6, -2, -3, -3, -1, -1, 0, 1, 2}, {-20,-20,-20,-20,-20,-20,-20,-10, -6, -2, -3, -3, -1, -1, 0, 1, 2}, {-20,-20,-20,-20,-20,-20,-20,-10, -6, -3, -4, -4, -2, -1, 0, 0, 2}, {-20,-20,-20,-20,-20,-20,-20,-18,-10, -4, -6, -6, -3, -2, -2, -2, 0}, {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -8, -8, -7, -7, -6, -6, -4}, {-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-16,-16,-14,-12,-10,-10, -8}, {-24,-24,-24,-24,-24,-24,-24,-20,-20,-20,-20,-20,-16,-16,-14,-14,-10}, {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-24,-24,-24}, {-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-46}, }; static int _psy_noisebias_impulse[11][17]={ /*63 125 250 500 1k 2k 4k 8k 16k*/ {-20,-20,-20,-20,-20,-18,-14,-10,-10, -2, 2, 2, 2, 2, 2, 3, 6}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -2, -2, -2, -2, 2}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0}, {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, -2}, {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}, {-30,-30,-30,-30,-30,-30,-24,-20,-10,-12,-14,-14,-10, -9, -8, -6, -4}, {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10, -8}, {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14}, {-34,-34,-34,-34,-30,-30,-30,-30,-30,-26,-26,-26,-26,-22,-20,-20,-16}, {-40,-40,-40,-40,-40,-40,-40,-40,-40,-36,-36,-36,-36,-36,-36,-30,-30}, {-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50}, }; static int _psy_noisebias_other[11][17]={ /*63 125 250 500 1k 2k 4k 8k 16k*/ {-20,-20,-20,-20,-20,-18,-14,-10, -6, -2, 2, 2, 3, 3, 4, 4, 10}, {-26,-26,-26,-26,-26,-22,-20,-14,-10, -2, -2, -2, 1, 1, 2, 2, 4}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -2, -3, -3, -1, -1, 0, 1, 2}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -1, -1, 0, 1, 2}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -2, -1, 0, 0, 2}, {-30,-30,-30,-30,-30,-30,-24,-20,-10, -4, -6, -6, -3, -2, -2, -2, 0}, {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -8, -8, -7, -7, -6, -6, -4}, {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10, -8}, {-34,-34,-34,-34,-30,-30,-30,-20,-20,-20,-20,-20,-16,-16,-14,-14,-10}, {-40,-40,-40,-40,-40,-40,-40,-30,-30,-30,-30,-30,-30,-24,-24,-24,-24}, {-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-46}, }; static int _psy_noiseguards_short[33]={ 2,2,-1, 4,4,-1, 4,4,15, 4,4,15, 4,4,15, 4,4,15, 4,4,15, 4,4,15, 4,4,15, 4,4,15, 4,4,15, }; static int _psy_noiseguards_long[33]={ 10,10,100, 10,10,100, 10,10,100, 10,10,100, 10,10,100, 10,10,100, 10,10,100, 10,10,100, 10,10,100, 10,10,100, 10,10,100, }; static double _psy_tone_masteratt[11]={ 3.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., }; static double _psy_tone_masterguard[11]={ -18.,-24.,-24.,-24.,-26.,-40.,-40.,-40.,-45.,-45.,-45., }; static double _psy_tone_suppress[11]={ -10.,-20.,-20.,-20.,-30.,-30.,-40.,-40.,-45.,-45.,-45., }; static double _psy_tone_0dB[11]={ 95.,95.,95.,95.,95.,105.,105.,105.,105.,105.,105., }; static double _psy_noise_suppress[11]={ -0.,-24.,-24.,-24.,-24.,-30.,-40.,-40.,-45.,-45.,-45., }; static int _psy_ehmer_bandlimit[11]={ 0,0,0,0,4,4,30,30,30,30,30, }; static vorbis_info_psy _psy_info_template={ {-1},-110.,-140., /* tonemask att,guard,suppr,curves peakattp,curvelimitp,peaksettings*/ 0.f, -40.f,-40.f, {{{0.}}}, 1, 0, {{{0.}}}, /*noisemaskp,supp, low/high window, low/hi guard, minimum */ 1, -0.f, .5f, .5f, 0,0,0, {-1},{-1},105.f,{{-1,-1,{{-1,-1,-1,-1}}}} }; /* ath ****************/ static double _psy_ath_floater[11]={ -100.,-100.,-100.,-100.,-100.,-100.,-105.,-105.,-105.,-110.,-120., }; static double _psy_ath_abs[11]={ -110.,-110.,-120.,-140.,-140.,-140.,-140.,-140.,-140.,-140.,-150., }; static float ATH_Bark_dB[][27]={ { 0.f, 15.f, 15.f, 15.f, 11.f, 10.f, 8.f, 7.f, 7.f, 7.f, 6.f, 2.f, 0.f, 0.f, -2.f, -5.f, -6.f, -6.f, -4.f, 4.f, 14.f, 20.f, 19.f, 17.f, 30.f, 60.f, 70.f, }, { 0.f, 15.f, 15.f, 15.f, 11.f, 10.f, 8.f, 7.f, 7.f, 7.f, 6.f, 2.f, 0.f, 0.f, -2.f, -5.f, -6.f, -6.f, -4.f, 0.f, 2.f, 6.f, 5.f, 5.f, 15.f, 30.f, 50.f, }, { 0.f, 15.f, 15.f, 15.f, 11.f, 10.f, 8.f, 7.f, 7.f, 7.f, 6.f, 2.f, 0.f, 0.f, -3.f, -5.f, -6.f, -6.f, -4.5f, -4.f, 2.f, 6.f, 5.f, 5.f, 15.f, 20.f, 40.f, } }; /* stereo ****************/ static int _psy_stereo_point_dB_44[11]={3, 3, 2, 2, 1, 0, 0, 0, 0, 0, 0}; static double _psy_stereo_point_kHz_44[2][11]={ {4., 6., 6., 6., 10., 6., 6., 4., 4., 4., 4.}, {6., 6., 6., 10., 10., 6., 6., 4., 4., 4., 4.} }; /* lowpass **************/ static double _psy_lowpass_44[11]={ 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. }; /* management noise offset */ static double _bm_max_noise_offset[11]={ 1.,2.,3.,3.,4.,4.,4.,4.,4.,4.,4. };
Minimizing Mistreatment by Female Adults: The Influence of Gender-Based Social Categories and Personality Differences on Attitudes about Child Sexual Abuse Abstract We investigated the effects of gender-based social categories (i.e., men, women, boys, and girls) on attitudes about child sexual abuse and individual differences in the use of such categories. In four experiments, we systematically varied perpetrators sex and victims sex. In three investigations, we assessed personality variables potentially related to participants use of these social categories. Across these four experiments, we varied perpetrator-victim relationships (teacher-student, neighbors) and victims ages. In experiment one, individuals had the least negative attitude about child sexual abuse involving adult female neighbors and eighth grade male neighbors. In experiment two, we replicated this effect with fifth grade victims and demonstrated that attitudes were moderated by individual differences in intolerance of ambiguity. In experiment three, we again replicated the aforementioned effect while (a) extending this finding to teacher-student relationships with eighth grade adolescent victims and (b) demonstrating the need for cognition was a moderator. In experiment four, we again replicated (a) our perpetrator sex/victim sex interactive effect and (b) need for cognition moderation while also demonstrating that these effects were applicable to fifth grade victims. Methodological limitations as well as clinical and policy implications (e.g., attenuating the underreporting incidents of child sexual abuse) are discussed.
Field The subject matter disclosed herein relates to an electronic gaming device. More specifically, the disclosure relates to providing one or more stacking functionalities on a gaming device. Information The gaming industry has numerous casinos located both worldwide and in the United States. Further, numerous gaming entities have one or more online (e.g., non-physical) locations on the internet and/or worldwide web and/or mobile gaming applications (e.g., hand held computers, notebook, etc.). A client of a casino or other gaming entity can gamble via various games of chance. For example, craps, roulette, baccarat, blackjack, and electronic games (e.g., a slot machine) are games of chance where a person may gamble on an outcome. Paylines of an electronic gaming device (e.g., a slot machine) are one way utilized to determine when predetermined winning symbol combinations are aligned in a predetermined pattern to form a winning combination. A winning event occurs when the player successfully matches the predetermined winning symbols in one of the predetermined patterns. A player's entertainment while playing one or more games may be enhanced by utilizing one or more stacking functionalities on the gaming device. By increasing the player's entertainment level, the player's enjoyment of the game may be enhanced, which may increase a player's game playing period.
OpenCL performance portability for generalpurpose computation on graphics processor units: an exploration on cryptographic primitives The modern trend toward heterogeneous manycore architectures has led to high architectural diversity in both high performance and highend embedded systems. To effectively exploit the computational resources of such a wide range of architectures, programming languages and APIs such as OpenCL have become increasingly popular. Although OpenCL provides functional code portability and the ability to fine tune the application to the target hardware, providing performance portability is still an open problem. Thus, many research works have investigated the optimization of specific combinations of application and target platform. In this paper, we aim at leveraging the experience obtained in the implementation of algorithms from the cryptography domain to provide a set of guidelines for modern manycore heterogeneous architecture performance portability and to establish a base on which domainspecific languages and compiler transformations could be built in the near future. We study algorithmic choices and the effect of compiler transformations on three representative applications in the chosen domain on a set of seven target platforms. To estimate how well the application fits the architecture, we define a metric of computational intensity both for the architecture and the application implementation. Besides being useful to compare either different implementation or algorithmic choices and their fitness to a specific architecture, it can also be useful to the compiler to guide the code optimization process. Copyright © 2014 John Wiley & Sons, Ltd.
Frameworks provide a tool for rapid application development, but often accrue technical debt as rapidly as they allow you to create functionality. Technical debt is created when maintainability isn't a purposeful focus of the developer. Future changes and debugging become costly, due to a lack of unit testing and structure. Here's how to begin structuring your code to achieve testability and maintainability - and save you time. We'll Cover (loosely) DRY Dependency Injection Interfaces Containers Unit Tests with PHPUnit Let's begin with some contrived, but typical code. This might be a model class in any given framework. This code will work, but needs improvement: This isn't testable. We're relying on the $_SESSION global variable. Unit-testing frameworks, such as PHPUnit, rely on the command-line, where $_SESSION and many other global variables aren't available. global variable. Unit-testing frameworks, such as PHPUnit, rely on the command-line, where and many other global variables aren't available. We're relying on the database connection. Ideally, actual database connections should be avoided in a unit-test. Testing is about code, not about data. This code isn't as maintainable as it could be. For instance, if we change the data source, we'll need to change the database code in every instance of App::db used in our application. Also, what about instances where we don't want just the current user's information? An Attempted Unit Test Here's an attempt to create a unit test for the above functionality. Let's examine this. First, the test will fail. The $_SESSION variable used in the User object doesn't exist in a unit test, as it runs PHP in the command line. Second, there's no database connection setup. This means that, in order to make this work, we will need to bootstrap our application in order to get the App object and its db object. We'll also need a working database connection to test against. To make this unit test work, we would need to: Setup a config setup for a CLI (PHPUnit) run in our application Rely on a database connection. Doing this means relying on a data source separate from our unit test. What if our test database doesn't have the data we're expecting? What if our database connection is slow? Relying on an application being bootstrapped increases the overhead of the tests, slowing the unit tests down dramatically. Ideally, most of our code can be tested independent of the framework being used. So, let's get down to how we can improve this. Keep Code DRY The function retrieving the current user is unnecessary in this simple context. This is a contrived example, but in the spirit of DRY principles, the first optimization I'm choosing to make is to generalize this method. This provides a method we can use across our entire application. We can pass in the current user at the time of the call, rather than passing that functionality off to the model. Code is more modular and maintainable when it doesn't rely on other functionalities (such as the session global variable). However, this is still not testable and maintainable as it could be. We're still relying on the database connection. Dependency Injection Let's help improve the situation by adding some Dependency Injection. Here's what our model might look like, when we pass the database connnection into the class. Now, the dependencies of our User model are provided for. Our class no longer assumes a certain database connection, nor relies on any global objects. At this point, our class is basically testable. We can pass in a data-source of our choice (mostly) and a user id, and test the results of that call. We can also switch out separate database connections (assuming that both implement the same methods for retrieving data). Cool. Let's look at what a unit test might look like for that. I've added something new to this unit test: Mockery. Mockery lets you "mock" (fake) PHP objects. In this case, we're mocking the database connection. With our mock, we can skip over testing a database connection and simply test our model. Want to learn more about Mockery? In this case, we're mocking a SQL connection. We're telling the mock object to expect to have the select , where , limit and get methods called on it. I am returning the Mock, itself, to mirror how the SQL connection object returns itself ( $this ), thus making its method calls "chainable". Note that, for the get method, I return the database call result - a stdClass object with the user data populated. This solves a few problems: We're testing only our model class. We're not also testing a database connection. We're able to control the inputs and outputs of the mock database connection, and, therefore, can reliably test against the result of the database call. I know I'll get a user ID of "1" as a result of the mocked database call. We don't need to bootstrap our application or have any configuration or database present to test. We can still do much better. Here's where it gets interesting. Interfaces To improve this further, we could define and implement an interface. Consider the following code. There's a few things happening here. First, we define an interface for our user data source. This defines the addUser() method. Next, we implement that interface. In this case, we create a MySQL implementation. We accept a database connection object, and use it to grab a user from the database. Lastly, we enforce the use of a class implementing the UserInterface in our User model. This guarantees that the data source will always have a getUser() method available, no matter which data source is used to implement UserInterface . Note that our User object type-hints UserInterface in its constructor. This means that a class implementing UserInterface MUST be passed into the User object. This is a guarantee we are relying on - we need the getUser method to always be available. What is the result of this? Our code is now fully testable. For the User class, we can easily mock the data source. (Testing the implementations of the datasource would be the job of a separate unit test). class, we can easily mock the data source. (Testing the implementations of the datasource would be the job of a separate unit test). Our code is much more maintainable. We can switch out different data sources without having to change code throughout our application. We can create ANY data source. ArrayUser, MongoDbUser, CouchDbUser, MemoryUser, etc. We can easily pass any data source to our User object if we need to. If you decide to ditch SQL, you can just create a different implementation (for instance, MongoDbUser ) and pass that into your User model. We've simplified our unit test, as well! We've taken the work of mocking a database connection out completely. Instead, we simply mock the data source, and tell it what to do when getUser is called. But, we can still do better! Containers Consider the usage of our current code: Our final step will be to introduce containers. In the above code, we need to create and use a bunch of objects just to get our current user. This code might be littered across your application. If you need to switch from MySQL to MongoDB, you'll still need to edit every place where the above code appears. That's hardly DRY. Containers can fix this. A container simply "contains" an object or functionality. It's similar to a registry in your application. We can use a container to automatically instantiate a new User object with all needed dependencies. Below, I use Pimple, a popular container class. I've moved the creation of the User model into one location in the application configuration. As a result: We've kept our code DRY. The User object and the data store of choice is defined in one location in our application. We can switch out our User model from using MySQL to any other data source in ONE location. This is vastly more maintainable. Final Thoughts Over the course of this tutorial, we accomplished the following: Kept our code DRY and reusable Created maintainable code - We can switch out data sources for our objects in one location for the entire application if needed Made our code testable - We can mock objects easily without relying on bootstrapping our application or creating a test database Learned about using Dependency Injection and Interfaces, in order to enable creating testable and maintainable code Saw how containers can aid in making our application more maintainable I'm sure you've noticed that we've added much more code in the name of maintainability and testability. A strong argument can be made against this implementation: we're increasing complexity. Indeed, this requires a deeper knowledge of code, both for the main author and for collaborators of a project. However, the cost of explanation and understanding is far out-weighed by the extra overall decrease in technical debt. The code is vastly more maintainable, making changes possible in one location, rather than several. Being able to unit test (quickly) will reduce bugs in code by a large margin - especially in long-term or community-driven (open-source) projects. Doing the extra-work up front will save time and headache later. Resources You may include Mockery and PHPUnit into your application easily using Composer. Add these to your "require-dev" section in your composer.json file: You can then install your Composer-based dependencies with the "dev" requirements: Learn more about Mockery, Composer and PHPUnit here on Nettuts+. For PHP, consider using Laravel 4, as it makes exceptional use of containers and other concepts written about here. Thanks for reading!
// currently hardcoded to do up to 10 tries to get a row from each class, which can be impossible for certain wrong sampling ratios private static Frame sampleFrameStratified(final Frame fr, Vec label, Vec weights, final float[] sampling_ratios, final long seed, final boolean debug, int count, String[] quasibinomialDomain) { if (fr == null) return null; assert(label.isCategorical()); assert(sampling_ratios != null && sampling_ratios.length == label.domain().length); final int labelidx = fr.find(label); assert(labelidx >= 0); final int weightsidx = fr.find(weights); final boolean poisson = false; Frame r = new MRTask() { @Override public void map(Chunk[] cs, NewChunk[] ncs) { final Random rng = getRNG(seed); for (int r = 0; r < cs[0]._len; r++) { if (cs[labelidx].isNA(r)) continue; rng.setSeed(cs[0].start()+r+seed); final int label = (int)cs[labelidx].at8(r); assert(sampling_ratios.length > label && label >= 0); int sampling_reps; if (poisson) { throw H2O.unimpl(); } else { final float remainder = sampling_ratios[label] - (int)sampling_ratios[label]; sampling_reps = (int)sampling_ratios[label] + (rng.nextFloat() < remainder ? 1 : 0); } for (int i = 0; i < ncs.length; i++) { if (cs[i] instanceof CStrChunk) { for (int j = 0; j < sampling_reps; ++j) { ncs[i].addStr(cs[i],cs[0].start()+r); } } else { for (int j = 0; j < sampling_reps; ++j) { ncs[i].addNum(cs[i].atd(r)); } } } } } }.doAll(fr.types(), fr).outputFrame(fr.names(), fr.domains()); Vec lab = r.vecs()[labelidx]; Vec wei = weightsidx != -1 ? r.vecs()[weightsidx] : null; double[] dist; if(quasibinomialDomain != null){ dist = wei != null ? new ClassDistQuasibinomial(quasibinomialDomain).doAll(lab, wei).dist() : new ClassDistQuasibinomial(quasibinomialDomain).doAll(lab).dist(); } else { dist = wei != null ? new ClassDist(lab).doAll(lab, wei).dist() : new ClassDist(lab).doAll(lab).dist(); } if (dist == null) return fr; if (debug) { double sumdist = ArrayUtils.sum(dist); Log.info("After stratified sampling: " + sumdist + " rows."); for (int i=0; i<dist.length;++i) { Log.info("Class " + r.vecs()[labelidx].factor(i) + ": count: " + dist[i] + " sampling ratio: " + sampling_ratios[i] + " actual relative frequency: " + (float)dist[i] / sumdist * dist.length); } } if (ArrayUtils.minValue(dist) == 0 && count < 10) { Log.info("Re-doing stratified sampling because not all classes were represented (unlucky draw)."); r.remove(); return sampleFrameStratified(fr, label, weights, sampling_ratios, seed+1, debug, ++count, quasibinomialDomain); } Frame shuffled = shuffleFramePerChunk(r, seed+0x580FF13); r.remove(); return shuffled; }
. Depression is one of the most common diseases worldwide, with more than 350 million people affected. Although many patients initially show a good response to antidepressant therapy, they tend to suffer from residual symptoms that affect their social, cognitive, physical and psychological domains. Residual symptoms severely impact the patient's global functioning and quality of life and increase the risk of recurrence. In the last few years, pharmacological research has focused on drugs able to mitigate the severity of depressive symptoms and to control persistent cognitive and functional disabilities. A novel antidepressant, with a multimodal mechanism of action that combines the classical inhibition of serotonin transporter (SERT) with the modulation of serotonin receptor activity, is vortioxetine. Its efficacy in the treatment of depression and cognitive symptoms has been well established in numerous randomized clinical trials. Three cases of patients with depressive disorders are presented, in which vortioxetine treatment improved depressive symptoms, cognitive symptoms and overall patient functioning. These anecdotal experiences suggest that vortioxetine, in addition to controlling all symptoms of depression, including cognitive symptoms, provides functional benefits in patients with depressive disorders.
"Crystal-clear" liquid-liquid transition in a tetrahedral fluid. For a model known to exhibit liquid-liquid transitions, we examine how varying the bond orientational flexibility affects the stability of the liquid-liquid transition relative to that of the crystal phases. For very rigidly oriented bonds, the crystal is favored over all amorphous phase transitions. We find that increasing the bond flexibility decreases both the critical temperature Tc for liquid-liquid phase separation and the melting temperature Tm. The effect of increasing flexibility is much stronger for melting, so that the distance between Tc and Tm progressively reduces and inverts sign. Under these conditions, a "naked" liquid-liquid critical point bulges out in the liquid phase and becomes accessible, without the possibility of crystallization. These results confirm that a crystal-clear, liquid-liquid transition can occur as a genuine, thermodynamically stable phenomenon for tetrahedral coordinated particles with flexible bond orientation, but that such a transition is hidden by crystallization when bonds are highly directional.
Klezmakers play music you can dance to – J. Lots of great ideas have come out of Silicon Valley garages: Apple Computer. Hewlett-Packard. Add the Klezmakers to that list. Nearly three years ago, the band came together in a Palo Alto garage. Some of its members had played together informally for a few years, and some had been in other bands, but all were searching for a way to express their love for klezmer music with their musical talent. The group will perform from 1 to 2 p.m. on the Jessica Saal Memorial main stage. It’s the traditional flavor of klezmer that keeps the band and its audiences engaged. “Many of us are Ashkenazi Jews, we have one non-Jewish member and another who converted to Judaism,” says Moise. “This isn’t just Ashkenazi music — it’s music from Eastern Europe. Although they’re serious about their music and strive for perfection, they definitely have fun performing music people can dance to. “ We do strive to be musical, we strive to get the craft and the music right,” says clarinet player Tom Belick. “The goal is to get to rehearsal on time, play together, and have fun,” adds Moise. They also have a sense of humor about their work, evident in the camaraderie that playing in a band together brings. “There’s no detail too small to discuss again,” says Kirschner, eliciting laughter from his fellow band members. In recent years, klezmer has gained in popularity. After a trail blazed by the popular Klezmatics, the Klezmakers are riding the wave of this revival. The Klezmakers and klezmer dancing led by Bruce Bierman will take place from 1 to 2 p.m. on the Jessica Saal Memorial main stage.
package com.fansolomon.bookingService.entity; import com.baomidou.mybatisplus.annotation.TableId; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDateTime; /** * <p> * 入场券规格表 * </p> * * @author zhangyuting * @since 2020-09-29 */ @Data @EqualsAndHashCode(callSuper = false) @ApiModel(value="TicketSpec对象", description="入场券规格表") public class TicketSpec implements Serializable { private static final long serialVersionUID = 6737185133792773468L; @TableId private String id; @ApiModelProperty(value = "券外键id") private String itemId; @ApiModelProperty(value = "规格名称") private String name; @ApiModelProperty(value = "库存") private Integer stock; @ApiModelProperty(value = "折扣力度") private BigDecimal discounts; @ApiModelProperty(value = "优惠价") private BigDecimal priceDiscount; @ApiModelProperty(value = "原价") private BigDecimal priceNormal; @ApiModelProperty(value = "创建时间") private LocalDateTime createdTime; @ApiModelProperty(value = "创建用户id") private String createdUser; @ApiModelProperty(value = "更新时间") private LocalDateTime updatedTime; @ApiModelProperty(value = "更新用户id") private String updatedUser; }
import os from dataclasses import dataclass from auth_middleware import JwtConfig # type: ignore from flask import current_app from core import Config as CoreConfig @dataclass(frozen=True) class Config(CoreConfig): aws_region = os.environ.get("AWS_REGION", "us-east-1") service_name = os.environ.get("SERVICE_NAME", "model-service") jwt_secret_key: str = os.environ.get("JWT_SECRET_KEY", "test-key") pennsieve_api_host: str = os.environ.get("PENNSIEVE_API_HOST", "api.pennsieve.net") gateway_internal_host: str = os.environ.get( "GATEWAY_INTERNAL_HOST", "api.pennsieve.net" ) max_record_count_for_property_deletion: int = int( os.environ.get("MAX_RECORD_COUNT_FOR_PROPERTY_DELETION", 100000) ) victor_ops_url: str = os.environ.get( "VICTOR_OPS_URL", "https://alert.victorops.com/integrations/generic/20131114/alert/a0e9a781-de39-4e2a-98be-111fae93d247", ) jobs_sqs_queue_id: str = os.environ.get("JOBS_SQS_QUEUE_ID", "jobs-sqs-queue-id") @property def jwt_config(self) -> JwtConfig: return JwtConfig(self.jwt_secret_key) @classmethod def from_app(cls) -> "Config": """ Get the currently loaded config for a request from the Flask app context. """ return current_app.config["config"]
Reliability Analysis for Radiographic Measurement of Limb Length Discrepancy: Full-Length Standing Anteroposterior Radiograph Versus Scanogram Patients with limb length discrepancy (LLD) often have associated angular deformities requiring a standing full-length radiograph of the lower limb in addition to a scanogram. The purpose of our study was to determine the intraobserver and interobserver reliability of measuring LLD with both techniques, using computed radiography. The LLD was measured on 70 supine scanograms and standing anteroposterior radiographs of the lower extremity by 5 blinded observers on 2 separate occasions. Intraclass correlation coefficient (ICC) and mean absolute difference (in millimeters) was calculated to assess intraobserver and interobserver reliability and found to be excellent for both radiographic techniques. Intraobserver ICC and mean absolute difference was 0.975 to 0.995 and 1.5 to 2.6 mm for scanogram and 0.939 to 0.996 and 1.5 to 4.6 mm for the standing radiograph, respectively. Repeated measurements for both radiographic studies were within 5 mm of the first measurement greater than 90% and within 10 mm greater than 95% of times. Interobserver ICC and mean absolute difference was 0.979 and 2.6 mm for scanogram and 0.968 and 3.0 mm for the standing radiograph. The reliability was excellent irrespective of age, sex, and underlying diagnosis other than Blount disease, which had good reliability. A standing anteroposterior radiograph of the lower extremity should be the imaging modality of choice when evaluating patients with limb length inequality who may have angular deformities because it allows a comprehensive evaluation of the extremity and is as reliable as a scanogram for measuring LLD. This approach may decrease the radiation exposure and financial burden involved in assessing patients with unequal limb lengths.
package com.firstpenguin.tinyurl.restservice.services.generators; import com.firstpenguin.tinyurl.restservice.exception.SequenceGenerationException; import lombok.Getter; import lombok.Setter; public abstract class URLSequenceGenerator implements Runnable { @Setter String prefix; @Setter String postfix; @Setter @Getter Integer seqLen; @Setter char[] allowedChars; @Setter boolean abort; public abstract String getSequence() throws SequenceGenerationException; }
<reponame>kaydoh/scale """Defines the URLs for the RESTful queue services""" from django.conf.urls import url import queue.views urlpatterns = [ url(r'^load/$', queue.views.JobLoadView.as_view(), name='load_view'), url(r'^queue/status/$', queue.views.QueueStatusView.as_view(), name='queue_status_view'), ]
BAGHDAD – The Islamic State of Iraq, the insurgent group that serves as a front for al-Qaeda in Iraq, announced Sunday that it had replaced two senior leaders killed in a raid last month. A statement, circulated on the Internet, was another indication that the group was seeking to reconstitute itself after a series of defeats that American and Iraqi military officials have described as a crucial setback for the group. Officials say scores of its fighters have recently been killed or arrested and that the network, long the most formidable and resilient militant group, is in disarray. The statement said his deputy would be Abu Abdallah al-Husseini al-Qurashi. “We implore God to help them make the right decisions,” the statement continued. The men’s names are almost certainly noms de guerre. Mohammed al-Alawi, a spokesman for Iraq’s minister of national security affairs, Sharwan al-Waili, said he had not yet seen the statement and had no immediate information on the two men. The men replace Abu Omar al-Baghdadi and Abu Hamza al-Muhajir, an Egyptian known as Abu Ayyub al-Masri, who were killed in an American and Iraqi raid near Tikrit. Al-Muhajir also served as the group’s military commander. In a statement Friday, the group said that position would be filled by Al-Nasser Lideen Allah Abu Suleiman. Despite American and Iraqi contentions that the movement has been dealt a perhaps crippling blow, insurgents have proven resilient enough to keep launching coordinated and far-reaching attacks. Last week, more than 100 people were killed and hundreds more were wounded in a series of assaults that included ambushes of police and military checkpoints in Baghdad and devastating bombings in three cities.
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_utils.h" #include "third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h" #include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h" namespace blink { LayoutUnit CalculateOutOfFlowStaticInlineLevelOffset( const ComputedStyle& container_style, const NGBfcOffset& origin_bfc_offset, const NGExclusionSpace& exclusion_space, LayoutUnit child_available_inline_size) { const TextDirection direction = container_style.Direction(); // Find a layout opportunity, where we would have placed a zero-sized line. NGLayoutOpportunity opportunity = exclusion_space.FindLayoutOpportunity( origin_bfc_offset, child_available_inline_size); LayoutUnit child_line_offset = IsLtr(direction) ? opportunity.rect.LineStartOffset() : opportunity.rect.LineEndOffset(); LayoutUnit relative_line_offset = child_line_offset - origin_bfc_offset.line_offset; // Convert back to the logical coordinate system. As the conversion is on an // OOF-positioned node, we pretent it has zero inline-size. LayoutUnit inline_offset = IsLtr(direction) ? relative_line_offset : child_available_inline_size - relative_line_offset; // Adjust for text alignment, within the layout opportunity. LayoutUnit line_offset = LineOffsetForTextAlign( container_style.GetTextAlign(), direction, opportunity.rect.InlineSize()); if (IsLtr(direction)) inline_offset += line_offset; else inline_offset += opportunity.rect.InlineSize() - line_offset; // Adjust for the text-indent. inline_offset += MinimumValueForLength(container_style.TextIndent(), child_available_inline_size); return inline_offset; } } // namespace blink
<reponame>eanson023/minzuchess-spring-boot<filename>src/main/java/work/eanson/controller/UserMainController.java package work.eanson.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import work.eanson.util.Context; /** * @author eanson */ @Controller @RequestMapping(value = "user_main", method = {RequestMethod.GET, RequestMethod.POST}) @Api(tags = "用户主要信息管理") public class UserMainController extends AbstractController { /** * 去我的主页 * * @param mv * @return */ @RequiresAuthentication @RequestMapping("home") @ApiOperation("去用户主页") public ModelAndView toMyUserInfo(ModelAndView mv) { Context context = new Context("get_user_main"); context.put("is_me", true); //没有 try { csgo.service(context); } catch (Exception e) { e.printStackTrace(); String referer = httpServletRequestThreadLocal.get().getHeader("Referer"); mv.setViewName("redirect:" + referer); return mv; } mv.setViewName("user_info"); //人称 mv.addObject("person", "我"); mv.addObject("who", "me"); //数据 mv.addObject("user_main", context.getResult().getData()); return mv; } /** * 去别人的主页 * * @param mv * @param username 用户名 * @return */ @RequestMapping("others/{username}") @ApiOperation("去别人主页") public ModelAndView toOtherUserInfo(ModelAndView mv, @PathVariable("username") String username) { mv.setViewName("user_info"); Context context = new Context("get_user_main"); context.put("is_me", false); context.put("username", username); try { csgo.service(context); } catch (Exception e) { e.printStackTrace(); String referer = httpServletRequestThreadLocal.get().getHeader("Referer"); if (referer == null) { referer = "/"; } mv.setViewName("redirect:" + referer); return mv; } //人称 mv.addObject("person", "他"); mv.addObject("who", "others"); //数据 mv.addObject("user_main", context.getResult().getData()); return mv; } /** * 公开棋盘 或者取消公开 */ @PostMapping("public_chess/{code}") @RequiresAuthentication @ResponseBody @ApiOperation("公开棋盘码") public void publicOrCancelChessBoard(@PathVariable("code") String code) throws Exception { Context context = new Context("public_or_cancel_chess_board"); context.put("code", code); csgo.service(context); } }
An Advanced Infrared Remote Control Sensor A monolithic infrared remote control sensor has been developed using a conventional bipolar process. It requires no external components, but nevertheless maintains the same qualities and performance as the existing hybrid type of infrared remote control sensor. The following issues are discussed: signal processing, the chip configuration, the noise characteristics of the sensor directivity gain and the plastic lens, and the alignment of the bandpass filter. >
HONOLULU (HawaiiNewsNow) - A high surf advisory will take effect at 6 a.m. Thursday for the east-facing shores of Kauai, Oahu, Molokai, Maui and the Big Island as strong trade winds bring a choppy swell to the islands. A strong high pressure system far to the northeast of the state will produce a large fetch of strong northeast trade winds toward the islands for the next several days. Surf is forecast to rise to 5 to 8 feet Thursday. Waves could increase to 7 to 10 feet Friday and Saturday. Beach goers can expect strong breaking waves, a dangerous shore break and strong long shore and rip currents that will make swimming difficult and dangerous. Anyone at the beach, including swimmers and surfers, should heed all advice from ocean safety officials and exercise caution.
/* * Copyright 2019 Akashic Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.yggdrash.contract.yeed; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.yggdrash.common.Sha3Hash; import io.yggdrash.common.contract.BranchContract; import io.yggdrash.common.contract.vo.dpoa.Validator; import io.yggdrash.common.contract.vo.dpoa.ValidatorSet; import io.yggdrash.common.crypto.HexUtil; import io.yggdrash.common.store.BranchStateStore; import io.yggdrash.common.store.StateStore; import io.yggdrash.common.store.datasource.HashMapDbSource; import io.yggdrash.common.utils.JsonUtil; import io.yggdrash.contract.core.ExecuteStatus; import io.yggdrash.contract.core.Receipt; import io.yggdrash.contract.core.ReceiptAdapter; import io.yggdrash.contract.core.ReceiptImpl; import io.yggdrash.contract.yeed.ehtereum.EthTransaction; import io.yggdrash.contract.yeed.intertransfer.TxConfirmStatus; import io.yggdrash.contract.yeed.propose.ProposeStatus; import io.yggdrash.contract.yeed.propose.ProposeType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; public class YeedTest { private static final YeedContract.YeedService yeedContract = new YeedContract.YeedService(); private static final Logger log = LoggerFactory.getLogger(YeedTest.class); private static final String ADDRESS_1 = "c91e9d46dd4b7584f0b6348ee18277c10fd7cb94"; // validator private static final String ADDRESS_2 = "1a0cdead3d1d1dbeef848fef9053b4f0ae06db9e"; // validator private static final String BRANCH_ID = "0x00"; private ReceiptAdapter adapter; private static BigInteger BASE_CURRENCY = BigInteger.TEN.pow(18); // 0.01 YEED private static BigInteger DEFAULT_FEE = BASE_CURRENCY.divide(BigInteger.valueOf(100L)); private JsonObject genesisParams = JsonUtil.parseJsonObject("{\"alloc\": " + "{\"c91e9d46dd4b7584f0b6348ee18277c10fd7cb94\":{\"balance\": \"1000000000\"}," + "\"1a0cdead3d1d1dbeef848fef9053b4f0ae06db9e\":{\"balance\": \"1000000000\"}," + "\"5e032243d507c743b061ef021e2ec7fcc6d3ab89\":{\"balance\": \"10\"}," + "\"cee3d4755e47055b530deeba062c5bd0c17eb00f\":{\"balance\": \"998000000000\"}," + "\"c3cf7a283a4415ce3c41f5374934612389334780\":{\"balance\": \"10000000000000000000000\"}," + "\"4d01e237570022440aa126ca0b63065d7f5fd589\":{\"balance\": \"10000000000000000000000\"}" + "}}"); @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { BranchStateStore branchStateStore = branchStateStoreMock(); branchStateStore.getValidators().getValidatorMap() .put("81b7e08f65bdf5648606c89998a9cc8164397647", new Validator("81b7e08f65bdf5648606c89998a9cc8164397647")); adapter = new ReceiptAdapter(); yeedContract.receipt = adapter; yeedContract.store = new StateStore(new HashMapDbSource()); yeedContract.branchStateStore = branchStateStore; Receipt result = new ReceiptImpl(); setUpReceipt(result); yeedContract.init(genesisParams); assertTrue(result.isSuccess()); } @After public void tearDown() { printTxLog(); } @Test public void totalSupply() { JsonObject alloc = genesisParams.getAsJsonObject("alloc"); BigInteger totalSupply = BigInteger.ZERO; for (Map.Entry<String, JsonElement> entry : alloc.entrySet()) { BigInteger balance = entry.getValue().getAsJsonObject() .get("balance").getAsBigInteger() .multiply(BASE_CURRENCY) ; // apply BASE_CURRENCY totalSupply = totalSupply.add(balance); } BigInteger res = yeedContract.totalSupply(); assertEquals(totalSupply, res); } @Test public void balanceOf() { BigInteger res = getBalance(ADDRESS_1); BigInteger res2 = getBalance(ADDRESS_1.toUpperCase()); assertEquals(BASE_CURRENCY.multiply(BigInteger.valueOf(1000000000)), res); assertEquals(res2, res); } @Test public void allowance() { BigInteger res = getAllowance(ADDRESS_1, ADDRESS_2); BigInteger res2 = getAllowance(ADDRESS_1.toUpperCase(), ADDRESS_2.toUpperCase()); assertEquals(BigInteger.ZERO, res); assertEquals(res2, res); } @Test public void transfer() { BigInteger sendAmount = BASE_CURRENCY; // 1 YEED final BigInteger sendAddress = getBalance(ADDRESS_1); final BigInteger receiveAmount = getBalance(ADDRESS_2); BigInteger feeAmount = DEFAULT_FEE; JsonObject paramObj = new JsonObject(); paramObj.addProperty("to", ADDRESS_2); paramObj.addProperty("amount", sendAmount); paramObj.addProperty("fee", feeAmount); log.debug("{}:{}", ADDRESS_1, sendAddress); log.debug("{}:{}", ADDRESS_2, receiveAmount); // SETUP Receipt receipt = setUpReceipt(ADDRESS_1); receipt = yeedContract.transfer(paramObj); assertTrue(receipt.isSuccess()); BigInteger senderRemainAmount = sendAddress.subtract(feeAmount).subtract(sendAmount); BigInteger receverRemainAmount = receiveAmount.add(sendAmount); assertEquals(senderRemainAmount, getBalance(ADDRESS_1)); assertEquals(receverRemainAmount, getBalance(ADDRESS_2)); // To much amount addAmount(paramObj, BigInteger.valueOf(1).add(senderRemainAmount)); receipt = yeedContract.transfer(paramObj); assertFalse(receipt.isSuccess()); // Same amount addAmount(paramObj, senderRemainAmount.subtract(feeAmount)); receipt = yeedContract.transfer(paramObj); assertTrue(receipt.isSuccess()); assertTrue(getBalance(ADDRESS_1).compareTo(BigInteger.ZERO) == 0); } @Test public void failTransfer() { JsonObject paramObj = new JsonObject(); paramObj.addProperty("to", "1a0cdead3d1d1dbeef848fef9053b4f0ae06db9e"); paramObj.addProperty("amount", -1000000); paramObj.addProperty("fee", -1000); Receipt receipt = setUpReceipt(ADDRESS_1); receipt = yeedContract.transfer(paramObj); assertFalse(receipt.isSuccess()); } @Test public void transferFrom() { String owner = ADDRESS_1; String spender = ADDRESS_2; String to = "cee3d4755e47055b530deeba062c5bd0c17eb00f"; BigInteger approveBalance = BASE_CURRENCY.multiply(BigInteger.valueOf(1000L)); final BigInteger transferFromBalance = BASE_CURRENCY.multiply(BigInteger.valueOf(700L)); final BigInteger toBalance = getBalance(to); // APPROVE approveByOwner(owner, spender, approveBalance.toString()); // CHECK allowence JsonObject param = new JsonObject(); param.addProperty("owner", owner); param.addProperty("spender", spender); BigInteger allowanceBalance = yeedContract.allowance(param); Assert.assertTrue("allowanceBalance : ", allowanceBalance.compareTo(approveBalance) == 0); JsonObject transferFromObject = new JsonObject(); transferFromObject.addProperty("from", owner); transferFromObject.addProperty("to", to); // 700 YEED transferFromObject.addProperty("amount", transferFromBalance); // Fee is 0.01 YEED transferFromObject.addProperty("fee", DEFAULT_FEE); Receipt receipt = setUpReceipt(spender); // Transfer From owner to receiver by spender yeedContract.transferFrom(transferFromObject); assertTrue(receipt.isSuccess()); assertEquals(approveBalance.subtract(transferFromBalance).subtract(DEFAULT_FEE), getAllowance(owner, spender)); assertEquals(toBalance.add(transferFromBalance), getBalance(to)); String logFormat = "{} : {}"; log.debug(logFormat, to, getBalance(to)); log.debug(logFormat, owner, getBalance(owner)); log.debug(logFormat, spender, getBalance(spender)); log.debug("getAllowance : {}", getAllowance(owner, spender)); printTxLog(); Receipt receipt2 = setUpReceipt("1a0cdead3d1d1dbeef848fef9053b4f0ae06db9e"); yeedContract.transferFrom(transferFromObject); // Insufficient funds assertFalse(receipt2.isSuccess()); allowanceBalance = getAllowance(owner, spender); // subtract feeBalance allowanceBalance = allowanceBalance.subtract(DEFAULT_FEE); addAmount(transferFromObject, allowanceBalance); // Transfer all amount of allowance yeedContract.transferFrom(transferFromObject); assertTrue(receipt2.isSuccess()); assertEquals(BigInteger.ZERO, getAllowance(owner, spender)); } private void approveByOwner(String owner, String spender, String amount) { JsonObject paramObj = new JsonObject(); paramObj.addProperty("spender", spender); paramObj.addProperty("amount", amount); paramObj.addProperty("fee", DEFAULT_FEE); final BigInteger spenderBalance = getBalance(spender); final BigInteger ownerBalance = getBalance(owner); Receipt receipt = setUpReceipt(owner); yeedContract.approve(paramObj); adapter.getLog().stream().forEach(l -> log.debug(l)); assertTrue(receipt.isSuccess()); assertEquals(spenderBalance, getBalance(spender)); assertTrue(ownerBalance.compareTo(getBalance(owner)) > 0); } @Test public void faucetTest() { String issuer = "<KEY>"; setUpReceipt("0x00", issuer, BRANCH_ID, 1); final JsonObject emptyParam = new JsonObject(); final BigInteger totalSupply = yeedContract.totalSupply(); JsonObject testTransfer = new JsonObject(); testTransfer.addProperty("to","81b7e08f65bdf5648606c89998a9cc8164397647"); testTransfer.addProperty("amount", BigInteger.valueOf(100L)); testTransfer.addProperty("fee", DEFAULT_FEE); yeedContract.transfer(testTransfer); assertSame(ExecuteStatus.ERROR, yeedContract.receipt.getStatus()); // Insufficient funds yeedContract.faucet(emptyParam); assertSame(ExecuteStatus.SUCCESS, yeedContract.receipt.getStatus()); assertTrue(yeedContract.totalSupply().compareTo(totalSupply) != 0); // Call faucet one more yeedContract.faucet(emptyParam); assertSame(ExecuteStatus.ERROR, yeedContract.receipt.getStatus()); // Already received or has balance yeedContract.transfer(testTransfer); assertSame(ExecuteStatus.SUCCESS, yeedContract.receipt.getStatus()); } @Test public void sendSameAccount() { String issuer = "4d01e237570022440aa126ca0b63065d7f5fd589"; final BigInteger balance = yeedContract.getBalance(issuer); setUpReceipt("0x00", issuer, BRANCH_ID, 1); JsonObject testTransfer = new JsonObject(); testTransfer.addProperty("to","4d01e237570022440aa126ca0b63065d7f5fd589"); testTransfer.addProperty("amount", BigInteger.valueOf(100L)); yeedContract.transfer(testTransfer); BigInteger after = yeedContract.getBalance(issuer); assertTrue(balance.compareTo(after) == 0); } @Test public void transferChannelTest() { String from = ADDRESS_1; final BigInteger serviceFee = DEFAULT_FEE; final BigInteger amount = BASE_CURRENCY.multiply(BigInteger.valueOf(1000L)); String testContractName = "TEST"; setUpReceipt("0x00", from, BRANCH_ID, 1); JsonObject transferChannelTx = new JsonObject(); transferChannelTx.addProperty("from", from); transferChannelTx.addProperty("to",testContractName); transferChannelTx.addProperty("amount", amount); transferChannelTx.addProperty("serviceFee", serviceFee); BigInteger originBalance = getBalance(from); // Deposit Test boolean result = yeedContract.transferChannel(transferChannelTx); BigInteger depositBalance = getBalance(from); assertTrue("Result is True", result); assertEquals("", originBalance.subtract(amount).subtract(serviceFee), depositBalance); JsonObject param = new JsonObject(); param.addProperty("contractName", testContractName); BigInteger contractBalance = yeedContract.getContractBalanceOf(param); assertEquals("Contract Stake Balance", amount, contractBalance); // Withdraw Test BigInteger withdrawAmount = amount.subtract(serviceFee); transferChannelTx.addProperty("from", testContractName); transferChannelTx.addProperty("to", from); transferChannelTx.addProperty("amount", withdrawAmount); log.debug(transferChannelTx.toString()); result = yeedContract.transferChannel(transferChannelTx); assertTrue("Result is True", result); BigInteger withdrawBalance = getBalance(from); assertEquals("", depositBalance.add(withdrawAmount), withdrawBalance); // Contract Balance is zero contractBalance = yeedContract.getContractBalanceOf(param); assertEquals("Contract Balance is zero", 0, contractBalance.compareTo(BigInteger.ZERO)); } private BranchStateStore branchStateStoreMock() { return new BranchStateStore() { ValidatorSet set = new ValidatorSet(); List<BranchContract> contracts; @Override public Long getLastExecuteBlockIndex() { return null; } @Override public Sha3Hash getLastExecuteBlockHash() { return null; } @Override public Sha3Hash getGenesisBlockHash() { return null; } @Override public Sha3Hash getBranchIdHash() { return null; } @Override public ValidatorSet getValidators() { return set; } @Override public boolean isValidator(String address) { return true; } @Override public List<BranchContract> getBranchContacts() { return contracts; } @Override public String getContractVersion(String contractName) { return "0x00"; } @Override public String getContractName(String contractVersion) { return "TEST"; } public void setValidators(ValidatorSet validatorSet) { this.set = validatorSet; } }; } private Receipt createReceipt(String issuer) { Receipt receipt = new ReceiptImpl("0x00", 200L, issuer); receipt.setBranchId(BRANCH_ID); return receipt; } private Receipt createReceipt(String transactionId, String issuer, String branchId, long blockHeight) { Receipt receipt = new ReceiptImpl(transactionId, 200L, issuer); receipt.setBranchId(branchId); receipt.setBlockHeight(blockHeight); return receipt; } private void setUpReceipt(Receipt receipt) { adapter.setReceipt(receipt); } private Receipt setUpReceipt(String issuer) { Receipt receipt = createReceipt(issuer); setUpReceipt(receipt); return receipt; } private Receipt setUpReceipt(String transactionId, String issuer, String branchId, long blockHeight) { Receipt receipt = createReceipt(transactionId, issuer, branchId, blockHeight); setUpReceipt(receipt); return receipt; } private void addAmount(JsonObject param, BigInteger amount) { param.addProperty("amount", amount); } private BigInteger getBalance(String address) { JsonObject obj = new JsonObject(); obj.addProperty("address", address); return yeedContract.balanceOf(obj); } private BigInteger getAllowance(String owner, String spender) { JsonObject obj = new JsonObject(); obj.addProperty("owner", owner); obj.addProperty("spender", spender); return yeedContract.allowance(obj); } private void printTxLog() { log.debug("txLog={}", adapter.getLog()); } }
Operational evaluation of volcanic source terms (volcanic ash and SO2) from inverse modelling for aviation An operational framework is developed to provide timely and frequent source term updates for volcanic emissions (ash and SO 2 ). The procedure includes running the Lagrangian particle dispersion model FLEXPART with an initial (a priori) source term, and combining the output with observations (from satellite, ground-based, etc. sources) to obtain an a posteriori source term. This work was part of the EUNADICS-AV (eunadics-av.eu), which is a continuation of the work developed in the VAST project (vast.nilu.no). The aim is to ensuring that at certain time intervals when new observational and meteorological data is available during an event, an updated source term is provided to analysis and forecasting groups. The system is tested with the Grimsvtn eruption of 2011. Based on a source term sensitivity test, one can find the optimum between a sufficiently detailed source term and computational resources. Because satellite and radar data from different sources is available at different times, the source term is generated with the data that is available the earliest after the eruption started and data that is available later is used for evaluation.
"""Generic filters and parsers.""" import re # Help text for markdown editors MARKDOWN_HELP_TEXT = ( """Enter valid GitHub markdown - <a href="https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax" target="_blank">see markdown guide</a>. We're using <b>"code-friendly" mode</b>, so __ and _ will be rendered literally! Use * and ** for italics/bold instead. """ ) MARKDOWN_IMAGE_HELP_TEXT = ( """ <br> Upload event images at the bottom of the page, and tag them in markdown like so: <pre> <span style="color: #79AEC8"># the URI will replace img&lt;N&gt; after save </span> ![alt text](img1) <span style="color: #79AEC8"># Use an image tag to define size. Defaults to 100% max-width.</span> &lt;img src="img2" width=200&gt; </pre> """ ) # To render/replace image URIs IMAGE_URI_EXPRESSIONS = ( { # markdown image tags 're': r'\(img\d\)', # regex to match 'tag': '(img{0})', # format string to replace }, { # html image tags 're': r'src="img\d"', 'tag': 'src="img{0}"', }, ) def get_blurb_from_markdown(text, style=True): """Extract a blurb from the first lines of some markdown text.""" if not text: return None text = text.replace('\r\n', '\n') lines = text.split('\n\n') blurb = lines[0] if style: return blurb # Strip style tags p = re.compile(r'<style>[\w\W]+</style>', re.MULTILINE) matches = p.findall(blurb) for m in matches: blurb = blurb.replace(m, '') return blurb def render_image_uri(markdown, images): """Render image URIs over markdown placeholders. Images must be ordered by pk - it appears that pk order will always reflect the ordering of images as they are uploaded on the admin UI, and therefore the ordering of URI tags entered by the user (e.g. img1, img2, img3 should respectively match images ordered by pk). """ if not (markdown and images): return markdown new = markdown.replace('', '') for i, image in enumerate(images): for e in IMAGE_URI_EXPRESSIONS: p = re.compile(e['re'], re.MULTILINE) m = p.search(new) if not m: # No tags to replace continue # Replace placeholder with real URI tag = e['tag'].format(i + 1) new = new.replace( tag, tag.replace(f'img{i + 1}', image.img_uri)) return new
Robert Carrier (chef) Biography Robert Carrier McMahon was born in Tarrytown, New York, the third son of a wealthy property lawyer father of Irish descent; his mother was the Franco-German daughter of a millionaire. After his parents went bankrupt in the 1930s Great Depression, they maintained their lifestyle by firing their servants and preparing their own elaborate dinner parties. Educated in New York City, Robert took part-time art courses and trained to become an actor. He had a part in the Broadway revue New Faces, before touring Europe with a rep company, singing the juvenile lead in American musicals. After returning to America, Robert often stayed at weekends with his beloved French grandmother in upstate New York. She taught him to cook, making biscuits and butter-frying fish caught in a nearby stream. Post World War II Carrier volunteered to serve in the United States Army during World War II as an intelligence officer in the Office of Strategic Services, a wartime forerunner of the Central Intelligence Agency. Speaking fluent French and understanding German thanks to his parentage, Carrier arrived in England in 1943, and after D-Day served in Paris as a cryptographer in General Charles de Gaulle's headquarters. Carrier chose to remain in Paris as a civilian after the cessation of hostilities, and dropped his surname McMahon: "It (Robert Carrier) sounds good in French and it looks well visually." Carrier initially worked for a US forces radio station and for a Gaullist newspaper/magazine, Spectacle, set up to support de Gaulle's RTF party in its failed bid for post-war power. After a theatrical magazine that he edited and partly owned was shut down in 1949, Carrier moved to St. Tropez to work in a friend's restaurant, Chez Fifine, where he found relief from a bout of depression. Starting to write about food as ration-restricted Europe got used to flavour again, Carrier moved to Rome, Italy, to improve his cookery repertoire, and work as a cowboy in an Italian musical revue. After a friend invited him to Great Britain for the 1953 coronation of Elizabeth II of the United Kingdom, he decided to relocate to London. He worked in the developing industry of public relations, marketing various food products including stock cubes, cornflour, New Zealand apples and a vegetarian dog food. With Oliver Lawson-Dick, Carrier wrote The Vanishing City, a historical perspective of London illustrated with reproductions of old engravings. Cookery career In 1957 Carrier wrote his first article on food, which he sold to Harper's Bazaar editor Eileen Dickson. He was soon writing regularly for the magazine before becoming a contributor to Vogue and then writing a weekly column for the colour supplement of the Sunday Times. This column brought him celebrity; the articles were collected and expanded to create his first cookery book, the lavishly illustrated Great Dishes of the World, in 1963. Although priced at 70/-, the present day equivalent of around £100, it sold 11 million copies. Assured of publicity, Carrier opened the eponymous restaurant Carrier's in 1959 in Camden Passage, Islington, then developed an international chain of cookshops, with the first in Harrods in 1967. His recipes were printed on wipe-clean cards (a convenient innovation), and were more specific in their quantities and directions than some of those of his competitor Elizabeth David; they made it feasible for an amateur to prepare food that would satisfy the eye and palate of even demanding dinner guests. In 1971, he saw a full-page advertisement in Country Life for Hintlesham Hall near Ipswich, Suffolk and bought it, unsurveyed, for £32,000. He planned to renovate it slowly as a country retreat but, realising its vulnerability and near dereliction with rotten floors and ceilings, he decided to save it all immediately. He employed 60 people to restore the house and opened it as a hotel and restaurant in August 1972. He also revived the Hintlesham Festival. A few years later, Carrier met a woman who lived near his Paris apartment. He thought her a remarkable cook but a poor businesswoman; so, when she got into financial difficulties over non-payment of tax, he offered to set her up as a cookery teacher at Hintlesham if she would learn to speak English. He invested about £300,000 converting the 16th-century outbuildings into a modern school. The school had a double auditorium and two classrooms, each with 12 cooking stations. The woman never learned English so he ran the school himself. He presented beginners' and intermediate courses. The mornings were devoted to generic cooking skills and, in the afternoons, students cooked recipes from the Hintlesham Hall restaurant menu. The school attracted people from throughout the anglophone world, but Carrier was disappointed to find that many were attracted more by his celebrity than by an interest in cookery. He found the repetitive work of teaching onerous and dull. In the late 1970s, Carrier began presenting a television series, Carrier's Kitchen, based on the cooking cards from his Sunday Times articles. After the more traditional British fare often presented by British TV cooking programme host Fanny Cradock in her black and white shows, Carrier in colour television format introduced British TV viewers to a more exotic range of Continental cooking. With a highly theatrical and camp style, and a penchant for superlatives ("Gooorgeous… Adooorable… Faaabulous!"), he attracted viewers as much for his drawling American vowels and shameless self-promotion. His later followed this with three other series, titled Food, Wine and Friends, The Gourmet Vegetarian and Carrier's Caribbean. From this greater publicity flowed a substantial magazine published weekly by Marshall Cavendish between 1981 and 1983. Retirement By the early 1980s, Carrier's television style was considered kitsch and too old-fashioned, and his food too complex. Ejected from his television show and bored of the celebrity culture, Carrier closed the Michelin two starred Hintlesham Hall in 1982, and sold it the following year to English hotelier Ruth Watson and her husband. After closing the also Michelin two starred Camden Passage restaurant, Carrier took a short stay in New York, and from 1984 went to live in France and at his restored villa in Morocco, regularly accompanied by his friend Oliver Lawson-Dick. On January 19, 1983, Carrier was the subject of the United Kingdom television show This Is Your Life. He became popular in the United States in the 1980s, writing a weekly European food column for a popular US magazine. In 1984 he became the face of the British restaurant industry, arguing vigorously and vocally for changes to the licensing laws. His efforts were rewarded by appointment as honorary OBE. Having lived in Marrakesh for several months of each year since the 1970s, Carrier used his Moroccan experiences as the basis for another cookbook in 1987, which further funded his retirement. His 1999 rewrite of Great Dishes of the World did not sell, because he replaced rich and calorific Carrier classics with modern pared-down Nouvelle Cuisine. By 1994 Carrier had returned to London, realising that most of his Christmas cards were from Britain. He also returned to television with GMTV, proclaiming the virtues of economical and vegetarian eating. Having sold his villa in Morocco, he owned a property in Provence where he spent his time painting pictures, tended by good friend Liz Glaze after the death of Oliver Lawson-Dick. Carrier was admitted to hospital in the South of France on the morning of June 27, 2006; his death was announced to the Press Association by Liz Glaze on the afternoon of the same day.
import { Route } from '@angular/router'; import { UserRouteAccessService } from '../../../shared'; import { LightboxDemoComponent } from './lightboxdemo.component'; export const lightboxDemoRoute: Route = { path: 'lightbox', component: LightboxDemoComponent, data: { pageTitle: 'primeng.overlay.lightbox.title' }, canActivate: [UserRouteAccessService] };
import { ProductManufacturer } from "../../packages/shopware-6-client/src/interfaces/models/content/product/ProductManufacturer"; import { Unit } from "../../packages/shopware-6-client/src/interfaces/models/system/unit/Unit"; import { Price } from "../../packages/shopware-6-client/src/interfaces/models/framework/pricing/Price"; import { CalculatedPrice } from "../../packages/shopware-6-client/src/interfaces/models/checkout/cart/price/CalculatedPrice"; import { Tax } from "../../packages/shopware-6-client/src/interfaces/models/system/tax/Tax"; import { ProductPrice } from "../../packages/shopware-6-client/src/interfaces/models/content/product/ProductPrice"; export interface ProductForProductPageHeadless { // basic product data id: string; ean: string | null; productNumber: string; additionalText: string | null; name: string | null; keywords: string | null; description: string | null; metaTitle: string | null; manufacturerNumber: string | null; manufacturer: ProductManufacturer | null; unit: Unit | null; // labels isCloseout: boolean | null; shippingFree: boolean | null; markAsTopseller: boolean | null; isNew: boolean; // whats the difference between calculated and not calculated prices? // can we get the price objects just to display for given sw-context-token and product page url path? calculatedPrices: Price[]; calculatedPrice: CalculatedPrice; price: Price[] | null; tax: Tax; prices: ProductPrice[]; parentId: string | null; // warehouse stocks available: boolean; // decission on how to display a quantity? as a text field, drop down etc. purchaseSteps: number | null; // 5 10 15 maxPurchase: number | null; minPurchase: number | null; // variants // regardless the type of the product options?: Array<{ // always all the siblings, other variants of the product, that customer can go to name: string; available: boolean; url: string; cover: { media: { title: string | null; alt: string | null; url: string; thumbnails: [ // How do we choose the right thumbnail to display for specific view port? { width: number; height: number; url: string; } ]; }; }; properties: Array<{ groupId: string; // "a3eb3fbc88bb4cfea87a57e16e52dedf" code: string; // color, size label: string; // thistle, red, xl }>; }>; // images media: Array<{ mimeType: string; position: number; title: string | null; alt: string | null; url: string; thumbnails: [ // How do we choose the right thumbnail to display for specific view port? { width: number; height: number; url: string; } ]; }>; // reviews productReviews: Array<{ reviewerName: string | null; reviewerEmail: string | null; points: number | null; content: string | null; title: string | null; }> | null; ratingAverage: number; }
/** * Test Spnego Client Login. */ public class TestSecureApiServiceClient extends KerberosSecurityTestcase { private String clientPrincipal = "client"; private String server1Protocol = "HTTP"; private String server2Protocol = "server2"; private String host = "localhost"; private String server1Principal = server1Protocol + "/" + host; private String server2Principal = server2Protocol + "/" + host; private File keytabFile; private Configuration testConf = new Configuration(); private Map<String, String> props; private static Server server; private static Logger LOG = Logger .getLogger(TestSecureApiServiceClient.class); private ApiServiceClient asc; /** * A mocked version of API Service for testing purpose. * */ @SuppressWarnings("serial") public static class TestServlet extends HttpServlet { private static boolean headerFound = false; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Enumeration<String> headers = req.getHeaderNames(); while(headers.hasMoreElements()) { String header = headers.nextElement(); LOG.info(header); } if (req.getHeader("Authorization")!=null) { headerFound = true; resp.setStatus(HttpServletResponse.SC_OK); } else { headerFound = false; resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); } public static boolean isHeaderExist() { return headerFound; } } @Before public void setUp() throws Exception { keytabFile = new File(getWorkDir(), "keytab"); getKdc().createPrincipal(keytabFile, clientPrincipal, server1Principal, server2Principal); SecurityUtil.setAuthenticationMethod(AuthenticationMethod.KERBEROS, testConf); UserGroupInformation.setConfiguration(testConf); UserGroupInformation.setShouldRenewImmediatelyForTests(true); props = new HashMap<String, String>(); props.put(Sasl.QOP, QualityOfProtection.AUTHENTICATION.saslQop); server = new Server(8088); ((QueuedThreadPool)server.getThreadPool()).setMaxThreads(10); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/app"); server.setHandler(context); context.addServlet(new ServletHolder(TestServlet.class), "/*"); ((ServerConnector)server.getConnectors()[0]).setHost("localhost"); server.start(); List<String> rmServers = new ArrayList<String>(); rmServers.add("localhost:8088"); testConf.set("yarn.resourcemanager.webapp.address", "localhost:8088"); asc = new ApiServiceClient() { @Override List<String> getRMHAWebAddresses(Configuration conf) { return rmServers; } }; asc.serviceInit(testConf); } @After public void tearDown() throws Exception { server.stop(); } @Test public void testHttpSpnegoChallenge() throws Exception { UserGroupInformation.loginUserFromKeytab(clientPrincipal, keytabFile .getCanonicalPath()); String challenge = YarnClientUtils.generateToken("localhost"); assertNotNull(challenge); } @Test public void testAuthorizationHeader() throws Exception { UserGroupInformation.loginUserFromKeytab(clientPrincipal, keytabFile .getCanonicalPath()); String rmAddress = asc.getRMWebAddress(); if (TestServlet.isHeaderExist()) { assertEquals(rmAddress, "http://localhost:8088"); } else { fail("Did not see Authorization header."); } } }
Whats distressing about having type 1 diabetes? A qualitative study of young adults perspectives Background Diabetes distress is a general term that refers to the emotional burdens, anxieties, frustrations, stressors and worries that stem from managing a severe, complex condition like Type 1 diabetes. To date there has been limited research on diabetes-related distress in younger people with Type 1 diabetes. This qualitative study aimed to identify causes of diabetes distress in a sample of young adults with Type 1 diabetes. Methods Semi-structured interviews with 35 individuals with Type 1 diabetes (2330 years of age). Results This study found diabetes related-distress to be common in a sample of young adults with Type 1 diabetes in the second phase of young adulthood (2330 years of age). Diabetes distress was triggered by multiple factors, the most common of which were: self-consciousness/stigma, day-to-day diabetes management difficulties, having to fight the healthcare system, concerns about the future and apprehension about pregnancy. A number of factors appeared to moderate distress in this group, including having opportunities to talk to healthcare professionals, attending diabetes education programmes and joining peer support groups. Young adults felt that having opportunities to talk to healthcare professionals about diabetes distress should be a component of standard diabetes care. Conclusions Some aspects of living with diabetes frequently distress young adults with Type 1 diabetes who are in their twenties. Clinicians should facilitate young adults attendance at diabetes education programmes, provide them with opportunities to talk about their diabetes-related frustrations and difficulties and, where possible, assist in the development of peer-support networks for young adults with diabetes. Most research into psychological morbidity in individuals with Type 1 diabetes has focused on serious psychopathology. Researchers have recently begun to argue, however, that a much larger number of individuals with diabetes experience sub-clinical diabetes-related distress than experience above-threshold psychological disorders, and that this distress may impact glycaemic control more than clinical disorders. Diabetes distress is a general term that refers to the emotional burdens, stressors and frustrations that stem from managing diabetes, a severe, complex condition. Recent research on Type 2 diabetes has found that distress begins to influence diabetes-specific behavioural indicators at much lower levels than was previously considered. Although diabetes distress has traditionally been seen as a symptom of clinical depression, researchers are now beginning to argue that depression should be seen as one form of diabetes distress. Qualitative studies suggest that many people who consider themselves to be distressed by their diabetes do not necessarily consider themselves to be depressed by it. To date, distress in people with diabetes (Type 1 and 2) has usually been measured and studied quantitatively. Depression and distress are both prevalent in individuals with Type 1 diabetes. Little research has been conducted specifically on distress in young adults (individuals between 18 and 30 years of age) with diabetes, though distress is also considered to be prevalent in this age group. For example 59% of young adults in Scott et al.'s study said that stress management was the second most important issue that they wanted to talk to healthcare professionals about. Hislop et al. used the CES-D depression scale to examine depression prevalence in a sample of 92 young adults with diabetes and found 35% reported depressive symptoms. These authors argued that the depression scale that they used in the study was likely identifying symptoms of diabetes distress. The majority of empirical and conceptual research on distress in young adults with diabetes has focused on young adults in their late teens and early twenties. Distress arises at this time of life from the strains and difficulties that young adults face balancing their diabetes management activities with their need to engage in normal developmental activities. Drawing on the work of Arnett diabetes researchers argue that young adulthood is a divided developmental stage, composed of an early transitional phase (approximately 18-22 years of age) but also a later one (approximately 23-30 years of age) that is characterized by increased lifestyle stability [3,25,. Young adults in their twenties are more future conscious and concerned about their diabetes management than their younger counterparts. They tend to lose their adolescent sense of invulnerability. Young adults in this range also experience distress, and some experience increased distress as they transition through their twenties [4,7,. Why these older individuals experience diabetes distress is an issue that has not receive significant attention from researchers, though existing research provides some indications. One reason may be that the mid to late twenties may be just as unstable a life period for some young people as the late teens and early twenties. Arnett notes that residential mobility is actually at its maximum for young people in their mid-20s, and that the 20s can be years of frequent changes in occupation, educational status and personal relationships. Young adults in this age range are transitioning to parenthood, to long-term personal relationships, to careers, to general adult health services, all the while trying to effectively manage their diabetes. These competing health and developmental priorities can lead some young people to feel overwhelmed. While clinicians have put substantial efforts into helping younger adults with Type 1 diabetes manage distress, for example by developing specialist young adult services, distress in young adults in their mid to late 20s has not received the same attention. Young people in this age are generally treated in adult services where psychological support is lacking. This qualitative study investigates factors that cause diabetes distress in young adults with Type 1 diabetes aged 23-30 (the age range that diabetes researchers refer to as the 'second phase of emerging adulthood'). Understanding the factors that drive distress is crucial for constructing appropriate interventions to combat it. Methods This study used a qualitative methodology and was conducted in Ireland. It received ethical approval from the research ethics committee of the Royal College of Surgeons in Ireland. The study used a purposeful sampling method, the most common type of qualitative sampling technique. The aim of this method was to recruit a sample of approximately 30 young adults with Type 1 diabetes, 23-30 years of age. Young adults (n = 32) were recruited primarily from an Irish Facebook support group for young adults with Type 1 diabetes, and from the Facebook page of Diabetes Ireland, Ireland's leading diabetes charity. Recruitment advertisements indicated that the project was looking to talk to young adults with Type 1 diabetes who were between 23 and 30 years of age. After the interviews with Facebook respondents were completed an additional three young adults were recruited from a specialist young adult clinic in Ireland. The themes that arose in the interviews with the three young adults from the hospital setting were similar to those in the interviews with the young adults who were recruited from Facebook and therefore the researchers did not seek to recruit more participants. Twenty-nine women and six men responded to the study. Since the purpose of the study was to determine factors that cause distress in young adults in general (and not to differentiate between the accounts of male and female interviewees), and because similar themes arose in the six male and twenty-nine female interviews, male and female interviewees' results are reported together. Previous studies that have used qualitative methods to investigate diabetes distress have also used unequal number of men and women. See Table 1 for young adults' demographic characteristics. The overall sample size (35 young adults) is within best practice guidelines for studies based on semistructured qualitative interviews. Table 2 indicates that the study reached data saturation at interview 3; every interview beyond that served to confirm the themes that emerged in the first three interviews, rather than introduce new themes. All interviews were conducted by the first author who at the time that the study was conducted was thirty-one years of age. Seventeen interviews were conducted over the telephone and eighteen in person. Interviews lasted 34-86 minutes, with telephone interviews being shorter. The development of the interview schedules was informed by literature review and expert opinion (feedback from the third author). The interview schedule was piloted with two people with diabetes who were in their early thirties. The baseline interview questions did not change as the interviews progressed, though the interviewer probed around particular issues that were raised in previous interviews, such as frustrations with the health system. Once an issue emerged as being important in an interview (such as feeling frustrated with the healthcare system), it was probed for in all subsequent interviews. Before each interview began, interviewees were given information about the project and what taking part in it would practically involve (the approximate length of the interview and the types of questions that the interview would cover). Interviewees were informed that the interviews would be taperecorded (unless they had any objections to this), and that the interviews would be typed up and reported in an anonymous format. Respondents who completed face-to-face interviews were asked to give written consent to take part in the study. Respondents who completed telephone interviews were asked to give verbal consent. The baseline questions were as follows: Interviews were thematically analyzed in a wordprocessing package (MS Word). The first and the second authors coded the first four interviews and the other authors provided feedback on their analysis. Analysis for the first four interviews began by 'open coding' the interview transcripts, giving each section of a transcript that addressed a particular issue a descriptive tag or 'code' (e. g. a section of a transcript could be labelled 'frustration with continuity of care'). These codes were compared and contrasted in order to determine if some of them could be subsumed under high level concepts or 'categories' (e.g. all posts labeled with the descriptive tags 'frustration with continuity of care' and 'frustration with disjointed care' were placed the higher level category 'frustration with health services'). Eight principle categories were identified and agreed upon (outlined in Table 2). Information in subsequent interviews was evaluated against these eight categories. Although the first author was sensitive to the emergence of new major categories while analyzing the remaining thirty young adult interviews, it was determined that all codes from these interviews could be slotted under the initial eight categories. These eight categories became the organizing themes of the results section for young adults. We checked the final draft of the article with the young adults who took part in the study. Young adults felt that the paper accurately described their experiences. I've read over it is very interesting and very true (Female, 26). Had a quick read through and it seems excellent, I certainly wouldn't have any discrepancies (Female, 27). Sources of distress Most interviewees considered diabetes to be emotionally difficult at least some of the time. Self-consciousness about diabetes A minority of young adults (n = 12) described feeling self-conscious about their diabetes and its management, and were worried about how others viewed them. The strength of these interviewees' self-consciousness varied. Some felt 'awkward' when they had to manage their diabetes around others. Others had stronger feelings and perceived diabetes to be a stigmatizing, discrediting condition that risked undermining their identities as young, healthy people. These interviewees felt that their diabetes risked making them inalienably 'different' from other people. A lot of people might feel a bit awkward if I was to inject in front of them (Male, 30) Interviewees who appeared to have strong stigmarelated perceptions tended to avoid activities that they felt would highlight or reveal their diabetes to others. Such activities included wearing CSII devices (Continuous Subcutaneous Insulin Infusion), or, in the case of two young adults recruited from the clinical setting, joining diabetes-related support groups on social media sites such as Facebook. Avoiding such 'stigmatizing activities' enabled these interviewees to suppress their condition and allow them to present identities as 'normal' young adults in front of other individuals. Interviewees reported that their feelings of selfconscious were generally strongest during the first phase of young adult adulthood (18-22 years of age), becoming attenuated as they transitioned through their twenties. However self-consciousnesses could come to the forefront again during major life or environmental transitions, such as beginning a new job or moving to a new country. These were generally situations where interviewees either lost access to previously supportive audiences who could help to (re)frame diabetes management as a 'normal' activity, or forced interviewees to manage their diabetes in front of new and (potentially) unsupportive audiences. It is kind of hard with working. You don't want to be taking out a diary and writing down and people looking at you. I feel a bit uncomfortable. I don't know the people that well inside there. In a new work environment I'd feel a bit uncomfortable. In my old work I would have cared less. I would have gone off and sat down for as long as I needed (Female, 23). Type 2 diabetes Just under half of interviewees (n = 15) described feeling angry and frustrated at Type 2 diabetes. There were two reasons for this anger. The first was that interviewees felt that there a strong risk that they themselves could be misidentified as having Type 2 diabetes. Interviewees felt that the general public had a very prototypical and negative view of diabetes (derived from media reports of Type 2 diabetes that linked the condition to moral laxity, fatness, laziness, eating too much candy etc.). that they mapped onto all people with diabetes, including people with Type 1. These participants felt that they constantly had to differentiate between the two conditions to ensure that they were not stigmatized for having Type 2 diabetes. These interviewees themselves appeared to have negative perspectives of Type 2 diabetes; they seemed to see themselves as risk-avoidant, responsible subjects who developed diabetes through no fault of their own, whereas they thought that people with Type 2 developed their diabetes as a result of moral failings (i.e. inabilities to control their bodies and appetites). Notably, there were a number of interviewees (see Table 2) who were concerned about being stigmatized for having Type 2 diabetes but who did not feel self-conscious per se about having Type 1 diabetes (e.g. they had little concerns about injecting in front of other people as long as they were not mistaken for having Type 2 diabetes). It was also evident that whereas self-consciousness about Type 1 diabetes often attenuated as interviewees transitioned through their twenties, concerns about Type 2 diabetes appeared to remain strong. That's something that drives me crazy, Type 1 and 2 diabetes. It makes me so annoyed. Type 1 diabetes, you don't get it because you're overweight. People are like, 'oh which kind do you have? Do you have the really bad kind?' I'm like, 'what do you mean by that?' Or they're like, 'oh I'm sorry, did you eat too many sweets?' Of course that's why I have it (Female, 23). We didn't bring diabetes on ourselves. We didn't have a choice. The majority of Type 2 s have a choice and they chose not to do what they should be doing. You feel like you're branded with the same brush as them (Female, 30). The second source of interviewees frustration was a feeling that Type 2 diabetes was receiving disproportionate attention and resources from the media, policy makers and charities. In contrast they felt that Type 1 diabetes was often neglected by these agencies and actors. I really do think that Type 1 gets left behind. Even yesterday was world diabetes day and on the news it was all oh 'if you improve your lifestyle and if you do this and that' you improve your risk and I'm there shouting 'this is Type 2 diabetes'! (Female, 28). I think with diabetes a lot of it goes to Type 2 prevention, whereas Type 1 tends to get left in the dark and doesn't get the services it should get (Female, 26). Day-to-day management Day-to-day management of diabetes was considered to be emotionally difficult by just over half of interviewees (n = 18). Diabetes management frequently took up a lot of their time and energy, to the extent that other aspects of their lives were often neglected. Diabetes management had a visible component that other people could easily see, related to diet and injections. Underneath that, however, there was a larger element that other people were unaware of, the hidden, continually needed calculations and restrictions. I wouldn't wish it on anybody. It's awful. You have to do this and you have to do that. There's more involved than just doing the finger when you eat (Female, 28). It's a huge thing. But no one can see it so it's always there and it's massive for you but it's invisible for everybody else (Male, 24). A majority of young adults (n = 21) considered diabetes to be a limiting influence on their lives, either preventing them from engaging fully in day-to-day activities such as work or forcing them to spend an excessive amount of time on diabetes management. Interviewees said that they often struggled to find an acceptable balance between their diabetes and their daily activities of their 'normal' lives. You feel like you're dedicating a lot of your time and effort and emotions into this aspect of your life and other aspects are kind of being neglected. Stuff like college work can get affected and going out with your friends. You're concentrating too much on this element and the rest of yourself is neglected a bit (Female, 27). A number of female interviewees felt that they put on weight easily, more easily than their female friends and colleagues, which they attributed to their need to take insulin. They also noted that they had greater difficulties losing excess weight once they had acquired it. I do find your weight does go up. I know it's a side effect of insulin but since I've been on the pump, definitely my weight's increased (Female, 28). Interviewees who had difficulties controlling their diabetes were often particularly frustrated and upset: difficult control made interviewees feel anxious about the future; hypo-/hyper-glycaemic states could negatively impact mood; and it made interviewees feel that they were contravening norms governing how diabetes was 'supposed' to be managed. Poor control therefore could have primary (biological) and secondary (psychological) impacts on mood. I just get fed up. Fed up injecting, fed up being tired. Sometimes I just feel like I've no life because I'm just exhausted. It's not fair on the kids. It's so hard to get up in the mornings because I have such high sugar readings (Female, 29). No one understood how frustrating it can be sometimes when you're doing your damndest to get it right and it's not working. Because it's your health on the line, it can be very upsetting (Female, 30). Interviewees tended to blame themselves whenever anything went wrong with their diabetes and guilt appeared to be an ingrained feature of many interviewees' diabetes management routines. Interviewees often seemed to see themselves as solely responsible for their diabetes management and felt that they had therefore personally failed when its management became suboptimal I felt guilty because I knew I should have been stricter than I was. It was my own fault for my levels being high (Female, 27) I'm always high or low. My sugars are never normal. I'm feeling crap then as well. That's my own fault for not doing it. It's just a big circle (Female, 24). Healthcare system struggles A number of interviewees (n = 16) described feeling frustrated as a result of struggles with the healthcare system. Some interviewees described long fights with the health system bureaucracy to obtain diabetes technologies such as CSII. Others were frustrated by a lack of integrated healthcare services, forcing them to go to clinics on multiple occasions for different tests. Still others were angry at long waiting times between appointments. A common source of frustration was lack of continuity of care with doctors, and a lack of time with healthcare professionals (especially doctors) when they finally got to see them. When I come away from clinic, I would never come away happy. You just feel so frustrated by the whole service and let down (Female, 28). These interviewees had strong fears about developing diabetes-related complications, and lesser though still present fears about dying. Fears relating to amputation were particularly intense. Interviewees felt that their concerns about the future increased as they transitioned through their twenties: they realized that they were not invincible, and they became increasingly conscious about the possible consequences of any poor control that they had in the past. Many young adults in this study had also transitioned out of specialist young adult clinics and in to general adult health services; as such they were beginning to encounterfor example in hospital waiting rooms-older people with diabetes who had experienced amputation, blindness or other serious consequences of poor diabetes control. Complications and the future That's the fear, the complications of diabetes are awful (Male, 28). I suppose because there were so many years that it was uncontrolled that I do kind of think, in the future will this effect kind of things when I'm older. Will I be one of those people that has to have their foot amputated (Female, 24). I'd be sitting there beside an old man with a leg amputated and another blind woman beside you. It was so depressing. What the hell like? (Female, 29). The unfairness of diabetes-related risk was of concern to some (n = 7) interviewees. These interviewees reported feeling anxious because there was only a probability, not a certainty, that things would work out for them and they would not develop diabetes-related complications if they took good control of their diabetes. Several of these interviewees made reference to other young adults with diabetes who they considered to be excessively risky (for example, taking drugs or binge drinking) and yet who did not appear to experience diabetes-related complications. It appeared that for these interviewees, diabetes was a universe where good deeds often went unrewarded and bad deeds unpunished. And then there's the whole long-term complications thing. I know you should look after yourself, but there's no guarantees. There are sometimes when I do get stressed out about it The friend that I mentioned, she does everything wrong and has had zero repercussions from it. She has no complications or anything. It just seemed a bit unfair (Female, 30). I have necrobiosys in my arm and I think whenever my sugars are high I can see that worsening. It seemed a bit unfair. I was trying to do everything right. It just seems very unfair. I'd always try to take care of my sugars and do a bit better (Female, 30). Negative media representations Media representations of Type 1 diabetes were a source of anger to a small number of interviewees. These interviewees felt the media representations of Type 1 were invariably predicated upon tragic models of illness, usually featuring older people struggling to live with the consequences of complications. Interviewees were quite angry about the absence of positive (or even balanced) media representations of Type 1 diabetes. People like, articles and news reports tend to go with worse case scenarios and it's scary. There are sometimes when I do get stressed out about it. There was one programme and they had some poor guy and he lost half a foot. I was like 'Jesus Christ'. Then there was some poor woman and while they were filming it she died. I was like 'holy crap'. It was very extreme. I don't want to be told that by the time I get to 60 I'm going to have one leg and be blind. (Female, 30). Pregnancy Pregnancy-related concerns were common amongst female interviewees. Interviewees were particularly concerned about miscarrying and the risk of having large babies, and the effects that this largeness could have on their own health and on their baby's. Interviewees were also afraid that they would become pregnant during a period where they had poor control. The whole idea of having a baby was going to be a new experience and really exciting and now for me it's really dampened by the fact that I'm going to be even more conscious of my diabetes (Female, 30). What's the point in trying when I could have a miscarriage. I think its 60/40 that I'll have a miscarriage more times than I'd actually have a baby. It does my head in basically (Female, 24). Managing distress Interviewees used a number of strategies to manage diabetes-related distress. One was to avoid-as far as possible-thinking about the negative aspects of diabetes. A reason why interviewees appeared to became so annoyed at negative media representations of diabetes because they disrupted their attempts to focus on the positives. Interviewees also made downward comparisons with people who they considered to be less fortunate than themselves, which served to represent their own circumstances in a more positive light. Some interviewees compared their current diabetes management practices with their past practices in order to demonstrate that their diabetes management had improved with time and they were on an upwards rather than downwards trajectory (this helped to manage fears about the future and developing complications). Well there's no real point in moping around, 'oh God, poor me'. Just get on with it. There's people way worse off. There are way worse diseases than diabetes (Male, 30) For years I didn't test at all so I'm like, at least I'm testing. To me it's ok. It could be better but it's ok (Female, 30). Another strategy was to put a sustained, conscious effort into seeking to develop increased control over diabetes, for example through acquiring diabetes technologies such as CSIIs or seeking to go on structured diabetes education courses. Knowledge acquired from structured courses seemed to help to empower interviewees, helped them to feel that diabetes management problems were errors that could be fixed rather than the outcomes of personal failings, which in turn ameliorated feelings of guilt and frustration. I'm a lot more relaxed about it than I had been. Like I was constantly frustrated about it, why isn't it working. But now , if it's high, before I would have gotten really annoyed and sometimes even upset if my sugars were high but now I go, ok obviously I miscalculated how much that piece of cake was and then I learn from that (Female, 30) Social support from healthcare professionals One strategy for managing diabetes-related distress was present in most young adults' accounts, and therefore we will consider it in more detail here. That solution was to obtain diabetes-related social support, which young adults received from three main sources: healthcare professionals, family members and peers with diabetes. Young adults felt that having opportunities to talk to doctors and nurses often helped them to manage their feelings of diabetes-related distress. I think the nurses don't get enough credit. There's the social aspect , the caring side (Female, 23). Young adults also thought that healthcare professionals should provide emotional support to young adults as part of their standard care. I honestly think there should be some kind of emotional support. That's part of your health that should be addressed in the clinic (Female, 23). However many interviewees noted that they rarely had the time or opportunity to discuss their diabetes-related emotional problems in clinic appointments. Appointments with doctors were often brief, occurred only once or twice a year, and young adults often saw a different doctor every time that they went to their diabetes clinic. Such doctors were often junior doctors in training who lacked expertise in diabetes and the psychosocial issues associated with the condition. Many young adults said they were uncomfortable bringing up diabetes-related distress problems with doctors who were effectively strangers. Appointments with doctors often focused on processing biomedical information, such as Hba1C scores, with emotional and psychosocial issues bracketed to one side. Appointments with doctors who young adults had not met before were often taken up with going over historical information, such as date of diagnosis, which further reduced the time that doctors had to explore young adults' feelings. You go in and see the registrar and they don't know who you are. You don't feel open or comfortable talking to him about how you're getting on. I think seeing the same person helps big time (Female, 23). When you go to the doctor they're all about the diabetes, looking after your control there's nobody there to talk to say 'have you had enough of it?' That would be something that would really help. A bit of support for that would be really worthwhile. To know that it's not only you (Female, 29). There was one or two doctors that made flying visits in and out and didn't really treat you like a patient. It was more like you're a file. They just have a quick look at the file and look at numbers without discussing any of the issues with you (Female, 27). Young adults' relationships with nurses were often better, but again the support that nurses provided was often not enough, only occurring in the context of brief clinical encounters that took place every six months to a year. I mean my diabetic nurse got me through it all. She was amazing, absolutely amazing (Female, 28). Support from family members Young adults also received diabetes-related social support from their families. The support provided by families was considered to be important by most interviewees. Families provided tangible support, mainly in the form of taking note of interviewees' health, particularly their blood sugar numbers and what they were eating. Tangible support was important because it helped to increase interviewees' feelings of mastery over their diabetes, and also helped reduce anxieties relating to acute diabetes complications such as hypoglycaemia. My wife would be what you'd call a concerned wife. She would be very strict around diet so she's good at keeping me in line and monitoring what I'm eating (Male, 30). Family members also provided young adults with emotional support. Emotional support manifested itself in several ways. Family members often reassured young adults that everything would 'work out o.k.' for them, which helped interviewees to regulate any feelings of anxiety that young adults had about developing diabetes complications. Family members also actively intervened to protect young adults from distressing items in their environment, such as negative media representations. I went to this diabetes focus group, there was two people sitting there and they were both talking about having complications. I came home and was like to mum, 'oh God, I'm nowhere near that stage in my life but still that's kind of a scary thought to think that could have complications'. But then, as my mum said, loads of people who don't have any other illness have complications or can't get pregnant (Female, 23). My mum was recording this programme and something came up on diabetes and complications. She deleted it because she knew if I saw it I'd have a fit (Female, 24). However family support on its own was considered to be insufficient by many interviewees. The interviewees who took part in this study were in the second phase of young adulthood and had often left their family homes, which meant that they usually received less intensive support from their families compared to when they were younger. Family members sometimes themselves became very anxious about young adults' diabetes management, forcing young adults to spend as much time regulating their family members' emotions as they did their own. Young adults felt that family members' support could at times edge towards social control attempts. Family members were also often felt to lack an understanding of what it was like to manage diabetes; family members' supportive attempts therefore sometimes miscarried as they did not consider the impact that their actions would have on young adults. I went on holidays in August and my aunt texted me to say there was an article in the Irish Times to say diabetics shouldn't wear sandals because of the risk to their feet. I was like, have a bit of common sense. I was so annoyed over that. I was like, have a bit of tact (Female, 30) I just get anxious and over think things. At the weekend it would be like, I kind of spend most of the day in bed. Just because I skip meals and then sometimes I just go out and buy junk and stay in my room. I could go home to my family but then I end up getting stressed out down there. Just anxiety and stress (Female, 25). Support from peers As was reported in the methods section, a large number of interviewees joined diabetes support groups on the Internet, especially on Facebook. Interviewees felt that other people with diabetes had empathy for their experiences and would not judge them or become anxious if they admitted that they had problems. Most interviewees said that they wanted to receive support from people who were their own age and who had Type 1 diabetes; they did not want to become involved with older people with Type 2 diabetes, either in terms of giving or receiving support. It's great to have someone who understands (Female, 30). I think the best thing ever is to have someone else who's in the same boat as you (Female, 30). Peers with diabetes helped young adults to regulate negative emotions. They provided young adults with positive examples of living with diabetes, examples that highlighted that living with diabetes was often difficult, and that interviewees were not alone in their suffering. Peers also provided young adults with practical information and motivation that interviewees could use to improve their diabetes control, which in turn could help them to reduce their feelings of being overwhelmed by their diabetes. X kept me sane, she was like, you're not doing badly, calm down. It's one thing to hear it from doctors but when it's somebody else who's actually been through it (Female, 30) It's supportive to hear other people say that they're not all perfect at managing their diabetes. It's hard. (Female, 28). Another advantage of peer support was that it was much more readily and easily attainable than support from healthcare professionals, who as noted previously often only saw interviewees several times a year. In contrast, some interviewees were able to receive peer support several times a day, whether from online or offline sources. I've spoken to three or four people through the Facebook group who've just been recently diagnosed and they've had questions for me. I've said ring me any time, I don't mind if you need to talk to someone and that alone is a relief to hear, to know that there's people there to talk to, again, because no one else really gets it (Female, 30). There were two notable issues about diabetes peersupport groups, however. One was that they were composed of untrained individuals who were sometimes quite young and quite distressed about their diabetes. One female interviewee, who helped to run an Internet support group, felt imprisoned by a need to convey a positive impression to other young adults with diabetes. So while she joined peer groups to receive emotional support, she ended up becoming more distressed out of a need to demonstrate to other young adults that diabetes was not distressing. I'm not a support worker. I'm quite worried that I'm not providing enough support for these people. I find it difficult to approach someone who I can see is having a problem. I think they expect me to have it perfect. I don't know. People have said when they meet me, it's great, it just shows that diabetes doesn't have to wear you down. I don't really want to admit to them if I'm struggling. I feel like I play this role, they look at me and go, there's hope there so I don't want to ruin that for them (Female, 27). Secondly, a number of young adults noted that peersupport groups required resources for them to be optimally successful. At a minimum, real-life support groups required rooms in clean, well-lighted places where meetings could be held. Support groups-both online and offline-also demanded significant amounts of time and effort from moderators and group organizers. These time demands could at times cause group moderators to experience some difficulties, as they usually ran these groups while working full-time jobs and juggling other commitments such as children. Several peer-group organizers who we interviewed noted that they had approached hospitals to ask for small amounts of funding to support their groups; however while hospitals were often enthusiastic about the idea of young adult support groups, they said that they were unable to fund them in any way. I said to a consultant, 'I know the Irish health system won't want to know because it may cost money'. He just laughed and was like, forget it. He said he can't get what he needs and he is the hospital, not a support group (Female, 30). Distress is not an issue Finally, four interviewees (see Table 2) indicated in their interviews that they were not distressed either by having or by managing diabetes. I've had it long enough that it seems like I've always had it. I don't remember it ever being hugely problematic (Female, 25). Two of these interviewees were male, two were female. Three were thirty years of age, one twenty-five. Three were married, the other in a long-term relationship. Three had been diagnosed with diabetes in their twenties, the other in her late teens. All indicated that they had positive relationships with their healthcare professionals. Two worked in finance; the other two had worked in finance in the past, and at the time that the study was conducted had gone back to University (both to study science subjects). All four therefore appeared to have support from the official health system, had stable personal lives, were educated, had quantitative backgrounds. All four appeared to take active problemsolving approaches to their diabetes, with three of the four noting that they preferred to solve diabetes-related problems for themselves rather than contact their diabetes clinic. I've a maths degree originally, so I was working out tables for how much sugar to set off against the carb intake and working out how much carbs I was eating and so on (Male, 30). I would be the kind of person who'd just figure it out myself. But you know, sat down, read what the disease was, how it's generally treated and how the regimes work (Male, 30). These interviewees also described themselves as being flexible and able to deviate from diabetes management guidelines without becoming anxious. They noted that they had adjusted very quickly to having diabetes. Two of these interviewees felt that that their lifestyles changed relatively little after they were diagnosed, and one said that his brother had previously been diagnosed with diabetes, which meant that his life had already been preadapted to diabetes to some extent prior to diagnosis. These interviewees also felt that they were psychologically resilient and able to deal with adversity without becoming overwhelmed. Discussion This study helps to address the lack of research on the causes of diabetes-related distress in young adults in their 20s. Quantitative research suggests that diabetes distress is an important issue in this age group. The utility of the study's findings are that they provide a list of topics that healthcare professionals can use to start dialogues with these young people. A range of sources of distress were identified by this project, including: stigma/self-consciousness; concerns about Type 2 diabetes; day-to-day management difficulties; struggles with the healthcare system; fears about the future; negative media portrayals of diabetes; and concerns about pregnancy. Previous research has identified several of these factors as being distressing to people with Type 1 diabetes, though not necessarily to young adults in their twenties. People with diabetes have been noted to become distressed when they feel restricted or disadvantaged. Many find the unremitting nature of day-to-day management to be emotionally difficult. A number of young adults feel awkward managing their diabetes around other people and a minority appear to fear that other people will not accept them. As noted, some interviewees in this study were either concerned that they would be stigmatized for having Type 1 diabetes, or concerned that they would be mistakenly stigmatized for having Type 2 diabetes. Several young adults themselves appeared to stigmatize other people with Type 2 diabetes. Schabert et al. note that diabetes-related stigma-whatever its source-can have significant negative impacts on people with diabetes' psychological well-being. The findings here suggest that stigma is not only a serious problem itself, it can also discourage young adults from seeking help for diabetes-related distress; one female interviewee, for example, noted that she would not join Facebook support groups in order to protect her identity. Young adults' concerns about being mistaken for having Type 2 diabetes likely reflect wider negative social understandings of Type 2 diabetes as a 'ticking timebomb', and people who develop Type 2 diabetes as risky, uncontrolled and obese subjects. It was evident that interviewees were anxious that the general public would be unable to differentiate between Type 1 and Type 2 diabetes. Interviewees' anxieties here could have been further accentuated by the fact that many young women with Type 1 diabetes appear to experience increases in their body mass index as they transition through their twenties. These young women may therefore feel that if other people see someone with a 'large' body, and associate that body with the word 'diabetes', they will assume that the young person has developed diabetes as a result of an inability to self-regulate. It was notable as well that some young people felt that people with Type 1 diabetes were competing for resources with people with Type 2 diabetes. Competition for scarce economic resources often intensifies stigmatization processes and may have contributed to some interviewees' hostility towards people with Type 2 diabetes. Fears about the future have previously been found to hang over the heads of some young people with diabetes like a 'sword of Damocles'. Complications can be distressing not only in and of themselves, but also because they can undermine young adults' life plans and career aspirations. Young adults have also been noted to be concerned about the complicating impacts of diabetes on pregnancy. Other studies have indicated that young adults can become very distressed at hypoglycaemia, though this was something that we did not detect to any great extent in this study. The young adults who we interviewed reported being much more anxious about developing hyperglycaemia than they were about 'going low'. Young adults' developmental position may help to explain some of these findings. As noted, the young adults in this study were in the second, 'stabilizing' phase of young adulthood. Previous theoretical research suggests that young people in this age range become increasingly concerned about their diabetes management. They tend to lose their adolescent sense of invulnerability. Simultaneously, they are transitioning from young adult to adult health services where they are either sometimes beginning to develop diabetes-related complications themselves, or beginning to see the consequences of such complications in other people. They desire to build positive relationships with healthcare providers and engage with their healthcare system. This theoretical work would suggest that fears about the future become increasingly salient for individuals in this age group, more than anxieties about shortterm complications, as would fears about pregnancy (young adults in their twenties would be at an age where they would seriously be beginning to consider having children, with all of the risks and complications that entails). It would also suggest that young adults-who wish to engage with health services in order to improve their control and to reduce their risk of developing complicationswould become distressed if they perceive services to be unresponsive to their needs. Overall, the findings of this study indicate that individuals in the second phase of young adulthood can experience significant diabetes-related emotional struggles. However, clinicians have often not paid the same attention to the emotional problems of these individuals as they have to their younger counterparts, those in their late teens and early 20s. 'Older' young adults in their mid to late 20s are often treated in adult services where psychological support is absent, where continuity of care is lacking and where interactions with professionals are focused on HbA1c scores and other clinical measures. It was notable in this study that although participants experienced diabetes-related distress, they also generally had reasonably good diabetes control. Although we cannot state this point definitively (as the study is based exclusively on patient perceptions of healthcare professionals' practices), it may be that some clinicians and other professionals are briefly interacting with these young adults, seeing reasonably good HbA1c scores, thinking that everything is acceptable, and moving on to the next patient; or are aware of distress in this group but do not feel that that they have the time or the expertise to deal with these issues within the context of regular clinical appointments. It may therefore be that distress in more 'successful' young adults such as the ones in this study is either being elided or bracketed by some professionals. It is important that healthcare professionals address diabetes-related distress in young adults with Type 1 diabetes, particularly given that distress is associated with poor clinical outcomes in many patients though there are subsets of patients for whom distress may have beneficial impacts upon self-care, possibly by encouraging young adults to regulate themselves in order to reduce feelings of anxiety. Gonzalez et al. suggest that the best way for professionals to manage diabetes distress may simply be to have brief, direct and ongoing conversations with patients. Finding the time to do so may be difficult in the context of a typical clinical appointment; nevertheless it is important. The findings of this study also suggest that it could be important to offer young adults opportunities to attend structured diabetes education programmes and provide them with access to technologies that they can use to improve their control such as CSII. All of these suggestions come with cost and resource implications. A number of researchers have indicated that an efficient way of helping young adults to manage distress may be by helping them to develop and maintain peer support networks. However the findings of this study indicate that volunteer-led peer support groups should not be seen as a way to provide young adults with 'free' social support. These groups require resources and inputs from volunteers, even if it is just in terms of their time and effort. It is unclear how resilient these peer-support networks will be over time without support (money/training/encouragement) from the official health system. The young adults who run them will grow older, and possibly less willing to supply peer-support to younger adults who are experiencing issues that they have 'grown out' of. Finally, the findings of this study suggest that it may be useful for clinicians and diabetes researchers to engage with the media to ensure that representations of diabetes are not overwhelmingly negative, and that Type 1 and Type 2 diabetes are sufficiently differentiated. The main limitation of the study is the self-selected nature of the young adult sample (as Table 1 highlights most of the sample was composed of educated young women with reasonably good control). Another limitation was that the sample was recruited from Facebook and may reflect a particularly engaged cohort of young people (those engaged with their diabetes to seek Internet support or information). Some of the solutions to diabetes distress that respondents proposed, such as peer support groups, may not be relevant for other individuals for whom interacting with peers with diabetes is not so important. We did not assess the intensity of young adults' diabetes-related distress; some young adults who felt angry at Type 2 diabetes might have been very angry at Type 2, others 'merely' annoyed. It is difficult to definitively state if, and if so how, the interviewer's identity impacted the information that was disclosed in the interviews. However it may have been that some very sensitive issues, such as distress arising as a result of psychosexual issues or eating disorder behaviours, were not revealed to the male interviewer by the predominantly female group who took part in this project. Conclusions Many aspects of managing diabetes distress young adults with Type 1 diabetes who are in their twenties. The most common factors identified in this study were stigma, day-to-day diabetes management difficulties, concerns about the future and apprehension about pregnancy. Young adults felt that diabetes distress was often missed during clinical appointments. A number of factors may help to moderate distress in young adults in their 20s, including having opportunities to talk to healthcare professionals, attending diabetes education programmes and joining peer support groups. Further research is needed to determine which interventions are most effective in addressing distress in this age group. It would also be useful if future research explores why some young adults do not become distressed as a result of living with a condition such as Type 1 diabetes.
<gh_stars>1-10 package com.hannesdorfmann.mosby.sample.dagger1.model; import com.hannesdorfmann.mosby.retrofit.exception.NetworkException; /** * @author <NAME> */ public class ErrorMessageDeterminer { public String getErrorMessage(Throwable e, boolean pullToRefresh) { if (e instanceof NetworkException) { return "Network Error: Are you connected to the internet?"; } return "An unknown error has occurred"; } }
/** * This file is part of FreeJ2ME. * * FreeJ2ME is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * FreeJ2ME is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with FreeJ2ME. If not, * see http://www.gnu.org/licenses/ * */ package javax.microedition.lcdui; public abstract class CustomItem extends Item { protected static final int KEY_PRESS = 4; protected static final int KEY_RELEASE = 8; protected static final int KEY_REPEAT = 0x10; protected static final int NONE = 0x00; protected static final int POINTER_DRAG = 0x80; protected static final int POINTER_PRESS = 0x20; protected static final int POINTER_RELEASE = 0x40; protected static final int TRAVERSE_HORIZONTAL = 1; protected static final int TRAVERSE_VERTICAL = 2; protected CustomItem(final String label) { setLabel(label); } public int getGameAction(final int keycode) { return 0; } protected final int getInteractionModes() { return 0xFC; } protected abstract int getMinContentHeight(); protected abstract int getMinContentWidth(); protected abstract int getPrefContentHeight(int width); protected abstract int getPrefContentWidth(int height); protected void hideNotify() { } protected final void invalidate() { } protected void keyPressed(final int keyCode) { } protected void keyReleased(final int keyCode) { } protected void keyRepeated(final int keyCode) { } protected abstract void paint(Graphics g, int w, int h); protected void pointerDragged(final int x, final int y) { } protected void pointerPressed(final int x, final int y) { } protected void pointerReleased(final int x, final int y) { } protected final void repaint() { } protected final void repaint(final int x, final int y, final int w, final int h) { } protected void showNotify() { } protected void sizeChanged(final int w, final int h) { } protected boolean traverse(final int dir, final int viewportWidth, final int viewportHeight, final int[] visRect_inout) { return true; } protected void traverseOut() { } }
Former Secretary of State John Kerry John Forbes KerryTrump: 'Iran is being given very bad advice by John Kerry' Trump removes sanctions waivers on countries buying oil from Iran Buttigieg to fundraise in DC with major Obama, Clinton bundlers next month: report MORE lambasted the current state of Washington in an interview that aired Sunday, railing against the partisanship plaguing Capitol Hill. “Washington is broken. Most Americans understand that. It’s a mess. The Congress is dysfunctional because it’s torn apart ideologically. Politically, it’s in a bad place. And it’s a sad thing,” Kerry said on John Catsimatidis’s radio show. “The extremes on both sides started to demand, ‘Well, you can’t do that and you can’t do this,’ and, in the end, nothing happened," he added. "Historically, our country has done best when people acted in the interest of the country, not in the interest of one party or the other party." Kerry predicted that the frustration with dysfunction on Capitol Hill would manifest itself in the upcoming midterm elections. “I think there’s going to be a reaction in the midterms. … People are very angry at what’s been going on. I don’t know which party benefits where on that. My hope is that, regardless of what party you come from, you’re going to come to Washington determined to work together to make things happen in the best interest of the country,” he said. Election prognosticators have floated Kerry, who lost the 2004 presidential election, as a potential 2020 presidential contender to face off against President Trump Donald John TrumpTrump calls Sri Lankan prime minister following church bombings Ex-Trump lawyer: Mueller knew Trump had to call investigation a 'witch hunt' for 'political reasons' The biggest challenge from the Mueller Report depends on the vigilance of everyone MORE. “I’m not ruling anything out, but I’m not sitting around actively laying the groundwork or making any plans. I think the focus of everybody right now should be on the election that’s going to take place in 33 days. We have an opportunity in the midterms to voice our dissatisfaction. We have a lot of good candidates around,” Kerry responded. Should Kerry run, he would likely join a crowded Democratic field, yet could differentiate himself by casting his candidacy as moderate while other candidates seek to appeal to the progressive wing of the party.
In recent years, servers and information communication devices have been widely spreading to support a social infrastructure, but the power consumption thereof increases and the need for reducing this increases. Therefore, in the field of telecommunications carriers and data center operators, the following DC power feeding system is known. An AC power supply is converted to high voltage of, for example, DC 380 volts (hereinafter, referred to as DC 380 V) to supply power with high voltage, whereby load current is decreased and thin wires can be used. Thus, the installation cost can be reduced. In addition, by adapting loads to DC 380 V and to high voltage DC power feeding, power loss due to DC/AC conversion and DC/DC conversion is reduced, whereby energy saving is achieved. In this field, servers and communication equipment which are loads are being increasingly adapted to DC 380 V. However, for example, in the case where there are AC loads such as an air conditioner, fire-fighting equipment, and an existing server that cannot be adapted to DC 380 V, power of DC 380 V is converted to AC power by a DC/AC conversion device and the AC power is supplied to these loads. In addition, in the case where there are loads such as DC-48-V loads and DC-12-V loads other than DC-380-V loads, power of DC 380 V is converted to voltages adapted to the respective loads by DC/DC conversion devices, and the converted voltages are supplied. In particular, in this field, the DC/AC conversion device and the DC/DC conversion device are called migration devices. One example of such devices is disclosed in Patent Document 1. In Patent Document 1, an electronic device having a circuit configuration shown in FIG. 3 of Patent Document 1 is mounted, as shown in FIG. 4, in an electronic device storage box in which electronic devices such as an exchange device and an optical fiber termination device are to be mounted. As shown in Patent Document 1, conventional standard electronic device storage boxes are storage boxes of JIS standard and EIA standard which are called 19-inch rack. A migration device 4 formed with a 19-inch rack as an electronic device storage box shown in FIG. 4 of Patent Document 1 is configured as shown in, for example, FIG. 1B of the drawings of the present application. The electronic device storage box is composed of a pair of box bodies, and one of the box bodies stores: communication electronic devices EM (DC) of DC-driven type such as a router and a switching hub; a DC/AC converter CV (AC) of AC-driven type; and a rectifier RF for performing DC power feeding. The other box body stores: communication electronic devices EM (AC) of AC-driven type such as a firewall; and four servers SV (DC) of DC-driven type. As shown in FIG. 3 of Patent Document 1, a commercial power supply is converted to DC power through AC/DC conversion, and then the DC power is directly supplied to DC loads, and meanwhile, for AC loads, the DC power is converted into AC power through DC/AC conversion and the AC power is supplied to the AC loads. Even in the case of DC loads, if, for example, a power supply is DC 100 V but the load is adapted to DC 48 V, the power supply is converted to DC 48 V through DC/DC conversion in accordance with the load, and the converted power is supplied to the load. In the case where a plurality of loads are connected to the load side of a rectifier 2 as shown in FIGS. 1A and 1B of the drawings of the present application, there is known a system of supplying power to the loads via a distribution panel provided with a wiring circuit breaker and a fuse as shown in Patent Document 2.
. Drug interactions are the side effect of administration of two or more drugs or a drug-food combination. Although some drug interactions are intentional and beneficial to the patient, the majority are unintentional and associated with a potentially harmful effect. The aim of this study was to search for interactions in rats between fluoride and zinc administered orally for 12 weeks and to elucidate any potential toxicological and therapeutic consequences. 60 male Wistar rats were divided into six groups of ten rats each and exposed to: 1. controls (distilled water); 2. sodium fluoride (NaF); 3. low-dose zinc (Zn); 4. high-dose zinc; 5. NaF + low-dose Zn; 6. NaF + high-dose Zn. At the end of the experiment the content of F- and Zn+ in serum, urine, incisors, femur and mandible was measured and densitometry of femoral bones was performed. Serum alkaline phosphatase, alanine and aspartate aminotransferase activities, as well as bilirubin and creatinine concentrations were determined to confirm non-toxicity of fluoride dose. Animals receiving NaF only demonstrated higher content of fluorine in serum, urine bones and teeth. Zinc concentrations in serum, urine, bones and teeth were elevated in rats receiving zinc with or without NaF. Fluorine accumulation in bones and teeth was reduced by Zn, but in general the effect lacked statistical significance. Zinc slightly reduced the concentrations of fluorine in serum and urine. Sodium fluoride slightly reduced the concentration of zinc in serum and urine. Bone mineral content (BMC) was significantly increased by NaF and was not further increased by co-administration of zinc. No changes in serum alkaline phosphatase, alanine and aspartate aminotransferase activities, bilirubin and creatinine concentrations were detected. In conclusion, simultaneous administration of fluorine and zinc may be beneficial for prevention and treatment of pathologic conditions in bones and teeth and is not accompanied by an increase in fluorine levels which could be responsible for toxicological symptoms.
// // UITextField+PSG_ChainFunction.h // YOUHUO // // Created by SNICE on 2018/6/6. // Copyright © 2018年 G. All rights reserved. // #import <UIKit/UIKit.h> @interface UITextField (PSG_ChainFunction) + (UITextField *)g_init; - (UIView *)g_viewMaker; - (UIControl *)g_controlMaker; #pragma mark - UITextInputTraits @property (nonatomic, copy, readonly) UITextField *(^g_autocapitalizationType)(UITextAutocapitalizationType); @property (nonatomic, copy, readonly) UITextField *(^g_autocorrectionType)(UITextAutocorrectionType); @property (nonatomic, copy, readonly) UITextField *(^g_spellCheckingType)(UITextSpellCheckingType) NS_AVAILABLE_IOS(5_0); @property (nonatomic, copy, readonly) UITextField *(^g_smartQuotesType)(UITextSmartQuotesType) NS_AVAILABLE_IOS(11_0); @property (nonatomic, copy, readonly) UITextField *(^g_smartDashesType)(UITextSmartDashesType) NS_AVAILABLE_IOS(11_0); @property (nonatomic, copy, readonly) UITextField *(^g_smartInsertDeleteType)(UITextSmartInsertDeleteType) NS_AVAILABLE_IOS(11_0); @property (nonatomic, copy, readonly) UITextField *(^g_keyboardType)(UIKeyboardType); @property (nonatomic, copy, readonly) UITextField *(^g_keyboardAppearance)(UIKeyboardAppearance); @property (nonatomic, copy, readonly) UITextField *(^g_returnKeyType)(UIReturnKeyType); @property (nonatomic, copy, readonly) UITextField *(^g_enablesReturnKeyAutomatically)(BOOL); @property (nonatomic, copy, readonly) UITextField *(^g_secureTextEntry)(BOOL); @property (nonatomic, copy, readonly) UITextField *(^g_textContentType)(UITextContentType) NS_AVAILABLE_IOS(10_0); #pragma mark - UIContentSizeCategoryAdjusting @property (nonatomic, copy, readonly) UITextField *(^g_adjustsFontForContentSizeCategory)(BOOL) NS_AVAILABLE_IOS(10_0); #pragma mark - textField @property (nonatomic, copy, readonly) UITextField *(^g_text)(NSString *); @property (nonatomic, copy, readonly) UITextField *(^g_attributedText)(NSAttributedString *) NS_AVAILABLE_IOS(6_0); @property (nonatomic, copy, readonly) UITextField *(^g_textColor)(UIColor *); @property (nonatomic, copy, readonly) UITextField *(^g_font)(UIFont *); @property (nonatomic, copy, readonly) UITextField *(^g_textAlignment)(NSTextAlignment); @property (nonatomic, copy, readonly) UITextField *(^g_borderStyle)(UITextBorderStyle); @property (nonatomic, copy, readonly) UITextField *(^g_defaultTextAttributes)(NSDictionary<NSString *, id> *); @property (nonatomic, copy, readonly) UITextField *(^g_placeholder)(NSString *); @property (nonatomic, copy, readonly) UITextField *(^g_attributedPlaceholder)(NSAttributedString *); @property (nonatomic, copy, readonly) UITextField *(^g_clearsOnBeginEditing)(BOOL); @property (nonatomic, copy, readonly) UITextField *(^g_adjustsFontSizeToFitWidth)(BOOL); @property (nonatomic, copy, readonly) UITextField *(^g_delegate)(id<UITextFieldDelegate>); @property (nonatomic, copy, readonly) UITextField *(^g_background)(UIImage *); @property (nonatomic, copy, readonly) UITextField *(^g_disabledBackground)(UIImage *); @property (nonatomic, copy, readonly) UITextField *(^g_allowsEditingTextAttributes)(BOOL) NS_AVAILABLE_IOS(6_0); @property (nonatomic, copy, readonly) UITextField *(^g_typingAttributes)(NSDictionary<NSString *, id> *) NS_AVAILABLE_IOS(6_0); @property (nonatomic, copy, readonly) UITextField *(^g_clearButtonMode)(UITextFieldViewMode); @property (nonatomic, copy, readonly) UITextField *(^g_leftView)(UIView *); @property (nonatomic, copy, readonly) UITextField *(^g_leftViewMode)(UITextFieldViewMode); @property (nonatomic, copy, readonly) UITextField *(^g_rightView)(UIView *); @property (nonatomic, copy, readonly) UITextField *(^g_rightViewMode)(UITextFieldViewMode); @property (nonatomic, copy, readonly) UITextField *(^g_clearsOnInsertion)(BOOL) NS_AVAILABLE_IOS(6_0); @property (nonatomic, copy, readonly) UITextField *(^g_targetAction)(id, SEL, UIControlEvents); @property (nonatomic, copy, readonly) UITextField *(^g_inputAccessoryView)(UIView *); @property (nonatomic, copy, readonly) UITextField *(^g_inputView)(UIView *); #pragma mark layer - (CALayer *)g_layerMaker; @end
Imaging diagnosis--celiac artery pseudoaneurysm associated with a migrating grass awn. The ultrasound and computed tomography findings of a retroperitoneal pseudoaneurysm associated with a grass awn are described in a 10-month-old dog. Ultrasound was used to localize the lesion and surrounding reaction as well as to determine its relationship with the celiac artery, but inadequate Doppler settings hindered the diagnosis of its vascular nature. Dual phase CT enabled further characterization, particularly its close relationship with the major retroperitoneal vessels. The imaging examination was fundamental in recommending nonsurgical therapy. The dog died as a consequence of the rupture of this pseudoaneurysm. A grass awn was confirmed.
5-HT1A receptor blockade reverses GABAA receptor 3 subunit-mediated anxiolytic effects on stress-induced hyperthermia Rationale Stress-related disorders are associated with dysfunction of both serotonergic and GABAergic pathways, and clinically effective anxiolytics act via both neurotransmitter systems. As there is evidence that the GABAA and the serotonin receptor system interact, a serotonergic component in the anxiolytic actions of benzodiazepines could be present. Objectives The main aim of the present study was to investigate whether the anxiolytic effects of (non-)selective subunit GABAA receptor agonists could be reversed with 5-HT1A receptor blockade using the stress-induced hyperthermia (SIH) paradigm. Results The 5-HT1A receptor antagonist WAY-100635 (0.11 mg/kg) reversed the SIH-reducing effects of the non--subunit selective GABAA receptor agonist diazepam (14 mg/kg) and the GABAA receptor 3-subunit selective agonist TP003 (1 mg/kg), whereas WAY-100635 alone was without effect on the SIH response or basal body temperature. At the same time, co-administration of WAY-100635 with diazepam or TP003 reduced basal body temperature. WAY-100635 did not affect the SIH response when combined with the preferential 1-subunit GABAA receptor agonist zolpidem (10 mg/kg), although zolpidem markedly reduced basal body temperature. Conclusions The present study suggests an interaction between GABAA receptor -subunits and 5-HT1A receptor activation in the SIH response. Specifically, our data indicate that benzodiazepines affect serotonergic signaling via GABAA receptor 3-subunits. Further understanding of the interactions between the GABAA and serotonin system in reaction to stress may be valuable in the search for novel anxiolytic drugs. Introduction Stress-related disorders are associated with dysfunction of both serotonergic and GABAergic pathways (;Kalueff and Nutt 2007;Nemeroff 2003). The clinical anxiolytic effects of selective serotonin reuptake inhibitors, 5-HT 1A receptor agonists and GABA A receptor agonists, indicate that both the GABA A ergic as well as the serotonergic system may be involved in the pathological basis underlying anxiety disorders (Nutt 2005;Zohar and Westenberg 2000). There is evidence that the GABA and the serotonergic system interact (Fernandez-Guasti and Lopez-Rubalcava 1998;;), although the evidence whether it plays a role in the stress response is inconsistent (;Thiebot 1986). Specifically, a serotonergic component in the anxiolytic actions of benzodiazepines has been suggested (;;). Hence, studying the interactions of the GABA A and serotonin system in stress and anxiety could be valuable in the search for novel anxiolytic drugs. Here, we investigate whether the anxiolytic effects of GABA A receptor agonists are dependent on 5-HT 1A receptor activation using the stress-induced hyperthermia (SIH) paradigm. The SIH response is the transient rise in body temperature in response to acute stress that is mediated by the autonomic nervous system (;). Both classical benzodiazepines and 5-HT 1A receptor agonists consistently reduce the SIH response (as well as basal body temperature at higher doses), whereas dopaminergic and noradrenergic systems are generally ineffective (). Classical (non-subunit selective) benzodiazepines bind to GABA A receptor 1 -, 2 -, 3 -, or 5 -subunits, and the various benzodiazepine effects are thought to be mediated through different GABA A receptor subtypes (Rudolph and Mohler 2006). Interactions with the serotonergic system may thus depend on the GABA A receptor composition. In the present study, we investigated whether the silent 5-HT 1A receptor antagonist WAY-100635 (WAY) could alter the SIH-reducing and hypothermic effects of the nonsubunit selective GABA A receptor agonist diazepam, the selective GABA A receptor 3 -subunit agonist TP003 (), and the preferential GABA A receptor 1subunit agonist zolpidem. Animals Eighty-four male NMRI mice (Charles River, The Netherlands) were housed in Macrolon type 3 cages enriched with bedding and nesting material under a 12-h light/12-h dark cycle (lights on from 0600 to 1800 hours) at controlled temperature (22±2°C) and relative humidity (40-60%) with free access to standard food pellets and tap water. Experiments were carried out with approval of the ethical committee on animal experiments of the Faculties of Sciences, Utrecht University, The Netherlands, and in accordance with the Declaration of Helsinki. The stress-induced hyperthermia (SIH) procedure The SIH tests were carried out one time per week according to standard procedures. A betweensubject design was used, and animals were randomly allocated to an experimental group. Cages were randomly and evenly allocated over daytimes (morning to afternoon). The temperature of mice was measured by rectally inserting a thermistor probe by a length of 2 cm. Digital temperature recordings were obtained with an accuracy of 0.1°C using a Keithley 871A digital thermometer (NiCr-NiAl thermocouple). The probe, dipped into silicon oil before inserting, was held in the rectum until a stable rectal temperature had been obtained for 20 s. Animals were injected intraperitoneally with vehicle or WAY-100635 on the left flank and with vehicle, diazepam, zolpidem, or TP003 on the right flank. All drugs were injected 60 min before the first temperature measurement (T 1 ). This first temperature measurement, representing the basal body temperature, functioned as an adequate stressor as well. The temperature was again measured 10 min later (T 2 ), representing the stress-induced body temperature. The SIH response was calculated by subtracting T 1 from T 2. Data analysis All experiments were carried out using a between-subject design. For each individual mouse, a basal temperature (T 1 ), an end temperature (T 2 ), and the difference (SIH response=T 2 − T 1 ) were determined. Treatment effects were evaluated using a two-way analysis of variance with explanatory factors drug 1 (WAY-100635 or vehicle) and drug 2 (diazepam/zolpidem/ TP003 or vehicle). In addition, a post-hoc analysis was carried out comparing diazepam/zolpidem/TP003 with vehicle under both WAY-100635 and vehicle conditions using a Tukey's Honestly Significant Difference (HSD) test. A probability level of p<0.05 was set as statistically significant. Discussion The present study investigated putative GABA-serotonin interactions using the SIH paradigm. Our main finding is that the non-selective GABA A receptor agonist diazepam Fig. 2 Effects of (a, b) diazepam (1 and 4 mg/kg, IP, n=8-10), (c) TP003 (1 mg/kg, IP, n=7-10), and (d) zolpidem (10 mg/kg, IP, n=8-10) administration in combination with WAY-100635 (0.1-1 mg/kg, IP) or vehicle on basal body temperature. Asterisk (*), p<0.05: drug effect compared to corresponding vehicle; number sign (#), p<0.05: drug effect under vehicle vs. WAY conditions and the 3 -subunit selective GABA A receptor agonist TP003 no longer reduced the SIH response and augmented hypothermia in the presence of the 5-HT 1A receptor antagonist WAY-100635, suggesting an interaction between the activation of the GABA A receptor 3 -subunits and 5-HT 1A receptors. In contrast, WAY-100635 did not have any effect when it was combined with the preferential 1 -subunit GABA A receptor agonist zolpidem. As WAY-100635 has no affinity for GABA A receptors, our data suggest that in the SIH paradigm, anxiolytic effects of GABA A receptor agonists may be mediated via the serotonin system. Thus, benzodiazepines may affect serotonergic signaling via 3 -subunits on a distinct group of serotonergic neurons. In support, the vast majority of serotonergic neurons express GABA A receptor 3 -subunit immunoreactivity but not GABA A receptor 1 -subunit staining (). This is remarkable as the 1 -subunit is highly prevalent in the central nervous system. The effects of the GABAergic drugs diazepam, TP003, and zolpidem on the SIH response and body temperature are generally in line with earlier SIH studies (;Vinkers et al., 2009. Diazepam effects on basal body temperature slightly varied over the experiments, which may be attributed to fluctuations in body temperature under vehicle conditions due to physiological variance, differences in environmental temperature, or the time of testing. Classical non-selective benzodiazepines enhance the inhibitory actions of GABA by binding to an allosteric site on GABA A receptors that contain 1 -, 2 -, 3 -, or 5subunits in combination with a and a 2 subunit (Rudolph and Mohler 2006). Zolpidem is approximately five-to tenfold more selective for 1 -subunit-containing GABA A receptors than 2 / 3 -subunit-containing receptors (), whereas TP003 is 3 -subunit selective with low modulation via 1 -, 2 -, and 5containing subtypes (). Recently, genetic and pharmacological evidence has indicated that -subunits may differentially contribute to the various classical benzodiazepine-induced effects such as anxiolysis, dependence, anticonvulsant activity, sedation, and amnesia (;). Here, we confirm and extend our earlier findings suggesting a role for the GABA A receptor 1 subunit in hypothermia and a role for the GABA A receptor 2/3 subunit in reduction of the SIH response ). In the present study, WAY-100635 did not affect the SIH response in any of the experiments when it was administered alone which is in line with earlier studies (. The 5-HT 1A receptor antagonist WAY-100635 is generally assumed to act as silent antagonist but has also been reported to exert anxiolytic or even anxiogenic effects depending on the experimental design (Cao and Rodgers 1997;;;;;;Stanhope and Dourish 1996). WAY-100635 has also been shown to reverse the SIH-reducing effects of 5-HT 1A receptor agonists such as buspirone and flesinoxan, confirming that WAY-100635 targets 5-HT 1A receptors (;). Interestingly, WAY-100635 has also been able to reverse the SIH reduction caused by the mGluR 2/3 receptor antagonist MGS0039, suggesting that the 5-HT 1A receptors may also be involved in the effects of glutamate receptor antagonists (). WAY-100635 could reverse the 3 -induced effects in the SIH paradigm by blocking presynaptic 5-HT 1A receptors that disinhibit serotonin release and turnover at synaptic levels (), which may then activate postsynaptic 5-HT receptors. Electrophysiological studies show that WAY-100635 increases serotonergic neuronal activity probably by blocking 5-HT 1A autoreceptors ;). In support, serotonergic raphe nuclei receive a prominent GABAergic input via distant sources as well as interneurons (;;;). However, this can only provide a partial explanation as WAY-100635 also augmented the benzodiazepine-induced hypothermia, putatively via an activation of 1 -subunits ). Also, raphe lesions did not attenuate the anticonflict activity of peripherally administered benzodiazepines, suggesting that difficulties may exist in generalizing findings from one paradigm to another (Green and Hodges 1986). Furthermore, it is striking that WAY-100635 reverses the SIH response while it augments the hypothermia. It may be hypothesized that GABA A -serotonin interactions relevant for thermoregulation exist in the preoptic area or dorsomedial hypothalamus (Dimicco and Zaretsky 2007) or, alternatively, that dorsal and median raphe projections differentially affect basal and stress-induced body temperature levels. In support, 5-HT was found to presynaptically inhibit GABA release in the thermoregulatory hypothalamic medial preoptic area, which could be blocked by a 5-HT 1A receptor antagonist (). We also cannot exclude the possibility that downstream activation of hypothalamic 5-HT 1A receptors, subsequent to the direct activation of GABA A receptors, is needed to maintain the core body temperature. Thus, detailed hypotheses on the potential interactive sites of GABA A receptors and 5-HT 1A receptors and their functional relevance must await further experimental analysis. Some studies have found decreased serotonin activity and turnover after benzodiazepine administration (;;;;), although others have not found such effects (;Thiebot 1986;). The present study used the SIH paradigm as an anxiolytic assay as it can repeatedly be used over the weeks without any habituation. However, the use of a single paradigm prevents a direct generalization of our results to other anxiolytic tests. In conclusion, the present study shows that 5-HT 1A receptor blockade reversed the anxiolytic effects of the non-selective GABA A receptor agonist diazepam and the 3 -selective GABA A receptor agonist TP003, whereas it enhanced benzodiazepine-induced hypothermia. In contrast, these effects were not present in combination with the preferential GABA A receptor 1 -subunit agonist zolpidem. Together, these data suggest that the GABA A receptor 3 -subunit functionally interacts with 5-HT 1A receptors of the serotonin system to exert its anxiolytic effects in the SIH paradigm. Conflicts of interest The authors declare no financial disclosures or conflicts of interest. Open Access This article is distributed under the terms of the Creative Commons Attribution Noncommercial License which permits any noncommercial use, distribution, and reproduction in any medium, provided the original author(s) and source are credited.
<gh_stars>0 import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' const { stringify } = JSON export async function serverlessPluginTypescript( event: APIGatewayProxyEvent, context: APIGatewayProxyResult, ) { return { body: stringify({ hello: 'serverless-plugin-typescript!' }), statusCode: 200, } }
// newAuthenticator creates an Authenticator for use in tests. func newAuthenticator() *Authenticator { config := &Config{ ClientID: "test1", ClientSecret: "efed2228-081e-4226-8135-55df6e9fa369", IssuerURL: "http://idp.local/auth/realms/test", LogoutURL: "http://idp.local/auth/realms/test/protocol/openid-connect/logout", CallbackURL: "http://app.local/auth/callback", DefaultReturnURL: "http://app.local", AllowedOrigins: []string{"http://app.local", "http://idp.local"}, SessionStore: memstore.NewMemStore([]byte("1234"), []byte("1234567890123456")), TokenStore: memstore.NewMemStore([]byte("1234"), []byte("1234567890123456")), StateStore: oauth2state.NewMemStateStore(), } verifier := stubVerifier{ verifyOK: true, } oauthCfg := stubOAuthPackage{ Config: oauth2.Config{ ClientID: config.ClientID, ClientSecret: config.ClientSecret, Endpoint: oauth2.Endpoint{ AuthURL: "http://idp.local/auth/realms/test/protocol/openid-connect/auth", TokenURL: "http://idp.local/auth/realms/test/protocol/openid-connect/token", }, RedirectURL: config.CallbackURL, Scopes: []string{oidc.ScopeOpenID}, }, exchangeOK: true, } var auth = &Authenticator{ Config: *config, verifier: &verifier, oauthPkg: &oauthCfg, } return auth }
package base import "hash/fnv" //Hash returns fnv hash value func Hash(key string) int { h := fnv.New64() _, _ = h.Write([]byte(key)) data := h.Sum(nil) keyNumeric := int64(0) shift := 0 for i := 0; i < 8 && i < len(data); i++ { v := int64(data[len(data)-1-i]) if shift == 0 { keyNumeric |= v } else { keyNumeric |= v << uint64(shift) } shift += 8 } if keyNumeric < 0 { keyNumeric *= -1 } return int(keyNumeric) }
This Is Acting Background and development This Is Acting is Sia's follow-up to her sixth studio album 1000 Forms of Fear (2014). In December 2014, Sia told Spin that she had "two [more records] completed and ready to go". She revealed details of This Is Acting for the first time in an interview published by NME in February 2015. In the article, she confirmed once again that work on the album was finished and that its content was "more pop" than her previous material. She also revealed that the success of 1000 Forms of Fear, specifically its lead single "Chandelier", encouraged her to continue releasing new material, and said of the album's title: "I'm calling it This Is Acting because they are songs I was writing for other people, so I didn't go in thinking 'this is something I would say'. It's more like play-acting. It's fun." The album's cover art features Sia's face digitally altered. Shortly after Sia's announcement, Out published a list of her "10 Greatest Hits for Other Artists" in anticipation of the album. Release and promotion During an online chat with fans in April 2015, Sia revealed that the album would "probably" be released in early 2016, but possibly before the end of 2015. The Target-exclusive deluxe edition of This Is Acting features a song by the name of "Summer Rain." It is believed that this song was rejected by Christina Aguilera. An alleged track list for Aguilera's eighth studio album was leaked early in 2015, and the fifth track was entitled "Summer Rain", suggesting that she was planning on recording and releasing a song dedicated to her daughter with the same name. Sia is also listed as one of the producers on the record. Now that a song whose title is identical to Aguilera's alleged track name has been realized and placed on Sia's extended album, it is thought to have been planned for Aguilera initially, but declined shortly after. On 7 November 2015, Sia performed "Alive" and "Bird Set Free" on Saturday Night Live; the episode was hosted by Donald Trump. She performed "Alive" on The Ellen DeGeneres Show and The Voice on 1 December, followed by "Alive" on The X Factor in the United Kingdom on 6 December. Sia appeared on The Graham Norton Show on 11 December, where she sang "Alive" and it was revealed that she considered wearing a prosthetic mask instead of a wig. Sia performed "Cheap Thrills" on 27 January 2016 on The Tonight Show Starring Jimmy Fallon. Sia also appeared on The Late Late Show with James Corden playing "Carpool Karaoke" with Corden. A deluxe edition of This Is Acting was released on 21 October 2016 featuring seven new tracks, including 3 brand new tracks: "Confetti", "Midnight Decisions", and "Jesus Wept", as well as the single remix of "Cheap Thrills", the Alan Walker remix of "Move Your Body", and the solo and Kendrick Lamar-assisted versions of "The Greatest". Singles In September 2015, Sia confirmed the album's lead single "Alive" would be released later that month and was originally written for Adele; the English singer and songwriter co-wrote but "rejected" the song at the last minute. The album's release date, 29 January 2016, was confirmed in early November 2015. "Cheap Thrills" was released as the album's second official single on 11 February 2016, and it was originally planned for Rihanna. "The Greatest" was released as the first single from the deluxe version of the album on 5 September 2016. It features vocals from American rapper Kendrick Lamar. "Move Your Body" was released as the fourth single from the album on 6 January 2017. The song was originally planned for Shakira. Promotion singles "Bird Set Free" was released as the first promotional single along with the pre-order of the album on 4 November 2015. The song was originally written for Pitch Perfect 2 but it was rejected in favor of "Flashlight". The song was then pitched to Rihanna. After being rejected, it was then recorded by Adele but did not make the cut for her third studio album, 25. "One Million Bullets" was released as the second promotional single on 27 November 2015. The song is the only one on the album that was not pitched to another artist. "Cheap Thrills" was announced as the album's third promotional release and was released on 16 December 2015. The song was one of two tracks rejected by Rihanna who, as Sia described, was a no-show at the recording sessions. "Reaper" was released as the fourth promotional single on 7 January 2016. The song was written by herself and Kanye West for Rihanna, but Sia decided to keep it. "Unstoppable" was released as the fifth and final promotional single on 21 January 2016. Jessie Morris of Complex commented that the song sounds like a "page torn right out of Demi Lovato's Confident book", while editors of other media platforms like Idolator noticed this as well, which raised speculation that the track was intentionally written for Lovato. Tour On 16 May 2016, Sia announced her first tour in five years, Nostalgic for the Present Tour, and the tour dates for the North American leg. Miguel and AlunaGeorge were announced as the opening acts for the first leg. Commercial performance This Is Acting debuted atop the ARIA Albums Chart in Australia, and received a gold certification for sales of over 35,000 copies. It debuted at number four on the US Billboard 200 with first-week sales of 81,000 album equivalent units (68,000 in pure album sales), which became Sia's highest sales week in the country. As of 1 January 2017, the album has sold 299,600 copies and 904,000 total equivalent units in the United States. In its 26th week on Billboard 200, the album vaulted back into the top 10 for the first time since its debut week, as it rose 11-6 with 30,000 units, supported by the success of the second single "Cheap Thrills", which reached the summit of the Billboard Hot 100 at the time. In its 39th week, it vaulted 18-11 due to the deluxe edition of the album being released, and became the greatest gainer of the week. Also, during this week, the lead single off the deluxe edition, "The Greatest", rose 25-19. As of August 2017, the album has sold 2,000,000 copies worldwide.
Effect of duration of diabetes on the protection observed in the diabetic rat against gentamicin-induced acute renal failure. We have previously shown that the rat with experimental diabetes (DM) of 4-6 months' duration exhibits complete functional and morphologic protection against gentamicin-induced acute renal failure. To assess the role of the duration of the diabetic state per se on the resistance to gentamicin, female Sprague-Dawley rats with diabetes of short (5 days, n = 7), intermediate (5 weeks, n = 5) and long duration (5 months, n = 7) were studied. Diabetes was induced by streptozotocin, 50-65 mg/kg b.w. i.v. Controls were identically treated sex- and age matched nondiabetic rats. The animals were kept in individual metabolic cages for 2 weeks and all received gentamicin 40 mg/kg/day for 9 days. Sham animals (DM and control) received Ringer's solution in place of gentamicin. Prior to gentamicin, plasma glucose levels and creatinine clearances (Ccr) were higher in the DM long duration group (619 +/- 25 (SE) mg/dl; 2.6 +/- 0.2 ml/min, respectively) than in the DM short (514 +/- 24; 2.0 +/- 0.1) and DM intermediate duration (442 +/- 30; 2.1 +/- 0.1) groups, while urine volume and glycosuria were similar. Following gentamicin the three control groups developed acute renal failure (maximal decrease in Ccr of 60 +/- 7, 72 +/- 9 and 71 +/- 7%, respectively; p less than 0.01 to less than 0.001), lysozymuria and acute tubular necrosis. There were no significant differences in the degree of renal impairment observed among the three control groups. In marked contrast, in the three DM groups these changes were absent and the renal cortical gentamicin content was lower than that of the control groups.(ABSTRACT TRUNCATED AT 250 WORDS)
<gh_stars>10-100 package org.sagebionetworks.web.client.widget.clienthelp; import org.gwtbootstrap3.client.ui.Modal; import org.gwtbootstrap3.client.ui.TabListItem; import org.gwtbootstrap3.client.ui.TabPane; import com.google.gwt.dom.client.SpanElement; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class FileClientsHelpViewImpl implements FileClientsHelpView { @UiField SpanElement id1; @UiField SpanElement id2; @UiField SpanElement id3; @UiField SpanElement id4; @UiField SpanElement id5; @UiField SpanElement id6; @UiField SpanElement versionUI1; @UiField SpanElement versionUI2; @UiField SpanElement versionUI3; @UiField SpanElement version1; @UiField SpanElement version2; @UiField SpanElement version3; @UiField Modal modal; @UiField TabListItem cliTabListItem; @UiField TabListItem pythonTabListItem; @UiField TabListItem rTabListItem; @UiField TabPane cliTabPane; @UiField TabPane pythonTabPane; @UiField TabPane rTabPane; Widget widget; public interface Binder extends UiBinder<Widget, FileClientsHelpViewImpl> { } @Inject public FileClientsHelpViewImpl(Binder binder) { this.widget = binder.createAndBindUi(this); FileClientsHelpViewImpl.setId(cliTabListItem, cliTabPane); FileClientsHelpViewImpl.setId(pythonTabListItem, pythonTabPane); FileClientsHelpViewImpl.setId(rTabListItem, rTabPane); } public static void setId(TabListItem tabListItem, TabPane tabPane) { String id = HTMLPanel.createUniqueId(); tabListItem.setDataTarget("#" + id); tabPane.setId(id); } @Override public Widget asWidget() { return widget; } @Override public void configureAndShow(String entityId, Long version) { id1.setInnerHTML(entityId); id2.setInnerHTML(entityId); id3.setInnerHTML(entityId); id4.setInnerHTML(entityId); id5.setInnerHTML(entityId); id6.setInnerHTML(entityId); String versionString = version.toString(); version1.setInnerHTML(versionString); version2.setInnerHTML(versionString); version3.setInnerHTML(versionString); modal.show(); } @Override public void setVersionVisible(boolean visible) { UIObject.setVisible(versionUI1, visible); UIObject.setVisible(versionUI2, visible); UIObject.setVisible(versionUI3, visible); } }
Visually impaired people, the identification of the need for specialist provision: a historical perspective A characteristic of social policy evolution is the way in which certain groups become identified as worthy of specialist concern. This article shows how visually impaired people acquired a separate identity for the purpose of social policy provision and discusses the implications of blind registration procedures. It charts, over the period 1834-1988, not only the rise but also the decline of specialist provision.
<filename>build.rs extern crate bindgen; use std::env; use std::path::PathBuf; fn main() { println!("cargo:rustc-link-lib=pci"); let bindings = bindgen::Builder::default() .header("wrapper.h") .blacklist_type("u8") .blacklist_type("u16") .blacklist_type("u32") .blacklist_type("u64") .generate() .expect("failed to generate bindings"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("failed to write bindings"); }
Reduce Fingerprint Construction for Positioning IoT Devices Based on Generative Adversarial Nets Fingerprint-based positioning is popular and applicable for Internet of Things (IoT) applications to offer seamless, intelligent and adaptive location-aware services for IoT devices. However, it takes time and cost to build the radio-map. This paper proposed deep convolutional Generative adversarial nets (DCGANs) to minimize the site survey time and cost, and to mitigate signal fluctuations. The radio-map was designed for receiving radio signals from detectable wireless local area network (WLAN) and cellular networks in scalable environments. The proposed fingerprinting-based positioning is a sequential combination of the hybrid support vector machine and long short-term memory algorithms. The experimental results indicate that the proposed method achieves a promising and reasonable positioning performance for IoT devices in scalable wireless environments.
package com.ihltx.utility.es.annotations; import com.ihltx.utility.es.ElasticSearchAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @ImportAutoConfiguration({ElasticSearchAutoConfiguration.class}) public @interface EnableElasticSearchAutoConfiguration { }
Characteristics of Heat Treated Al7Si-Mg-Zn - 5 wt.% SiC Squeeze Casted Composite with Variation of Mg Content for Tactical Vehicle Application Composite as main materials for ballistic applications has been developed in order to reduce density which leads to lower fuel consumption and faster mobilization. Composite is required to own high hardness and high impact strength for good ballistic performance. Particulate composites Al-7Si-Mg-Zn reinforced by SiC is designed for ballistic applications due to its light weight and high hardness. Whilst the high hardness showed brittle properties, heat treatment process is applied to this composite to reduce it. This research aims to study the effect of magnesium as alloying element to composite Al-7Si-Mg-Zn reinforced by SiC particulate which applied to precipitation hardening. Composites Al-7Si-Zn-SiC with 2, 4 and 6 wt. % Mg is solution treated at 500 oC for 1 hour, followed by ageing at 200 oC. The characterization was carried out by hardness testing, microstructure observations, SEM and EDX observations, impact testing and fractographic observations. Results showed that Mg does not affect hardness of composite by precipitation hardening. Composite with 2, 4, 6 wt. % Mg had 63.83, 62.27, 62.48 HRB on its peak hardness. Mg did not become precipitate in matrix Al-7Si-Mg-Zn because of its low diffusivity in aluminium. Mg worked as wetting agent that reduces interface tension between aluminium matrix and SiC particles in order for composite to own better interface bonding. Therefore impact testing showed significant increase of impact strength with the increase of Mg content. Composite with 2, 4, 6 wt. % Mg had 2075, 3006, 3257 J/mm2 impact strength respectively
/** Configuration aspect for SuperQuota. */ public class SuperQuotaConfigAspect extends RuleBasedConfigAspect<MetricRule, SuperQuotaAttribute> { public static final String NAME = "quota"; private final Service serviceConfig; public static SuperQuotaConfigAspect create(Model model) { return new SuperQuotaConfigAspect(model); } private SuperQuotaConfigAspect(Model model) { super( model, SuperQuotaAttribute.KEY, NAME, MetricRule.getDescriptor(), model.getServiceConfig().getQuota().getMetricRulesList()); this.serviceConfig = this.getModel().getServiceConfig(); } @Override public List<Class<? extends ConfigAspect>> mergeDependencies() { return ImmutableList.of(); } @Override public void startMerging() { if (!serviceConfig.hasQuota()) { return; } super.startMerging(); } @Override public void startNormalization(Builder builder) { super.startNormalization(builder); // startNormalization() clears MetricRules. } @Override protected boolean isApplicable(ProtoElement element) { return element instanceof Method; } @Override @Nullable protected SuperQuotaAttribute evaluate(ProtoElement element, MetricRule rule, boolean isFromIdl) { return new SuperQuotaAttribute(rule); } @Override protected void clearRuleBuilder(Builder builder) { builder.getQuotaBuilder().clearMetricRules(); } @Override protected void addToRuleBuilder(Builder builder, String selector, SuperQuotaAttribute attribute) { builder .getQuotaBuilder() .addMetricRules(attribute.getRule().toBuilder().setSelector(selector).build()); } }
#ifndef RBGL_MINCUT_H #define RBGL_MINCUT_H #include <boost/graph/edge_connectivity.hpp> namespace boost { template < typename VertexListGraph, typename OutputIterator > typename graph_traits<VertexListGraph>::edges_size_type min_cut(VertexListGraph & g, OutputIterator s_set, OutputIterator vs_set) { typedef graph_traits<VertexListGraph> Traits; typedef typename Traits::vertex_descriptor vertex_descriptor; typedef typename Traits::vertex_iterator vertex_iterator; typedef typename Traits::degree_size_type degree_size_type; typedef typename Traits::edge_iterator edge_iterator; typedef typename Traits::edges_size_type edges_size_type; typedef color_traits<default_color_type> Color; typedef adjacency_list_traits<vecS, vecS, directedS> Tr; typedef typename Tr::edge_descriptor Tr_edge_desc; typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_capacity_t, degree_size_type, property<edge_residual_capacity_t, degree_size_type, property<edge_reverse_t, Tr_edge_desc> > > > FlowGraph; typedef typename graph_traits<FlowGraph>::edge_descriptor edge_descriptor; vertex_descriptor u, v, p, k; vertex_iterator vi, vi_end; edge_descriptor e1, e2; edge_iterator ei, ei_end; edges_size_type delta, alpha_star, alpha_S_k; bool inserted; std::set < vertex_descriptor > S, neighbor_S; std::vector < vertex_descriptor > S_star, nonneighbor_S; std::vector < default_color_type > color(num_vertices(g)); std::vector < edge_descriptor > pred(num_vertices(g)); FlowGraph flow_g(num_vertices(g)); typename property_map < FlowGraph, edge_capacity_t >::type cap = get(edge_capacity, flow_g); typename property_map < FlowGraph, edge_residual_capacity_t >::type res_cap = get(edge_residual_capacity, flow_g); typename property_map < FlowGraph, edge_reverse_t >::type rev_edge = get(edge_reverse, flow_g); // This loop is to convert undirected graph to directed graph, // each edge in undirected graph has unit capacity // each arc in directed graph also has unit capacity for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) { u = source(*ei, g), v = target(*ei, g); tie(e1, inserted) = add_edge(u, v, flow_g); cap[e1] = 1; tie(e2, inserted) = add_edge(v, u, flow_g); cap[e2] = 1; rev_edge[e1] = e2; rev_edge[e2] = e1; } tie(p, delta) = detail::min_degree_vertex(g); S_star.push_back(p); alpha_star = delta; S.insert(p); neighbor_S.insert(p); detail::neighbors(g, S.begin(), S.end(), std::inserter(neighbor_S, neighbor_S.begin())); std::set_difference(vertices(g).first, vertices(g).second, neighbor_S.begin(), neighbor_S.end(), std::back_inserter(nonneighbor_S)); while (!nonneighbor_S.empty()) { k = nonneighbor_S.front(); alpha_S_k = edmonds_karp_max_flow (flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]); if (alpha_S_k < alpha_star) { alpha_star = alpha_S_k; S_star.clear(); for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi) if (color[*vi] != Color::white()) S_star.push_back(*vi); } S.insert(k); neighbor_S.insert(k); detail::neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin())); nonneighbor_S.clear(); std::set_difference(vertices(g).first, vertices(g).second, neighbor_S.begin(), neighbor_S.end(), std::back_inserter(nonneighbor_S)); } /* To extract mincut sets: S and (V - S) */ std::vector < bool > in_S_star(num_vertices(g), false); typename std::vector < vertex_descriptor >::iterator si; for (si = S_star.begin(); si != S_star.end(); ++si) in_S_star[*si] = true; for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi) if ( in_S_star[*vi] ) *s_set++ = *vi; else *vs_set++ = *vi; return alpha_star; } } #endif // RBGL_MINCUT_H
. A great progress has been made recently in the diagnosis of the retrocochlear deafness by the supraliminal hearing test and the binaural audiometric test. We diagnosed the retrocochlear deafness by the special hearing tests performed at the Kanto Rosai Hospital.In this paper, the data for the function of the central auditory pathway in patients with cerebral apoplexy and in normal hearing persons are to be analysed by means of the discriminant function by age-groups. Of 302 sublects, 229 cases are apoplectic patients, 73 cases with normal hearing. The results of the special hearing tests were subjected to the discriminant analysis.The results were as follows:1) The coefficient and discriminant point to classify the data for each item of the special hearing tests and the rate of misclassification were clarified.2) The probability of misclassification decreased in inverse proportion to the number of the test items.3) The probability of misclassification in the middle-aged group (30 to 40 years of age) was the lowest of all age-groups.4) The patients suspicious of the disorder of the central auditory pathway could be diagnosed and classified correctly from the data of each item of the special hearing tests, analysed by means of the discriminant function.Currently even the experts find it difficult to diagnose the disorder of the central auditory pathway, and to determine the affected site of the brain from the mere results of the special hearing tests. However, the integral judgment of the data of the special hearing tests with the introduction of the discriminant function would certainly make it easy and accurate for either experts or non-experts to recognize the disorder of the central auditory pathway.
/** * Copyright (C) 2014 Esup Portail http://www.esup-portail.org * @Author (C) 2012 <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.esupportail.publisher.web.rest.dto; import java.io.Serializable; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; import lombok.ToString; /** * * @author GIP RECIA - <NAME> * 15 oct. 2014 */ @ToString @EqualsAndHashCode @NoArgsConstructor public class SubjectContextKeyDTO implements Serializable { /** */ private static final long serialVersionUID = -3963584394811440859L; @NotNull @NonNull @Getter @Setter private SubjectKeyExtendedDTO subjectKey; @NotNull @NonNull @Getter @Setter private ContextKeyDTO contextKey; /** * @param subjectKey * @param contextKey */ public SubjectContextKeyDTO(@NotNull final SubjectKeyExtendedDTO subjectKey, @NotNull final ContextKeyDTO contextKey) { super(); this.subjectKey = subjectKey; this.contextKey = contextKey; } public SubjectContextKeyDTO(@NotNull final SubjectDTO subject, @NotNull final ContextKeyDTO contextKey) { super(); this.subjectKey = new SubjectKeyExtendedDTO(subject.getModelId().getKeyId(), subject.getModelId().getKeyType()); this.contextKey = contextKey; } }
// binds the data to the view and textview in each row @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { String userStatus = mUserStatuses.get(position); String userName = mUserNames.get(position); holder.myUserName.setText(userName); if (userStatus.equals(strStaffLogIn)){ holder.myUserStatus.setBackground(mContext.getResources().getDrawable(R.drawable.radius_circle_green)); } else if (userStatus.equals(strStaffLogOut)){ holder.myUserStatus.setBackground(mContext.getResources().getDrawable(R.drawable.radius_circle_red)); } else { holder.myUserStatus.setBackground(mContext.getResources().getDrawable(R.drawable.radius_circle_gray)); } }
package stream_test import ( "errors" "testing" "github.com/stretchr/testify/assert" grpcMock "github.com/nhatthm/grpcmock/mock/grpc" "github.com/nhatthm/grpcmock/stream" "github.com/nhatthm/grpcmock/test/grpctest" ) func TestWrappedStream_SendMsg_Upstream(t *testing.T) { t.Parallel() msg := &grpctest.Item{Id: 42} testCases := []struct { scenario string mockUpstream grpcMock.ServerStreamMocker mockSender grpcMock.ServerStreamMocker expectedError error }{ { scenario: "upstream error", mockUpstream: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("SendMsg", msg). Return(errors.New("upstream error")) }), expectedError: errors.New("upstream error"), }, { scenario: "upstream no error", mockUpstream: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("SendMsg", msg). Return(nil) }), }, { scenario: "sender error", mockUpstream: grpcMock.NoMockServerStream, mockSender: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("SendMsg", msg). Return(errors.New("sender error")) }), expectedError: errors.New("sender error"), }, { scenario: "sender no error", mockUpstream: grpcMock.NoMockServerStream, mockSender: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("SendMsg", msg). Return(nil) }), }, } for _, tc := range testCases { tc := tc t.Run(tc.scenario, func(t *testing.T) { t.Parallel() s := stream.Wrap(tc.mockUpstream(t)) if tc.mockSender != nil { s.WithSender(tc.mockSender(t)) } err := s.SendMsg(msg) assert.Equal(t, tc.expectedError, err) }) } } func TestWrappedStream_RecvMsg_Upstream(t *testing.T) { t.Parallel() msg := &grpctest.Item{Id: 42} testCases := []struct { scenario string mockUpstream grpcMock.ServerStreamMocker mockReceiver grpcMock.ServerStreamMocker expectedError error }{ { scenario: "upstream error", mockUpstream: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("RecvMsg", msg). Return(errors.New("upstream error")) }), expectedError: errors.New("upstream error"), }, { scenario: "upstream no error", mockUpstream: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("RecvMsg", msg). Return(nil) }), }, { scenario: "receiver error", mockUpstream: grpcMock.NoMockServerStream, mockReceiver: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("RecvMsg", msg). Return(errors.New("receiver error")) }), expectedError: errors.New("receiver error"), }, { scenario: "receiver no error", mockUpstream: grpcMock.NoMockServerStream, mockReceiver: grpcMock.MockServerStream(func(s *grpcMock.ServerStream) { s.On("RecvMsg", msg). Return(nil) }), }, } for _, tc := range testCases { tc := tc t.Run(tc.scenario, func(t *testing.T) { t.Parallel() s := stream.Wrap(tc.mockUpstream(t)) if tc.mockReceiver != nil { s.WithReceiver(tc.mockReceiver(t)) } err := s.RecvMsg(msg) assert.Equal(t, tc.expectedError, err) }) } }
<reponame>shihab4t/Competitive-Programming #include <stdio.h> int main(void) { int i, j, k; for (k = 0; k < 10; k++) { printf("Enter first number: "); scanf("%d", &i); printf("Enter second number: "); scanf("%d", &j); if (j) printf("%d\n", i/j); else printf("Cannot divide by zero\n"); } return 0; }