content
stringlengths
7
2.61M
<reponame>fossabot/snow-owl /* * Copyright 2011-2020 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.core.domain; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Date; /** * Represents the configuration object used by a SNOMED CT RF2 Importer implementation. * @deprecated - refactored and redesigned - see {@link SnomedRf2ImportConfiguration} - to eliminate the necessity of a memory stored object {@link ISnomedImportConfiguration} */ public interface ISnomedImportConfiguration extends ISnomedRF2Configuration { /** * Determines whether the importer should create versions after processing each effective time "layer" in an RF2 * import file. Only applicable for {@link Rf2ReleaseType#FULL FULL} imports. * * @return {@code true} if a version should be created for each individual effective time value in RF2 import files, * {@code false} otherwise */ boolean shouldCreateVersion(); /** * Returns the current status of the import process. * * @return the import status */ ImportStatus getStatus(); /** * Returns the start date of the import, or <code>null</code> if it hasn't started yet. * * @return the import's starting date */ Date getStartDate(); /** * Returns the completion date of the import, or <code>null</code> if it hasn't completed yet. * * @return the import's completion date */ Date getCompletionDate(); /** * Returns the short name of the Code System to use for the import. * * @return the short name of the Code System to use. */ String getCodeSystemShortName(); /** * Enumerates possible values for the state of an RF2 import process. */ static enum ImportStatus { WAITING_FOR_FILE("Waiting for file"), RUNNING("Running"), COMPLETED("Completed"), FAILED("Failed"); private String label; private ImportStatus(final String label) { this.label = checkNotNull(label, "label"); } @Override public String toString() { return label; } } }
<reponame>HackWars/hackwars-classic package GUI; /** * *data to be sent to the server. *@author <NAME> *@author <NAME> */ public abstract class ApplicationData{ //data String function; Object parameters; public ApplicationData(String function,Object parameters){ this.function=function; this.parameters=parameters; } public String getFunction(){ return(function); } public Object getParameters(){ return(parameters); } }
Outpatient antibiotic use in the United States: time to "get smarter". prescribing rates (for cephalosporins and macrolides in particular) and a higher proportion of penicillin non-susceptible and multidrug non-susceptible invasive pneumococcal isolates. This finding is in line with several European ecologic studies examining the relationship between outpatient antibiotic use and pneumococcal non-susceptibility in the last 10 years . Taken together, these studies convincingly demonstrate
#include "utils.h" #include "WaveClimate.h" #include <math.h> static double GetWaveHeight(struct WaveClimate* this, int timestep) { return this->wave_heights[(int)floor(timestep / this->t_resolution)]; } static double GetWavePeriod(struct WaveClimate* this, int timestep) { return this->wave_periods[(int)floor(timestep / this->t_resolution)]; } static double GetWaveAngle(struct WaveClimate* this, int timestep) { if (this->asymmetry >= 0 && this->stability >= 0) { double angle = RandZeroToOne() * (PI / 4); // random angle 0 - pi/4 if (RandZeroToOne() >= this->stability) // random variable determining above or below 45 degrees { angle += PI / 4; } if (RandZeroToOne() >= this->asymmetry) // random variable determining direction of approach (positive = left) { angle = -angle; } return angle; } return this->wave_angles[(int)floor(timestep / this->t_resolution)]; } static struct WaveClimate new(double* wave_periods, double* wave_angles, double* wave_heights, double asymmetry, double stability, int num_timesteps, int num_wave_inputs) { double* periods = malloc(num_wave_inputs * sizeof(double)); double* heights = malloc(num_wave_inputs * sizeof(double)); double* angles = malloc(num_wave_inputs * sizeof(double)); int i; for (i = 0; i < num_wave_inputs; i++) { periods[i] = wave_periods[i]; heights[i] = wave_heights[i]; angles[i] = wave_angles[i]; } double t_resolution = ((double)num_timesteps) / num_wave_inputs; return (struct WaveClimate) { .t_resolution = t_resolution, .wave_periods = periods, .wave_angles = angles, .wave_heights = heights, .asymmetry = asymmetry, .stability = stability, .GetWaveHeight = &GetWaveHeight, .GetWavePeriod = &GetWavePeriod, .GetWaveAngle = &GetWaveAngle }; } const struct WaveClimateClass WaveClimate = { .new = &new };
A British national of Vietnamese origin is facing extradition to the United States for his alleged role helping Al Qaeda in the Arabian Peninsula (AQAP) create and distribute the type of online propaganda that has become a staple of domestic terrorists. The indictment, filed in New York federal court in June 2012, alleges that Minh Quang Pham “provided expert advice and assistance in photography and graphic design of media” for AQAP. In addition to helping AQAP craft its propaganda, authorities also allege that Pham helped disseminate the propaganda. These graphics, coupled with Western references, practical information and anti-Semitic narratives have made AQAP’s Inspire magazine an effective recruitment and radicalization tool. Before traveling to Yemen in 2010 and bringing his professional expertise to AQAP, Pham reportedly established a business in London as a web and graphics designer. The indictment also alleges that Pham met with two unnamed Americans, a likely reference to Anwar al-Awlaki, AQAP’s American-born ideologue who also served as its chief of external operations, and Samir Khan, an American blogger who was believed to be the principal editor of Inspire. Both Awlaki and Khan were killed in a drone strike in September 2011. Pham is formally charged with providing material support to AQAP, receiving military training from a terrorist organization, firearms charges and two other related crimes. He reportedly traveled from the UK to Yemen in 2010 where he allegedly received weapons training, took an oath of allegiance to AQAP, and provided his expert media advice to the terrorist organization. British authorities arrested Pham last June, coinciding with the announcement of the American charges against him. He had previously been in immigration custody after ammunition was allegedly found in his bag after he returned from the Middle East. His extradition hearing is scheduled for August. If convicted on all charges, he faces the possibility of life in prison.
package com.github.ylgrgyq.reservoir; /** * Annotates a program element that exists, or is more widely visible than otherwise necessary, only * for use in test code. */ public @interface VisibleForTesting { }
Identification of genes that contribute to fitness of African and Global clades of Salmonella Enteritidis during infection of macrophages Non-typhoidal Salmonella (NTS) usually cause gastroenteritis in humans, but in recent years NTS have begun to cause epidemics of bloodstream infections in Africa. Salmonella Enteritidis is the second most common serovar associated with this invasive form of NTS disease (iNTS) in Africa. To establish a systemic infection, Salmonella must survive and replicate within host cells, with macrophages being a primary target. Genomic characterisation of S. Enteritidis isolates from human bloodstream has identified two new clades that are unique to Africa and distinct from the Global Epidemic clade. The African S. Enteritidis clades exhibit genomic degradation, and possess a distinct prophage repertoire and are multi-drug resistant. However, little is known about the virulence factors that allow African S. Enteritidis to cause systemic infection in susceptible hosts. We screened libraries of random insertion mutants of African and Global S. Enteritidis by transposon insertion sequencing (TIS), and identified about 280 genes belonging to each clade that contribute to bacterial survival and replication in murine macrophages. The genes were associated with 5 pathogenicity-islands, or encoded the global regulators PhoPQ and OmpR-EnvZ. Experiments are ongoing to investigate the role in intra-macrophage replication of genes that are uniquely identified in African Salmonella. It is hoped that our findings will contribute to a greater understanding of African Salmonella infection biology, and that some of the virulence-associated genes could be potential targets for novel therapeutics.
<reponame>jyothiprakashpanaik/Backend from django.urls import path from .views import (RegisterView, VerifyEmail, LoginApiView, ProfileGetView, ProfileUpdateView, PasswordTokenCheckAPI, RequestPasswordResetEmail, SetNewPasswordAPIView, UserProfileGetView, ChangePassword, SendVerificationMail, CheckAuthView, SearchUser) # Friend Related View from .views import SendFriendRequest, RemoveFriend, AcceptFriendRequest, FriendsShowView from .views import FriendRequestShowView, RequestSendShowView, testing from rest_framework_simplejwt.views import TokenRefreshView urlpatterns = [ path('register/', RegisterView.as_view(), name="register"), path('email-verify/', VerifyEmail.as_view(), name="email-verify"), path('send-email/', SendVerificationMail.as_view(), name='send-email'), path('profile/', ProfileGetView.as_view(), name="profile"), path('profile/<str:owner_id__username>', ProfileUpdateView.as_view(), name="profile"), path('profile/<str:username>/', UserProfileGetView.as_view(), name="userProfile"), path('login/', LoginApiView.as_view(), name="login"), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('request-reset-email/', RequestPasswordResetEmail.as_view(), name="request-reset-email"), path('password-reset/<uidb64>/<token>/', PasswordTokenCheckAPI.as_view(), name='password-reset-confirm'), path('password-reset-complete', SetNewPasswordAPIView.as_view(), name='password-reset-complete'), path('password-change/', ChangePassword.as_view(), name='password-change'), path('check-auth/', CheckAuthView.as_view(), name='check-auth'), path('password-reset-complete', SetNewPasswordAPIView.as_view(), name='password-reset-complete'), path('search-user', SearchUser.as_view(), name='search-user'), # Friends Related Path Start path('user/send-request', SendFriendRequest.as_view(), name='Send_Friend_Request'), path('user/remove-friend', RemoveFriend.as_view(), name='Remove_Friend'), path('user/accept-request', AcceptFriendRequest.as_view(), name='Accept_Friend_Request'), path('user/friends', FriendsShowView.as_view(), name='Show_Friends_List'), path('user/show-request', FriendRequestShowView.as_view(), name='Show_Friend_Request_List'), path('user/show-send-request', RequestSendShowView.as_view(), name='Show_Friend_Request_Send_List'), # Friends Related Path End path('testing', testing), ]
package com.mall.admin.product.category.ud.controller; import com.mall.admin.product.category.ud.service.ProductCategoryService; import com.mall.common.pojo.ProductCategory; import com.mall.common.util.JWTUtil; import com.mall.common.vo.ResultVO; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /* * 作者:官宣轩 * 日期:2020-09-27 */ @RestController @CrossOrigin @RequestMapping("/productCategoryUd") @Api(tags = "后台商品分类修改接口") public class ProductCategoryUdController { @Resource private ProductCategoryService productCategoryService; @RequestMapping(value = "/del",method = RequestMethod.DELETE) @ApiOperation(value = "后台商品分类修改接口", notes = "需要携带token") @ApiImplicitParams({ @ApiImplicitParam(name = "token", value = "token验证信息", required = true, type = "String") }) public ResultVO productCategoryDel(@RequestParam Integer productCategoryId, @RequestHeader(required = true) String token) { // 验证token Jws<Claims> jws = JWTUtil.Decrypt(token); // 获取解析的token中的用户名、id等 // String adminId = jws.getBody().getId(); String issuer = jws.getBody().getIssuer(); if ("admin".equals(issuer)){ boolean b = productCategoryService.productCategoryDel(productCategoryId); if (b){ return new ResultVO(0,"删除成功"); }else { return new ResultVO(1,"删除失败,请联系管理员!"); } }else { return new ResultVO(1,"没有权限,请联系管理员!"); } } @RequestMapping(value = "/update",method = RequestMethod.POST) @ApiOperation(value = "后台商品分类修改接口", notes = "需要携带token") @ApiImplicitParams({ @ApiImplicitParam(name = "token", value = "token验证信息", required = true, type = "String") }) public ResultVO productCategoryUpdate(@RequestParam Integer productCategoryId,@RequestParam String name,@RequestParam Integer parentId,@RequestParam String productUnit,@RequestParam Integer sort,@RequestParam String description, @RequestHeader(required = true) String token) { // 验证token Jws<Claims> jws = JWTUtil.Decrypt(token); // 获取解析的token中的用户名、id等 // String adminId = jws.getBody().getId(); String issuer = jws.getBody().getIssuer(); if ("admin".equals(issuer)){ ProductCategory productCategory = new ProductCategory(); productCategory.setId(productCategoryId); productCategory.setName(name); productCategory.setParentId(parentId); productCategory.setProductUnit(productUnit); productCategory.setSort(sort); productCategory.setDescription(description); boolean b = productCategoryService.productCategoryUpdate(productCategory); if (b){ return new ResultVO(0,"修改成功"); }else { return new ResultVO(1,"修改失败,请联系管理员!"); } }else { return new ResultVO(1,"没有权限,请联系管理员!"); } } }
/** * Class that handles and combines drag events generated from multiple views, and then fires * off events to any OnDragDropListeners that have registered for callbacks. */ public class DragDropController { private final List<OnDragDropListener> mOnDragDropListeners = new ArrayList<OnDragDropListener>(); private final DragItemContainer mDragItemContainer; private final int[] mLocationOnScreen = new int[2]; /** * Callback interface used to retrieve(取回) views based on the current touch coordinates(坐标) of the * drag event. The {@link DragItemContainer} houses the draggable views that this * {@link DragDropController} controls. */ public interface DragItemContainer { View getViewForLocation(int x, int y); } public DragDropController(DragItemContainer dragItemContainer) { mDragItemContainer = dragItemContainer; } /** * @return True if the drag is started, false if the drag is cancelled for some reason. */ boolean handleDragStarted(int x, int y) { final View tileView = mDragItemContainer.getViewForLocation(x, y); if (tileView == null) { return false; } for (int i = 0; i < mOnDragDropListeners.size(); i++) { mOnDragDropListeners.get(i).onDragStarted(x, y, tileView); } return true; } public void handleDragHovered(View v, int x, int y) { v.getLocationInWindow(mLocationOnScreen); final int screenX = x + mLocationOnScreen[0]; final int screenY = y + mLocationOnScreen[1]; final View view; if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){ view = mDragItemContainer.getViewForLocation( x, y); if(view == null){ return; } for (int i = 0; i < mOnDragDropListeners.size(); i++) { mOnDragDropListeners.get(i).onDragHovered(x, y, view); } }else { view = mDragItemContainer.getViewForLocation( screenX, screenY); if(view == null){ return; } for (int i = 0; i < mOnDragDropListeners.size(); i++) { mOnDragDropListeners.get(i).onDragHovered(screenX, screenY, view); } } } public void handleDragFinished(int x, int y, boolean isRemoveView) { if (isRemoveView) { for (int i = 0; i < mOnDragDropListeners.size(); i++) { mOnDragDropListeners.get(i).onDroppedOnRemove(); } } for (int i = 0; i < mOnDragDropListeners.size(); i++) { mOnDragDropListeners.get(i).onDragFinished(x, y); } } public void addOnDragDropListener(OnDragDropListener listener) { if (!mOnDragDropListeners.contains(listener)) { mOnDragDropListeners.add(listener); } } public void removeOnDragDropListener(OnDragDropListener listener) { if (mOnDragDropListeners.contains(listener)) { mOnDragDropListeners.remove(listener); } } }
package li.cil.tis3d.client.render.entity; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.render.Frustum; import net.minecraft.client.render.entity.EntityRenderDispatcher; import net.minecraft.client.render.entity.EntityRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.Identifier; @Environment(EnvType.CLIENT) public class InvisibleEntityRenderer<T extends Entity> extends EntityRenderer<T> { public InvisibleEntityRenderer(final EntityRenderDispatcher dispatcher) { super(dispatcher); } @Override public Identifier getTexture(final T entity) { return null; } @Override public boolean shouldRender(final T entity, final Frustum frustum, final double x, final double y, final double z) { return false; } }
//=========================================== // The following is for 8192D 2Ant BT Co-exist definition //=========================================== #define BTC_RSSI_COEX_THRESH_TOL_8192D_2ANT 6 typedef enum _BT_INFO_SRC_8192D_2ANT{ BT_INFO_SRC_8192D_2ANT_WIFI_FW = 0x0, BT_INFO_SRC_8192D_2ANT_BT_RSP = 0x1, BT_INFO_SRC_8192D_2ANT_BT_ACTIVE_SEND = 0x2, BT_INFO_SRC_8192D_2ANT_MAX }BT_INFO_SRC_8192D_2ANT,*PBT_INFO_SRC_8192D_2ANT; typedef enum _BT_8192D_2ANT_BT_STATUS{ BT_8192D_2ANT_BT_STATUS_IDLE = 0x0, BT_8192D_2ANT_BT_STATUS_CONNECTED_IDLE = 0x1, BT_8192D_2ANT_BT_STATUS_NON_IDLE = 0x2, BT_8192D_2ANT_BT_STATUS_MAX }BT_8192D_2ANT_BT_STATUS,*PBT_8192D_2ANT_BT_STATUS; typedef enum _BT_8192D_2ANT_COEX_ALGO{ BT_8192D_2ANT_COEX_ALGO_UNDEFINED = 0x0, BT_8192D_2ANT_COEX_ALGO_SCO = 0x1, BT_8192D_2ANT_COEX_ALGO_HID = 0x2, BT_8192D_2ANT_COEX_ALGO_A2DP = 0x3, BT_8192D_2ANT_COEX_ALGO_PAN = 0x4, BT_8192D_2ANT_COEX_ALGO_HID_A2DP = 0x5, BT_8192D_2ANT_COEX_ALGO_HID_PAN = 0x6, BT_8192D_2ANT_COEX_ALGO_PAN_A2DP = 0x7, BT_8192D_2ANT_COEX_ALGO_MAX }BT_8192D_2ANT_COEX_ALGO,*PBT_8192D_2ANT_COEX_ALGO; typedef struct _COEX_DM_8192D_2ANT{ // fw mechanism BOOLEAN bPreBalanceOn; BOOLEAN bCurBalanceOn; // diminishWifi BOOLEAN bPreDacOn; BOOLEAN bCurDacOn; BOOLEAN bPreInterruptOn; BOOLEAN bCurInterruptOn; u1Byte preFwDacSwingLvl; u1Byte curFwDacSwingLvl; BOOLEAN bPreNavOn; BOOLEAN bCurNavOn; //BOOLEAN bPreDecBtPwr; //BOOLEAN bCurDecBtPwr; //u1Byte preFwDacSwingLvl; //u1Byte curFwDacSwingLvl; //BOOLEAN bCurIgnoreWlanAct; //BOOLEAN bPreIgnoreWlanAct; //u1Byte prePsTdma; //u1Byte curPsTdma; //u1Byte psTdmaPara[5]; //u1Byte psTdmaDuAdjType; //BOOLEAN bResetTdmaAdjust; //BOOLEAN bPrePsTdmaOn; //BOOLEAN bCurPsTdmaOn; //BOOLEAN bPreBtAutoReport; //BOOLEAN bCurBtAutoReport; // sw mechanism BOOLEAN bPreRfRxLpfShrink; BOOLEAN bCurRfRxLpfShrink; u4Byte btRf0x1eBackup; BOOLEAN bPreLowPenaltyRa; BOOLEAN bCurLowPenaltyRa; BOOLEAN bPreDacSwingOn; u4Byte preDacSwingLvl; BOOLEAN bCurDacSwingOn; u4Byte curDacSwingLvl; BOOLEAN bPreAdcBackOff; BOOLEAN bCurAdcBackOff; BOOLEAN bPreAgcTableEn; BOOLEAN bCurAgcTableEn; //u4Byte preVal0x6c0; //u4Byte curVal0x6c0; u4Byte preVal0x6c4; u4Byte curVal0x6c4; u4Byte preVal0x6c8; u4Byte curVal0x6c8; u4Byte preVal0x6cc; u4Byte curVal0x6cc; //BOOLEAN bLimitedDig; // algorithm related u1Byte preAlgorithm; u1Byte curAlgorithm; //u1Byte btStatus; //u1Byte wifiChnlInfo[3]; } COEX_DM_8192D_2ANT, *PCOEX_DM_8192D_2ANT; typedef struct _COEX_STA_8192D_2ANT{ u1Byte preWifiRssiState[4]; BOOLEAN bBtBusy; BOOLEAN bBtUplink; BOOLEAN bBtDownLink; BOOLEAN bA2dpBusy; }COEX_STA_8192D_2ANT, *PCOEX_STA_8192D_2ANT; //=========================================== // The following is interface which will notify coex module. //=========================================== VOID EXhalbtc8192d2ant_InitHwConfig( IN PBTC_COEXIST pBtCoexist ); VOID EXhalbtc8192d2ant_InitCoexDm( IN PBTC_COEXIST pBtCoexist ); VOID EXhalbtc8192d2ant_IpsNotify( IN PBTC_COEXIST pBtCoexist, IN u1Byte type ); VOID EXhalbtc8192d2ant_LpsNotify( IN PBTC_COEXIST pBtCoexist, IN u1Byte type ); VOID EXhalbtc8192d2ant_ScanNotify( IN PBTC_COEXIST pBtCoexist, IN u1Byte type ); VOID EXhalbtc8192d2ant_ConnectNotify( IN PBTC_COEXIST pBtCoexist, IN u1Byte type ); VOID EXhalbtc8192d2ant_MediaStatusNotify( IN PBTC_COEXIST pBtCoexist, IN u1Byte type ); VOID EXhalbtc8192d2ant_SpecialPacketNotify( IN PBTC_COEXIST pBtCoexist, IN u1Byte type ); VOID EXhalbtc8192d2ant_HaltNotify( IN PBTC_COEXIST pBtCoexist ); VOID EXhalbtc8192d2ant_Periodical( IN PBTC_COEXIST pBtCoexist ); VOID EXhalbtc8192d2ant_BtInfoNotify( IN PBTC_COEXIST pBtCoexist, IN pu1Byte tmpBuf, IN u1Byte length ); VOID EXhalbtc8192d2ant_DisplayCoexInfo( IN PBTC_COEXIST pBtCoexist );
<reponame>xiaoer371/youqia // // MCSelectedMemberCell.h // NPushMail // // Created by wuwenyu on 16/4/1. // Copyright © 2016年 sprite. All rights reserved. // #import <UIKit/UIKit.h> @class MCContactModel; static const CGFloat paddingX = 2; static const CGFloat paddingY = 2; static const CGFloat textFieldPaddingX = 15; @interface MCSelectedMemberCell : UICollectionViewCell - (void)configureCellWithModel:(MCContactModel *)model indexPath:(NSIndexPath *)path; @end
PUBLIC FINANCE AND WAR IN ANCIENT GREECE* Before the Persian Wars the Greeks did not rely on public finance to fight each other. Their hoplites armed and fed themselves. But in the confrontation with Persia this private funding of war proved to be inadequate. The liberation of the Greek states beyond the Balkans required the destruction of Persia's sea power. In 478 bc Athens agreed to lead an alliance to do just this. It already had Greece's largest fleet. But each campaign of this ongoing war would need tens of thousands of sailors and would go on for months. No single Greek city-state could pay for such campaigns. The alliance thus agreed to adopt the Persian method for funding war: its members would pay a fixed amount of tribute annually. This enabled Athens to force Persia out of the Dardanelles and Ionia. But the Athenians also realized that their military power depended on tribute, and so they tightened their control of its payers. In so doing they turned the alliance into an empire.
// Unless explicitly stated otherwise all files in this repository are // dual-licensed under the Apache-2.0 License or BSD-3-Clause License. // // This product includes software developed at Datadog // (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc. #include <php.h> #include "../commands_helpers.h" #include "../ddappsec.h" #include "../ddtrace.h" #include "../logging.h" #include "../msgpack_helpers.h" #include "../tags.h" #include "../version.h" #include "client_init.h" #include "mpack-common.h" #include "mpack-node.h" #include "mpack-writer.h" static dd_result _pack_command(mpack_writer_t *nonnull w, void *nullable ctx); static dd_result _process_response(mpack_node_t root, void *nullable ctx); static void _process_meta_and_metrics(mpack_node_t root); static const dd_command_spec _spec = { .name = "client_init", .name_len = sizeof("client_init") - 1, .num_args = 4, .outgoing_cb = _pack_command, .incoming_cb = _process_response, }; dd_result dd_client_init(dd_conn *nonnull conn) { return dd_command_exec_cred(conn, &_spec, NULL); } static dd_result _pack_command( mpack_writer_t *nonnull w, ATTR_UNUSED void *nullable ctx) { // unsigned pid, string client_version, runtime_version, rules_file mpack_write(w, (uint32_t)getpid()); dd_mpack_write_lstr(w, PHP_DDAPPSEC_VERSION); dd_mpack_write_lstr(w, PHP_VERSION); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers) mpack_start_map(w, 5); { dd_mpack_write_lstr(w, "rules_file"); const char *rules_file = DDAPPSEC_G(rules_file); bool has_rules_file = rules_file && *rules_file; if (!has_rules_file) { mlog(dd_log_info, "datadog.appsec.rules was not provided. The helper " "will atttempt to use the default file"); } dd_mpack_write_nullable_cstr(w, rules_file); } dd_mpack_write_lstr(w, "waf_timeout_us"); mpack_write(w, (uint64_t)DDAPPSEC_G(waf_timeout_us)); dd_mpack_write_lstr(w, "trace_rate_limit"); mpack_write(w, (uint32_t)DDAPPSEC_G(trace_rate_limit)); dd_mpack_write_lstr(w, "obfuscator_key_regex"); dd_mpack_write_nullable_cstr(w, DDAPPSEC_G(obfuscator_key_regex)); dd_mpack_write_lstr(w, "obfuscator_value_regex"); dd_mpack_write_nullable_cstr(w, DDAPPSEC_G(obfuscator_value_regex)); mpack_finish_map(w); return dd_success; } static dd_result _check_helper_version(mpack_node_t root); static dd_result _process_response( mpack_node_t root, ATTR_UNUSED void *nullable ctx) { // Add any tags and metrics provided by the helper _process_meta_and_metrics(root); // check verdict mpack_node_t verdict = mpack_node_array_at(root, 0); bool is_ok = dd_mpack_node_lstr_eq(verdict, "ok"); if (is_ok) { mlog(dd_log_debug, "Response to client_init is ok"); return _check_helper_version(root); } // not ok, in which case expect at least one error message const char *ver = mpack_node_str(verdict); size_t verlen = mpack_node_strlen(verdict); mpack_node_t errors = mpack_node_array_at(root, 2); mpack_node_t first_error_node = mpack_node_array_at(errors, 0); const char *first_error = mpack_node_str(first_error_node); size_t first_error_len = mpack_node_strlen(first_error_node); mpack_error_t err = mpack_node_error(verdict); if (err != mpack_ok) { mlog(dd_log_warning, "Unexpected client_init response: %s", mpack_error_to_string(err)); } else { if (verlen > INT_MAX) { verlen = INT_MAX; } if (first_error_len > INT_MAX) { first_error_len = INT_MAX; } mlog(dd_log_warning, "Response to client_init is not ok: %.*s: %.*s", (int)verlen, ver, (int)first_error_len, first_error); } return dd_error; } static void _process_meta_and_metrics(mpack_node_t root) { mpack_node_t meta = mpack_node_array_at(root, 3); if (mpack_node_map_count(meta) > 0) { if (dd_command_process_meta(meta)) { // If there are any meta tags and setting them succeeds // we set the sampling priority dd_tags_set_sampling_priority(); } } mpack_node_t metrics = mpack_node_array_at(root, 4); dd_command_process_metrics(metrics); } static dd_result _check_helper_version(mpack_node_t root) { mpack_node_t version_node = mpack_node_array_at(root, 1); const char *version = mpack_node_str(version_node); size_t version_len = mpack_node_strlen(version_node); int version_len_int = version_len > INT_MAX ? INT_MAX : (int)version_len; mlog( dd_log_debug, "Helper reported version %.*s", version_len_int, version); if (!version) { mlog(dd_log_warning, "Malformed client_init response when " "reading helper version"); return dd_error; } if (!STR_CONS_EQ(version, version_len, PHP_DDAPPSEC_VERSION)) { mlog(dd_log_warning, "Mismatch of helper and extension version. " "helper %.*s and extension %s", version_len_int, version, PHP_DDAPPSEC_VERSION); return dd_error; } return dd_success; }
/* Check and get userdata from stack with specified index and return it as AnyFn. Throw lua_error on incorrect Lua type. Lua stack changes [-0, +0, v] */ AnyFn* lua_checkdvanyfn(lua_State* L, int32 index) { AnyFn* pAnyFn = static_cast<AnyFn*>(luaL_checkudata(L, index, AnyFnTName)); DVASSERT(pAnyFn, "Can't get AnyFn ptr"); return pAnyFn; }
Knowledge, attitude, and practice toward zoonotic diseases among different professionals at selected coastal areas in Barguna district, Bangladesh Objective: The study was performed to determine the level of knowledge, attitude, and practice among different professionals toward zoonotic diseases in selected coastal areas of Barguna district, Bangladesh. Materials and Methods: A total of 485 respondents were randomly selected from different upazilas (sub-districts) of Barguna district, Bangladesh. A questionnaire-based survey was conducted to collect data about awareness of zoonosis, hygienic management, zoonotic disease transmission from different species of domestic animals and consumption of their products, consciousness on management of pet animals, disease transmission from wild animals, effects of natural disaster on zoonosis, and extension works on zoonosis provided by government or private sector. Results: Based on the level of knowledge of the different respondents, meat (43.92%) is the prime way for transmission of zoonotic disease followed by egg (18.14%) and milk (13.61%). The awareness regarding management of pet animals (23.71%) and zoonotic disease from wild animals (26.69%) were more or less similar. It has been observed that 33.81% respondents were conscious about natural disaster causing zoonotic infection. The respondents also mentioned that extension services about zoonotic infection provided by government or private sector was 34.22%. Among all the respondents, the awareness of zoonotic infection was high in employee of livestock department followed by employee of health department and teachers. Conclusion: The awareness of zoonoses was high in employee of livestock department followed by the employee of health department, teachers, and other professionals. The present study observed that low educational background of professionals or non-health educated professionals is not conscious on zoonotic diseases. Further work should be taken to assess the prevention and control strategies regarding zoonosis in study area. Introduction The objectives of veterinary medicine are to provide betterment and characteristic improvement of animal and human health. Cosivi et al. reported that contribution and liability of veterinary medicine promote well being of human health. The term zoonoses originally comes from Greek world "zoo" means animals and "noses" means sickness. WHO and FAO defined that zoonoses are infectious diseases that transmitted between people and animals. In microbial diseases of human, 61% are zoonotic and 13% of these infections are known as emerging and reemerging diseases. Daszak et al. reported that 75% of zoonotic infection derived from emerging infectious disease. A number of determinants are responsible for zoonotic infection; the main cause is coming into close contact between animals and humans. The vast majority of the animals (domestic, companion, and pets) acts as carriers and reservoir of many zoonotic infections. It has been reported that peoples of developing countries are living very close with animals where livestock usually provide draught power, transportation, fuel, and clothing. The national economy of a country might be influenced by zoonotic disease, which might have direct effect on animal production and health. The public health important diseases in livestock impair This is an Open Access article distributed under the terms of the Creative Commons Attribution 4.0 Licence (http://creativecommons.org/ licenses/by/4.0) the economy of a country due to trade barrier, expensive marketing cost to ensure safe animal products for human consumption, decrease in attraction to consumer products. WHO reported that zoonotic diseases have great importance from the viewpoint of public health; most of the diseases cause enormous sufferings and increases annual mortality of thousands of children and adult. Environmental alteration due to natural and manmade calamities, increase in human population, deforestation causes migration of rural people to urban habitats, and increasing susceptibility of zoonotic diseases. Zoonotic diseases of the developing countries have been associated with farming patterns, educational background, food habits, presence or absence of reservoir population, and awareness about disease control program. Babu et al. reported that 28.06% peoples are aware about zoonotic diseases in Andra Pradesh, India. They also mentioned that employee of veterinary and medical departments are more aware about different types of zoonotic diseases as compared with other professionals. Hygienic management followed by farmer is very negligible which increase the susceptibility of zoonotic diseases. Girma et al. found that peoples with low education have limited consciousness on public health important diseases which are transmitted from the animals. Climate change effects are the biggest threat of Bangladesh. The vulnerable countries like Bangladesh is now facing various natural calamities, such as cyclones, frequent flooding, soil erosion, intrusion of salt water, and destruction of biodiversity. Therefore, the coastal areas of Bangladesh have adequate chance of contaminated food with polluted water. Potential sources of contaminants are-fecal materials from infected livestock, carriage of animals and birds, infected wild animals, rodents, intensive husbandry of livestock, disposal of sewage, etc. The risk of transmission of pathogen to human with contaminated water is increasing day by day. Biosecurity, chemoprophylaxis, and immunoprophylaxis are the important tools for the prevention and control strategies of diseases of animals. In the developing countries, the prevention of some zoonotic diseases is not feasible due to limited compensation by the government to the livestock owners. However, there are only few reports on the level of awareness of zoonotic diseases in various professionals in Bangladesh. The present study was undertaken to assess the level of knowledge, attitude, and practices toward zoonotic diseases in different professionals. Study area and size of population The study was conducted in different upazilas (sub-district) of Barguna district (Fig. 1), Bangladesh from April 2018 to August 2018. The target professionals consisting of farmers, butchers, day labors, drivers, teachers, engineers, human and animal health employees, agriculturists, businessmen, bank, and private employees. A total of 485 respondents were selected randomly from different areas of the study area. Design of the study and sample size Well-designed structured questionnaire was used for interviewing the respondents of this study. Educational background of the various respondents were determined by stratified random sampling. The respondents were asked regarding awareness of zoonosis, hygienic management followed by farmers, transmission of zoonosis from animals and their products, awareness on management of pet and wild animals, and extension services on zoonosis by government and private sector. The written consents were taken from the respondents to publish their data. Data collection and analysis Data were collected and analyzed to determine the percentage of awareness of various professionals on zoonotic diseases. Results and Discussion Animals living in the developing countries are very close to human population. In the developing countries, the animals provide fuel, clothing, transportation, and also the source of protein, such as milk, meat and eggs. For this reason, animals are human linkage in that countries provide serious health risk of human. Assessment of awareness of zoonotic disease in various professionals in study area might play a pivotal role in prevention and control measures of the diseases. The peoples from different professionals were selected to assess the perception of awareness of the target community peoples. A total of 485 respondents (Table 1) were selected who have different level of education (elementary education to post graduate education). The respondents of the study can read and write of their own language. In performed study revealed that 38.97% (Table 2) peoples were aware about zoonosis, which is comparatively Table 2. Awareness on zoonosis and hygienic management followed by respondents. higher than the report of Babu et al. who reported consciousness of zoonosis as 28.06%. In performed study, the consciousness of hygienic management of the farmers was found low in respective area where cleaning animal shed with disinfectant (4.76%), cleaning animal shed without disinfectant (37.14%), washing hand before milking (26.67%), milking without washing hands (19.04%), washing udder before milking (18.57%), and milking without washing hands (27.14%) were recorded. Babu et al. reported that 100% farmers were not conscious on washing of udder with disinfectant and cleaning of shed with disinfectants which are inclined to the reported study. Prabhakar et al. reported that 61% butchers were having awareness of zoonotic disease and more or less similar than reported study where 50% butchers were conscious on zoonosis. It has also been revealed that 30.8% respondents were aware regarding the risk of zoonotic disease. The highest percentage of respondents in the reported study mentioned that dog (52.99%) is the important source of the transmission of zoonotic disease followed by cat (28.87%), poultry (28.25%), cattle/buffalo (16.085%), and sheep/goat (9.90%) shown in Table 3. Babu et al. revealed that 100% respondents were conscious on zoo caused by dog followed by poultry (25.89%), pig (18.58%), cattle (4.93%), and sheep/goat (3.97%) which supports the performed study. Categories of respondents The respondents in this study revealed that consumption of meat (43.92%) is the prime way for zoonosis followed by egg (18.14%) and milk (13.61%) shown in Table 4. It has been reported that 22.46% and 14.10% respondents were conscious on consumption of meat and milk, respectively causes zoonotic infection which support the performed study. Girma et al. also showed that the percentage of awareness and knowledge of non-health professionals on zoonosis due to consumption of meat (80.21%), milk (71.88%), and honey (91.67%) was higher. The awareness regarding management of pet animals (23.71%) and zoonotic disease from wild animals (26.69%) are recorded in Table 5. It has been reported that 8.46% respondents were conscious on management of dog which is lower than recorded study. Zoonotic diseases from wildlife represent a major public health problem affecting through the world. Many emerging and re-emerging diseases at present are transmitted from wild animals. Therefore, consciousness on zoonosis from wild animals should be increased in the study area. In recent performed study mentioned that 33.81% respondents ( Table 6) were conscious about natural disaster prone zoonosis in the coastal area. The natural disasters in the coastal areas of Bangladesh has adequate chance of zoonosis due to close contact of public health with infected livestock, carriage of animals and birds, infected wild animals, including rodents and intensive husbandry of livestock. Climate change in the world leads to more warm and humid climate, especially in the developing countries which increase the risk of transmission of vector and airborne zoonotic infection. Sachan and Singh mentioned that outbreak of emerging zoonotic disease in the present world due to adverse effect of climate changes on biodiversity, microflora, and distribution of animals. The respondents in this study observed that extension services about zoonotic infection provided by government or private sector was 34.22% shown in Table 7. So, lack of extension services regarding zoonoses in study area increase the risk of infection. Conclusion The awareness of zoonotic infection was high in employee of Livestock Department followed by employee of Health Department, teachers, or other professionals. Thus, this study indicates that low educational backgrounds of professionals or non-health educated professionals are less conscious regarding zoonotic diseases. The data of the performed study might be useful to assess the target population risk for zoonotic infection. Further study need to be performed to assess the appropriate prevention and control strategies regarding zoonosis in the coastal areas.
/** * A bean demonstrating how to use the Timeout annotation. * @author Andrew Pielage <[email protected]> */ @ApplicationScoped @Timeout(1500) public class ClassLevelTimeoutBean { public static final long AWAIT = 3000; /** * Example method that simulates a long running query. * @param shouldTimeout */ public void timeout(boolean shouldTimeout) { if (shouldTimeout) { try { // Simulate a long running query Thread.sleep(AWAIT); } catch (InterruptedException ex) { // Om nom nom } } } }
Gina Haspel is appearing before the Senate on Wednesday, where lawmakers will likely grill President Trump’s nominee to head the CIA. Gina Haspel is appearing before the Senate on Wednesday, where lawmakers will likely grill President Trump's nominee to head the CIA over her ties to aggressive interrogations after 9/11. At issue is the time Haspel, currently the agency's deputy director, spent running a secret CIA prison in Thailand — during which an al-Qaeda militant was reportedly subjected to waterboarding and other brutal tactics in 2002. Senators have also questioned her role in ordering tapes of the interrogations destroyed years later. Haspel, who joined the CIA in the mid-1980s, would be the first female director in the agency's 70-year history if she's confirmed. "Despite repeatedly facing false or misleading allegations against her, the facts show that Gina Haspel has served her nation honorably and acted legally," the White House said Wednesday.
Myth: A Very Short Introduction The forest of yellow sticky-notes now protruding from my copy of Sigrid Schmidts book prompts me to design a questionnaire for Ju|'hoan, and other click-speakers, covering a host of new angles and topics. These include how early laws given by anteaters to humans signalled the end of humans and animals being one and the same; why the Moon and Hare story is linked to male initiation; why hare meat is linked to death; why tricksters assume the form of big meat animals (antelopes); what meaning or practice may be associated with the motif of evidentiary sticking of tabooed or stolen objects; what is the significance of differently-coloured honeys; why women, as well as men, may sometimes be guardians of the animals; which precise bones in the breast of a sheep are seen to have resuscitative powers or can escape out of the mouths of devouring lions, and are thus known as merrythoughts; why old persons in the stories are always represented as human beings, never as animals; whether drying (for instance, of animal skins) is seen as a kind of resuscitation (and that is why items made from the skins are often named for the animals from which the skins are taken); what might be the relationship (seasonal, for instance) among digging sticks, tortoises, and truffles; and on and on. After several hundred pages of carefully assembled story explications and comparisons, Schmidt has completed the groundwork for masterful mini-essays on a number of questions increasingly dear to the hearts of folklorists and anthropologists. These questions are about contact and transmission, individual performers and performances, and the conditions of recording and translation. By the books end, the little essays taken together have built into a most humanizing discourse, one situated well within postmodern or revisionist trends in the social sciences of the last few decades. In illustration of this important point and also in conclusion, I quote with permission the last textual paragraph in this satisfying book:
/** * Return true if the prefix of "ch" is "ignorable". Here, "ignorable" means * that "ch" has only one digit and separater characters. The one digit is * assumed to be trunk prefix. */ static bool checkPrefixIsIgnorable(const char* ch, int i) { bool trunk_prefix_was_read = false; while (i >= 0) { if (tryGetISODigit(ch[i]) >= 0) { if (trunk_prefix_was_read) { return false; } else { trunk_prefix_was_read = true; } } else if (isDialable(ch[i])) { return false; } i--; } return true; }
A well-established top 10 firm are currently seeking a Private Client Tax Assistant Manager for their office in Guildford. The ideal candidate will be CTA qualified with significant tax experience within an accountancy practice. As a Private Client Tax Assistant Manager, you will support and be involved in the continued expansion of the private client services advisory work generally for HNWIs including tax areas such as international, private equity, UK property, trusts and owner managed businesses.
<reponame>carlosmendoza/it1 package rest; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import tm.TM; import vos.IndiceOcupacion; import vos.Oferta; import vos.OfertaRFC12; import vos.OfertaTotal; @Path("ofertas") public class OfertaServices { @Context private ServletContext context; private String getPath() { return context.getRealPath("WEB-INF/ConnectionData"); } private String doErrorMessage(Exception e) { return "{ \"ERROR\": \"" + e.getMessage() + "\"}"; } // Se obtienen todas las ofertas de todos operadores @GET @Path("indicesDisponibilidad") @Produces({ MediaType.APPLICATION_JSON }) public Response getIndicesDisponibilidad() { TM tm = new TM(getPath()); List<IndiceOcupacion> ofertas; try { ofertas = tm.getIndicesOcupacion(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(ofertas).build(); } @GET @Produces({ MediaType.APPLICATION_JSON }) public Response getOfertas() { TM tm = new TM(getPath()); List<Oferta> ofertas; try { ofertas = tm.getAllOfertas(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(ofertas).build(); } @GET @Path("idOferta/{id}") @Produces({ MediaType.APPLICATION_JSON }) public Response getOfertaPorId(@PathParam("id") String idOferta) { TM tm = new TM(getPath()); Oferta o; try { if (idOferta == null ) throw new Exception("Id de la oferta no valido"); else { o = tm.darOfertaPorId(Integer.parseInt(idOferta)); } } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(o).build(); } @GET @Path("idOperdador/{idO}") @Produces({ MediaType.APPLICATION_JSON }) public Response getOfertaPorOperador(@PathParam("idO") String idOperador) { TM tm = new TM(getPath()); List<Oferta> ofertas; try { if (idOperador == null || idOperador.length() == 0) throw new Exception("Id del operador no valido"); else { ofertas= tm.darOfertasPorOperador(Integer.parseInt(idOperador)); } } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(ofertas).build(); } @GET @Path("ofertasPopulares") @Produces({ MediaType.APPLICATION_JSON }) public Response getOfertasPopulares() { TM tm = new TM(getPath()); List<OfertaTotal> o; try { o = tm.darOfertasPopulares(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(o).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response addOferta(Oferta oferta) { TM tm = new TM(getPath()); try { tm.addOferta(oferta); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(oferta).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response addOfertaLista(List<Oferta> oferta) { TM tm = new TM(getPath()); try { tm.addOfertaLista(oferta); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(oferta).build(); } @DELETE @Path("idOferta/{id}") public void deleteOferta(@PathParam("id") int idOferta) { TM tm = new TM(getPath()); try { tm.deleteOferta(idOferta); } catch (Exception e) { } } @GET @Path("maximaOcupacion") @Produces({ MediaType.APPLICATION_JSON }) public Response rfc12ReservaMaxima() { TM tm = new TM(getPath()); ArrayList<OfertaRFC12> n; try { n=tm.rfc12ReservaMaxima(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(n).build(); } @GET @Path("minimaOcupacion") @Produces({ MediaType.APPLICATION_JSON }) public Response rfc12ReservaMinima() { TM tm = new TM(getPath()); ArrayList<OfertaRFC12> n; try { n=tm.rfc12ReservaMaxima(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(n).build(); } }
<gh_stars>0 /* MIT License Copyright (c) 2019 MaticVrtacnik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ENTITY_EDITOR_SYSTEM_HPP #define ENTITY_EDITOR_SYSTEM_HPP #include <set> //TODO maybe change to unordered_set #include "System.hpp" #include "GUISystem.hpp" #include "../Collision/Collision.hpp" #include "../Component/MeshComponent.hpp" #include "../TransformVariables.hpp" #include "../GUI/GUIWindowStack.hpp" #include "../GUI/GUI.hpp" #include "../Deprecated/CollisionRenderer.hpp" namespace Engine{ namespace Entities{ namespace Systems{ enum EditingMode{ EDITING_TRANSLATE, EDITING_ROTATE, EDITING_SCALE, }; class EntityEditorSystem : public System{ private: Physics::CollisionRenderer m_collisionRenderer; private: Entity *m_selectedEntity = nullptr; std::set<Entity*> m_selectedEntities; EditingMode m_editingMode = EDITING_TRANSLATE; glm::vec3 m_previousLocation = glm::vec3(0.0f); glm::vec3 m_startingLocation = glm::vec3(0.0f); bool m_pickingX = false; bool m_pickingY = false; bool m_pickingZ = false; private: void rayPicking(); void setSelectedEntity(Entity *entity); void calculateOffset(); void editTranslation(); void editRotation(); void editScaleScreen(); void editScaleWorld(); void handleButtonInput(); void renderEditorMeshes(); public: EntityEditorSystem(); ~EntityEditorSystem(); void init() override; void preUpdate(float fps) override; void update(float fps) override; void postUpdate(float fps) override; void onEntityAdded(Entity &entity) override; void onEntityRemoved(Entity &entity) override; private: template <typename Component, typename... Args> void initComponentGUIAction(const std::string &windowName, Args&&... args); }; template <typename Component, typename... Args> void EntityEditorSystem::initComponentGUIAction(const std::string &windowName, Args&&... args){ auto &_stack = getWorld().getVariables().m_gui->getIndex(). getChild<GUI::GUIWindow>("tab").getChild<GUI::GUITab>("tab"). getWindow("components").getChild<GUI::GUIWindowStack>("stack"); auto &_button = _stack.getWindow(windowName).getChild<GUI::GUIButton>("x"); int _windowHeight = _stack.getWindow(windowName).getScale().y; _button.setAction([this, windowName, _windowHeight, &args...](){ if (m_selectedEntity != nullptr){ bool _hasComponent = m_selectedEntity->hasComponent<Component>(); auto &_GUISystem = getWorld().getSystem<GUISystem>(); _GUISystem.setGUIComponent(windowName, _windowHeight, !_hasComponent); if (_hasComponent){ m_selectedEntity->removeComponent<Component>(); } else{ m_selectedEntity->addComponent<Component> { std::forward<Args>(args)... }; } setSelectedEntity(m_selectedEntity); m_selectedEntity->activate(); } }); } } } } #endif //ENTITY_EDITOR_SYSTEM_HPP
Assessment of altimetry using ground-based GPS data from the 88S Traverse, Antarctica, in support of ICESat-2 Abstract. We conducted a 750km kinematic GPS survey, referred to as the 88S Traverse, based out of South Pole Station, Antarctica, between December 2017 and January 2018. This ground-based survey was designed to validate spaceborne altimetry and airborne altimetry developed at NASA. The 88S Traverse intersects 20% of the ICESat-2 satellite orbits on a route that has been flown by two different Operation IceBridge airborne laser altimeters: the Airborne Topographic Mapper (ATM; 26 October 2014) and the University of Alaska Fairbanks (UAF) Lidar (30 November and 3 December 2017). Here we present an overview of the ground-based GPS data quality and a quantitative assessment of the airborne laser altimetry over a flat section of the ice sheet interior. Results indicate that the GPS data are internally consistent (1.1±4.1cm). Relative to the ground-based 88S Traverse data, the elevation biases for ATM and the UAF lidar range from −9.5 to 3.6cm, while surface measurement precisions are equal to or better than 14.1cm. These results suggest that the ground-based GPS data and airborne altimetry data are appropriate for the validation of ICESat-2 surface elevation data.
/* * Copyright (C) 2017 * <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 de.flapdoodle.solid.formatter; import static org.junit.Assert.assertEquals; import java.time.LocalDateTime; import java.util.Date; import org.junit.Test; import de.flapdoodle.solid.types.Maybe; import de.flapdoodle.solid.types.dates.Dates; public class StringFormatFormatterTest { @Test public void formatDate() { java.util.Formatter f; Date date = Dates.map(LocalDateTime.of(2017, 3, 12, 18, 33)); Maybe<String> result = new StringFormatFormatter("%1$td.%1$tm.%1$tY %1$tH:%1$tM").format(date); assertEquals("12.03.2017 18:33",result.get()); } }
Cholinergic Targets in Lung Cancer. Lung cancers express an autocrine cholinergic loop in which secreted acetylcholine can stimulate tumor growth through both nicotinic and muscarinic receptors. Because activation of mAChR and nAChR stimulates growth; tumor growth can be stimulated by both locally synthesized acetylcholine as well as acetylcholine from distal sources and from nicotine in the high percentage of lung cancer patients who are smokers. The stimulation of lung cancer growth by cholinergic agonists offers many potential new targets for lung cancer therapy. Cholinergic signaling can be targeted at the level of choline transport; acetylcholine synthesis, secretion and degradation; and nicotinic and muscarinic receptors. In addition, the newly describe family of ly-6 allosteric modulators of nicotinic signaling such as lynx1 and lynx2 offers yet another new approach to novel lung cancer therapeutics. Each of these targets has their potential advantages and disadvantages for the development of new lung cancer therapies which are discussed in this review.
Computational evaluation of major components from plant essential oils as potent inhibitors of SARS-CoV-2 spike protein COVID-19, caused by SARS-CoV-2 has recently emerged as a global pandemic. Intense efforts are ongoing to find a vaccine or a drug to control the disease across the globe. Meanwhile, alternative therapies are also being explored to manage the disease. Phytochemicals present in essential oils are promising candidates which have been known to possess wide range of therapeutic activities. In this study, major components of several essential oils which are known for their antimicrobial properties have been docked against the S1 receptor binding domain of the spike (S) glycoprotein, which is the key target for novel antiviral drugs, to ascertain their inhibitory effects based on their binding affinities. It has been found that some monoterpenes, terpenoid phenols and phenyl propanoids such as anethole, cinnamaldehyde, carvacrol, geraniol, cinnamyl acetate, L-4-terpineol, thymol and pulegone from essential oils extracted from plants belonging to families such as Lamiaceae, Lauraceae, Myrtaceae, Apiaceae, Geraniaceae and Fabaceae are effective antiviral agents that have potential to inhibit the viral spikeprotein. Introduction A novel coronavirus (nCoV19) was first reported to have infected humans in Wuhan city of Hubei province, China in the late 2019, which was later termed as severe acute respiratory syndrome Coronavirus 2 (SARS-CoV-2). Coronavirus disease 19 caused by this virus has been declared a global pandemic and Public Health Emergency of International Concern (PHEIC) by WHO since it is affecting millions of people across the world in alarming proportions. The symptoms and manifestations of this disease is similar to respiratory distress indicated previously by beta coronaviruses which were responsible for causing Severe Acute Respiratory Syndrome (SARS) and Middle East Respiratory Syndrome (MERS). Currently, America and Europe are worst affected with about 1.3 and 1.4 million cases respectively. Cases in Eastern Mediterranean, West Pacific, South-East Asia and Africa are also increasing steadily. Presently, efforts are being intensified by scientists across the world for development of vaccine and drugs to treat COVID-19. FDA approved drugs are being repurposed to test their efficacy against SARS-CoV-2 to address the urgency of the situation. Simultaneously alternative plant-based therapies are also being explored to either find a cure or manage the disease. Although, drugs used in western medicine system are predominantly synthetic compounds, over the past few decades natural phyto compounds are being researched owing to their enormous structural and chemical diversity. Bioactive phyto compounds which were used to treat ailments traditionally, have now become indispensable source for many drugs that prevent, manage or treat a plethora of diseases Plant essential oils are being studied extensively since they are known to possess numerous versatile properties such as antimicrobial, antibacterial, antiviral, antiparasitic and insecticidal. They are a diverse mixture of organic compounds predominantly composed of terpenes, terpenoids, phenylpropanoids and aldehydes . The chemical composition and structural components of essential oils majorly contribute to their activity. Essential oils fall under 'GRAS' (generally regarded as safe) category, therefore, they have an edge over synthetic drugs with an added advantage of being safe and non-toxic. The role of essential oils in treating infectious, acute and chronic diseases has been well documented . Though synthetic drugs will be tested for toxicity, minimal side effects can definitely be expected. Hence, essential oil based therapeutic approach can be prioritised in case the efficacy is comparable with synthetic drugs. Previous studies indicate that many essential oils have been effective in inhibiting wide array of microorganisms. In the context of this study related to antiviral properties, a few essentials oils have been effective against RNA and DNA viruses such as avian influenza A virus, herpes simplex virus type 1 (HSV-1) and type 2 (HSV-2), dengue virus type 2, Junin virus, influenza virus adenovirus type 3, poliovirus, and coxsackievirus B1. Since there are very few drug compounds available for treating viral diseases, more insight into drug development based on phyto compounds could be considered. Synergism between these molecules may also be explored with an ultimate goal to find novel antiviral lead molecules. In silico studies play a significant role in accelerating the drug discovery process. To assess the therapeutic potential of certain compounds, it is essential to know the interaction between the ligands and the protein at molecular level. An initial in silico study involving many techniques considerably reduces the time needed for lead molecule identification . For any computational study, the structure of the protein under consideration is of prime importance to understand the interactions and the effects that follow. The protein structure can be modelled through other ways too, in case of unavailability of a 3D protein crystal structure . In this case, the crystal structure of the SARS-CoV-2 spike glycoprotein (S) and main protease (M pro ) has been recently deduced. The S protein is further comprised of two units namely S1, which is also called as receptor binding domain (RBD) as it is involved in binding to the host Angiotensin converting enzyme 2 (ACE2) and S2, which is responsible for fusion of viral and cellular membrane. The S1 subunit of S protein is of clinical importance because inhibiting the RBD can lead to conformational changes in it, as a result, the first step of viral infection is obstructed. In the present study, molecular docking and the conceptual density functional theory (DFT) approach has been utilized to assess the antiviral properties of major components of certain essential oils derived from plants that are notable for antimicrobial activity. The interaction between RBD and essential oil components were assessed based on their binding modes and affinities. Hydrogen bonding and hydrophobic interactions also suggest stable interaction between the protein and ligand. The major objectives of this study were to dock essential oil components against the RBD of the S protein and to identify potential antiviral compounds that specifically inhibit viral attachment and replication in the host. The conceptual DFT study has also been performed to understand and validate the chemical nature of the phytochemicals based on the various molecular descriptors which are derived from the electron density of the molecules. Preparation of protein structure The protein target is the receptor binding domain (RBD) of S1 subunit of SARS-CoV-2 'S' glycoprotein (PDB ID: 6M0J). The crystallographic 3D structure of the protein was particularly chosen since RBD is the key site for targeting inhibitory ligands. It was retrieved from protein data bank (http://www.rcsb.org/). The protein was visualised using PyMol (http://www.pymol.org) and the water molecules, co-crystal ligands like NAG, Cl, Zn and ACE2 structure that were bound to the RBD were removed. Further, the protein was prepared using Autodock vina in PyRx open source software by adding charges and minimizing the energy of the protein and subsequently converting it to pdbqt format. Selection and preparation of ligands The components of essential oils are well known for a variety of activities including antimicrobial, antiviral, antifungal and antibacterial. Major components from certain essential oils such as thyme, cinnamon, clove, star anise, basil, holy basil, eucalyptus, geranium, oregano and ajwain, have been selected as ligands since the efficacy of these components are well established against various organisms. The 3D structure of the ligands were downloaded from PUB-CHEM database (https://pubchem.ncbi.nlm.nih.gov/). It is a chemical database which contains exhaustive information about chemical compounds such as their 2D and 3D structures, properties, bioactivity and safety. The ligands were loaded into the PyRx virtual screening software using OpenBabel control. The OpenBabel software converts the SDF files of the ligands to PDB format. Further, the ligands are prepared by detecting the torsion root, correcting the torsion angles, assigning charges, optimizing using UFF (Universal force field) and finally converting them to pdbqt format to generate 3D atomic coordinates of the molecules. The 2D images of these ligands are presented in Table 1. Active site prediction There could be many sites suitable for ligand binding, but the most appropriate site would be the radial area around the cocrystal ligand site with about 25.0 from the ligand coordinates. ACE2 was complexed with RBD in the 3D crystal structure of protein 6M0J. Therefore the site at and around which ACE2 was bound would be the active site of interest. Recently, the crystal structure of SARS-CoV-2 RBD bound to ACE2 has been characterized. The study suggests that the overall binding mode of SARS-CoV-2 RBD-ACE2 is almost similar to SARS-CoV RBD-ACE2. Small structural changes in SARS-CoV-2 such as insertion of b5, b6 strands, a4, a5 helices and loops in between b4 and b7 contain most of the contacting residues such as Tyr449, Tyr453, Asn487, Phe486, Tyr489, Gln493, Gly496, Gln498 Thr500, Gly502, Tyr505. To further validate the active sites, the protein structure was submitted to active site prediction server maintained by SCFBio, IIT-D, to predict all possible sites (http://www.scfbio-iitd.res.in/dock/ ActiveSite.jsp). About nine cavities were suggested by the server. Molecular docking Molecular docking is an in silico technique that predicts the interactions between a protein and small molecules based on the geometry and the scores. In this study, docking was performed using Autodock vina in PyRx virtual screening open source software. Autodock vina has better performance in comparison to Autodock 4.0 in terms of average accuracy of binding mode prediction, speed and also automatic pre-calculation of grid maps which is done internally. The protein and ligand molecules to be docked are selected under the vina wizard control. A grid appears over the protein structure. The grid size can be adjusted according to the active site residues that are selected and autodock vina is run. The docking results can be viewed under 'analyse results' tab. Conceptual DFT Density functional theory (DFT) is helpful in analyzing the molecular and/or atomic structure using the energies of their molecular orbitals and can provide crucial insights on structureactivity relationship of molecules. The theory is based on the Hohenberg-Kohn theorem A subfield of DFT, known as Conceptual DFT, has been used in this study to observe the chemical behavior of a molecule using electron density relevant concepts. Ten different molecular descriptors have been calculated that are derived from electron density of molecules. The descriptors include total energy, lowest unoccupied molecular orbital (LUMO), highest occupied molecular orbital (HOMO), energy gap, global softness, absolute hardness, molecular dipole moment, electronegativity, electrophilicity index and chemical potential. Binding site characterization The ACE2 binding site in the complex protein and residues suggested by literature and the sites predicted by active site prediction server by SCFBio were scrutinized and compared. Out of the nine cavities suggested by SCFBio server, four of them were located in the distal end of the RBD and the residues in that area almost matched the ones suggested by literature. The residues proposed to be a part of binding site are Tyr453, Arg454, Leu455, Lys458, Ser459, Ser469, Glu471, Pro491, Leu492, Gln493 and Tyr489. Fig. 1 represents the binding site determined by this study. Molecular docking Docking technique essentially aids in identifying putative inhibitors to a particular protein. In this case, the ligands are docked against RBD of S protein to identify potential antiviral compounds. All the ligands were docked in the binding pocket that was proposed. Carvacrol, cinnamaldehyde, cinnamyl acetate, geraniol, L-4- terpineol and anethole displayed better binding affinity with high docking scores compared to the rest of the ligands. Out of all the conformations generated during docking, one conformation each for every ligand with least RMSD were selected.These ligands displayed one or more hydrogen bonding interaction with residues Arg454, Lys458, Ser459, Ser469, Glu471, Leu492 and Tyr505. The hydrogen bonding and hydrophobic interaction between the ligands and protein along with their binding affinities has been tabulated in Table 2. Though, thymol, camphene, pulegone, ocimene and menthol also displayed good binding affinity, they lacked hydrogen bonding interactions with protein. Since there are many hydrophobic residues around the ligands in the binding pocket, hydrophobic interactions between them may contribute to the stability of the complex. The docked poses of each of the top ligands in RBD domain are depicted in Figs. 2e7. They have been represented in distinct colours for better visualisation. All the selected ligands docked together in the binding site characterized has been represented in Fig. 8. Conceptual DFT Initially, the phytochemicals were optimized using B3LYP function with a 6-31G (d) basis in Gaussian 16 to estimate their molecular properties using Fukui's molecular orbital theory Molecular orbital energies like HOMO energy (E HOMO ) and LUMO energy (E LUMO ) were calculated. E HOMO and E LUMO are important descriptors which stands for ability of the molecules to donate and accept electrons, respectively. Maps representing the density of electrons in different regions of the molecules at HOMO and LUMO were generated and analyzed. Table 3 represents the E HOMO and E LUMO values of the phytochemicals. Fig. 9 represents the electron density maps of molecular orbitals of selected phytochemicals. Density maps of the molecular orbitals were constructed and analyzed. Energy gap (DE) between the molecular orbitals of the molecules were estimated with the formula: DE E LUMO -E HOMO. It is important to mention that energy gap is directly proportional to the reactivity of the molecules which can be correlated to the transition of molecules from HOMO to LUMO. Hence, we have calculated the band energy gap of phytochemicals and plotted their distribution in Fig. 9 a-terpinene showed the lowest energy gap between HOMO and LUMO with a DE value of 2.58 eV. o-Cymene has the maximum energy difference between orbitals for all the compounds with a value of 12.57 eV. Compounds like cinnamaldehyde, anethole, cinnamyl actetate, pulegone, ocimene, thymol, carvacrol and menthol scored DE lesser than 6.0 eV. Molecular dipole moment of a molecule can be correlated with its chemical reactivity, as the two are directly proportional to each other. Compounds like cinnamaldehyde, menthone, camphor, pulegone, cinnamylacetate and eugenol scored molecular dipole moments greater than 2.0 debye, with cinnamaldehyde being the highest with 4.53 debye. From the values of E HOMO and E LUMO, we derived the values of other descriptors like Electronegativity (c), Electrophilicity index (u), Chemical potential (m), Global softness (s) and Absolute hardness of the phytochemicals. Electronegativity of a compound is a key descriptor as it influences the ability of a molecule to accept electrons. Lower the electronegativity of a molecule, higher will be its efficiency of inhibition. Cinnamaldehyde has the lowest electronegativity value among the phytochemicals with a score of 4.34. Other compounds like aterpinene, methone, camphor, pulegone, cinnamylacetate, ocimene and p-cymene scored values lesser than 3.0. The values of descriptors of the phytochemicals calculated based on conceptual DFT are correlated with the docking analysis. We have identified that cinnamaldehyde, one of the phytochemicals with a high docking score, has been the best scoring molecule, considering all the descriptors. The high electronegativity of cinnamaldehyde compared to other phytochemicals correlates well with the docking analysis. Discussion In silico techniques have a primary role in early drug discovery process. A computational analysis of drug-protein interactions gives a fair picture of probable lead molecules which can further be tested in vitro. In case of COVID-19, the scientific fraternity is under immense pressure to develop a drug or vaccine. Since identifying a novel antiviral drug candidate particularly for SARS-CoV-2 and conducting clinical trials for the same will be time consuming, drugs are being repurposed to address the situation. Hydroxychloroquine sulphate which was used to treat malaria has been proposed to treat COVID-19 since it has an immunomodulatory effect that stops the cytokine storm generation in the host system. Similarly, Remdesvir was originally meant to treat ebola virus disease but was found to be ineffective. It was repurposed to treat SARS and MERS and was found to be effective, but in case of COVID-19, it failed in the phase 3 clinical trials. Ribavirin, which was an antiviral drug to treat RSV (Respiratory Syncytial Virus) is also being considered to treat this infection. Synergestic effect of lopinavir, oseltamivir and ritonavir have been found to be highly effective against SARS-CoV-2 protease. Exploring plant-based drugs may also be considered because phyto drugs have been known to treat many diseases. They represent about 60% of all the drugs in western medicine. Medicinal herbs contain numerous active ingredients that may be used for the development of therapeutic agents. Essential oils are plant-based volatile liquids. Some oils and their components are known for their antiviral properties. Clove and oregano oils could inhibit polio virus, coxsackie virus B1 and adeno virus type 3. Similarly, essential oils such as thyme, eucalyptus, tea tree could inhibit herpes simplex virus (HSV) by 96% and some monoterpene compounds could inhibit the same by 80%. Eugenol, which is a terpene present in clove essential oil also exhibited virucidal effect against human herpes virus. Likewise, many essential oils have displayed antiviral properties. Therefore in our study, major components of essential oils known for antiviral or rather antimicrobial activity in general have been selected as a ligand set. The Docking analysis and DFT calculation of these ligands against RBD of S protein has resulted in some components showing better inhibitory effects against the target, though almost all were competent to be potent antiviral agents. Anethole which is a phenol methyl ether is abundantly present in star anise essential oil (~80%), fennel oil (~60%) and some other plants belonging to Apiaceae, Myrtaceae and Fabaceae families. Oseltamivir contains shikimic acid, which is also derived from star anise. Thymol, carvacrol, which are monoterpenoids and geraniol, which is an acyclic monoterpene alcohol possess a broad range of activities. They are majorly present in essential oil extracted from plants belonging to Lamiaceae and Geraniaceae family respectively. The phenol ring structure with an addition of hydroxyl group renders them highly efficient antivirals. Cinnamaldehyde and cinnamyl acetate present in cinnamon essential oil are phenylpropanoids with versatile properties known to possess high antioxidant, anti inflammatory, antifungal, antiviral, anticancer and antibacterial properties. L-4-terpineol is present in ample amounts in tea tree and lavender essential oils. Tea tree oil is a notable antiviral essential oil, and also, it has the ability to suppress the production of inflammatory mediators, thereby reducing post-infection inflammation in lungs. Other terpenes such as pulegone, camphene, menthol and ocimene are also efficient antiviral components since their binding affinities are high and hydrophobic interactions are strong enough for stable complex formation, even though they lacked hydrogen bond formation with the target protein. The molecular descriptors calculated by conceptual DFT technique has further complemented the docking results to prove that the above mentioned compounds are highly potent antiviral agents. The RBD comprises of about 188 amino acid residues.The residues in the binding site characterized in this study are located in the cavity which is at the distal end of the RBD. The important residues for interaction range from Tyr449 to Tyr505. The residues in the RBD that interact with ACE2 also fall in the above mentioned range. About 14 hydrogen bonds are involved in RBD-ACE2 longitudinal interaction as pointed out by Lan et al. since ACE 2 is a large protein, whereas ligands are small molecules that have stabilized with a couple of hydrogen bond interactions. The stability of the ligands may also be attributed to strong hydrophobic interactions in the cavity owing to amino acids in the vicinity as depicted in Table 2. The binding site characterized in this study could be considered an important site for targeting drugs in vitro with antiviral potential since it has been validated thoroughly through in silico methods. Conclusion COVID-19 is a highly contagious viral respiratory disease which has to be controlled to prevent further spread and fatalities. The potent antiviral terpenes and phenylpropanoids identified through this study could play a vital role in inhibiting the viral replication in host system and thereby halting further damage. The binding site presented in this study is of utmost importance to elicit the determined action and this site could play vital role in targeting other drugs too. The conceptual DFT study has rendered more insight into the chemical nature of the phytochemicals based on the molecular descriptors which are derived from the electron density of the molecules. In silico methods may also be used to discover other phyto-compounds, suitable for treatment, through virtual screening. Declaration of competing interest The authors declare that they have no conflict of interest.
/** Generated by english-annotation-buster, Powered by Google Translate.**/ /** * Classes supporting the {@code org.springframework.web.reactive.function.server} package. * Contains a {@code HandlerAdapter} that supports {@code HandlerFunction}s, * a {@code HandlerResultHandler} that supports {@code ServerResponse}s, and * a {@code ServerRequest} wrapper to adapt a request. */ /** * 支持{@code org.springframework.web.reactive.function.server}包的类。 * 包含支持{@code HandlerFunction}的{@code HandlerAdapter},支持{@code ServerResponse}的{@code HandlerResultHandler}和{@code ServerRequest}包装器适应要求。 * */ @NonNullApi @NonNullFields package org.springframework.web.reactive.function.server.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
The present invention relates to clusters of media devices, and more specifically, to updating content directories in clusters of media devices. Media devices have advanced from first generation devices, which are used individually as distinct devices, to devices which operate as part of a cluster of devices in a content cluster to store and playback digital content. An important ability is the presentation of the list of digital content available to the user in the content cluster. A set of one or more consumer electronic devices which cooperate together to hold and playback digital content may be referred to as a content cluster. The digital content may be still pictures, video, and/or audio files. The cluster enables devices to access content held on other devices in the cluster over a data network. Devices in a content cluster typically provide the role of storage devices which store digital content, and/or rendering devices which playback such content. It is possible for both roles to be embodied in one device. The devices may be bound together in a cluster connected together over a data network of one or more networking protocols and methods. The devices in a cluster may be located together in close proximity of one another, or may be widely separated physically. A content cluster may or may not have a device which operates as a master or head device coordinating the activities of devices in the cluster.
<reponame>wtlgo/vk-java-sdk // Autogenerated from vk-api-schema. Please don't edit it manually. package com.vk.api.sdk.queries.docs; import com.vk.api.sdk.client.AbstractQueryBuilder; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.client.actors.UserActor; import com.vk.api.sdk.objects.base.responses.OkResponse; import java.util.Arrays; import java.util.List; /** * Query for Docs.edit method */ public class DocsEditQuery extends AbstractQueryBuilder<DocsEditQuery, OkResponse> { /** * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters * * @param client VK API client * @param actor actor with access token * @param ownerId value of "owner id" parameter. * @param docId value of "doc id" parameter. Minimum is 0. * @param title value of "title" parameter. */ public DocsEditQuery(VkApiClient client, UserActor actor, int ownerId, int docId, String title) { super(client, "docs.edit", OkResponse.class); accessToken(actor.getAccessToken()); ownerId(ownerId); docId(docId); title(title); } /** * User ID or community ID. Use a negative value to designate a community ID. * * @param value value of "owner id" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ protected DocsEditQuery ownerId(int value) { return unsafeParam("owner_id", value); } /** * Document ID. * * @param value value of "doc id" parameter. Minimum is 0. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ protected DocsEditQuery docId(int value) { return unsafeParam("doc_id", value); } /** * Document title. * * @param value value of "title" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ protected DocsEditQuery title(String value) { return unsafeParam("title", value); } /** * tags * Document tags. * * @param value value of "tags" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public DocsEditQuery tags(String... value) { return unsafeParam("tags", value); } /** * Document tags. * * @param value value of "tags" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public DocsEditQuery tags(List<String> value) { return unsafeParam("tags", value); } @Override protected DocsEditQuery getThis() { return this; } @Override protected List<String> essentialKeys() { return Arrays.asList("title", "owner_id", "doc_id", "access_token"); } }
Effect of Zinc and Cadmium on -Aminolevulinate Dehydratase of Red Blood Cells in Protecting against Enzyme Losses during Storage The effect of zinc and cadmium on -aminolevulinate dehydratase of bovine erythrocytes stored at - 30 °C for different times was determined. The results show a. storage of erythrocytes leads to an enhancement of the enzyme activity, which after six weeks is 165% (500 ZnCl2) respectively 220% (100 CdCl2) for red blood cells of calves, and after four weeks is 420% respectively 450% (same concentrations) for red blood cells of adult cattle, b. the older the samples are, the higher is the metal concentration, needed for activation.
#pragma once constexpr auto DEFAULT_DESC = "Have fun coding, put in your project's description here."; constexpr auto README_CMAKE_BOILERPLATE = "${{CPPROJ_PROJECT_NAME}}\n" "----\n" "\n" "${{CPPROJ_PROJECT_DESC}}\n" "\n" "## Dependencies\n" "\n" "To make development faster, the project used:\n" "\n" "## Building\n" "\n" "Required a compiler supporting C++${{CPPROJ_CXX_STANDARD}}\n" "\n" "```\n" "mkdir build && cd build\n" "cmake ..\n" "cmake --build .\n" "```\n" "\n" "## Future\n" "\n" "* Future scope of the project, OR your TODO list, that you may not be implementing now\n" "\n" ":copyright: Author ${{CPPROJ_YEAR}}\n" "\n"; constexpr auto README_MAKE_BOILERPLATE = "${{CPPROJ_PROJECT_NAME}}\n" "----\n" "\n" "Have fun coding, put in your project's description\n" "\n" "## Dependencies\n" "\n" "To make development faster, the project used:\n" "\n" "## Building\n" "\n" "Required a compiler supporting C++${{CPPROJ_CXX_STANDARD}}\n" "\n" "```\n" "make" "```\n" "> Add more relevant commands according to your project\n" "\n" "## Future\n" "\n" "* Future scope of the project, OR your TODO list, that you may not be implementing now\n" "\n" ":copyright: Author ${{CPPROJ_YEAR}}\n" "\n";
<reponame>mi-schi/php-code-checker __all__ = ['phploc', 'phpmetrics', 'pdepend']
How does Divine Life provide safety in everyday life? Please join us for our healing services. Everyone is welcome. WEDNESDAY EVENING TESTIMONY MEETING: 7:00 – 8:00 PM. The meeting begins with a hymn sung by all, then Inspirational readings from the desk are read by the Reader, The Lord’s Prayer is prayed and a hymn is sung followed by those present who would like to share how prayer has helped heal challenges in their lives. We end the meeting with a hymn. SUNDAY SERVICE: 10 - 11 AM. what the LORD has done. The Golden Text is from the Contemporary English Version. Which holdeth our soul in life, and suffereth not our feet to be moved. And he shewed me a pure river of water of life, clear as crystal, proceeding out of the throne of God and of the Lamb. In the midst of the street of it, and on either side of the river, was there the tree of life, which bare twelve manner of fruits, and yielded her fruit every month: and the leaves of the tree were for the healing of the nations. And the Spirit and the bride say, Come. And let him that heareth say, Come. And let him that is athirst come. And whosoever will, let him take the water of life freely.
/** * Signals a StatsItem user wants to show does not exist. */ public class ShownItemOutOfBoundException extends RuntimeException { public ShownItemOutOfBoundException() { super("The stats item selected does not exist."); } }
This invention relates to facsimile equipment and more particularly to the generation of frequency modulated facsimile signals representing dark/light variations or light/dark variations on a document. Facsimile transmitters or transceivers having a transmitting capability frequency generate frequency modulated signals which are substantially sinusoidal in waveform. Typically, these sinusoidal signals vary in frequency from 1500 Hz. representing white to 2400 Hz. representing black with various intermediate frequencies representing shades of gray. It is common practice to generate the sinusoidal signals of utilizing a voltage controlled oscillator which produces an output of the desired frequency in response to voltages representing the dark/light variations as detected by a light sensitive device. The output from the voltage controlled oscillator which has a frequency equal to the frequency of the facsimile transmission signal is then filtered to remove high frequency components. This filtering is necessary to eliminate the high frequency components but undesirably decreases the speed of response of the transmitter to instantaneous dark/light variations so as to introduce phase distortion and delay. U.S. Pat. Nos. 3,911,207 and 4,015,077 assigned to the assignee of this invention, disclose facsimile equipment which generates facsimile signals in the above-described manner. In general, it is desirable to transmit the dark/light transmission information over appropriate communication links, e.g., telephone lines, as rapidly as possible so as to maximize the use of the available bandwidth and provide optimum document resolution. This requires that the transmitting circuitry be capable of rapid changes in frequency representing a dark/light variation or light/dark variation. In other words, it is desirable that the frequency modulated facsimile signal be capable of a substantially instantaneous change in slope. In the prior art, the facsimile signals have not been capable of the desired instantaneous change in frequency. Rather, the prior art has been characterized by a limited speed of response which can result in output signal phase distortion. Where the facsimile signal has been coupled to the network acoustically, the delays have not been that critical since acoustic coupling effectively limited the faithful reproduction of dark/light variations even if high frequency shift rates were achievable. However, with the advent of liberalized direct coupling for facsimile transceivers as disclosed in copending application Ser. No. 689,263 filed May 24, 1976, it becomes more important to assure that the speed of response is limited only by the unpredictable characteristics of the telephone network itself and not the facsimile transmission equipment. The prior art includes techniques for synthesizing sinusoidal waveforms using digital techniques. In this connection, reference is made to an article entitled, "Create Sinewaves Using Digitalized IC's," Radio Electronics, November, 1976. As shown there, the output from the counters are summed to achieve a step-like sinusoidal waveform which is then smoothed by filtering.
from fastapi import HTTPException class NotFoundException(HTTPException): def __init__(self, item): msg = f"{item} not found" super().__init__(status_code=404, detail=msg)
<reponame>famargon/vertx-microservices-sample package com.example.apigateway; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import io.vertx.circuitbreaker.CircuitBreaker; import io.vertx.circuitbreaker.CircuitBreakerOptions; import io.vertx.core.AbstractVerticle; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.StaticHandler; import io.vertx.servicediscovery.Record; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import io.vertx.servicediscovery.types.HttpEndpoint; public class APIGatewayVerticle extends AbstractVerticle { protected ServiceDiscovery discovery; private CircuitBreaker circuitBreaker; @Override public void start(Future<Void> future) throws Exception { discovery = ServiceDiscovery.create(vertx); circuitBreaker = CircuitBreaker.create("circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(5) .setTimeout(10000L).setFallbackOnFailure(true).setResetTimeout(30000L)); // get HTTP host and port from configuration, or use default value String host = config().getString("api.gateway.http.address", "localhost"); int port = config().getInteger("api.gateway.http.port", 8787); // (1) Router router = Router.router(vertx); // (2) // body handler router.route().handler(BodyHandler.create()); // (4) // api dispatcher router.route("/*").handler(this::dispatchRequests); // (10) // create http server vertx.createHttpServer().requestHandler(router::accept).listen(port, host, ar -> { // (14) if (ar.succeeded()) { publishApiGateway(host, port); future.complete(); } else { future.fail(ar.cause()); } }); } private void publishApiGateway(String host, int port){ discovery.publish(HttpEndpoint.createRecord("api-gateway", host, port, "/"), res -> { if(!res.succeeded()){ System.out.println(res.cause()); } }); } private Future<List<Record>> getAllEndpoints() { Future<List<Record>> future = Future.future(); discovery.getRecords(record -> record.getType().equals(HttpEndpoint.TYPE), future.completer()); return future; } private void dispatchRequests(RoutingContext context) { // run with circuit breaker in order to deal with failure circuitBreaker.execute(future -> getAllEndpoints().setHandler(ar -> routeRequest(context, future, ar)) ).setHandler(ar -> { if (ar.failed()) { context.response().setStatusCode(502).putHeader("content-type", "application/json") .end(new JsonObject().put("error", "bad_gateway").encodePrettily()); System.out.println(ar.cause()); } }); } private void routeRequest(RoutingContext context, Future<Object> future, AsyncResult<List<Record>> ar) { if (ar.succeeded()) { List<Record> recordList = ar.result(); for(Record r : recordList){ System.out.println(r.getName() + " "+ r.getMetadata().encodePrettily()); } // get relative path and retrieve prefix to dispatch client String path = context.request().uri(); if (path.length() == 1) { notFound(context, "invalid request, this is an api gateway"); future.complete(); return; } String prefix = StringUtils.substringBefore(StringUtils.substringAfter(path, "/"),"/"); // generate new relative path String newPath = path.substring(prefix.length()+1); System.out.println("new path " + newPath); // get one relevant HTTP client, may not exist Optional<Record> client = recordList.stream() .filter(record -> record.getMetadata().getString("api.name") != null && record.getMetadata().getString("api.name").equals(prefix)) .findAny(); // (4) simple load balance if (client.isPresent()) { doDispatch(context, newPath, discovery.getReference(client.get()).get(), future); // (5) } else { notFound(context, "not found"); // (6) future.complete(); } } else { future.fail(ar.cause()); // (8) } } private void doDispatch(RoutingContext context, String path, HttpClient client, Future<Object> cbFuture) { HttpClientRequest req = client.request(context.request().method(), path, response -> { response.bodyHandler(body -> { if (response.statusCode() >= 500) { // api endpoint server // error, circuit breaker // should fail cbFuture.fail(response.statusCode() + ": " + body.toString()); } else { HttpServerResponse toRsp = context.response().setStatusCode(response.statusCode()); response.headers().forEach(header -> { toRsp.putHeader(header.getKey(), header.getValue()); }); // send response toRsp.end(body); cbFuture.complete(); } ServiceDiscovery.releaseServiceObject(discovery, client); }); }); context.request().headers().forEach(header -> { req.putHeader(header.getKey(), header.getValue()); }); if (context.user() != null) { req.putHeader("user-principal", context.user().principal().encode()); } // send request if (context.getBody() == null) { req.end(); } else { req.end(context.getBody()); } } private void notFound(RoutingContext context, String message) { context.response().setStatusCode(404).putHeader("content-type", "application/json") .end(new JsonObject().put("message", message).encodePrettily()); } }
The survey found that if presidential elections were held in which only Abbas and Hamas leader Ismail Haniyeh ran, 35.3% said they would vote for Abbas, while 19.3% said they would vote for Haniyeh. More than 60% of Palestinians support the Palestinian Authority’s position not to accept the US as a sole mediator in the peace process, according to a Palestinian public poll published last Tuesday. The poll, conducted by the Jerusalem Media and Communication Center, showed that more than 80% of Palestinians don’t believe that US President Donald Trump’s yet-to-be-announced plan for peace in the Middle East, which is also known as the “Deal of the Century,” would produce anything acceptable to the Palestinians. It also found that the percentage of Palestinians opposed to the Oslo Accords was on the rise. The survey, which was conducted between June 26 and July 7, interviewed 1,200 Palestinians from the West Bank and Gaza Strip, and has a margin of error of 3%. The poll’s results showed that Palestinians were divided over the idea of returning to peace negotiations with Israel – 49.1% were in favor of renewed negotiations and 45.6% opposed them. The PA leadership’s position regarding Trump’s “Deal of the Century” has led to some improvement in its standing, the poll showed. The percentage of those who trust PA President Mahmoud Abbas rose to 11.1% in this poll as opposed to 10.6% in a previous poll published last January. Furthermore, there was a rise in the percentage of those who trust Abbas’s ruling Fatah faction more than other groups – from 22.3% to 25% over the same period. The survey found that if presidential elections were held in which only Abbas and Hamas leader Ismail Haniyeh ran, 35.3% said they would vote for Abbas, while only 19.3% said they would vote for Haniyeh. If elections were held without Abbas, jailed Fatah operative Marwan Barghouti and Haniyeh would receive virtually the same amount of votes: 11.7% and 11.6%, respectively. Abbas’s arch-rival in Fatah, Mohammed Dahlan, came in third with 8.3%. Asked about the Oslo Accords that were signed 25 years ago between Israel and the PLO, more than 45% of current respondents said the agreements had harmed Palestinian national interests, as opposed to 33.6% in March 2013. Only 11.9% claimed they had served Palestinian national interests, and 34% said the accords had made no difference. More than 61% of respondents said they opposed the Oslo Accords (up from 48.3% in March, 2013) compared to 24% who said they supported them. With regards to the ongoing dispute between Hamas and Fatah, more than 37% of respondents held the Ramallah-based PA government responsible for the crisis, as opposed to 29% who blamed Hamas. The majority of respondents (56.9%) expressed their pessimism towards the likelihood that the reconciliation agreement signed in October 2017 would be implemented as opposed to 35.5% who were optimistic. The poll showed that the greatest percentage of respondents – 39.3% – depend on social media as a source of news, followed by 28% who depend on television, 17.3% who depend on news websites, 7.4% on radio and only 1.4% on newspapers.
<filename>fast_dataset_cleaner/front/src/components/SampleAnnotation.tsx import React from 'react'; import { withStyles, WithStylesProps } from 'react-with-styles'; import { FastDatasetCleanerThemeType } from '../theme/FastDatasetCleanerTheme'; import Sample from './Sample'; import { SampleType } from '../types/Annotation'; import FetchService from '../services/Fetch'; import { closeBannerWidth } from './Banner'; type Props = { images: SampleType[]; isBannerOpen: boolean; fetchService: FetchService; navigationDirection: string; handleChangeValue: Function; } & WithStylesProps; function SampleAnnotation(props: Props) { const { isBannerOpen, images, fetchService, navigationDirection, handleChangeValue, css, styles } = props; return ( <div {...css(styles.mainColumn)}> {images.map( (sample: SampleType) => <Sample sample={sample} isBannerOpen={isBannerOpen} handleChangeValue={handleChangeValue} navigationDirection={navigationDirection} fetchService={fetchService} key={sample.name} /> )} </div> ); } const unit = 8; const mainColumnHeight = { large: `calc(100vh - 2 * ${0.5 * unit}px)`, xlarge: `calc(100vh - 2 * ${unit}px)`, }; export default withStyles(({ color, unit, speed, breakpoints }: FastDatasetCleanerThemeType) => ({ mainColumn: { background: color.page, marginLeft: closeBannerWidth + 2 * unit, marginRight: 0, paddingTop: unit, paddingBottom: unit, display: 'flex', flexWrap: 'wrap', height: mainColumnHeight.xlarge, transition: `background ${speed.fast}s ease-in-out`, [breakpoints.large]: { paddingTop: 0.5 * unit, paddingBottom: 0.5 * unit, marginLeft: closeBannerWidth + 4 * unit, height: mainColumnHeight.large, }, }, }))(SampleAnnotation);
MSU trustees froze tuition for incoming freshmen this fall and approved plans to institute a block tuition structure for the 2019-2020 school year. EAST LANSING - Michigan State University trustees froze tuition rates for incoming freshmen this fall and approved plans to institute a block tuition structure for the 2019-2020 school year. Tuition for freshmen will stay at the $482 per credit hour. For most sophomores, juniors and seniors, rates will go up by $12 per credit hour, an increase of about 2.5% for sophomores and 2.2% for upperclassmen. The rate of increase is the same for out-of-state freshmen, according to budget guidelines presented at Friday's Board of Trustees meeting. Juniors and seniors enrolled in the College of Business or the College of Engineering will pay an extra $18 per credit hour, an increase of about 3% for engineers and 3.2% for business majors. Interim President John Engler justified the rate increases by noting that salaries for College of Business and College of Engineering grads were $59,503 and $66,495, respectively. The average starting salary for graduates is about $53,000. The bigger changes are coming in the 2019-20 academic year, when tuition rates for all undergrads will be frozen and a new rate structure rolled out. Students will be billed on a block rate if they take between 12 and 18 credits. Freshmen will pay $7,230 per semester, while sophomores will pay $7,410 per semester, the same rates they'll pay in 2018 for 15 credits. Juniors and seniors in engineering or business programs will pay $8,595 per semester while their counterparts in other colleges will pay $8,325. Those taking fewer will pay the 2018-19 rate per hour, and those taking more will pay per credit at 19 credits and above. The block tuition structure. won't apply to graduate students and resident medical students. The changes to tuition rates are meant to encourage students to take more credits and complete their degrees sooner, Engler said during the meeting.
Q: Can I make a cake with finely ground coffee instead of cocoa powder? I used all my cocoa powder. Will it taste good if I use coffee instead? If anyone has done this before, please share your experiences and hints. A: Coffee cake is good, but it's better to start from a recipe for coffee cake than try to adapt a chocolate cake. Cocoa powder brings an appreciable amount of fat and bulk to the recipe. You need to be very careful about terminology. Coffee powder in many places refers to powdered instant (soluble) coffee, which isn't the best coffee drink but is very suiatable as a flvouring. It should be dissolved in liquid before adding tot he cake mix (following the recipe). I have seen coffee powder used to refer to finely ground coffee beans. It's not unknown to add these to food, but it's not common. We discussed this recently. A: Yes you can.But dont expect it to be a chocolate cake. Also the quantity of coffee must be 1/6 th the amount of cocoa powder you would have used for chocolate cake. Otherwise your cake will definitely turn bitter. Cocoa and Coffee are altogether different material. These are not substitutes. You can try with cocoa powder, Coffee powder(try with instant ) and mix cocoa powder and coffee. You will get three different flavor profile. A: Potentially, but using ground coffee as an ingredient often doesn't work that well as it can add a gritty texture and excessive bitterness. Bear in in mind that when you make coffee to drink the process generally involves a carefully controlled brewing time and separating the ground from the liquor and even if you make 'cowboy coffee' you avoid drinking the grounds. Instant coffee is better direct substitute for cocoa powder or alternatively you can brew some coffee and add it as a liquid ingredient, although this may require adjusting the recipe a bit so you don't end up with too much liquid in the mixture.
<reponame>jonri/StuntPlayground /* Stunt Playground MainFrameListener */ #ifndef _STUNTPLAYGROUND_HIGHSCORE_ #define _STUNTPLAYGROUND_HIGHSCORE_ #include <Ogre.h> namespace StuntPlayground { // simple class for storing high scores. class HighScore { public: void load( std::string filename ); void save( std::string filename ); bool possibleJumpTime( Ogre::Real time ) { if (time > mTime) { mTime = time; return true; } return false; } bool possibleJumpDist( Ogre::Real dist ) { if (dist > mDist) { mDist = dist; return true; } return false; } bool possible2Wheels( Ogre::Real time ) { if (time > m2WH) { m2WH = time; return true; } return false; } bool possibleFlips( Ogre::Real flips ) { if (flips > mFlips) { mFlips = flips; return true; } return false; } Ogre::Real mTime; Ogre::Real mDist; Ogre::Real m2WH; Ogre::Real mFlips; }; } // end NAMESPACE StuntPlayground #endif // _STUNTPLAYGROUND_HIGHSCORE_
High Quality remodeled home in a Cul de sac. Block construction, Quartz countertops, new flooring, stacked stone fireplace, mountain views, new cabinets with self closing drawers. The water heater is new. Too many extras to list. Bring your best buyer. This is first class. Feel free to call me to discuss the amount of work done to the home. It is rare to find homes this size that offer room for expansion if desired. Some sketches are available from the architect.
import { BrowserTestCase } from '@atlaskit/webdriver-runner/runner'; import { getExampleUrl } from '@atlaskit/webdriver-runner/utils/example'; import Page from '@atlaskit/webdriver-runner/wd-wrapper'; /* Url to test the example */ const exampleUrl = getExampleUrl('design-system', 'checkbox', 'testing'); /* Css selectors used for the test */ const checkboxLabelQuery = "[data-testid='the-checkbox--checkbox-label']"; const hiddenCheckboxQuery = "[data-testid='the-checkbox--hidden-checkbox']"; BrowserTestCase( 'Checkbox should be able to be clicked by data-testid', {}, async (client: any) => { const testPage = new Page(client); await testPage.goto(exampleUrl); await testPage.waitFor(checkboxLabelQuery, 5000); await testPage.click(checkboxLabelQuery); const checkbox = await testPage.$(hiddenCheckboxQuery); const isChecked = await checkbox.getProperty('checked'); expect(isChecked).toBe(true); }, ); BrowserTestCase( 'Checkbox should be checked when clicked with a modifier such as shift+click', { skip: ['chrome'] }, // modified clicks requires the browser.performActions() method, but this function does not exist when running in Chrome async (client: any) => { const testPage = new Page(client); await testPage.goto(exampleUrl); await testPage.waitFor(checkboxLabelQuery, 5000); await testPage.modifierClick('Shift'); // shift is chosen here as it is OS-agnostic unlike cmd+click, and should behave in the same way const checkbox = await testPage.$(hiddenCheckboxQuery); const isChecked = await checkbox.getProperty('checked'); expect(isChecked).toBe(true); }, );
from __future__ import division import calculate_species_relative_abundance import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats from scipy.special import erf import math import sympy as sp import scipy species_abun_dict_zeros = calculate_species_relative_abundance.load_species_abun_dict() species_abun_dict = {} for species in species_abun_dict_zeros.keys(): species_abun_dict[species] = {} na_nonzero_abun = [] af_nonzero_abun = [] for abun in species_abun_dict_zeros[species]['Africa']: if abun != '0.0': af_nonzero_abun.append(abun) for abun in species_abun_dict_zeros[species]['North America']: if abun != '0.0': na_nonzero_abun.append(abun) species_abun_dict[species]['Africa'] = af_nonzero_abun species_abun_dict[species]['North America'] = na_nonzero_abun #####collect all species abundances and variance of abundance within group for each species varplot_dict = {} africa_abun = [] na_abun = [] for species in species_abun_dict.keys(): africa_abun.append(species_abun_dict[species]['Africa']) na_abun.append(species_abun_dict[species]['North America']) if len(species_abun_dict[species]['Africa']) > 1 and len(species_abun_dict[species]['North America']) > 1: varplot_dict[species] = {} varplot_dict[species]['Africa'] = [] varplot_dict[species]['North America'] = [] varplot_dict[species]['Africa'].append(np.var(np.array(species_abun_dict_zeros[species]['Africa']).astype(np.float))) varplot_dict[species]['North America'].append(np.var(np.array(species_abun_dict_zeros[species]['North America']).astype(np.float))) #flatten lists of lists into 1 list africa_abun = [float(item) for sublist in africa_abun for item in sublist] na_abun = [float(item) for sublist in na_abun for item in sublist] #####collect log mean abundance within group for each species mean_abundance_dict = calculate_species_relative_abundance.load_species_mean_abun_dict() log_africa_mean_abun = [] log_north_america_mean_abun = [] for species_abundance in mean_abundance_dict.keys(): log_africa_mean_abun.append(np.log10(mean_abundance_dict[species_abundance]['Africa'])) log_north_america_mean_abun.append(np.log10(mean_abundance_dict[species_abundance]['North America'])) #get list of mean abundances for plotting and mean abundances for varplot_dict africa_mean_abun = [] na_mean_abun = [] species_order_mean = [] for species in mean_abundance_dict.keys(): species_order_mean.append(species) africa_mean_abun.append(mean_abundance_dict[species]['Africa']) na_mean_abun.append(mean_abundance_dict[species]['North America']) if len(species_abun_dict[species]['Africa']) > 1 and len(species_abun_dict[species]['North America']) > 1: varplot_dict[species]['Africa'].append(mean_abundance_dict[species]['Africa']) varplot_dict[species]['North America'].append(mean_abundance_dict[species]['North America']) species_prev_dict = calculate_species_relative_abundance.load_species_prev_dict() africa_prev = [] na_prev = [] species_order_prev = [] for species in species_prev_dict.keys(): species_order_prev.append(species) africa_prev.append(species_prev_dict[species]['Africa']) na_prev.append(species_prev_dict[species]['North America']) #rescale abundances africa_abun = np.array(africa_abun) na_abun = np.array(na_abun) rescaled_africa_abun = (np.log10(africa_abun) - np.log10(africa_abun).mean())/np.log10(africa_abun).std() rescaled_na_abun = (np.log10(na_abun) - np.log10(na_abun).mean())/np.log10(na_abun).std() fig, axs = plt.subplots(2, 2, figsize=(15,15)) hist_na, bin_edges_na = np.histogram(rescaled_na_abun, density=True, bins=30) bins_mean_na = [0.5 * (bin_edges_na[i] + bin_edges_na[i+1]) for i in range(0, len(bin_edges_na)-1 )] hist_af, bin_edges_af = np.histogram(rescaled_africa_abun, density=True, bins=30) bins_mean_af = [0.5 * (bin_edges_af[i] + bin_edges_af[i+1]) for i in range(0, len(bin_edges_af)-1 )] def Klogn(emp_mad, c, mu0=-19,s0=5): # This function estimates the parameters (mu, s) of the lognormal distribution of K m1 = np.mean(np.log(emp_mad[emp_mad>c])) m2 = np.mean(np.log(emp_mad[emp_mad>c])**2) xmu = sp.Symbol('xmu') xs = sp.Symbol('xs') eq1 = - m1 + xmu + np.sqrt(2/math.pi)*xs*(sp.exp(-((np.log(c)-xmu)**2)/2/(xs**2))/(sp.erfc((np.log(c)-xmu)/np.sqrt(2)/xs))) eq2 = - m2 + xs**2 + m1*xmu+np.log(c)*m1-xmu*np.log(c) sol = sp.nsolve([eq1,eq2],[xmu,xs],[mu0,s0]) return(float(sol[0]),float(sol[1])) na_mad_log10 = np.log10(na_mean_abun) na_hist_mad, na_bin_edges_mad = np.histogram(na_mad_log10, density=True, bins=20) na_bins_mean_mad = [0.5 * (na_bin_edges_mad[i] + na_bin_edges_mad[i+1]) for i in range(0, len(na_bin_edges_mad)-1 )] na_prob_to_plot = [sum( (na_mad_log10>=na_bin_edges_mad[i]) & (na_mad_log10<=na_bin_edges_mad[i+1]) ) / len(na_mad_log10) for i in range(0, len(na_bin_edges_mad)-1 )] na_bins_mean_plot = [np.exp(na_bins_mean_mad[i]) for i in range(len(na_bins_mean_mad))] af_mad_log10 = np.log10(africa_mean_abun) af_hist_mad, af_bin_edges_mad = np.histogram(af_mad_log10, density=True, bins=20) af_bins_mean_mad = [0.5 * (af_bin_edges_mad[i] + af_bin_edges_mad[i+1]) for i in range(0, len(af_bin_edges_mad)-1 )] af_prob_to_plot = [sum( (af_mad_log10>=af_bin_edges_mad[i]) & (af_mad_log10<=af_bin_edges_mad[i+1]) ) / len(af_mad_log10) for i in range(0, len(af_bin_edges_mad)-1 )] af_bins_mean_plot = [np.exp(af_bins_mean_mad[i]) for i in range(len(af_bins_mean_mad))] plt.clf() fig, axs = plt.subplots(2, 2, figsize=(15,15)) # range of abundances to plot x=np.arange(-14,-1,step=0.1) axs[0,0].scatter(na_bins_mean_plot, na_prob_to_plot, alpha=0.5, s=30, label = "North America") axs[0,0].scatter(af_bins_mean_plot, af_prob_to_plot, alpha=0.5, s=30, label = "Africa") #ax.scatter(bins_mean_af, hist_af, alpha=0.5, s=30, label = "Africa") #c_values = [10e-8, 10e-7, 10e-6] c = 10e-7 #for value in numpy.linspace(numpy.quantile(emp_mad, 0.25), numpy.quantile(emp_mad, 0.5), 5): (mu,sigma) = Klogn(np.array(na_mean_abun), c) axs[0,0].plot(np.exp(x), np.sqrt(2/math.pi)/sigma *np.exp(-(x-mu)**2 /2/(sigma**2))/scipy.special.erfc((np.log(c)-mu)/np.sqrt(2)/sigma)) (mu,sigma) = Klogn(np.array(africa_mean_abun), c) axs[0,0].plot(np.exp(x), np.sqrt(2/math.pi)/sigma *np.exp(-(x-mu)**2 /2/(sigma**2))/scipy.special.erfc((np.log(c)-mu)/np.sqrt(2)/sigma)) #plot truncated lognormal fitted for K>log(c) #ax.plot(numpy.log10(numpy.exp(x)),numpy.sqrt(2/math.pi)/sigma *numpy.exp(-(x-mu)**2 /2/(sigma**2))/scipy.special.erfc((numpy.log(c)-mu)/numpy.sqrt(2)/sigma),'-k') #ax.plot(numpy.exp(x), numpy.sqrt(2/math.pi)/sigma *numpy.exp(-(x-mu)**2 /2/(sigma**2))/scipy.special.erfc((numpy.log(c)-mu)/numpy.sqrt(2)/sigma),'-k') axs[0,0].set_xscale('log', basex=10) axs[0,0].set_yscale('log', basey=10) axs[0,0].set_xlim(10**(-4), 1) axs[0,0].legend() axs[0,0].set_xlabel('Mean Relative Abundance Distribution') axs[0, 1].scatter(bins_mean_na, hist_na, alpha=0.5, s=30, label = "North America") axs[0, 1].scatter(bins_mean_af, hist_af, alpha=0.5, s=30, label = "Africa") axs[0, 1].set_xlabel('Rescaled Log Abundance Distribution') axs[0, 1].legend() na_var = [varplot_dict[s]['North America'][0] for s in varplot_dict.keys()] af_var = [varplot_dict[s]['Africa'][0] for s in varplot_dict.keys()] na_mean_varplot = [varplot_dict[s]['North America'][1] for s in varplot_dict.keys()] af_mean_varplot = [varplot_dict[s]['Africa'][1] for s in varplot_dict.keys()] na_slope, intercept, r_value, p_value, se = stats.linregress(np.log10(na_mean_varplot), np.log10(na_var)) x_log10_range = np.linspace(min(np.log10(na_mean_varplot)) , max(np.log10(na_mean_varplot)) , 1000) y_log10_fit_range = slope*x_log10_range + intercept axs[1, 0].plot(10**x_log10_range, 10**y_log10_fit_range, lw=2, linestyle='--', zorder=2) af_slope, intercept, r_value, p_value, se = stats.linregress(np.log10(af_mean_varplot), np.log10(af_var)) x_log10_range = np.linspace(min(np.log10(af_mean_varplot)) , max(np.log10(af_mean_varplot)) , 1000) y_log10_fit_range = slope*x_log10_range + intercept axs[1, 0].plot(10**x_log10_range, 10**y_log10_fit_range, lw=2, linestyle='--', zorder=2) axs[1, 0].scatter(na_mean_varplot, na_var, alpha=0.5, label=str('North America (slope = %.2f)' % na_slope)) axs[1, 0].scatter(af_mean_varplot, af_var, alpha=0.5, label =str('Africa (slope = %.2f)' % af_slope)) axs[1, 0].set_xlabel('Mean Relative Abundance') axs[1, 0].set_ylabel('Variance of Abundance') axs[1, 0].set_xscale("log") axs[1, 0].set_yscale("log") axs[1, 0].legend(loc = 'upper left') axs[1, 1].scatter(na_mean_abun, na_prev, alpha=0.5, label='North America') axs[1, 1].scatter(africa_mean_abun, africa_prev, alpha=0.3, label='Africa') axs[1, 1].set_xlabel('Mean Relative Abundance') axs[1, 1].set_ylabel('Prevalence') axs[1, 1].set_xlim(10e-9,20e-2) axs[1, 1].set_ylim(0.002,1) axs[1, 1].set_yscale("log") axs[1, 1].set_xscale("log") axs[1, 1].legend() plt.savefig('C:/Users/sarah/Garud Lab/plots/macroecology_plot.png', bbox_inches='tight', dpi=600)
Chylous cyst of the small bowel mesentery presenting as a contained rupture of an abdominal aortic aneurysm. A 74-year-old man was admitted as an emergency with a two-week history of postural hypotension. Three days previously he had suffered two blackouts and had noticed malaena stools. An ultrasound scan of the abdomen revealed a 7.5 cm abdominal aortic Fig. 1. Computerised tomographic (CT) scan of the abdomen showing a large fluid-filled mass (white arrow) adjacent to an abdominal aneurysm associated with a retroperitoneal fluid aortic aneurysm, suggesting a contained rupture. collection. Subsequent Computed Tomography (CT) scanning confirmed an infrarenal abdominal aortic aneurysm with a retroperitoneal fluid collection to the right compressing the inferior vena cava (IVC, Fig. 1) and right renal vein (Fig. 2). A hypodense formation was seen in the pelvis of the left kidney, but this was reported as a baggy pelvis of the kidney. A working diagnosis of a contained rupture of his abdominal aortic aneurysm was made. He was taken to theatre that same evening and laparatomy performed as an emergency procedure. At laparotomy a large infrarenal AAA was confirmed. There was no evidence of rupture but the small bowel mesentery contained a 5 cm loculated chylous mass
Tree Monitoring Using Ground Penetrating Radar: Two Case Studies Using Reverse-Time Migration Non-destructive testing (NDT) for health monitoring of trees is a suitable candidate for detecting signs of early decay. Recent developments have highlighted that ground-penetrating radar (GPR) has the potential to provide with a robust and accurate detection tool with minimum computational and operational requirements in the field. In particular, a processing framework is suggested in that can effectively remove ringing noise and unwanted clutter. Subsequently, an arc length parameterisation is employed in order to utilise a wheel-measurement device to accurately position the measured traces. Lastly, two migration schemes; Kirchhoff and reversetime migration, are successfully applied on numerical and laboratory data in. In the current paper, the detection scheme described in using reverse-time migration is tested in two case studies that involve diseased urban trees within the greater London area, UK (Kensington and Gunnersbury park). Both of the trees were cut down after the completion of the measurements and furthermore cut into several slices to get direct information with regards to their internal structure. The processing scheme described in managed to adequately detect the internal decay present in both trees. The aforementioned case studies provide coherent evidences to support the premise that GPR is capable of detecting decay in diseased trunks and therefore has the potential to become an accurate and efficient diagnostic tool against emerging infectious diseases of trees.
<reponame>BeHappyForMe/retrieval-faq import argparse import os import pickle import logging import logging.handlers from sklearn.metrics.pairwise import cosine_similarity import code from tqdm import trange, tqdm import numpy as np import pandas as pd from elmoformanylangs import Embedder import pkuseg import sys sys.path.append("..") from metric import mean_reciprocal_rank, mean_average_precision e = Embedder('D:\\NLP\\my-wholes-models\\zhs.model') seg = pkuseg.pkuseg() logger = logging.getLogger(__name__) handler2 = logging.FileHandler(filename="ELMo.log") logger.setLevel(logging.DEBUG) handler2.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s") handler2.setFormatter(formatter) logger.addHandler(handler2) def main(): parser = argparse.ArgumentParser() parser.add_argument("--train_file", default='../data/right_samples.csv', type=str, required=False, help="training file") parser.add_argument("--evaluate_file", default='../data/eval_touzi.xlsx', type=str, required=False, help="training file") parser.add_argument("--do_evaluate", action="store_true", help="Whether to run evaluate.") parser.add_argument("--do_predict", default=True, action="store_true", help="Whether to run predict.") parser.add_argument("--batch_size", default=16, type=int, required=False, help="batch size for train and eval") args = parser.parse_args() if not os.path.exists("embeddings.pkl"): train_df = pd.read_csv(args.train_file, sep='\t') candidate_title = train_df['best_title'].tolist() candidate_reply = train_df["reply"].tolist() titels = [] for title in tqdm(candidate_title, desc='对原问题进行分词ing'): titels.append(seg.cut(title)) embeddings = [] for i in trange(0, len(titels), 16, desc='获取ELMo的句子表示'): mini_embeddings = e.sents2elmo(titels[i:min(len(titels), i + 16)]) for mini_embedding in mini_embeddings: # 获取句子向量,对词取平均 embeddings.append(np.mean(mini_embedding, axis=0)) if i == 0: print(len(embeddings)) print(embeddings[0].shape) print("原始问题句子向量表示获取完毕,保存ing") with open("embeddings.pkl", 'wb') as fout: pickle.dump([candidate_title, candidate_reply, embeddings], fout) else: with open("embeddings.pkl", 'rb') as fint: candidate_title, candidate_reply, embeddings = pickle.load(fint) if args.do_evaluate: evulate_df = pd.read_excel(args.evaluate_file, '投资知道') # code.interact(local=locals()) evulate_df = evulate_df[['问题', '匹配问题']] evulate_df = evulate_df[evulate_df['问题'].notna()] evulate_df = evulate_df[evulate_df['匹配问题'].notna()] questions = evulate_df['问题'].tolist() matched_questions = evulate_df['匹配问题'].tolist() matched_questions_indexs = [] for k, q in enumerate(matched_questions): flag = False for i, _q in enumerate(candidate_title): if q == _q: matched_questions_indexs.append([i]) flag = True break if not flag: matched_questions_indexs.append([-1]) matched_questions_indexs = np.asarray(matched_questions_indexs) # print("size of matched_questions_index:{}".format(matched_questions_indexs.shape)) questions = [seg.cut(question.strip()) for question in questions] question_embedding = [np.mean(emb, 0) for emb in e.sents2elmo(questions)] scores = cosine_similarity(question_embedding, embeddings) # print("scores shape : {}".format(scores.shape)) sorted_indices = scores.argsort()[:, ::-1] # code.interact(local=locals()) mmr = mean_reciprocal_rank(sorted_indices == matched_questions_indexs) map = mean_average_precision(sorted_indices == matched_questions_indexs) logger.info("mean reciprocal rank: {}".format(mmr)) logger.info("mean average precision: {}".format(map)) if args.do_predict: while True: title = input("你的问题是?\n") if len(str(title).strip()) == 0: continue title = [seg.cut(str(title).strip())] title_embedding = np.mean(e.sents2elmo(title)[0], 0).reshape(1, -1) scores = cosine_similarity(title_embedding, embeddings)[0] top5_indices = scores.argsort()[-5:][::-1] for index in top5_indices: print("可能的答案,参考问题:" + candidate_title[index] + "\t答案:" + candidate_reply[index] + "\t得分:" + str( scores[index])) if __name__ == '__main__': main()
<reponame>wanching0730/first-nestjs-example<filename>src/article/article.entity.ts<gh_stars>0 import { Entity, PrimaryGeneratedColumn, Column, OneToOne, ManyToOne, OneToMany, JoinColumn, AfterUpdate, BeforeUpdate } from 'typeorm'; import { UserEntity } from '../user/user.entity'; import { CommentEntity } from './comment.entity'; @Entity('article') export class ArticleEntity { @PrimaryGeneratedColumn() id: number; @Column() slug: string; @Column() title: string; @Column({default: ''}) description: string; @Column({default: ''}) body: string; @Column({ type: 'timestamp', default: () => "CURRENT_TIMESTAMP"}) created: Date; @Column({ type: 'timestamp', default: () => "CURRENT_TIMESTAMP"}) updated: Date; @BeforeUpdate() updateTimestamp() { this.updated = new Date; } @Column('simple-array') tagList: string[]; @ManyToOne(type => UserEntity, user => user.articles) author: UserEntity; @OneToMany(type => CommentEntity, comment => comment.article, {eager: true}) comments: CommentEntity[]; @Column({default: 0}) favoriteCount: number; }
/* * Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved. * * * * Copyright 2004 The Apache Software 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 org.apache.jasper.runtime; import java.lang.IllegalStateException; import java.io.Writer; import java.io.PrintWriter; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.JspWriter; import com.sun.enterprise.web.io.ByteWriter; /** * ServletResponseWrapper used by the JSP 'include' action. * * This wrapper response object is passed to RequestDispatcher.include(), so * that the output of the included resource is appended to that of the * including page. * * @author <NAME> */ public class ServletResponseWrapperInclude extends HttpServletResponseWrapper { /** * PrintWriter which appends to the JspWriter of the including page. */ private PrintWriter printWriter; private JspWriter jspWriter; // START CR 6466049 /** * Indicates whether or not the wrapped JspWriter can be flushed. */ private boolean canFlushWriter; // END CR 6466049 public ServletResponseWrapperInclude(ServletResponse response, JspWriter jspWriter) { super((HttpServletResponse)response); this.jspWriter = jspWriter; if (jspWriter instanceof JspWriterImpl && ((JspWriterImpl)jspWriter).shouldOutputBytes()) { this.printWriter = new PrintWriterWrapper((JspWriterImpl)jspWriter); } else { this.printWriter = new PrintWriter(jspWriter); } // START CR 6466049 this.canFlushWriter = (jspWriter instanceof JspWriterImpl); // END CR 6466049 } /** * Returns a wrapper around the JspWriter of the including page. */ public PrintWriter getWriter() throws IOException { return printWriter; } public ServletOutputStream getOutputStream() throws IOException { throw new IllegalStateException(); } /** * Clears the output buffer of the JspWriter associated with the including * page. */ public void resetBuffer() { try { jspWriter.clearBuffer(); } catch (IOException ioe) { } } // START CR 6421712 /** * Flush the wrapper around the JspWriter of the including page. */ public void flushBuffer() throws IOException { printWriter.flush(); } // END CR 6421712 // START CR 6466049 /** * Indicates whether or not the wrapped JspWriter can be flushed. * (BodyContent objects cannot be flushed) */ public boolean canFlush() { return canFlushWriter; } // END CR 6466049 // START PWC 6512276 /** * Are there any data to be flushed ? */ public boolean hasData() { if (!canFlushWriter || ((JspWriterImpl)jspWriter).hasData()) { return true; } return false; } // END PWC 6512276 static private class PrintWriterWrapper extends PrintWriter implements ByteWriter { private JspWriterImpl jspWriter; PrintWriterWrapper(JspWriterImpl jspWriter) { super(jspWriter); this.jspWriter = jspWriter; } public void write(byte[] buff, int off, int len, int strlen) throws IOException { jspWriter.write(buff, off, len, strlen); } } }
def step(a, b): if a > n - 3 or b == 0 or b == n - 1 or l[a + 1][b] == '#' or l[a + 2][b] == '#' or l[a + 1][b - 1] == '#' or l[a + 1][b + 1] == '#': return False else: l[a] = l[a][:b] + '#' + l[a][b + 1:] l[a + 1] = l[a + 1][:b - 1] + '###' + l[a + 1][b + 2:] l[a + 2] = l[a + 2][:b] + '#' + l[a + 2][b + 1:] return True n = int(input()) l = [input() for i in range(n)] ans = 'YES' for i in range(n): for j in range(n): if l[i][j] == '.' and not step(i, j): ans = 'NO' print(ans)
Abstract 1200: Associations between genetically predicted blood protein biomarkers and pancreatic ductal adenocarcinoma risk Pancreatic ductal adenocarcinoma (PDAC) is one of most lethal malignancies with few known risk factors and biomarkers. Identification of disease biomarkers is critical for understanding the pathogenesis of this cancer and identifying high risk individuals for close surveillance. Several blood protein biomarkers have been linked to PDAC in previous studies, but these studies have assessed only a limited number of biomarkers usually in small samples. To identify novel circulating protein biomarkers of PDAC, we studied 8,280 cases and 6,728 controls of European descent from the Pancreatic Cancer Cohort Consortium and the Pancreatic Cancer Case-Control Consortium, by using genetic instruments. Protein quantitative trait loci (pQTLs) for 1,226 plasma proteins identified in a large INTERVAL study of 3,301 healthy European descendants were used as instruments to evaluate associations between genetically predicted protein levels and PDAC. For proteins showing a significant association, we further conducted conditional analysis with adjustments for previously identified risk variants to assess whether the observed associations between genetically predicted protein concentrations and PDAC risk were independent of the risk variants identified in genome-wide association studies (GWAS). Furthermore, for the proteins that were associated with PDAC risk, we performed an enrichment analysis of the genes encoding these proteins to examine whether they are enriched in specific pathways, functions or networks. We observed associations between predicted concentrations of 38 proteins and PDAC risk at a false discovery rate of In conclusion, we identified 38 protein biomarker candidates for PDAC risk, which if validated by additional studies, may contribute to the etiological understanding of PDAC tumor development. Citation Format: Jingjing Zhu, Xiang Shu, Xingyi Guo, Duo Liu, Jiandong bao, Roger Milne, Graham G Giles, Chong Wu, Mengmeng Du, Emily White, Harvey A Risch, Nuria Malats, Eric J. Duell, Phyllis J. Goodman, Donghui Li, Paige Bracci, Verena Katzke, Rachel E Neale, Steven Gallinger, Stephen Van Den Eeden, Alan Arslan, Federico Canzian, Charles Kooperberg, Brian Wolpin, Laura Beane-Freeman, Ghislaine Scelo, Kala Visvanatha, Christopher A. Haiman, Loic Le Marchand, Herbert Yu, Gloria M Petersen, Rachael Stolzenberg-Solomon, Alison P Klein, Laufey T Amundadottir, Qiuyin Cai, Jirong Long, Xiao-Ou Shu, Wei Zheng, Lang Wu. Associations between genetically predicted blood protein biomarkers and pancreatic ductal adenocarcinoma risk . In: Proceedings of the Annual Meeting of the American Association for Cancer Research 2020; 2020 Apr 27-28 and Jun 22-24. Philadelphia (PA): AACR; Cancer Res 2020;80(16 Suppl):Abstract nr 1200.
class jlfwdL { } class x3OXrJe { public static void cZw (String[] FukKIK4iCVq) throws WKK { int VXU; } public static void ziF4oB (String[] vUG) throws kTnS3o { ( 5668889.xhwl0n1RsvJ7).idSqS2D9C6; boolean[] MRyzN; boolean[][][][][] B = -Ev1Zk7cHeF.X(); boolean fskZEZmHeIp; { boolean[][][][][] rrop3ytSgRA; void[][][] HNtQLjEDnuppSO; } while ( -new KzyZZMMqDwfM()[ ( new H3m1mb().Ot12())[ X5[ hah9mqp5H3()[ 8.laQsliRq()]]]]) new Msrr().Cnu0qPP3; { void[] xNRhqMaen; ; } { void oTzVP; !ui1BiJKPmk()[ JPF5P0Zq5LY.orZg7sJmj4()]; return; ; bpetaJ7SWP3Eeu[] Tf7hL; void gaL48l; return; if ( -!( !new int[ !false._Pdyd0b()].v_9Fh)[ new int[ !!!-new rytJJwl().zXGI()].r0JRsCWmkXt()]) { if ( ( ( ( new boolean[ -EiOd7JZ()[ -new nB10KxwC8IbnG[ new int[ uhFPQtaLuM.TlRlJ07PTs7gVK()].j7()].pf4ufRAqVK()]].muzhx9s()).JTfATS()).QSKhbUC()).jCf7h_M6Hb) while ( !true[ null[ this.rSQwBojqL7T]]) TX2f2U1abNh()[ -!-new _eftfQ6_mhX9w_().LAQ()]; } void f9PgHABaLK; boolean[][] iFcaQYvp; int AsFN3; { ; } -fQvae[ true.h()]; ; if ( new int[ new boolean[ -true.sx77Jpe7xD()][ !--new ApH2bGG9B7().gj_9YwiFue0O]].yBMszM78MMCIA()) !!-null.bNZGUYVw8; !!null.sY(); while ( !false.SrJdn) while ( !pabsaH3gS().gzi0tWGrOs()) while ( false.hrR) while ( ( this[ new oT[ !!2041900.zsM8Jy1zu644C()][ true[ true[ !--!new boolean[ -!345.H7QZtrpue7].StCqI_wWiF]]]]).dOVYDNlxY0Gy) if ( !879833.wZy1ow()) { p22is UyjsU2qxrvV; } ; Gdur[] O7tPy4mpJdp; } if ( true[ xG().gPSNPCjMYxG()]) -new int[ this.wqAS()].l();else while ( !new ICzLoadY39di0[ LX().wVXjj_uo()][ !!RyRTv9.EUqkLwAXQt1FIS()]) while ( ( !this.fT8hCAYX)[ --!!218.fRo9ejFtkxr4()]) return; int[][] eqY = new boolean[ !s4iaanKYW().bWwU0g9()].sAKK; { bWyuxvOLAb _; while ( !true.OfrL4Qvqf2ZOAd()) -669369.pzyo0sBEpD37D; { if ( false.WI()) { f TlaL181g; } } return; { boolean[][][] LImZVt4a9SgAg; } { ; } void k7ftKPzdW06HW; ; JK9XmtxR[][][] Yi; return; boolean CeqWPrmP7DFO87; boolean B7FkfiSamA2; int[][][][][] xZIAt; if ( ( -499698866[ ( !!!null.mpRoL()).PII]).bQdrY9nRLSpZI1) while ( EsVVCBadl[ !Y0WHoxgHyl1[ -new WY().uSR_()]]) while ( -null.uCEDQS2VP) return; return; s_dccmg1r.sRoBb9Wt; { void j8_I0Y; } } while ( false.hnxp9OyBf()) if ( v().I3GjSML2DDB0()) { int[] FMqumkEsZFgTl; } void[][][] Y = 462[ !( --true.swx1mU1h).GfENJw_qDB] = -HRs().gBmNQw(); !this[ !_5nqIS.GoTEZ0hGANH]; Sf3LcEnDd6M[][] AaG6bzMA = z().f_Co_OfMR() = !-y86WVN()[ ---this[ !!---!!true.GjsmH]]; { void mQlPOmYmJy6j; void[] lS; return; { ; } int d4LzxG0u0PsWrB; int yslSMY; { gNL5sw5z12l3qH[][] VZeRTf1NkEE; } void[][] gSMURImLzD4tFW; { void TtwZ7; } boolean[][] x0n1S7; if ( !554.Zj2M) ; void[] Thsi6YcTywo; if ( -null[ !-53[ -!-!-null.w()]]) while ( -YnOA[ null.pF26()]) if ( null.OAG8_0) { void[][] _; } void[][][] kHizWVx2W; if ( new tQnTkoeY().NY0fiK) -!--nbZuTB8W()[ !437.r()]; boolean ExP9CSeITfle3T; ; int[][][] j4I; } void[] O = new cviikUR().hdCTTpyH = !-971.TH_NEd3QtSxbL; return ( new e().nkqXBlE()).fa9YpCqT(); int Ld27O7rESUJQpj = -!true[ !true.kaumUv5nSSQXI] = --!-( LICVAs6cU2BX07().NjGocmQLjPYKrE)[ true.H0NAlYAVCUw()]; } } class I { } class os { } class maSR { }
<filename>pkg/util/labels_test.go package util import ( "github.com/openshift/source-to-image/pkg/api" "github.com/openshift/source-to-image/pkg/api/constants" "io/ioutil" "os" "path/filepath" "testing" ) func TestImageMetadataLabels(t *testing.T) { tests := []struct { json string count int }{ { json: "{\"labels\": [{\"org.tenkichannel/service\":\"rain-forecast-process\"}]}", count: 1, }, { json: "{\"labels\": [{\"labelkey1\":\"value1\"},{\"labelkey2\":\"value2\"}]}", count: 2, }, { json: "{\"labels\": [{\"labelkey1\":\"value1\",\"labelkey2\":\"value2\"}]}", count: 2, }, } for _, tc := range tests { tempDir, err := ioutil.TempDir("", "image_metadata") if err != nil { t.Fatalf("could not create temp dir: %v", err) } defer os.RemoveAll(tempDir) err = os.Chmod(tempDir, 0777) if err != nil { t.Fatalf("could not chmod temp dir: %v", err) } err = os.MkdirAll(filepath.Join(tempDir, constants.SourceConfig), 0777) if err != nil { t.Fatalf("could not create subdirs: %v", err) } path := filepath.Join(tempDir, constants.SourceConfig, MetadataFilename) err = ioutil.WriteFile(path, []byte(tc.json), 0700) if err != nil { t.Fatalf("could not create temp image_metadata.json: %v", err) } cfg := &api.Config{ WorkingDir: tempDir, } data := GenerateOutputImageLabels(nil, cfg) if len(data) != tc.count { t.Fatalf("data from GenerateOutputImageLabels len %d when needed %d for %s", len(data), tc.count, tc.json) } } }
Human peripheral lymphocytes defined by antimyelinassociated glycoprotein antiserum in healthy individuals and in patients with multiple sclerosis ABSTRACT We investigated both the association between MAGpositive cells and active natural killer cells stained by antiLeu11 and the percentage of MAGpositive cells in patients with multiple sclerosis (MS) by indirect immunofluorescence study. Eighty percent of MAGpositive cells were stained with antiLeu11. The percentage of MAGpositive cells of 41 healthy individuals was from 5.1 to 16.1% (8.5±2.7%). The percentage of Leu7positive cells (13.8 ± 4.9%) was always greater than that of MAGpositive cells. In 5 of 17 samples from 14 patients with MS, the percentage of MAGpositive cells was reduced. This finding was not related to disease activity and was not a pathognomonic feature of MS. The percentage of Leu7positive cells in patients with MS was not statistically different from that in healthy individuals; however, 4 patients showed a normal number of Leu7positive cells and a reduced number of MAGpositive cells. These studies suggest that MAGpositive cells are closely related to active natural killer cells and that MAG is a useful marker of human natural killer cells.
<filename>src/app/components/recipes/Recipes.tsx import React from 'react'; import Recipe from './Recipe'; import { MDBContainer, MDBRow } from 'mdbreact'; import './Recipes.css'; import { RecipeCategoryEnum, ReceipeOriginEnum } from './types'; const Recipes = () => { return ( <MDBContainer className="recipes-container"> <MDBRow> <Recipe imgSource="/images/tortellini.JPG" category={RecipeCategoryEnum.MAIN_DISH} readMoreLink="" titleId="yummyfood.recipe.title.tortellini" origin={ReceipeOriginEnum.ITALIA} teaserId="yummyfood.recipe.teaser.tortellini" /> <Recipe imgSource="/images/rolat.JPG" category={RecipeCategoryEnum.MAIN_DISH} readMoreLink="" titleId="yummyfood.recipe.title.swiss-roll" origin={ReceipeOriginEnum.CENTRAL_EUROPE} teaserId="yummyfood.recipe.teaser.swiss-roll" /> <Recipe imgSource="/images/chickpea_curry.JPG" category={RecipeCategoryEnum.MAIN_DISH} readMoreLink="" titleId="yummyfood.recipe.title.chickpea-curry" origin={ReceipeOriginEnum.THAILAND} teaserId="yummyfood.recipe.teaser.chickpea-curry" /> <Recipe imgSource="/images/sopa_de_mani.JPG" category={RecipeCategoryEnum.MAIN_DISH} readMoreLink="" titleId="yummyfood.recipe.title.sopa-mani" origin={ReceipeOriginEnum.BOLIVIA} teaserId="yummyfood.recipe.teaser.sopa-mani" /> <Recipe imgSource="/images/gibanica.jpg" category={RecipeCategoryEnum.MAIN_DISH} readMoreLink="" titleId="yummyfood.recipe.title.gibanica" origin={ReceipeOriginEnum.SERBIA} teaserId="yummyfood.recipe.teaser.gibanica" /> <Recipe imgSource="/images/phad_thai.JPG" category={RecipeCategoryEnum.MAIN_DISH} readMoreLink="" titleId="yummyfood.recipe.title.phad-thai" origin={ReceipeOriginEnum.THAILAND} teaserId="yummyfood.recipe.teaser.phad-thai" /> </MDBRow> </MDBContainer> ); }; Recipes.displayName = 'Recipes'; export default Recipes;
1. Field of the Invention This invention relates to a beauty treatment device, and more particularly a beauty treatment device having freely rotating space guide wheels for causing a freely rotating roller as a patter to make an up and down motion while describing an eccentrical circular orbit and maintaining the patting depth by the roller at a predetermined distance wherein the roller is caused to repeatedly pat the skin surface at an effective rate to remove subcutaneous adipose tissues and stimulate subcutaneous muscular layers to prevent the skin from being loosened; and the patter is adapted to move smoothly along the skin surface while making a patting motion. 2. Description of the Prior Art It is widely practiced as a beauty treatment, particularly as a facelifting technique to tap or pat the skin surface with fingertips and other means. And, various massagers have heretofore been used, which give vibrations to the skin surface or lightly tap the human body. Most of those beauty treatment devices which give vibrations to the skin, however, involve the massaging of the skin by depressing the skin surface or giving a circular motion to the skin. These devices may cause the skin to stretch, leading to the loosening of the skin or even wrinkles in extreme cases. The present inventor has already proposed a beauty treatment device which repeatedly gives gentle impacts on the skin surface. That is, the beauty treatment device previously proposed by the present inventor has a space guide fixedly mounted on a device body, and a patter fitted to an actuator which is caused to reciprocate by a drive unit so that the patter advances toward the open end of the space guide to pat the skin surface at a given rate. Although this type of beauty treatment device has a facelifting effect of removing subcutaneous adipose tissues, it has the following disadvantage. That is, when the user wants to change the patting position, he has to detach the device from the skin and then replace it at a desired position partly because the space guide is fixedly mounted on the device body and partly because the patter is adapted to make an up and down reciprocating motion. That is, if the user changes the patting position while applying the device onto the skin surface, the skin is unwantedly stretched sideways.
/** * Utility to connect to s3 */ public class S3Util { private static final Logger LOG = Logger.getLogger(S3Util.class); private S3Util() { throw new UnsupportedOperationException(); } public static AmazonS3 getS3Client(String accessKey, String secretKey) { AWSCredentials awsCredentials = AWSUtil.createAWSCredentials(accessKey, secretKey); AmazonS3 s3client; if (awsCredentials != null) { s3client = new AmazonS3Client(awsCredentials); } else { s3client = new AmazonS3Client(); } return s3client; } public static TransferManager getTransferManager(String accessKey, String secretKey) { AWSCredentials awsCredentials = AWSUtil.createAWSCredentials(accessKey, secretKey); TransferManager transferManager; if (awsCredentials != null) { transferManager = new TransferManager(awsCredentials); } else { transferManager = new TransferManager(); } return transferManager; } public static void shutdownTransferManager(TransferManager transferManager) { if (transferManager != null) { transferManager.shutdownNow(); } } public static String getBucketName(String s3Path) { String bucketName = null; // s3path if (s3Path != null) { String[] s3PathParts = s3Path.replace(LogFeederConstants.S3_PATH_START_WITH, "").split(LogFeederConstants.S3_PATH_SEPARATOR); bucketName = s3PathParts[0]; } return bucketName; } public static String getS3Key(String s3Path) { StringBuilder s3Key = new StringBuilder(); if (s3Path != null) { String[] s3PathParts = s3Path.replace(LogFeederConstants.S3_PATH_START_WITH, "").split(LogFeederConstants.S3_PATH_SEPARATOR); ArrayList<String> s3PathList = new ArrayList<String>(Arrays.asList(s3PathParts)); s3PathList.remove(0);// remove bucketName for (int index = 0; index < s3PathList.size(); index++) { if (index > 0) { s3Key.append(LogFeederConstants.S3_PATH_SEPARATOR); } s3Key.append(s3PathList.get(index)); } } return s3Key.toString(); } /** * Get the buffer reader to read s3 file as a stream */ public static BufferedReader getReader(String s3Path, String accessKey, String secretKey) throws IOException { // TODO error handling // Compression support // read header and decide the compression(auto detection) // For now hard-code GZIP compression String s3Bucket = getBucketName(s3Path); String s3Key = getS3Key(s3Path); S3Object fileObj = getS3Client(accessKey, secretKey).getObject(new GetObjectRequest(s3Bucket, s3Key)); try { GZIPInputStream objectInputStream = new GZIPInputStream(fileObj.getObjectContent()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(objectInputStream)); return bufferedReader; } catch (IOException e) { LOG.error("Error in creating stream reader for s3 file :" + s3Path, e.getCause()); throw e; } } public static void writeIntoS3File(String data, String bucketName, String s3Key, String accessKey, String secretKey) { InputStream in = null; try { in = IOUtils.toInputStream(data, "UTF-8"); } catch (IOException e) { LOG.error(e); } if (in != null) { TransferManager transferManager = getTransferManager(accessKey, secretKey); try { if (transferManager != null) { transferManager.upload(new PutObjectRequest(bucketName, s3Key, in, new ObjectMetadata())).waitForUploadResult(); LOG.debug("Data Uploaded to s3 file :" + s3Key + " in bucket :" + bucketName); } } catch (AmazonClientException | InterruptedException e) { LOG.error(e); } finally { try { shutdownTransferManager(transferManager); in.close(); } catch (IOException e) { // ignore } } } } }
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { appPath } from '../../app-path.const'; @Component({ selector: 'app-payment-info', templateUrl: './payment-info.component.html', styleUrls: ['./payment-info.component.css'] }) export class PaymentInfoComponent implements OnInit { public path = appPath; constructor() { } ngOnInit() { } }
Q: Run webinar with more than one webcam I'm trying to create a little home office webinar setup. I'd love to use more than one camera. One to point at my face, and another to point at a drawing, or diagram I'm making. I will likely be using webrtc as a platform, but would love it if I could set it up to work with Skype and Google hangouts and such. Is there a way to have two usb webcams plug into a switcher, and then just click a button or hit a switch and change which camera feeds into my webinar program? Ideally there would be black screen while switching. A: Webcams live in the universe of being devices plugged into computers, and switchers live in the universe of standard video sources being plugged into them. These two universes only talk to each other via specialized interfaces (if at all). Happily, there exists software that gives you switcher-like functionality as a software package for your computer. One such package is manycam. There are others you can find. Trying to get webcam video out of your computer as video, into a switcher, then back into your computer so that it can be webcast is about 3x more difficult than it needs to be. And it requires a lot more space on a physical desktop.
package com.newmedia.erxeslibrary.Configuration; import com.newmedia.erxeslibrary.model.Conversation; import com.newmedia.erxeslibrary.model.ConversationMessage; import com.newmedia.erxeslibrary.model.EngageData; import com.newmedia.erxeslibrary.model.Integration; import com.newmedia.erxeslibrary.model.KnowledgeBaseArticle; import com.newmedia.erxeslibrary.model.KnowledgeBaseCategory; import com.newmedia.erxeslibrary.model.KnowledgeBaseLoader; import com.newmedia.erxeslibrary.model.KnowledgeBaseTopic; import com.newmedia.erxeslibrary.model.Supporter; import com.newmedia.erxeslibrary.model.User; import io.realm.annotations.RealmModule; @RealmModule(library = true,classes = {Conversation.class, ConversationMessage.class, EngageData.class, Integration.class, User.class, KnowledgeBaseArticle.class, KnowledgeBaseCategory.class, KnowledgeBaseLoader.class, KnowledgeBaseTopic.class,Supporter.class}) public class ErxesRealmModule { }
On Frame Fingerprinting and Controller Area Networks Security in Connected Vehicles Modern connected vehicles are equipped with a large number of sensors, which enable a wide range of services that can improve overall traffic safety and efficiency. However, remote access to connected vehicles also introduces new security issues affecting both inter and intra-vehicle communications. In fact, existing intra-vehicle communication systems, such as Controller Area Network (CAN), lack security features, such as encryption and secure authentication for Electronic Control Units (ECUs). Instead, Original Equipment Manufacturers (OEMs) seek security through obscurity by keeping secret the proprietary format with which they encode the information. Recently, it has been shown that the reuse of CAN frame IDs can be exploited to perform CAN bus reverse engineering without physical access to the vehicle, thus raising further security concerns in a connected environment. This work investigates whether anonymizing the frames of each newly released vehicle is sufficient to prevent CAN bus reverse engineering based on frame ID matching. The results show that, by adopting Machine Learning techniques, anonymized CAN frames can still be fingerprinted and identified in an unknown vehicle with an accuracy of up to 80 %. I. INTRODUCTION In recent years, the digitalization of the automotive sector and release of new technologies in the market have lead to a dramatic growth in the number of Electronic Control Units (ECUs) present inside vehicles. The data sent from these components is a valuable source of information for researchers and companies proposing solutions for connected vehicles, such as fleet management and cloud services, ). As of today, most of the data sent from these ECUs transit on the Controller Area Network (CAN) bus, a message-based protocol considered the de-facto world standard for in-vehicle communications. CAN allows ECUs to send messages to each other without a master node orchestrating the communication. However, attention was brought to the lack of security of the CAN bus, due to the fact that no encryption is put in place -. In this regard, a variety of attacks have been presented in literature,. The magnitude of such threats will likely be amplified by the increase of vehicle connectivity and the subsequent augment of access points for attacks. Despite the absence of security features, the data transiting on the CAN bus is not easily interpretable. As a matter of fact, each Original Equipment Manufacturer (OEM) encodes the data with its own proprietary format, which is kept secret from the general public. The only way to disclose information regarding these formats is through reverse engineering, which is traditionally performed by following a list of tedious manual operations. Recent works have focused on automating this process to reduce the time and manual effort required -. The proposed solutions are mostly based on correlating the CAN data with external sensors and involve precise actions to be performed by a trained operator during data collection. In one of our recent studies we unveiled that the IDs of CAN frames sent by ECUs can be exploited to carry out reverse engineering in a highly automated way. The main reason is that a limited number of Tier-1 suppliers provide the majority of ECUs to car manufacturers worldwide. As a consequence, the same ECU can be found in the electronic system of multiple vehicle models, which send the same frames using the same frame IDs. This characteristic can be exploited by matching the frame of a vehicle to reverse engineer with frames of known vehicles sharing the same frame ID. Differently from related work, this approach is event-agnostic, i.e. the data can be decoded without knowing the events occurred at data collection time. By using this method, an attacker with remote access to the CAN bus of a connected vehicle can perform reverse engineer and inject an attack without physical access nor prior knowledge about the target vehicle. OEMs seem unwilling to bring core modifications to the CAN protocol (i.e., by adding encryption) as it would inevitably bring massive disruptions in the supply chains. One potential solution to protect against frame matching based reverse engineering approaches and improve the security of the CAN bus, while meeting the necessities of the OEMs, is to avoid the reuse of frame IDs for newly released vehicle models. In this work, we investigate whether the abandonment of the frame ID reuse practice is sufficient to completely anonymize the frames, thus nullifying the benefit of a reverse engineering approach based on frame matching. In particular, we study the possibility of performing matching on anonymized frames by exploiting other properties of the frames. If confirmed, the implication would be that frame-matching based algorithms can still be used to perform CAN bus reverse engineering despite the ID anonymization with minimal extra effort. This would further corroborate the view that OEMs must improve the CAN bus security by applying substantial modifications to the protocol. To validate this thesis, we propose a frame deanonymization algorithm, which makes use of Machine Learning (ML) models to fingerprint frames based on their characteristics and dynamic behaviour. The ML models can then recognize the frames in a new vehicle to reverse engineer based on previously acquired knowledge. The contribution of this work can be summarized as follows: We investigate the benefits of allocating a complete new set of IDs to each newly released vehicle model. We present and evaluate a new ML-based algorithm, whose goal is to deanynonymize frames. This algorithm works under Open Set Recognition (OSR) assumptions. We discuss the implications of such a method in the scope of CAN bus security. II. BACKGROUND AND RELATED WORK The communication on the CAN bus relies on messages, or frames. The frames do not contain any information regarding the sender nor the receiver ECU. A CAN frame is composed of a number of fields, as shown in Figure 1. This work focuses on three of them: (i) Identifier (ID) -uniquely represents the frame and assigns its priority, (ii) Data Length Code (DLC) -reports the payload length expressed as an integer between 0-8 Byte, and (iii) Payload -contains the actual information carried by the frame. ECUs send one or more CAN frames periodically. In absence of collisions, these frames are received by all the ECUs connected to the bus. While an ECU can receive or send frames with different IDs, all frames associated with the same ID are sent by the same ECU. Due to the lack of a master node supervising the communication on the bus, multiple messages can be sent simultaneously by different ECUs, thus generating a collision. When a collision occurs, higher priority frames (defined by their IDs) override lower priority frames, which then have to be re-transmitted. CAN bus reverse engineering is the process of finding the boundaries of the signals within a frame payload, known as tokenization, and decode their format (e.g. scale factor and offset) and their semantic meaning (i.e. what vehicle function they encapsulate), known as translation. In the manual approach, the reverse engineering is performed by a human operator who physically connects and disconnects ECUs and detects changes in the CAN traffic. Some signals can also be retrieved by injecting diagnostic messages through the OBD-II port to generate a response from the CAN bus. In automated reverse engineering, tokenization is mostly achieved by analyzing the flipping of the bits composing the frames over time,. After tokenization, typically, the tokens are compared with GPS/IMU data, which offer a ground truth about the current status of the vehicle at driving time, to find correlations. The injection of specific diagnostic messages and the analysis of subsequent responses from the CAN bus is often automated too. The translation, or part of it, can be achieved through ML-based classification,,. In this approach, an ML classifier is trained to recognize the characteristics (or features) of each signal among CAN traces from known vehicles, so that it can later exploit this knowledge on an unknown vehicle. By analyzing a large dataset containing CAN traces obtained from 427 distinct vehicle models, we noticed that OEMs do not change the frame IDs when mounting the same ECU on multiple vehicle models. Assuming a decoded set of frames is available (i.e., via manual reverse engineering), this can be exploited to decode unknown CAN traces by simply matching the unknown frame IDs with the ones from the decoded dataset. One way to prevent this is to anonymize the frame IDs for each newly released vehicle model. In this work, we show that it is still possible to fingerprint and identify anonymized frames with high accuracy, hence facilitating the automated reverse engineering process based on frame matching. III. FINGERPRINTING ANONYMIZED CAN FRAMES In this work, we assume that frame IDs are anonymized, i.e., same ECU model manufactured by the same OEM and installed in any two different vehicle models use different frame IDs for frames carrying the same vehicle functions. In particular, we make two fundamental assumptions: 1) Following the standard CAN protocol, the new ID associated to a frame should uniquely identify that frame. 2) The attribution of new IDs operated by the OEM should not be random, but rather preserve the frames priority. This assumption is important because lower-priority frames have more chances to be overwritten by higher-priority frames, when sent on the CAN bus simultaneously. Hereafter, we present a tool to deanonymize frames which are anonymized following the aforementioned assumptions. The pipeline of this method is shown in Figure 2. The tool firstly divides the CAN trace collected from the vehicle to reverse engineer into n sub-traces, where n corresponds to the amount of unique IDs. Every sub-trace contains the payload and DLC of the frames with the same ID, following the temporal order in which they appear in the trace. Then, from each sub-trace we extract six features described as follows: Payload Length -it corresponds to the number of data payload bytes, as reported in the DLC field. Mean Sending Frequency -it is the mean frames sending frequency, as recorded by the CAN dongle. Standard Deviation of Sending Frequency -it is the standard deviation of the frames sending frequency, as recorded by the CAN dongle. The sending frequency is influenced by the precision of the internal clock of the sending ECU. As demonstrated by Cho and Shin, this property can be used to fingerprint the sending ECUs. Percentage of Active Bits -it corresponds to the percentage of bits that flip at least once among the total number of bits in the frame payload throughout the trace. A bit is said to flip, when its value changes from 0 to 1 or vice versa. Mean Bit Flip Rate -it is the mean flip rate of the bits in the frame. Assuming a sub-trace composed by f consecutive frames, the Bit Flip Count (BFC) of a bit b in the payload corresponds to the total number of times that the bit b flips. The bit flip rate is then calculated as BFC/(f − 1). Frame Priority -the frames within a trace are divided into quartiles based on their priority, which is given by their frame ID. The trace splitting and features extraction process are referred in Figure 2 (step 1). Once a sample is generated for every sub-trace in the described manner, the algorithm splits the set of samples into two distinct subsets according to their length (extracted from the DLC) (see step 2, Figure 2). The first subset contains all frames whose payload is 8 Byte while the other includes all frames whose payload is shorter than 8 Byte. We refer to frames in the former set as long frames and to the frames in the latter as short frames. From a preliminary analysis of a dataset of 427 traces, each collected from a different vehicle model, we discovered that as much as 70.5 % of frames are long, while 29.5 % are short. The reason behind this division is that the feature Payload Length, while constituting a helpful discriminant for fingerprinting the short frames, is ineffective for the long frames. Therefore, this feature is removed from the set of long frames. Each of the two sets of samples is given in input to an ML model, specifically trained on samples (see step 3, Figure 2) of the same kind (i.e., from long or short frames). This model is trained exclusively on samples from the same industrial group/alliance of the current vehicle to reverse engineer. The underlying rationale is that vehicles are more likely to have more frames in common with models from the same industrial group. Preliminary tests highlight that training specifically a classifier for each industrial group rather than on all samples leads to lower amount of misclassified samples, due to the reduced variance. Finally, all the samples are deanonymized (see step 4, Figure 2). IV. PERFORMANCE EVALUATION Our algorithm is validated on a set of 10 s CAN traces obtained from 427 distinct vehicle models from 28 different automotive brands belonging to 15 different industrial groups from EU, USA, Japan, India and South Korea. Each of these traces was collected by a partner company with a PCAN-USB FD from a parked vehicle, with no action performed by a human operator. The vehicles in our evaluation set contain a total of 33 034 CAN frame IDs, from which we extract an equal number of samples. Table I summarizes other relevant information for all (anonymized) industrial groups in the evaluation set. For each industrial group, the table reports: The number of vehicle traces (n. vehicle traces). The number of unique frames that are found across all vehicle models (n. unique frames), as identified by their ID. The table highlights that a bigger and more variegated set of vehicle models corresponds to an increase in the total number of unique frames. The mean number of unique frames per vehicle (mean n. frames per vehicle). It depends on the level of digitalization of the vehicles produced by the manufacturer, which is usually correlated to the market segment (i.e. high-end vehicle models have more electronic components). The percentage of long and short frames on the total number of unique frames (long / short frames). A. Performance Metrics In our evaluation we adopt a leave-one-out-cross-validation approach. Namely, each vehicle in the dataset is iteratively considered as the vehicle to reverse engineer and its ground truth is discarded. The classifiers are then trained on the rest of the dataset. Our classification task is an Open Set Recognition (OSR) problem. In an OSR problem the knowledge of the world is incomplete at training time. As opposed to the standard closed-world classification scenario, the ML models do not have only to classify samples from known classes, but also to adequately reject samples belonging to unknown classes. As a matter of fact, apart from the ECUs mounted in previous vehicle models, we expect newly released vehicle models to be also equipped with last generation components, which will send frames unseen until then. For this reason, the trace of a new vehicle to reverse engineer may contain frames that the ML model has never been trained on. In the OSR scenario the classes are typically divided into four sets: Known Known Class (KKC), Known Unknown Class (KUC), Unknown Known Class (UKC), Unknown Unknown Class (UUC). KKC is the set of classes for whom a distinct label is available. In our case, it is the set of labels (the frame IDs) associated with the frames on which the model was trained on. On the contrary, UUC is the set of the classes on which the classifier has never been trained on and for whom no side semantic information is available at training time. KUC and UKC are out of the scope of this work. Being an OSR, we cannot evaluate our tool with metrics commonly accepted for standard ML close-world problems, such as the accuracy and F1-Score. New accuracy metrics for OSR tasks are firstly presented by Jnior et al. and respectively reported in Equation and Equation, namely Accuracy for KKC (AKS) and Accuracy for UUC (AUS): In Equation, TP i, TN i, FP i, FN i correspond respectively to the number of true positives, true negatives, false positives, and false negatives for the i-th KKC i ∈ {1,..., C}, where C corresponds to the cardinality of KKC. Note that FN i includes the samples of KKC wrongly classified as unknowns. In Equation, true unknowns TU correspond to the samples of UUC correctly classified as unknown, while false unknowns FU correspond to the samples of UUC wrongly classified with one of the KKC labels. B. Classifiers OSR problems are mainly addressed in two ways: (i) by enabling a common ML classifier to reject unknown samples, and (ii) by employing a classifier inherently designed to deal with UUC. Regarding (i), we adapt a Random Forest (RF) classifier and a Fully Connected Neural Network (FCNN) to reject samples whose confidence score for the predicted label is below a certain rejection threshold, in the way described in. We choose RF due to its robustness to outliers and the consistent handling of unbalanced datasets, which is particularly relevant in our case. After a tuning on the RF, we discovered that the optimal performance is obtained with around 200 tree estimators. Regarding FCNN, we choose it for its robustness to outliers and the overall superior performance of neural networks compared to traditional ML classifiers documented in literature. After an extensive tuning on the number of layers and neurons for each layer, we found out that having more than three hidden layers with more than 1024 neurons each (and ReLu activation function) does not improve the overall performance of the model. For what concerns (ii), we have reviewed the main inherently-Open Set (OS) classifiers in literature. The vast majority of related works specifically addresses computer vision tasksas OSR is especially relevant for this field -and, therefore, the new classifiers are designed accordingly. In this regard, a particular effort is put into the adaptation or design of new Convolutional Neural Network (CNN) architectures,. However, since our data is characterized by a maximum of six features, as opposed to the high-dimensional data typically processed in computer vision tasks, the majority of the methods presented in literature are unsuitable for our task. For this reason, we selected two algorithms, PI-SVM and Extreme Value Machine (EVM), which can process input with different spatial properties without the need of data dimensionality transformations. PI-SVM integrates the notions of data distribution from Extreme Value Theory (EVT) into the widely known Support Vector Machine (SVM) classifier. EVM is a brand new algorithm, which also exploits the EVT theory about data distribution to group samples in consistent areas of the space. C. Comparison between classifiers We first analyze the results obtained by RF, FCNN, EVM, and PI-SVM to assess which classifier provides the best performance overall. After testing PI-SVM and EVM based on the source code released by the authors and the settings suggested in the respective papers,, we performed an extensive tuning of the hyperparameters to optimize their performance. The tuning revealed that EVM and PI-SVM score AKS and AUS lower than 20 %. Given their poor performance, we further show only the results obtained with RF and FCNN. Figure 3 shows the average AKS and AUS, along with 95 % confidence intervals, obtained testing RF and FCNN on the evaluation dataset. The figure highlights that AKS and AUS can vary greatly according to the choice of the rejection threshold. As expected, an increase of the rejection threshold corresponds to a decrease of the AKS and an increase of the AUS. As a matter of fact, the higher the threshold, the more samples are rejected. This causes an increase of the samples in KKC wrongly rejected (hence, the worsening of the AKS), and a decrease of the samples in UUC wrongly labeled as known (hence, the improvement of the AUS). RF performs equal or better than all the other classifiers on both samples from the short and long frames subsets on all considered metrics and datasets. RF and FCNN achieve a similar AUS for what concerns samples from short frames. It is interesting to notice that, for high values of the rejection threshold, FCNN achieves a higher AKS compared to RF when considering samples from both the short and the long frames. It has been shown in that the probabilistic output provided by most classifiers is skewed towards the extreme values (0 and 1) and, thus, does not enable an understanding of the true probability of the prediction correctness. It follows that the predictions probabilities outputted by the selected classifiers do not correspond to the actual probability of a sample belonging to a determined class. Hence, since different classifiers calculate the probabilistic scores according to different logic, the setting of a certain rejection threshold can have consistently different impact on AKS and AUS. D. Result Analysis Having designated RF as ultimate classifier for the task, based on the superior classification accuracy compared to the other algorithms, we further investigate its performance. In particular, we analyze the results obtained on the different industrial groups/alliances. Figure 4 illustrates the average AKS and AUS, with 95 % confidence intervals, obtained by RF with a rejection threshold of 0.2 on all vehicles for each industrial group/alliance. The results show a high variance in the average performance scored by the models trained on vehicles from different industrial groups for all considered metrics. We have not found any clear correlation between the classification accuracy and any other characteristic related to the composition of the sample sets for each industrial group reported in Table I. Finally, we investigate the importance of the features Percentage of Active Bits and Mean Bit Rate. As mentioned in Section IV, the traces in the dataset were collected on parked vehicles. For this reason, numerous signals are never triggered and their bits never flip. Such signals are, for instance, all those related to the steering wheel or the vehicle speed. Following an analysis of the dataset, we discovered that, due to this phenomenon, the traces have 53.8 % of frames whose bits in the payload never flip. We refer to these frames as inactive. In contrast, the frames in which at least one bit flips during data collection are called active. The consequence of having inactive frames is that both the Percentage of Active Bits and Mean Bit Rate of the samples extracted from them are 0, thus making these two features irrelevant for their fingerprinting. By extension, we refer to the samples generated from the active and inactive frames as, respectively, active and inactive samples. In this scope, we investigate the impact that inactive samples have on the overall classification performance. Figure 5 compares the mean AKS and AUS obtained by the classifier on active and inactive samples according to different rejection threshold. The results show that RF achieves higher AKS and AUS on active samples compared to inactive samples. For instance, with a no-rejection threshold (i.e. equal to 0), the classifier achieves an AKS of 79.8 % on active samples extracted from the short frames set, compared to 61.7 % scored on inactive samples from the same set, thus marking a difference of 18.1 % in the performance. Still assuming no threshold, an even larger gap of almost 25 % remarks the difference in the performance achieved by the classifier on active samples compared to inactive samples extracted from the long frames set. The presented results show that the features Percentage of Active Bits and Mean Bit Rate impact greatly on the classification performance. This fact suggests that the classification can be sensitively more accurate if the classifier is trained on samples from traces collected on vehicles that are driven. V. CONCLUSION In this work, we study whether anonymizing the CAN frame IDs makes frame matching based CAN bus reverse engineering methods ineffective, thus preventing vehicle-agnostic remote attacks on CAN bus. We test the efficacy of this approach by fingerprinting frames whose IDs are anonymized. In this scope, we train ML classifiers to recognize frames based on six features extracted exploiting DLC, bit flipping, sending frequency and frame priority. We evaluate our fingerprinting method on 33 034 samples extracted from traces collected on 427 different vehicle models. The results show that an RF classifier can recognize frames with a 8 Byte-long payload and frames with a shorter payload with a mean AKS up to 44.1 % and 68.7 % respectively. When considering samples extracted from frames with at least one flipping bit, a superior AKS up to 57.7 % and 79.8 % is achieved on samples extracted from long and short payload frames respectively. The presented results highlight that anonymizing the CAN frame IDs does not prevent reverse engineering based on frame matching. This suggests that connected vehicles are vulnerable to the remote decoding of CAN data by potential adversaries who can then inject attacks with minimal effort. In conclusion, to preserve better the anonymity of the CAN data transiting in-vehicle networks, substantial changes in the CAN encoding practices is necessary. Future work includes research for new features able to increase the fingerprinting performance. We also plan to look for an effective defense against the fingerprinting of frames. Such a solution will have to respect the assumptions made in the paper, while keeping the CAN protocol unchanged to meet the needs of the OEMs.
Commentary: Using basic behavior research on children's emotions to inform prevention research: a commentary on Pooley and Fiddick Social referencing "Mr. Yuk". evaluating the developmental appropriateness of the facial expression depicted on Mr. Yuk stickers, a long-standing and widely used poison prevention program (Childrens Hospital of Pittsburgh, 2008). The article addresses an important concept in pediatric psychology, which is the prevention of unintentional injury or death among young children. Unintentional ingestion of poison accounts for >99% of poison exposure among children under the age of 6 years, with children under the age of 4 years comprising nearly half of all calls to poison centers (Litovitz, White, & Watson, 2005). The article correctly recognizes the need to include young children as targets in poison prevention and control campaigns. Though educating parents to supervise children and store dangerous substances out of reach of young children are critical components to prevent poison ingestion, they are not sufficient at eliminating the risk of unintentional ingestion. Indeed, a large proportion of unintentional injuries and poisonings occur in settings in which parents step away only for a few moments, but are still present in the home (Ozanne-Smith, Day, Parsons, & Dobbin, 2001). Thus, it is important to identify developmentally appropriate strategies to deter children from ingesting dangerous substances, regardless of parental presence. The authors are to be commended for their innovative approach to systematically examine a key feature (i.e., facial expression) of the widely used child poison prevention program, Mr. Yuk stickers. Specially, through a logical series of basic behavioral experiments rooted in empirically supported research methods (Fiddick, 2004; Rozin, Lowery, Imada, & Haidt, 1999), they obtained the
The Development of Branch Libraries in Leicester Abstract The public library system developed slowly in Leicester and encountered much opposition before it began. With the eventual success of its central library, the establishment of branch libraries was mooted. Despite the failure of the very first branch, subsequent branches were successful and answered a very definite need for localized provision of public library services at a time when the central library was inadequate to cope with a rapid growth in demand.
<reponame>devoll/trace-image-batch-ai<gh_stars>0 declare class Window { active: boolean; alignChildren: string; alignment: string; bounds: Bounds; cancelElement: object; characters: number; readonly children: Array<object>; defaultElement: object; enabled: boolean; readonly frameBounds: Bounds; frameLocation: Point; readonly frameSize: Dimension; readonly graphics: ScriptUIGraphics; helpTip: string; indent: number; justify: string; layout: LayoutManager; location: Point; margins: number; maximized: boolean; minimized: boolean; maximumSize: Dimension; minimumSize: Dimension; orientation: string; readonly parent: object; preferredSize: Dimension; properties: object; shortcutKey: string; size: Dimension; spacing: number; text: number; readonly type: TI.WindowType; visible: boolean; readonly window: WIndow; readonly windowBounds: Bounds; constructor( type: TI.WindowType, title?: string, bounds?: Bounds, creation_properties?: { resizeable?: boolean, su1PanelCoordinates?: any, closeButton?: boolean, maximizeButton?: boolean, minimizeButton?: boolean, independent?: boolean } ): void; add(type: string, bounds?: Bounds, text?: string, creation_props?: any): ControlObject | ContainerObject; addEventListener(eventName: string, handler: object, capturePhase: boolean): boolean; alert(message: string, title: string, errorIcon?:boolean = false): void; center(window: Window): void; close(returns?: any): void; confirm(message: string, noAsDefault: boolean = false, title: string): boolean; dispatchEvent(): UIEvent; find(type: string, title: string): Window; hide(): void; notify(eventName: NotifyEventName): void; onClose: FunctionCallbackEvent; onDraw: FunctionCallbackEvent; onMove: FunctionCallbackEvent; onMoving: FunctionCallbackEvent; onResize: FunctionCallbackEvent; onResizing: FunctionCallbackEvent; onShortcutKey: FunctionCallbackEvent; onShow: FunctionCallbackEvent; prompt(prompt: string, defaultValue: string, title: string): string; remove(what: any): void; removeEventListener(eventName: string, handler:FunctionCallbackEvent, capturePhase?: boolean = false): boolean; show():void; static alert(message: string, title?: string, errorIcon?: boolean): void; static confirm(message: string, noAsDflt?: boolean, title?: string): boolean; static find(resourceName: string): Window | null; static find(type: TI.WindowType, title: string): Window | null; static prompt(message: string, preset: string, title?: string): string | null; } declare class ContainerObject { alignChildren: string; alignment: string; bounds: Bounds; readonly children: Array<any>; graphics: any; // ScriptUIGraphics object layout: LayoutManager; location: Point; margins: Margins; maximumSize: Dimension; minimumSize: Dimension; orientation: string; readonly parent: Window | ContainerObject; preferredSize: Dimension; properties: any; selection?: any; // For Tab only size: Dimension; spacing: number; text: string; visible: boolean; window: Window; windowBounds: Bounds; /** * Methods */ add(type: string, bounds?: Bounds, text?: string, creation_props?: any): ContainerObject | ControlObject; add(type: string, value: string): void; // For ListBox items addEventListener( eventName: string, handler: () => void, capturePhase?: boolean): void; center(window?: Window): void; close(result?: number): void; dispatchEvent(eventObj: any): boolean; findElement(name: string): ControlObject | null; hide(): void; notify(event?: string): void; remove(index: number): void; remove(text: string): void; remove(child: ControlObject): void; removeAll(): void; removeEventListener(eventName: string, handler: () => void, capturePhase?: boolean): void; show(): any; update(): void; } declare class Margins { } declare class ControlObject { active: boolean; alignment: string; bounds: Bounds; characters: number; checked: boolean; columns?: any; // For Listbox object enabled: boolean; expanded?: boolean; // For ListItem object graphics: any; helpTip: string; icon: string | File; image: any; indent: number; index?: number; // For ListItem items: ControlObject[]; itemSize: Dimension; jumpdelta: number; justify: string; location: Point; maximumSize: Dimension; minimumSize: Dimension; maxvalue: number; minvalue: number; readonly parent: ControlObject; preferredSize: Dimension; properties: any; selected?: Boolean; // For listitem selection?: Array<ListItem> | ListItem; // For ListBox only, Array of ListItem shortcutKey: string; size: Dimension; stepdelta: number; subitems: Array<{ text: string, image: any}>; text: string; textselection: string; title: string; titleLayout: { alignment: any, characters: number, spacing: number, margins: [ number, number, number, number ], justify: string, trancate: string }; type: string; value: boolean | number; visible: Boolean; window: Window; windowBounds: Bounds; function_name: any; /** * Methods */ addEventListener(eventName: string, handler: () => void, capturePhase?: boolean): void; dispatchEvent(eventObj: any): boolean; hide(): void; notify(event?: string): void; removeEventListener( eventName: string, handler: () => void, capturePhase?: boolean): void; show(): void; toString(): string; valueOf(): number; } declare class ListItem { } type FunctionCallbackEvent = () => void; enum NotifyEventName { dialog = "dialog", palette = "palette", window = "window" } declare class BoundsPosition { x: number; y: number; width: number; height: number; } declare class BoundsPoints { left: number; top: number; right: number; bottom: number; } declare type Bounds = BoundsPosition | BoundsPoints | [ number, number, number, number ]; /** * Defines the size of a window or UI element. Contains a 2-element array. * Specifies the height and width of an element in pixels. A Dimension object is created when you set an element’s * size property. You can set the property using a JavaScript object with properties named width and height, * or an array with 2 values in the order [wd, ht]. */ declare type Dimension = [ number, number ]; declare class ScriptUIGraphics { } /** * Controls the automatic layout behavior for a window or container. * The subclass AutoLayoutManager implements the default automatic layout behavior. */ declare class LayoutManager { layout(): void; resize(): void; }
Coherent Dense Cores. I. NH3 Observations In a study of the velocity dispersion of molecular gas in NH3 maps of four dense cores, we find that: within the interiors of dense cores, the line widths are roughly constant at a value slightly but significantly higher than a purely thermal line width; and at the edges of the maps of the dense cores, it appears that the line width starts to increase. We suggest that these dense cores are "coherent" in that the nonthermal, turbulent, contributions to the line width are so small that observed velocity dispersion is nearly independent of scale within the cores. In the second paper of this series (Goodman et al.), by analyzing maps of the cores' environments, we find an apparent transition to this coherent regime from a more turbulent one, at about the size scale of a FWHM NH3 contour, or ~0.1 pc. Analysis of velocity gradients in dense cores and their environs indicates that the cores appear to spin independently of their surroundings, along an axis not obviously related to their shape. Comparison of gradients implied by the relative velocities of high-density cores in complexes and gradients in the extended low-density gas in these complexes suggests a picture in which the coherent cores behave as (independently spinning) test particles, floating along in a turbulent flow. An appendix to this paper presents a new algorithm for predicting the intrinsic width of the 18 hyperfine lines in the NH3 inversion spectrum from a Gaussian fit to the main hyperfine blend and an estimate of the optical depth.
Design and Verification of a 2 Dimension Mechanism used in Cryogenic Vacuum Environment In order to monitor the state of the test product during the thermal test, a two-dimensional mechanism installed the infrared thermal imager used in cryogenic vacuum environment was designed. The two-dimensional mechanism is placed on the opposite of the specimen. According to the actual needs, it drives the infrared thermal imager to move to the designated area. The transmission mechanism is using the ball screw. The whole system includes transmission mechanism, stepping motor, supporting mechanism and control system. For environmental requirements of vacuum 10-4pa and 100K, some special design enables the two-dimensional mechanism to overcome the failure of the low temperature, and realize the vacuum environment lubrication and cryogenic vacuum environment stepping motor overheat. The two-dimensional mechanism has been designed and verified, and it is able to satisfy the cryogenic vacuum environmental requires. 1.Introduction During the thermal test, the product is placed in a sealed container. The status of the product such as its surface temperature cannot be easily gotten. In order to monitor the state of the test product during the thermal test, it needs a mechanism to move the camera and detect the product during the thermal test. The two-dimensional mechanism is used in cryogenic vacuum environment. There are two moving directions of the mechanism, horizontal and vertical. The horizontal movement range is 2000mm, the vertical movement range is 1000mm. This paper analyzed and designed the two-dimensional mechanism used in the cryogenic vacuum environment, including mechanism design, thermal design and control system development. It solving the failure of the low temperature, vacuum environment lubrication and cryogenic vacuum environment stepping motor overheat. After test and verification, it can satisfy the requirement of the cryogenic vacuum environmental. 2.Scheme implementation The development process of the two-dimensional mechanism includes mechanism design, product manufacture, product assembly, thermal design, thermal control implementation, control system development, control cabinet design, electrical design, system integration and testing, as it is shown in the Figure 1. Mechanism Design There are two moving directions of the mechanism, horizontal and vertical. To ensure the motion accuracy and prevent camera on the vertical direction from sliding automatically. The transmission mechanism is using the ball screw. The stepping motor connect to the screw and realize the mechanism moving, selecting the Phytron vacuum stepping motor. Its maximum torque is 4.3Nm, it can work in the vacuum environment. To avoid the motor temperature rise too fast when the motor is not working in the vacuum environment, a delay is installed in the motor circuit and the controller calculate the motor stop time and monitor the motor temperature. If the motor stops for more than a certain time or the motor temperature is too high then control the relay cuts the circuit, it can be controlled by engineer either. Lubrication and sealing should also be considered in the vacuum environment. The common lubrication oil will fall in the cryogenic environment, in the vacuum environment it will evaporate and cause pollution. So the vacuum lubricating grease is required in the cryogenic vacuum environment. It also needs to ensure that there is no airtight space in the mechanism during the thermal vacuum test. In case that the vacuum is not qualified due to the degassing of the mechanism, it can be realized by punching holes in the mechanism shell. To prevent the cables from dragging and wearing, the cable drag chain was designed to protect the cables. The maximum torque is required in the horizontal direction when the mechanism is accelerating or decelerating, so the horizontal direction was taken as an example for calculation and analysis. Firstly, the inertia of the load is calculated, the Function is as fellows : In this function, the J l is the load inertia, W is the load weight, V is the motor linear velocity, N is the rotate speed. After calculating the inertia is 3.5kgcm3. Then the maximum torque is calculated, the Function is as fellows : In this function, the J l is the load inertia, J m is the motor inertia, N is the rotate speed, t is the accelerating or decelerating time, the torque is 1.03Nm, it is smaller than the motor torque, the schematic diagram of the mechanism is in the Thermal Design During the thermal test, the background environment is a cryogenic vacuum environment. In such environment, there is only radiation heat transfer. In order to prevent the lead screw deformation causing the device cannot work, the cable become brittle and the stepping motor is too cold to start in this environment. The thermal control design is needed. In this study, the heating plates was attached on the guide rail and the motor casing to provide heating power and avoid the mechanism temperature being too low. Installing the multilayer heat insulation assembly on the surface of the device, due to its high thermal resistance and low surface emissivity, it can keep the mechanism at constant temperature. To ensure the reliability of thermal control design, the Thermal Desktop software was used for simulation. Thermal Desktop can be quickly combine with the AutoCAD software. During the simulation, the material of the mechanism is stainless steel, the thermal conductivity is 12.6W/mK and the specific heat capacity is 490J/kgK. The surface optical material is multilayer heat insulation assembly, the emissivity is 0.1, the heat sink temperature is 100K, the total heat power is 30W. The simulation result are shown in the figure3. Figure 3 Thermal simulation result As it is shown in the Figure 3, under the condition that the motor is not working, the motor temperature is about 265 K, the motor can work normally at this temperature. The guide temperature is between 267K to 276K, the deformation of the lead screw is very small, the mechanism can work smoothly. Control System The control system includes control cabinet design, motion control and temperature control, they are integrated in a web server. Engineers can operate the motion control system and the temperature control system on a workstation access the web server. The control cabinet is shown in the Figure 4, the size of the control cabinet is 1000mm1000mm300mm , It includes the motor drivers, moving control card, web server, temperature controller and power supply. Figure 4 Control cabinet The motion control system is using the motion control card as the controller. It control the motor driver and sends pulse signals to the stepping motor, then realize the purpose of controlling motor acceleration, deceleration and changing its rotation direction, the schematic diagram of motion control is as follows: Figure 5 Motion control schematic diagram The MR13 temperature controller was used for the temperature control. PT100 was used as the input sensor, it measuring the temperature of the mechanism. The heating plates was used heat the mechanism. The output of the temperature controller connect to solid state relay then it connect to the heating plates, At the same time the heating plates circuit is connected to the power supply, the schematic diagram of temperature control is as follows: Human machine interface(HMI) The HMI design is after the mechanism design and electrical design. Engineers control the twodimensional mechanism by setting parameters on the interface. Temperature control and motion control are on the main page, the temperature control zone is on the left side of the page and the motion control zone is on the right side of the page. In the process of temperature control, the engineer sets the target temperature and alarm threshold in the temperature parameter setting page, the target temperature and real-time temperature of the measuring point can be fed back on the page and the temperature curve can be drawn. Motion control includes moving control, zero point control, and program control. The function of moving control is to control the two motors when motion speed and distance are set respectively. The zero point control is control the mechanism moves to the origin position. The programming control is to set the motion parameters by the engineer so that the two motors move simultaneously according to the conditions of the engineer. The feedbacks such as motion speed, target position and current position are on the main page too. The main page is shown in Figure 7. 3.Verification and Conclusion After the design of the 2 dimensional mechanism, in order to verify its mechanical performance in the cryogenic vacuum environment, the 2 dimensional mechanism, is put into the environment simulator for test. The test environment includes atmospheric pressure test, vacuum test and cryogenic test. In these three environment, the motion of the 2 dimensional mechanism were tested in different speed and acceleration and the temperature control effect was verified. The flowchart of the test process is shown in the Figure 8 and Figure 8 The process of the two dimensional mechanism During the test, the mechanism was put into an environmental simulator. Firstly, it was test at normal temperature and pressure. In this environment, the moving control, program control and emergency stop control of the mechanism are tested. Then the simulator was sealed and test the machine in the vacuum environment, the moving conditions are similar to the atmospheric environment test. At last test the machine on the cryogenic vacuum environment, the moving conditions are similar too. The transmission mechanism adopts the ball screw, with its advantage of high transmission efficiency, high precision and good rigidity. In the circuit and program design, some measure are taken to cut the motor circuit, effectively prevent the motor over heating when it works in the vacuum environment. The motor and guide rail were adopted the thermal control measures, solving the problem that the mechanism deformation and environment temperature is too low to start the motor. The 2 dimensional mechanism can moving smoothly in the atmospheric pressure, vacuum and cryogenic environment. In the cryogenic environment the transmission mechanism didn't stuck, and can move normally in the automatic and manual mode according to the working conditions. The temperature control of the motor and guide rail is also controlled within the appropriate range, guaranteeing a good working performance. It fulfill the requirement of design of a 2 dimension mechanism used in cryogenic vacuum environment, it embodies the engineering value in the vacuum cryogenic environment.
/** * Scrolls panel to view and highlights panel for xx seconds */ public void highlight() { if(!isRendered()) return; scrollToView(); addStyleName("panel-highlight"); Timer timer = new Timer() { public void run() { try { removeStyleName("panel-highlight"); } catch (Exception e) { } } }; timer.schedule(Constants.DELAY_HIGHLIGHT); }
import { gzip, ungzip } from "pako"; /** * Compress text using GZIP * @param text The text to compress * @returns Compressed text */ function compress(text: string): string { return gzip(text, { level: 9, to: "string" }); } /** * Decompress a compressed string (GZIP) * @param text The compressed text * @returns Decompressed text */ function decompress(text: string): string { return ungzip(text, { to: "string" }); } export function getCompressionResources() { return { "compression/v1/compressText": compress, "compression/v1/decompressText": decompress }; }
import { Center, Spinner, Stack } from "@chakra-ui/react"; import Head from "next/head"; import { useRouter } from "next/router"; import React from "react"; import { useMeQuery } from "../generated/graphql"; import Header from "./Header"; import Loading from "./Loading"; export default function Layout({ children }) { const { data, loading } = useMeQuery({ notifyOnNetworkStatusChange: true }); const router = useRouter(); if (loading) { return ( <Loading /> ); } return ( <Stack height="100vh" alignItems="center" > <Head> <title>OnlyWeebs</title> </Head> {(router.pathname !== '/') && <Header maxW="6xl" margin="0 auto" width="100%" user={data?.me} />} {children} </Stack> ); }
import urllib from middleware.registerRequest import get_request def url(*segments, **vars): base_url = get_request().application_url path = '/'.join(str(s) for s in segments) if not path.startswith('/'): path = '/' + path if vars: path += '?' + urllib.urlencode(vars) return base_url + path
export interface IReqRegisterAccount { username: string; phoneNumber: string; fullname: string; email: string; password: string; } export interface IReqLogin { email: string; password: string; } export interface IReqVerifyAccount { email: string; code: string; } export interface IReqChangePassword { oldPassword: string; newPassword: string; } export interface IReqChangeEmail { email: string; } export interface IReqVerifyUpdateEmail { currentEmail: string; email: string; code: string; } export interface IReqForgotPassword { email: string; } export interface IReqVerifyCodeForgotPassword { email: string; code: string; } export interface IReqUpdateAccount { username: string; phoneNumber: string; fullname: string; email: string; gender: string; introduction: string; } export interface IReqUpdateAvatar { file: File; }
Emerging resistance mutations in PI-naive patients failing an atazanavir-based regimen (ANRS multicentre observational study) Background Atazanavir is a PI widely used as a third agent in combination ART. We aimed to determine the prevalence and the patterns of resistance in PI-naive patients failing on an atazanavir-based regimen. Methods We analysed patients failing on an atazanavir-containing regimen used as a first line of PI therapy. We compared the sequences of reverse transcriptase and protease before the introduction of atazanavir and at failure . Resistance was defined according to the 2014 Agence Nationale de Recherche sur le SIDA et les Hpatites Virales (ANRS) algorithm. Results Among the 113 patients, atazanavir was used in the first regimen in 71 (62.8%) patients and in the first line of a PI-based regimen in 42 (37.2%). Atazanavir was boosted with ritonavir in 95 (84.1%) patients and combined with tenofovir/emtricitabine or lamivudine (n=81) and abacavir/lamivudine or emtricitabine (n=22). At failure, median VL was 3.05log10copies/mL and the median CD4+ T cell count was 436cells/mm3. The median time on atazanavir was 21.2months. At failure, viruses were considered resistant to atazanavir in four patients (3.5%) with the selection of the following major atazanavir-associated mutations: I50L (n=1), I84V (n=2) and N88S (n=1). Other emergent PI mutations were L10V, G16E, K20I/R, L33F, M36I/L, M46I/L, G48V, F53L, I54L, D60E, I62V, A71T/V, V82I/T, L90M and I93L/M. Emergent NRTI substitutions were detected in 21 patients: M41L (n=2), D67N (n=3), K70R (n=1), L74I/V (n=3), M184V/I (n=16), L210W (n=1), T215Y/F (n=3) and K219Q/E (n=2). Conclusions Resistance to atazanavir is rare in patients failing the first line of an atazanavir-based regimen according to the ANRS. Emergent NRTI resistance-associated mutations were reported in 18% of patients.
Assessing Compliance to National Guidelines for Pediatric Wrist and Ankle Fractures in a District General Hospital Pediatric ankle and wrist fractures are very common injuries encountered by orthopedic departments. The National Institute of Clinical Excellence has published guidelines that should be adhered to when treating these common fractures. This audit included 560 patients that have sustained wrist and ankle fractures between 2008 and 2019 at Queen Elizabeth Hospital Burton (QHB) that required surgical management. The results show that 99.7% (478/479) wrist fractures and 70.8% (57/81) of ankle fractures received surgical management within the timeframe outlined by NICE. This audit has shown that QHB has been successfully treating wrist fractures within the guidelines set by NICE but has failed to meet the standards for ankle fractures. Introduction The National Institute of Clinical Excellence (NICE) has set guidelines for wrist and ankle fracture management in order to achieve the best functional outcome for patients with less pain and a better range of movement. Distal radius fractures are extremely common injuries in the pediatric population, with one-third of patients suffering this injury before the age of 17 and representing 9% of all childhood injuries. There is evidence that the incidence rates of distal radius fractures are growing and alongside it the rate of surgical intervention, resulting in an increased burden on the health service. Ankle fractures are also common injuries with some literature stating the annual incidence rate to be 1 in 1000 and accounts for 9%-18% of physeal injuries in children aged between 10 and 15 years. There is an ever-growing trend in obesity globally, and research has shown there is an increased propensity and severity of ankle injuries in children with a higher body mass index (BMI). NICE has recommended that distal radius fractures should be treated within 72 hours if intra-articular and within seven days if extraarticular, with redisplacement fractures undergoing treatment within 72 hours from when they present. With regard to ankle fractures, they should ideally be treated either on the day of injury or the next day. As a result of the high prevalence of both wrist and ankle injuries in the pediatric population, it is important to have a set of standards against which treating units can compare their results against. The guidelines produced by NICE provide a framework to which we have been able to compare our results and highlight any discrepancies. The purpose of this retrospective audit was to determine whether Queen Elizabeth Hospital Burton (QHB) has adhered to NICE guidelines when managing pediatric wrist and ankle fractures. This paper not only demonstrates the results of our audit as a tertiary center treating such patients with these injuries but highlights the importance of ongoing assessments of practice. Study design This was a single-center, retrospective audit carried out in Queens Hospital Burton, a level three trauma unit treating both adult and pediatric populations. This audit collected data for all pediatric patients treated at this unit for an ankle or a wrist injury between 2008 and 2019. During this period, there were 698 patients that were treated in Queens Hospital Burton and were therefore included in our study. These patients were managed with a procedure that included manipulation under anesthesia with or without Kirschner wire (MUA ± K-wire) and open reduction and internal fixation (ORIF). Inclusion criteria Strict inclusion criteria were upheld; patients included required an operation secondary to a fracture, and all the data points must be available to be included in the audit. Exclusion criteria Patients that did not require operative intervention secondary to a fracture and those with incomplete data sets were excluded from this study. Due to the lack of data, 64 patients were excluded, and a further 74 patients were excluded due to their operative indications not being secondary to a fracture. Data collection Data points covered basic patient data of hospital unit number and date of birth as well as the details of the operation including the surgical indication, type of operation, and any complications. The patient's discharge date and length of stay were also recorded. The data were collected on Microsoft Excel (Microsoft Corporation, New Mexico, USA) and analyzed with basic analysis tools within the program. Current NICE guidelines for the timing of treatment for distal radius and ankle fractures were identified as shown in Table 1. Timing of surgery for ankle fractures If treating an ankle fracture with surgery, consider operating on the day of injury or the next day. Timing of surgery for distal radius fractures When needed for distal radius fractures, perform surgery within 72 hours of injury for intra-articular fractures and within 7 days of injury for extraarticular fractures. When needed for redisplacement of distal radius fractures, perform surgery within 72 hours of the decision to operate. Results A total of 560 patients were identified and included in the audit; of those, 479 cases consisted of pediatric wrist fractures and the remaining 81 were pediatric ankle fractures ( 4: Length of time till operation for ankle fractures Complication rates following wrist and ankle surgery were very low; there were six cases (0.012%) where complications arose for wrist fractures with four consisting of failure of fixation, one failure of conservative management following manipulation under anesthesia, and one that resulted in nerve palsy. There was one patient (0.012%) who received ankle surgery that resulted in failure of fixation ( Table 5). Discussion The majority of wrist fracture patients received their treatment in a timely manner, with only one wrist fracture patient not being treated within the timeframe recommended by NICE guidelines. This was due to the lack of operating time, which eventually delayed the treatment. This high percentage is perhaps attributed to the fact that a significant proportion of these patients (96.6%) received manipulation under anesthesia with or without Kirschner wire fixation, which is a relatively quick operation. A recent cohort study of 43 patients found that patients treated with Kirschner wires significantly had shorter operative times than those who were treated with an open reduction and internal fixation (ORIF) procedure. NICE guidelines also give a more lenient timeframe to complete surgical treatment for wrist fractures compared to ankle fractures. The complication rate for wrist fractures was 0.12% (6/479) with four failing following manipulation and cast. A recent meta-analysis that included three randomized controlled trials (RCTs) and three cohort studies reveals that the rate of redisplacement of distal radius fractures following cast immobilization is 45.7%, which is significantly greater than what was found in our audit. A possible explanation for this could be that we achieved anatomic reduction through an image intensifier in the operating room. A recent meta-analysis has been shown to significantly reduce the need for subsequent operative treatment and improve the quality of reduction. Other complications mentioned in the literature following distal radius fractures include non-union, malunion, infections, tendon injuries, and complex pain syndrome, which were not observed in our audit, likely due to the majority of our patients being treated with manipulation under anesthesia with or without Kirschner wires. There was a larger proportion of patients undergoing ankle surgery who did not meet the standards set out by NICE, with 29.6% (24/81) of ankle fractures not receiving appropriate surgical intervention in a timely manner. The standards set by NICE give a short window of opportunity for patients to receive surgical treatment for ankle fractures, primarily due to swelling and soft-tissue complications, which can ensue due to the rubbing of the cast and blistering of the skin. Once there is significant swelling or blistering of the soft tissues, fixation is preferred after the soft tissues have settled. Anatomic reduction is a key with ankle fractures to reduce the risk of chronic pain leading into adulthood, and multiple attempts at reduction should not be performed due to the risk of injury to the physis and growth arrest. One patient was found to have a failure of fixation as a complication. Other complications can include osteochondral defects, malunion, and extensor retinaculum syndrome, which were not found in our audit as they require longer follow-up and further imaging. This highlights a limitation in our audit that our problems are confined to more immediate post-operative complications. Further studies could be performed to observe whether there is an increase in the rates of complication if NICE guidelines are not adhered to. Conclusions This audit has shown that QHB has been prioritizing and treating the pediatric patients as per the NICE guidelines for wrist fractures while falling short with regard to ankle fractures. Regardless of this, complication rates for both were very low. Recommendations to improve on this matter are to increase the departmental awareness and education within not only the orthopedic department but also other departments in order to ensure efficient treatment of patients. Additional Information Disclosures Human subjects: Consent was obtained or waived by all participants in this study. Animal subjects: All authors have confirmed that this study did not involve animal subjects or tissue. Conflicts of interest: In compliance with the ICMJE uniform disclosure form, all authors declare the following: Payment/services info: All authors have declared that no financial support was received from any organization for the submitted work. Financial relationships: All authors have declared that they have no financial relationships at present or within the previous three years with any organizations that might have an interest in the submitted work. Other relationships: All authors have declared that there are no other relationships or activities that could appear to have influenced the submitted work.
Remission of Schizoaffective Disorder Using Homeopathic Medicine: 2 Case Reports. Context Research on the schizophrenia spectrum is primarily focused on pharmaceutical interventions, although alternative treatments have been gaining increasing popularity in recent years because patients are seeking treatments that are effective and have reduced side effects. A significant body of evidence already exists supporting the effectiveness of homeopathy to treat a wide array of illnesses. Objective The research team intended to demonstrate the need for using both alternative and conventional treatments to improve clinical outcomes in the treatment of schizoaffective disorder. Design The research team performed 2 case studies. Setting The study took place at Arizona Natural Health Center (Tempe, AZ, USA), an outpatient clinic where Dr Tara Peyman worked as a naturopathic doctor from 2008 to 2014. Participants The participants were a 23-y-old female (case 1) and a 34-y-old female (case 2), both of whom had been diagnosed with schizoaffective disorder of the bipolar type. Intervention Individualized homeopathic treatment was initiated for the 2 patients, who previously had received medication of atypical antipsychotics and mood stabilizers. Outcome Measures A Likert scale was used to evaluate the intensity of each patient's symptoms at each follow-up, based on self-reporting, using a scale from 1 to 10, with a score of 10 being the highest. Results During the course of treatment, both patients' symptoms normalized, and they regained their ability to hold jobs, attend school, and maintain healthy relationships with their families and partners while requiring fewer pharmaceutical interventions. Conclusions The 2 current case reports demonstrate a successful integrative approach to the treatment of schizoaffective disorder. They illustrate the value of individualized homeopathic prescriptions with proper case management in the successful treatment of that disorder. Future large-scale, double-blind, placebo-controlled studies should investigate individualized homeopathic treatments for mental health concerns, because the diseases cause great economic and social burden.
Development and validation of a risk model for the prediction of cardiovascular hospital admission using CMR-based phenotype in patients with known or suspected cardiovascular disease Cardiovascular diseases remain the leading cause of morbidity worldwide and impose the highest economic burden among noncommunicable diseases. Much of these costs are related to hospitalizations for adverse cardiovascular events, which may be reduced by targeted management of high-risk patients. Cardiac markers derived from CMR imaging have been shown to be strong independent predictors of prognosis within specific cohorts. However, its capacity to broadly contribute to risk models aimed at predicting incident cardiac hospitalization has not been demonstrated. Using a large clinical outcomes registry of patients clinically referred for CMR, develop and validate a nomogram for prediction of cardiovascular hospital admission. A total of 7127 consecutive patients were prospectively recruited between 02/2015 and 07/2019. All patients completed standardized health questionnaires and CMR imaging protocols. A nomogram was developed for prediction of cardiovascular hospitalization, inclusive of admission for heart failure, MI, cardiac arrest, heart transplant, LVAD implantation, or stroke. The risk model was derived from 80% (n=5702) of the cohort using Cox modelling that included CMR, medication, laboratory, and patient-reported health variables. Model validation was assessed by discrimination and calibration procedures applied to the remaining 20% of patients (n=1425). A minimum follow-up of six months was mandated. The derivation cohort was comprised of 38% females with a median age of 56 (IQR 4465) years. During a median follow-up of 934 days, 514 (9.0%) events occurred. The validation cohort was similarly comprised of 37% females with a median age of 57 (IQR 4466) years. During a median follow-up of 970 days, 142 (10.0%) events occurred. Numerous CMR parameters were significantly different between those experiencing versus not experiencing the primary composite outcome, including: LVEF (44% vs 59%, p<0.0001), RVEF (52% vs 55%, p<0.0001), LV mass (65g/m2 vs 56g/m2, p<0.0001), and LA volume (43mL/m2 vs 34mL/m2, p<0.0001). These and other CMR-derived characteristics were independently predictive of the composite outcome by univariate modelling (Figure 1A). An eight-variable nomogram (Figure 1B) was developed using a stepwise multivariate model that exhibited high discrimination in both the derivation and validation cohorts (C-index 0.81 and 0.83, respectively). Continuous model calibration curves indicated satisfactory external performance. The model was able to discriminate risk of hospitalization at 1-year with a dynamic range of 2099%. Using data available at time of CMR imaging, we derived and validated a Cox-based nomogram that offers robust prediction of future cardiovascular admissions. This tool may provide value for the identification of patients who may benefit from targeted surveillance and management strategies, and may offer a foundation for improved patient-specific cost modelling. Figure 1 Type of funding source: None
The panel on farmers wants to identify sectors where mega projects can be established, writes Srinand Jha. The Chairman of the National Commission on Farmers (NCF) MS Swaminathan favours mapping the country’s geological area to identify “low biological sectors” where mega projects including Special Economic Zones (SEZs) can be established. The NCF’s fifth and final report, released on Thursday, recommends that prime farmland be conserved for agriculture and not be diverted for non-agricultural purposes. It also calls for a review of the existing Land Acquisition Act to provide for a ‘pro-farmer’ skew to the legislation. Tackling farmer-related tasks as a “national endeavour”, with the joint partnership and responsibility of the central and state governments, is the crying need today, Swaminathan said at a press conference. Favouring the idea of moving agriculture to the concurrent list of subjects, he said this would facilitate coherence between the macro policies of trade (managed by the Union) and the developmental policies managed by the states. On farmers’ suicides, Swaminathan underscored the need to address larger issues concerning the agrarian crisis that have driven farmers to suicides. “Agriculture and industry needed to reinforce rather than fight one another,” he averred in the backdrop of the meeting of state agriculture ministers being convened later this month by Union Agriculture Minister Sharad Pawar. Pitching in with a strong case for the implementation of the Minimum Support Price (MSP) for all crops, Swaminathan said that pricing and marketing were ‘critical areas’ for ushering in the second green revolution. Favouring a ‘universal PDS system’ instead of the targeted PDS regime as at present, he said the MSP should be 50 per cent more than the weighted average cost of production. “The second green revolution belongs to dry land and rain-fed areas,” he said while elaborating that millets and pulses were predominantly crops of rain-fed and dry farming areas.
Academic Acceleration: Is it Right for My Child? The June issue of PHP focuses on the topic of acceleration. I am a product of acceleration. Early admission to first grade was my school districts solution to the precocious 5-year-old who showed up with her mother to the district offices. In fact, my mother sought out the districts help because she wasnt sure what to do with me at home anymore. I could read, had a large vocabulary, and far more enjoyed the company of adults than my same-aged peers. It seemed like a logical next step off to first grade I went, and by third grade I had been placed in the districts new gifted program. There are certainly some things I would have changed about my educational history but skipping kindergarten would not be one of them (even though this meant that as I got older there were arguments with my parents about why I couldnt do the things some of my older friends were doing!). Graduating early from high school gave me time after college to go to graduate school, which then planted the seed for me to pursue a doctoral degree. After working with gifted children and their families for nearly two decades, I rarely see the option to accelerate offered or even considered by schools despite the large body of literature supporting its use. This issue provides background information and practical advice regarding acceleration to share with other parents, caregivers, and school personnel.
<filename>src/js/algorithms/main/index.ts // Interfaces import { ApplicationInterface } from "../../bot/interface.ts"; // Methods import { candlesticks } from "../../binance/market.ts"; // Helpers import Logger from "../../helpers/log.ts"; import { timestamp } from "../../helpers/string.ts"; import { clamp } from "../../helpers/number.ts"; export default async function (request: ApplicationInterface) { // prepare data const curr = parseFloat(request.avgPrice.price); const fee = request.account.makerCommission + request.account.buyerCommission; const pair = request.config.pair[0] + request.config.pair[1]; const candles = await candlesticks(pair, (request.config.scope as string) || "1w"); const minValue = parseFloat(request.info.filters.find(item => item.filterType === "MIN_NOTIONAL")?.minNotional as string || "0"); let ATL: number = Number.POSITIVE_INFINITY; let ATH: number = Number.NEGATIVE_INFINITY; let AVG = 0; // loop through all entries for (let i = 0; i < candles.length; i++) { const candle = candles[i]; const value = (parseFloat(candle.open) + parseFloat(candle.close)) / 2; AVG += value; if (!ATL || value < ATL) ATL = value; else if (!ATH || value > ATH) ATH = value; } // calculate avg AVG /= candles.length; ATL = (ATL + AVG) / 2; AVG = (ATH + AVG) / 2; const upperMargin = AVG * (request.config.profit / 100) + fee * (AVG * (request.config.profit / 100)); const lowerMargin = AVG * (request.config.profit / 100) + fee * (AVG * (request.config.profit / 100)); // visual feedback console.log(`\x1b[32m${pair}\x1b[37m info:`); console.log(`ATL: ${ATL}`); console.log(`ATH: ${ATH}`); console.log(`AVG: ${AVG}`); // ------------------------------------------------- // Profit check // ------------------------------------------------- // check profit amount if (request.profit > request.config.profit) { if (parseFloat(request.balance[request.config.pair[1]].free) > minValue && AVG > curr) { const quantity = clamp(parseFloat(request.balance[request.config.pair[1]].free), minValue, request.config.maxBalanceUsage); // logs console.log(`\nCurrent profit is of ${request.profit}, above the required ${request.config.profit}, buying`); Logger.general(`${pair} [${timestamp(undefined, true)}] Buying quantity ${quantity} with price of ${curr}`); return { type: "BUY", timeInForce: "GTC", price: curr, quantity: quantity, }; } else if (parseFloat(request.balance[request.config.pair[0]].free) > minValue && AVG < curr) { const quantity = clamp(parseFloat(request.balance[request.config.pair[0]].free), minValue, request.config.maxBalanceUsage); // logs console.log(`\nCurrent profit is of ${request.profit}, above the required ${request.config.profit}, selling`); Logger.general(`${pair} [${timestamp(undefined, true)}] Selling quantity ${quantity} with price of ${curr}`); return { type: "SELL", timeInForce: "GTC", price: curr, quantity: quantity, }; } } // ------------------------------------------------- // Resistance check // ------------------------------------------------- // buy if below average if ((ATL + AVG) / 2 - lowerMargin > curr) { // check balance if (parseFloat(request.balance[request.config.pair[1]].free) < minValue) { console.log(`\nCurrent value of ${curr} is below the buy line that is ${(ATL + AVG) / 2 - lowerMargin}, but you do not have any funds`); } else { const quantity = clamp(parseFloat(request.balance[request.config.pair[1]].free), minValue, request.config.maxBalanceUsage); // logs console.log(`\nCurrent value of ${curr} is below the buy line that is ${(ATL + AVG) / 2 - lowerMargin}, buying`); Logger.general(`${pair} [${timestamp(undefined, true)}] Buying quantity ${quantity} with price of ${curr}`); return { type: "BUY", timeInForce: "GTC", price: curr, quantity: quantity, }; } } // sell if above average else if ((ATH + AVG) / 2 + upperMargin < curr) { // check balance if (parseFloat(request.balance[request.config.pair[0]].free) < minValue) { console.log(`\nCurrent value of ${curr} is above the sell line that is ${(ATH + AVG) / 2 + upperMargin}, but you do not have any funds`); } else { const quantity = clamp(parseFloat(request.balance[request.config.pair[0]].free), minValue, request.config.maxBalanceUsage); // logs console.log(`\nCurrent value of ${curr} is above the sell line that is ${(ATH + AVG) / 2 + upperMargin}, selling`); Logger.general(`${pair} [${timestamp(undefined, true)}] Selling quantity ${quantity} with price of ${curr}`); return { type: "SELL", timeInForce: "GTC", price: curr, quantity: quantity, }; } } }
/** * Wraps the call to XACMLPolicyWriter. * * @param path Path to file to be written to. * @param policy PolicyType or PolicySetType * @return Path - the same path passed in most likely from XACMLPolicyWriter. Or NULL if an error occurs. */ public static Path writePolicyFile(Path path, Object policy) { if (policy instanceof PolicyType) { return XACMLPolicyWriter.writePolicyFile(path, (PolicyType) policy); } else if (policy instanceof PolicySetType) { return XACMLPolicyWriter.writePolicyFile(path, (PolicySetType) policy); } else { throw new IllegalArgumentException("Expecting PolicyType or PolicySetType"); } }
<filename>Web_django/api/migrations/0004_remove_pic_base64.py # Generated by Django 3.1.4 on 2020-12-05 14:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0003_pic_base64'), ] operations = [ migrations.RemoveField( model_name='pic', name='base64', ), ]
King William Ale House History The King William Ale House stands as part of a group of three houses, which were built in approximately 1670; originally built as a refuge for poor women, the buildings were later converted into public houses. The three buildings were designated as a Grade II* listed building on 8 January 1959, and currently include two public houses, the King William Ale House as well as The Famous Royal Navy Volunteer, with a restaurant between them. The building is timber-framed, with brick stacks; the front of the building is gabled with three jettied floors. It has a single-story wing to the back block on Little King Street, which also dates to the 17th century. The sash windows of the building are in an 18th-century style, but restored in the late 20th century. The King Street entrance includes an 18th-century shop front, with a 17th-century door frame. Present usage The King William Ale House is owned and operated by Samuel Smith Brewery. It has two entrances, one on King Street, the other on Little King Street. Inside there is a stone fireplace and a number of seating booths. The pub also has sufficient space for pool tables. The draught ales are kept in kegs rather than casks.
Tunable long-wavelength broad band asymmetric quantum well infrared photodetector We present a theoretical investigation of a GaAs/AlGaAs infrared detector consisting of three asymmetric quantum wells. Each well is designed to yield absorption and a photoresponse at peak wavelengths of 8.2 m, 9.5 m and 10.8 m respectively. The device operation is based on an intersubband bound to quasi-bound transition. Asymmetry in the barriers is shown to give rise to the dependence of the spectral line width on applied reverse bias.
Circulating white blood cells and lung function impairment: the observational studies and Mendelian randomization analysis Abstract Background Circulating white blood cell (WBC) counts have been related to lung function impairment, but causal relationship was not established. We aimed to evaluate independent effects and causal relationships of WBC subtypes with lung function. Methods The 19,159 participants from NHANES 20112012 (n=3570), coke-oven workers (COW, n=1762) and Dongfeng-Tongji (DFTJ, n=13,827) cohorts were included in the observational studies. The associations between circulating counts of WBC subtypes and prebronchodilator lung function were evaluated by linear regression models and LASSO regression was used to select effective WBC subtypes. Summary statistics for WBC-associated SNPs were extracted from literature, and Mendelian randomization (MR) analysis with inverse-variance weighted (IVW) method was applied to estimate the causal effects of total WBC and subtypes on lung function among 4012 subjects from COW (n=1126) and DFTJ cohorts (n=2886). Results Total WBC counts were negatively associated with lung function among three populations and their pooled analysis indicated that per 1109 cells/L increase in total WBC was associated with 36.13 (95% CI: 30.35, 41.91) mL and 25.23 (95% CI: 19.97, 30.50) mL decrease in FVC and FEV1, respectively. Independent associations with lung function were found for neutrophils, monocytes, eosinophils and basophils (all p<.05), except lymphocytes. Besides, IVW MR analysis showed that genetically predicted total WBC and neutrophil counts were associated with reduced FVC (p=.017 and.021, respectively) and FEV1 (p=.048 and.043, respectively). Conclusions WBC subtypes were independently associated with lower lung function except lymphocytes. Our findings suggest that circulating neutrophils may be causal factors in lung function impairment. KEY MESSAGES White blood cell (WBC) subtypes were negatively associated with lung function level except lymphocytes in the observational studies. Associations of WBC subtypes with lung function may be modified by sex and smoking. Mendelian randomization analysis shows that neutrophils may be causal factors in lung function impairment. Supplementary materials Pearson's correlation coefficients between different WBC subtypes. Table S2 Relationships of total and differential WBC counts with lung function among subjects without cancers (single-marker model). Table S3 Relationships of total and differential WBC counts with lung function among subjects without using anti-infectious drugs (single-marker model). Table S4 Characteristics of SNPs associated with total and differential WBC counts in published GWAS. Table S5 The associations of total and differential WBC counts related SNPs with confounders in the COW and DFTJ studies. Table S6 Between-instrument heterogeneity test for the Mendelian randomization analysis of total and differential WBC counts with lung function. Definitions of common lifestyles In the NHANES 2011-2012, subjects with a positive answer to the question "Have you smoked at least 100 cigarettes in your entire life" were classified as smokers; otherwise, they were classified as non-smokers. Subjects with at least 12 alcohol drinks per year or in lifetime were classified as alcohol drinkers; otherwise, they were classified as non-alcohol drinkers. Subjects with vigorous work activity ≥75 min/week or moderate work activity ≥150 min/week or a combination ≥150 min/week were classified as exercisers; otherwise, they were classified as non-exercisers. In the COW and DFTJ studies, participants who have smoked >1 cigarette/day for >6 months were classified as smokers; otherwise, they were classified as non-smokers. Participants who have drunk alcohol >1 time/week for >6 months were classified as alcohol drinkers; otherwise, they were classified as non-alcohol drinkers. During the last 6 months, participants who have spent ≥30 min at a time and ≥5 times/week exercising in leisure time were classified as exercisers; otherwise, they were classified as non-exercisers. SUPPLEMENTARY NOTES Single-marker regression, multiple-marker regression, and interaction analyses were performed with SAS 9.4, and LASSO regression and MR analyses were conducted using R 3.5.3 software. SAS and R codes were listed as follows..001 Eosinophil and basophil counts were transformed by common logarithm (log10) to approximate normal distribution. SAS codes for single-marker regression analysis Total and differential WBC counts Table S3 Relationships of total and differential WBC counts with lung function among subjects without using anti-infectious drugs (single-marker model). Notes: *Total and differential WBC counts were included in the multiple linear regression model separately, and the model was adjusted for age, sex, race (only in NHANES 2011-2012 population), height, smoking, alcohol use, and exercise. 192.43 Abbreviation: WBC, white blood cell; GWAS, genome-wide association study. *These SNPs were not genotyped or imputed in the participants of present research. Notes: Summary statistics were derived from the largest GWAS of total and differential WBC in the Asian population. Total WBC counts were standardized by Z-score, and the study sample size was 107,964. Neutrophil, monocyte, eosinophil, and basophil counts were standardized by rank-based inverse normal transformation and the study sample size for the genome-wide analysis was 62,076. Notes: Effect estimates were obtained from linear regression model for height and logistic regression model for smoking, drinking and exercise, with adjustment for age, gender, and chip types (only in DFTJ study). Fixed-effect (heterogeneity P ≥0.05) or random-effect (heterogeneity P <0.05) meta-analysis was used to combine results from COW and DFTJ studies (n=4,012). *These SNPs were significantly associated with the covariates at the Bonferroni-corrected level and they were then excluded as IVs in the following MR analysis. These SNPs were identified as potential outliers by MR-PRESSO method and they were further excluded as IVs in the following MR analysis.
package gov.hhs.onc.dcdt.web.view; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) public @interface RequestView { String value(); ViewDirectiveType directive() default ViewDirectiveType.NONE; boolean override() default false; }
package components import ( "encoding/json" "reflect" "testing" "github.com/api7/apisix-seed/internal/core/comm" "github.com/api7/apisix-seed/internal/core/entity" "github.com/api7/apisix-seed/internal/core/storer" "github.com/api7/apisix-seed/internal/discoverer" "github.com/api7/apisix-seed/internal/utils" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) type TestNodes struct { entity.BaseInfo Nodes []*entity.Node } func (t *TestNodes) SetNodes(nodes []*entity.Node) { t.Nodes = nodes } func init() { // Init Mock Discoverer discoverer.Discoveries = map[string]discoverer.NewDiscoverFunc{ "mocks": discoverer.NewDiscovererMock, } _ = discoverer.InitDiscoverer("mocks", nil) } func TestRewriter(t *testing.T) { caseDesc := "sanity" giveCache := map[string]interface{}{ "/prefix/mocks/1": &TestNodes{}, } giveKey := "/prefix/mocks/1" giveEntities := make(utils.Message, 0, 1) giveEntities.Add("entity", "/prefix/mocks/1") giveNodes := make(utils.Message, 0, 2) giveNodes.Add("node", "test.com:80") giveNodes.Add("weight", "10") wantNodes := []*entity.Node{ { Host: "test.com", Port: 80, Weight: 10, }, } headerVals := []string{utils.EventUpdate, "mocks"} watch, err := comm.NewMessage(headerVals, giveEntities, giveNodes) assert.Nil(t, err, caseDesc) watchCh := make(chan *comm.Message) discover := discoverer.GetDiscoverer("mocks") mDiscover := discover.(interface{}).(*discoverer.MockInterface) mDiscover.On("Watch").Run(func(args mock.Arguments) {}).Return(watchCh) rewriter := Rewriter{ Prefix: "/prefix", } rewriter.Init() doneCh := make(chan struct{}) mStg := &storer.MockInterface{} mStg.On("Update", mock.Anything, mock.Anything, mock.Anything).Run(func(args mock.Arguments) { assert.Equal(t, giveKey, args[0], caseDesc) input := TestNodes{} err := json.Unmarshal([]byte(args[1].(string)), &input) assert.Nil(t, err) assert.Equal(t, len(wantNodes), len(input.Nodes), caseDesc) for i := range wantNodes { assert.Equal(t, *wantNodes[i], *input.Nodes[i], caseDesc) } assert.NotEqual(t, 0, input.UpdateTime, caseDesc) doneCh <- struct{}{} }).Return(nil) storer.ClrearStores() err = storer.InitStore("mocks", storer.GenericStoreOption{ BasePath: "/prefix/mocks", Prefix: "/prefix", ObjType: reflect.TypeOf(TestNodes{}), }, mStg) assert.Nil(t, err, caseDesc) store := storer.GetStore("mocks") for k, v := range giveCache { store.Store(k, v) } watchCh <- &watch <-doneCh obj, ok := store.Store(giveKey, nil) assert.True(t, ok, caseDesc) objTn, ok := obj.(*TestNodes) assert.True(t, ok, caseDesc) assert.Equal(t, len(wantNodes), len(objTn.Nodes), caseDesc) for i := range wantNodes { assert.Equal(t, *wantNodes[i], *objTn.Nodes[i], caseDesc) } }
<gh_stars>0 line = input() (a, b, c) = [float(i) for i in line.split(' ')] triangle_area = (a * c) / 2 pi = 3.14159 circle_area = pi * (c ** 2) trapeze_area = (c * (a + b)) / 2 square_area = b * b rectangle_area = a * b print('TRIANGULO: {:.3f}'.format(triangle_area)) print('CIRCULO: {:.3f}'.format(circle_area)) print('TRAPEZIO: {:.3f}'.format(trapeze_area)) print('QUADRADO: {:.3f}'.format(square_area)) print('RETANGULO: {:.3f}'.format(rectangle_area))
#define _CRT_SECURE_NO_DEPRECATE #include <windows.h> #include <tchar.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #ifndef UNICODE #define UNICODE #define _UNICODE #endif #include "conio.h" struct FileInfoStruct { LPTCH fileName; UINT size; LPUINT outputArray; }; typedef FileInfoStruct* LPFileInfoStruct; CRITICAL_SECTION cs; // generate bin files with random integers VOID binFilesWithRandomInt(UINT numOfFiles); // sorting algo VOID bubblesort(LPUINT array, UINT size); // Thread routine DWORD WINAPI threadSortFile(LPVOID param); int _tmain(INT argc, LPTSTR argv[]) { LPHANDLE arrayHandle; LPFileInfoStruct lpFileInfoStruct; UINT numberThreads; HANDLE hOut; DWORD nOut; if (argc < 3) { _ftprintf(stderr, _T("USAGE: %s <input file(s)> <output file>"), argv[0]); return 1; } numberThreads = argc - 2; //protects printf, so that only one thread can print at a time InitializeCriticalSection(&cs); // allocate the handles for threads arrayHandle = (LPHANDLE)malloc((numberThreads) * sizeof(HANDLE)); // allocate the array of structures for data sharing with the threads lpFileInfoStruct = (LPFileInfoStruct)malloc((numberThreads) * sizeof(FileInfoStruct)); // threads creation for (UINT i = 0; i < numberThreads; i++) { // save file name for each thread lpFileInfoStruct[i].fileName = argv[i+1]; // create and start thread arrayHandle[i] = CreateThread(0, 0, threadSortFile, (LPVOID)&lpFileInfoStruct[i], 0, NULL); if (arrayHandle[i] == INVALID_HANDLE_VALUE) { _ftprintf(stderr, _T("Error creating thread %d\n"), i+1); return 2; } } // main thread waits WaitForMultipleObjects(numberThreads, arrayHandle, TRUE, INFINITE); for (UINT i = 0; i < numberThreads; i++) { CloseHandle(arrayHandle[i]); } free(arrayHandle); UINT finalArraySize = 0; for (UINT i = 0; i < numberThreads; i++) { finalArraySize += lpFileInfoStruct[i].size; } LPUINT finalArray = (LPUINT)malloc(finalArraySize * sizeof(UINT)); for (UINT i = 0; i < numberThreads; i++) { for (UINT j = 0; j < lpFileInfoStruct[i].size; j++) { finalArray[i+j] = lpFileInfoStruct[i].outputArray[j]; } } free(lpFileInfoStruct); bubblesort(finalArray, finalArraySize); // print to stdout _ftprintf(stdout, _T("Writing to file %s\n"), argv[argc - 1]); _ftprintf(stdout, _T("%d "), finalArraySize); for (UINT i = 0; i < finalArraySize; i++) _ftprintf(stdout, _T("%d "), finalArray[i]); _ftprintf(stdout, _T("\n")); // save final array to output file hOut = CreateFile(argv[argc - 1], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hOut == INVALID_HANDLE_VALUE) { _tprintf(_T("Error creating file %s %x\n"), argv[argc - 1], GetLastError()); } if (!WriteFile(hOut, &finalArraySize, sizeof(finalArraySize), &nOut, NULL) || nOut != sizeof(finalArraySize)) { _ftprintf(stderr, _T("Error writing %x\n"), GetLastError()); free(finalArray); CloseHandle(hOut); return 3; } if (!WriteFile(hOut, finalArray, finalArraySize * sizeof(UINT), &nOut, NULL) || nOut != (finalArraySize * sizeof(UINT))) { _ftprintf(stderr, _T("Error %x\n"), GetLastError()); free(finalArray); CloseHandle(hOut); return 4; } free(finalArray); CloseHandle(hOut); _ftprintf(stdout, _T("Press enter to continue...\n")); _gettchar(); return 0; } VOID bubblesort(LPUINT array, UINT size) { UINT tmp; for (UINT i = 0; i < size-2; i++) { if (array[i]>array[i+1]) { tmp = array[i + 1]; array[i + 1] = array[i]; array[i] = tmp; } } return; } // used by thread to sort his file DWORD WINAPI threadSortFile(LPVOID param) { LPFileInfoStruct lpFilestructInfo = (LPFileInfoStruct)param; HANDLE hIn; DWORD nRead; hIn = CreateFile(lpFilestructInfo->fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // protect printf, only one thread can print on stdout at a time EnterCriticalSection(&cs); if (hIn == INVALID_HANDLE_VALUE) { _ftprintf(stderr, _T("Error opening file %s %x\n"), lpFilestructInfo->fileName, GetLastError()); return 5; } else { _ftprintf(stdout, _T("Opened: %s\n"), lpFilestructInfo->fileName); } UINT num; if (!ReadFile(hIn, &num, sizeof(UINT), &nRead, NULL) || nRead != sizeof(UINT)) { _ftprintf(stderr, _T("Error %s %x\n"), lpFilestructInfo->fileName, GetLastError()); return 6; } else { _ftprintf(stdout, _T("n=%d : "), num); } LPUINT arrayValues = (LPUINT)malloc(num * sizeof(UINT)); for (UINT i = 0; i < num; i++) { if (!ReadFile(hIn, &arrayValues[i], sizeof(i), &nRead, NULL) || nRead != sizeof(i)) { _ftprintf(stderr, _T("Error reading values %s %x\n"), lpFilestructInfo->fileName, GetLastError()); return 7; } else { _ftprintf(stdout, _T("%d "), arrayValues[i]); } } _ftprintf(stdout, _T("\n")); LeaveCriticalSection(&cs); //sort array bubblesort(arrayValues, num); // set the results inside the structure lpFilestructInfo->size = num; lpFilestructInfo->outputArray = arrayValues; // release resources CloseHandle(hIn); // then return 0 return 0; } VOID binFilesWithRandomInt(UINT numOfFiles) { TCHAR filename[10]; for (UINT i = 0; i < numOfFiles; i++) { _stscanf(filename, _T("file_%d"), i); HANDLE hOut = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hOut == INVALID_HANDLE_VALUE) { _ftprintf(stderr, _T("Error opening file %s %x\n"), filename, GetLastError()); exit(10); } srand((UINT)time(NULL)); UINT numInt = rand()%100; DWORD nOut; if (!WriteFile(hOut, &numInt, sizeof(UINT), &nOut, NULL) || nOut != sizeof(UINT)) { _ftprintf(stderr, _T("Error %x\n"), GetLastError()); CloseHandle(hOut); exit(11); } UINT n; for (UINT i = 0; i < numInt; i++) { n = rand() % 100; if (!WriteFile(hOut, &n, sizeof(UINT), &nOut, NULL) || nOut != sizeof(UINT)) { _ftprintf(stderr, _T("Error %x\n"), GetLastError()); CloseHandle(hOut); exit(11); } } CloseHandle(hOut); } }
Last week I met with my wonderful friend Adrianna and her two dogs Lucky and Donny, I was amazed to see the change in Donny, he's come such a long way in such a short time. This is his story: My name is Donny. I am a black and white border collie mix and I grew up a stray. Nobody wanted me. I quickly learned to keep away from humans. I got badly kicked by a man one day and there were a few times when kids would throw stones at me. In the summer of 2014 I found a quiet neighbourhood and took to hanging out with some other stray dogs. There was safety in numbers, but sometimes things got rough. I was kind of bottom of the pack. I guess I was just a frightened youngster and timid too. Whilst on the streets I noticed this kind looking lady. She had a little male dog that she called Lucky. I used to see her with Lucky and I wished that I could be owned and loved like that. Sometimes the lady made a move to approach me, but I would run away. I was too scared to trust. Too scared of getting hurt. But despite my fears, I kind of took to following the lady when she was out on her walks. I always kept my distance, but I knew she noticed me and I loved the way the little dog looked at her. He was always wagging his tail and the way she petted him, it made me think that perhaps some humans were OK. On September 6th 2014 I followed the lady further than usual and then I guess a scent wafted towards my nose. I was always on the look-out for food. I was always hungry. I figure I wasn’t really paying attention. I knew about the road and I knew about the cars, but that morning I was just too preoccupied. The car came out of the blue. It hit me hard. I remember everything in a blur and then the most excruciating pain in my right eye. I recalled the car driving off at speed and the sound of my own whimpering howl. I fled in terror. Time seemed to stand still and minutes turned into hours. My whole body ached and I couldn’t see through my injured eye. I lay licking my paws and trying to find comfort. Then I remember seeing the lady’s concerned face with my one good eye. She had a man with her from the Department of Agriculture and although I was afraid, I felt too weak to even try to escape. I let them take me. They took me for urgent medical attention and the vet told the lady that miraculously my only injury was an eye trauma from that initial impact. The vet said that the eye would need surgery and that it was an expensive procedure. The vet said it probably made more sense to put me down since I was a stray. The lady looked at me and she said “No, I can’t let that happen.” She looked at me with the same love that she always gave to the little dog. Although I was terrified I somehow knew this lady would keep me safe and she did. It’s been over two years since the lady rescued me and I’ve never looked back. An awesome charity called C.A.R.E. assisted with my medical care and I made it through the surgery in one piece. Every day I got a bit stronger both physically and emotionally. The lady was so kind and gentle and it wasn’t long before Lucky and me became like brothers. The lady even convinced me to start walking on a leash. She tells me I’m a loyal and loving dog. Although I’m still a bit wary of strangers, the lady has taught me that not all humans wish me harm. Thank-you to my beautiful friend Adrianna for making a difference. #50daysofniceness
The last few times we looked at top-down sci-fi survival-strategy (is that a thing? Genres are becoming so tricky lately) Rimworld it was merely flirting with the idea of being genuinely playable, but recent buzz had it that the Rimworld was now inhabitable at last. It doesn’t take much to convince me to starve to death on an alien world, so I thought I’d check in. I’m pleased to report that, despite still being in alpha Rimworld is now very much weaving the spell it needs to. It’s made up of parts borrowed from all over – Prison Architect’s look, Minecraft’s resources, Project Zomboid’s defensive mentality, Don’t Starve’s, er, starving and a whole lot of Dwarf Fortress’ poppier side – but they’ve come together very well. Here’s the setup: you’re crashed on a randomly-generated alien world, of varying hostility depending on what starting settings you chose, and you need to build some sort of life there. You’ll need shelter, food, power and defence as a starting point, but each of those requires the right equipment and the right resources. These can found or mined, and for much of the time the pace of the game is such that you’re able to get on with this stuff – slowly building up, slowly increasing the quality of your habitat, slowly becoming self-sufficient. Intermittently, raiders arrive, or an animal gets upset about something – honestly, you won’t believe how many times my colonists got attacked by a furious squirrel – and you’ll need to be able to defend yourself, both by giving your guys weapons and by constructing turrets. But turrets require power, power requires solar energy, the sun’s not up to much at night or in winter and, well, that’s the way Rimworld spirals out. Everything requires something else, but there’s a pleasantly organic nature to the technological upscaling and co-dependency here. It’s not a frenzy of build, build, build, but this ever-widening circle, dutifully getting on with creating stability in a treacherous place. It could probably get away with being a pure sandbox, but the elements of chaos, driven by an impressively invisible ‘AI storyteller’, really bring the survival fantasy to life. Rabid squirrels are a small problem, but something like an invading tribe is more serious. You’ve got to manually toggle your colonists into combat mode, then deal with the fact they’re just not very good at shooting, then in the aftermath deal with injuries, corpses and potentially prisoners. Untreated wounds lead to death, bodies lying about the place upset people (though the emotional health aspect of the game doesn’t seem totally developed as yet), while wounded enemies could represent a threat or a potential ally. Little decisions, potentially fatal decisions. What this kind of game needs to excel at is constantly shifting priorities, rather than just a clear ladder to steadily climb, and so far Rimworld is doing a fine job of that. One second I’m fixated on needing to find more steel, the next I’m hauling a newly one-armed colonist off to a medical med and praying her colleagues can stop the bleeding in time. Despite the presence of an AI string-puller, I’ve very rarely found Rimworld to be wantonly cruel, rolling some invisible dice to decide that I’m going to suffer, because clear thinking and most all accumulated knowledge of what’s required will resolve most, if not all, problems. There’s always a cause for each effect. This is a world with clear rules, and the trial and error needed to learn them means hilarious mishaps and rewarding revelations. Build batteries outside, for instance, and they’ll short out when it rains, potentially starting a fire in your settlement. It wasn’t just a fire which started for no reason. There’s a hell of a lot to learn, and not too much help, but it all funnels out gradually and logically. Clearly Rimworld’s a long way from finished, but now it feels like the rabbit hole it needs to be. I have all these goals in my mind, with building a spaceship and escaping right at the end of them, but I know they’re going to take a long time, I know they’re going to shift, and I know they’re going to be marred by tragedy. And accidental hilarity, too. Those damned squirrels! There’s scope to make it deliberately hilarious too – on my first attempt at Rimworld, one of my three starting colonists was a noble who refused to do any manual labour. She just ambled about the place while the other two worked their bums off to build her a bed, cook her food and fetch rocks from a million miles away. I wasn’t too upset when the pirates took her life. All this said, I’m not in love with how Rimworld looks. It’s very Prison Architect in the great outdoors, and I never entirely took to PA’s South Parky art style either. The interface is pretty awkward too, but when you’re talking about a game whose partial inspiration is Dwarf Fortress, maligning any GUI feels a bit rich. Push on past these starting hurdles and Rimworld’s well worth it, though, and I’m saying that at a point where I’ve barely scratched its surface. Whereas some of these grand-scale management games can feel like a collection of disconnected ideas without overarching purpose, Rimworld very much seems to have its eyes on the prize. It’s imbued with a sense of impetus, and it deftly creates the vignettes of hilarity and tragedy needed to make it feel like a functioning place. I like it a lot. If you’re after a slow-burn survival and construction game which doesn’t involve getting unexpectedly shot/bitten in the face at any given moment, here’s your new home. The Rimworld Alpha – currently at version 9e – is out now. It costs $30.
<gh_stars>0 use std::fs; use std::path::Path; use crate::error::msg::SemError; use crate::vm::VM; use crate::vm::{exception_get_and_clear, Fct, FctId}; use dora_parser::ast::{self, Ast}; use crate::driver::cmd; use crate::object; use crate::os; use crate::timer::Timer; use dora_parser::lexer::reader::Reader; use crate::semck; use crate::semck::specialize::specialize_class_id; use crate::ty::BuiltinType; use dora_parser::parser::Parser; pub fn start(content: Option<&str>) -> i32 { os::mem::init_page_size(); let fuzzing = content.is_some(); let args = if fuzzing { Default::default() } else { cmd::parse() }; if args.flag_version { println!("dora v0.01b"); return 0; } let mut ast = Ast::new(); let empty = Ast::new(); let mut vm = VM::new(args, &empty); if let Err(code) = parse_all_files(&mut vm, &mut ast, content) { return code; } vm.ast = &ast; if vm.args.flag_emit_ast { ast::dump::dump(&vm.ast, &vm.interner); } semck::check(&mut vm); // register signal handler os::register_signals(); let main = if vm.args.cmd_test { None } else { find_main(&vm) }; if vm.diag.lock().has_errors() { vm.diag.lock().dump(&vm); let no_errors = vm.diag.lock().errors().len(); if no_errors == 1 { println!("{} error found.", no_errors); } else { println!("{} errors found.", no_errors); } return 1; } if !vm.args.cmd_test && main.is_none() { println!("error: no `main` function found in the program"); return 1; } // if --check given, stop after type/semantic check if vm.args.flag_check { return 0; } let mut timer = Timer::new(vm.args.flag_gc_stats); vm.threads.attach_current_thread(); let code = if vm.args.cmd_test { run_tests(&vm) } else { run_main(&vm, main.unwrap()) }; vm.threads.detach_current_thread(); vm.threads.join_all(); os::unregister_signals(); if vm.args.flag_gc_stats { let duration = timer.stop(); vm.dump_gc_summary(duration); } code } const STDLIB: &[(&str, &str)] = &include!(concat!(env!("OUT_DIR"), "/dora_stdlib_bundle.rs")); fn parse_all_files(vm: &mut VM, ast: &mut Ast, content: Option<&str>) -> Result<(), i32> { let fuzzing = content.is_some(); let stdlib_dir = vm.args.flag_stdlib.clone(); if let Some(stdlib) = stdlib_dir { parse_dir(&stdlib, vm, ast)?; } else { for (filename, data) in STDLIB { parse_bundle(filename, data, vm, ast)?; } } if fuzzing { return parse_str(content.unwrap(), vm, ast); } let arg_file = vm.args.arg_file.clone(); let path = Path::new(&arg_file); if path.is_file() { parse_file(&arg_file, vm, ast) } else if path.is_dir() { parse_dir(&arg_file, vm, ast) } else { println!("file or directory `{}` does not exist.", &arg_file); Err(1) } } fn run_tests<'ast>(vm: &VM<'ast>) -> i32 { let mut tests = 0; let mut passed = 0; for fct in vm.fcts.iter() { let fct = fct.read(); if !is_test_fct(vm, &*fct) { continue; } tests += 1; print!("test {} ... ", vm.interner.str(fct.name)); if run_test(vm, fct.id) { passed += 1; println!("ok"); } else { println!("failed"); } } println!( "{} tests executed; {} passed; {} failed.", tests, passed, tests - passed ); // if all tests passed exit with 0, otherwise 1 if tests == passed { 0 } else { 1 } } fn run_test<'ast>(vm: &VM<'ast>, fct: FctId) -> bool { let testing_class = vm.vips.testing_class; let testing_class = specialize_class_id(vm, testing_class); let testing = object::alloc(vm, testing_class).cast(); vm.run_test(fct, testing); // see if test failed with exception let exception = exception_get_and_clear(); exception.is_null() && !testing.has_failed() } fn is_test_fct<'ast>(vm: &VM<'ast>, fct: &Fct<'ast>) -> bool { // tests need to be standalone functions, with no return type and a single parameter if !fct.parent.is_none() || !fct.return_type.is_unit() || fct.param_types.len() != 1 { return false; } // parameter needs to be of type Testing let testing_cls = vm.cls(vm.vips.testing_class); if fct.param_types[0] != testing_cls { return false; } // the function needs to be marked with the @test annotation fct.is_test } fn run_main<'ast>(vm: &VM<'ast>, main: FctId) -> i32 { let res = vm.run(main); let fct = vm.fcts.idx(main); let fct = fct.read(); let is_unit = fct.return_type.is_unit(); // main-fct without return value exits with status 0 if is_unit { 0 // else use return value of main for exit status } else { res } } fn parse_dir(dirname: &str, vm: &mut VM, ast: &mut Ast) -> Result<(), i32> { let path = Path::new(dirname); if path.is_dir() { for entry in fs::read_dir(path).unwrap() { let path = entry.unwrap().path(); if path.is_file() && path.extension().unwrap() == "dora" { parse_file(path.to_str().unwrap(), vm, ast)?; } } Ok(()) } else { println!("directory `{}` does not exist.", dirname); Err(1) } } fn parse_file(filename: &str, vm: &mut VM, ast: &mut Ast) -> Result<(), i32> { let reader = if filename == "-" { match Reader::from_input() { Ok(reader) => reader, Err(_) => { println!("unable to read from stdin."); return Err(1); } } } else { match Reader::from_file(filename) { Ok(reader) => reader, Err(_) => { println!("unable to read file `{}`", filename); return Err(1); } } }; parse_reader(reader, vm, ast) } fn parse_bundle(filename: &str, data: &str, vm: &mut VM, ast: &mut Ast) -> Result<(), i32> { let reader = Reader::from_string(filename, data); parse_reader(reader, vm, ast) } fn parse_str(file: &str, vm: &mut VM, ast: &mut Ast) -> Result<(), i32> { let reader = Reader::from_string("<<code>>", file); parse_reader(reader, vm, ast) } fn parse_reader(reader: Reader, vm: &mut VM, ast: &mut Ast) -> Result<(), i32> { let filename: String = reader.path().into(); let parser = Parser::new(reader, &vm.id_generator, ast, &mut vm.interner); match parser.parse() { Ok(file) => { vm.files.push(file); assert_eq!(ast.files.len(), vm.files.len()); Ok(()) } Err(error) => { println!( "error in {} at {}: {}", filename, error.pos, error.error.message() ); println!("error during parsing."); Err(1) } } } fn find_main<'ast>(vm: &VM<'ast>) -> Option<FctId> { let name = vm.interner.intern("main"); let fctid = match vm.sym.lock().get_fct(name) { Some(id) => id, None => { return None; } }; let fct = vm.fcts.idx(fctid); let fct = fct.read(); let ret = fct.return_type; if (ret != BuiltinType::Unit && ret != BuiltinType::Int) || fct.params_without_self().len() > 0 { let pos = fct.ast.pos; vm.diag .lock() .report(fct.file, pos, SemError::WrongMainDefinition); return None; } Some(fctid) }
<gh_stars>0 import pygame #importa a biblioteca Pygame import random #importa a biblioteca Random pygame.init() cor_fundo = (150,255,159)#Define a cor do fundo cor_cobra = (255,0,0)#Define a cor da cobra cor_comida = (128,60,60)#Define a cor da comida cor_pontos =(0,0,0)#Define a cor dos pontos dimensoes = (600, 600) #Valores Iniciais tempo = 7.5 x = 300 y = 300 d = 20 dx = 0 dy = 0 x_comida = round(random.randrange(0, 600 -d)/20)*20 y_comida = round(random.randrange(0, 600 -d)/20)*20 fonte = pygame.font.SysFont("hack", 35) lista_cobra = [[x,y]] tela = pygame.display.set_mode((dimensoes)) pygame.display.set_caption("Snake") tela.fill(cor_fundo) clock = pygame.time.Clock() def desenha_cobra(lista_cobra): tela.fill(cor_fundo) for unidade in lista_cobra: pygame.draw.rect(tela, cor_cobra, [unidade[0],unidade[1],d,d]) def mover_cobra(dx, dy, lista_cobra): delta_x = 0 delta_y = 0 for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: dx = -d dy = 0 elif event.key == pygame.K_RIGHT: dx = d dy = 0 elif event.key == pygame.K_UP: dx = 0 dy = -d elif event.key == pygame.K_DOWN: dx = 0 dy = d x_novo = lista_cobra[-1][0] + dx y_novo = lista_cobra[-1][1] + dy lista_cobra.append([x_novo, y_novo]) del lista_cobra[0] # x = x + delta_x # y = y + delta_y return dx, dy, lista_cobra def verifica_comida(dx,dy,x_comida,y_comida,lista_cobra,tempo): head = lista_cobra[-1] x_novo = head[0] + dx y_novo = head[1] + dy if head[0] == x_comida and head[1] == y_comida: lista_cobra.append([x_novo, y_novo]) tempo = tempo + 0.5 x_comida = round(random.randrange(0, 600 -d)/20)*20 y_comida = round(random.randrange(0, 600 -d)/20)*20 pygame.draw.rect(tela, cor_comida, [x_comida, y_comida, d, d]) return x_comida, y_comida, lista_cobra, tempo def verifica_parede(lista_cobra): head = lista_cobra[-1] x = head[0] y = head[1] if x not in range(600) or y not in range(600): raise Exception def verifica_mordeu_cobra(lista_cobra): head = lista_cobra[-1] corpo = lista_cobra.copy() del corpo[-1] for x, y in corpo: if x == head[0] and y == head[1]: raise Exception def atualizar_pontos(lista_cobra): pontos = str(len(lista_cobra)) score = fonte.render("Scores: " + pontos, True, cor_pontos) tela.blit(score, [0, 0]) while True: pygame.display.update() desenha_cobra(lista_cobra) dx, dy, lista_cobra = mover_cobra(dx, dy, lista_cobra) x_comida, y_comida, lista_cobra, tempo = verifica_comida(dx,dy,x_comida,y_comida,lista_cobra,tempo) print(lista_cobra) verifica_parede(lista_cobra) verifica_mordeu_cobra(lista_cobra) atualizar_pontos(lista_cobra) clock.tick(tempo)
<reponame>lastweek/source-freebsd /* * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2019 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice(s), this list of conditions and the following disclaimer as * the first lines of this file unmodified other than the possible * addition of one or more copyright notices. * 2. Redistributions in binary form must reproduce the above copyright * notice(s), this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``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 HOLDER(S) 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. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <sys/types.h> #include <sys/mman.h> #include <sys/syscall.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include "libc_private.h" __weak_reference(shm_open, _shm_open); __weak_reference(shm_open, __sys_shm_open); #define SHM_OPEN2_OSREL 1300048 #define MEMFD_NAME_PREFIX "memfd:" int shm_open(const char *path, int flags, mode_t mode) { if (__getosreldate() >= SHM_OPEN2_OSREL) return (__sys_shm_open2(path, flags | O_CLOEXEC, mode, 0, NULL)); /* * Fallback to shm_open(2) on older kernels. The kernel will enforce * O_CLOEXEC in this interface, unlike the newer shm_open2 which does * not enforce it. The newer interface allows memfd_create(), for * instance, to not have CLOEXEC on the returned fd. */ return (syscall(SYS_freebsd12_shm_open, path, flags, mode)); } /* * The path argument is passed to the kernel, but the kernel doesn't currently * do anything with it. Linux exposes it in linprocfs for debugging purposes * only, but our kernel currently will not do the same. */ int memfd_create(const char *name, unsigned int flags) { char memfd_name[NAME_MAX + 1]; size_t namelen; int oflags, shmflags; if (name == NULL) return (EBADF); namelen = strlen(name); if (namelen + sizeof(MEMFD_NAME_PREFIX) - 1 > NAME_MAX) return (EINVAL); if ((flags & ~(MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_HUGETLB | MFD_HUGE_MASK)) != 0) return (EINVAL); /* Size specified but no HUGETLB. */ if ((flags & MFD_HUGE_MASK) != 0 && (flags & MFD_HUGETLB) == 0) return (EINVAL); /* We don't actually support HUGETLB. */ if ((flags & MFD_HUGETLB) != 0) return (ENOSYS); /* We've already validated that we're sufficiently sized. */ snprintf(memfd_name, NAME_MAX + 1, "%s%s", MEMFD_NAME_PREFIX, name); oflags = O_RDWR; shmflags = 0; if ((flags & MFD_CLOEXEC) != 0) oflags |= O_CLOEXEC; if ((flags & MFD_ALLOW_SEALING) != 0) shmflags |= SHM_ALLOW_SEALING; return (__sys_shm_open2(SHM_ANON, oflags, 0, shmflags, memfd_name)); }
LONDON/DUBAI (Reuters) - Only five of 14 non-OPEC oil producers have agreed so far to meet the group on Saturday for talks aimed at widening a deal to reduce output, casting doubt on whether OPEC will secure the full cuts it is seeking, two OPEC sources said. The Organization of the Petroleum Exporting Countries, which finalised its first oil output cut in eight years last month to prop up prices, is to hold talks with non-member countries in Vienna in the hope that they will also limit supply. The last time non-OPEC countries joined the organization in cutting output, in late 2001 as prices dropped in the aftermath of the Sept. 11 attacks, non-members promised cuts of 462,000 barrels per day, not quite the 500,000 bpd OPEC then sought. Currently, Russia has said it will cut 300,000 bpd, meaning other non-OPEC producers combined will need to pledge the same amount to lower output by the 600,000 bpd OPEC wants - half the reduction OPEC is making. Some OPEC sources familiar with discussions were reasonably sure the outside producers would deliver enough commitments. Other OPEC sources were skeptical a pledge for the full amount would be made this time. Among the 14 non-OPEC countries invited to attend Saturday’s meeting, only Azerbaijan, Kazakhstan, Oman, Mexico and Russia have accepted. A third OPEC source said cut pledges amounting to 500,000 bpd were more likely. Besides Russia, only Oman has publicly stated it is willing to cut production. In public comments, Azerbaijan has indicated it will lower supply, while Kazakhstan has said it is undecided. OPEC President Mohammed al-Sada, speaking at the Nov. 30 news conference after OPEC finalised its output reduction, was confident that non-OPEC would deliver the 600,000 bpd. Saturday’s meeting at OPEC’s Vienna headquarters will start at 10:00 a.m. local time (0900 GMT) and be chaired jointly by Sada and Russian Energy Minister Alexander Novak, according to a draft copy of the agenda seen by Reuters. OPEC will still implement its cut of 1.2 million bpd even if Russia becomes the only non-member to contribute, OPEC member Nigeria said on Wednesday.
Wisconsin Cytology Proficiency Testing Program. Results of voluntary testing in 1994. OBJECTIVE The Wisconsin Cytology Proficiency Testing Program (WCPTP) was developed cooperatively by the Wisconsin State Laboratory of Hygiene, the Wisconsin Society of Pathologists and the Wisconsin Society of Cytology to enable pathologists and cytotechnologists in Wisconsin to meet Clinical Laboratory Improvement Act of 1988 (CLIA '88) requirements for proficiency testing (PT). STUDY DESIGN A joint steering committee designed the WCPTP to comply with all CLIA '88 regulations. The WCPTP application to the Health Care Financing Administration received tentative approval in May 1994. In 1994, mock PT was conducted at meetings of both state societies, and voluntary, on-site PT was conducted at 19 laboratories. RESULTS Each of the 119 participants (49 pathologists, 70 cytotechnologists) was tested with sets of 10 glass slides, each representing one of four specified categories: A, unsatisfactory; B, normal/benign; C, low grade squamous intraepithelial lesion; and D, high grade squamous intraepithelial lesion and cancer. The failure rate for pathologists was 22.5% (11/49) and for cytotechnologists, 1.4% (1/70). The CLIA '88 scoring system for pathologists is more stringent. If cytotechnologists were scored as pathologists, 10% (7/70) would have failed. Using the cytotechnologist grid, 14.5% (7/49) of the pathologists would have failed. CONCLUSION This voluntary program provided some preliminary insights into the issues related to PT evaluation of personnel competence and diagnostic criteria.
Biophysical and biological activity of a synthetic 8.7-kDa hydrophobic pulmonary surfactant protein SP-B. We have synthesized pulmonary surfactant apoprotein SP-B peptides by solid-phase chemistry and demonstrated their ability to enhance the surface-active properties of synthetic lipid mixtures. The synthetic peptides were reactive with antiserum generated against the native bovine surfactant peptide. Both peptides conferred surfactant-like properties to synthetic lipid mixtures as assessed by a Wilhelmy balance and pulsating bubble surfactometer. Likewise, mixtures of synthetic SP-B peptides and lipid restored compliance of isolated surfactant-deficient rat lungs. This work demonstrates the utility of SP-B as a functional component of pulmonary surfactant mixtures for treatment of respiratory distress syndrome or other disorders characterized by surfactant deficiency.
n=int(input()) A=list(map(int,input().split())) def rui(A): R=[A[0]]*len(A) for i in range(len(A)-1): R[i+1]=R[i]+A[i+1] return R R=rui(A) S=sum(A) ans=10**20 for i in range(n-1): a=R[i] ; b=S-a ans=min(ans, abs(a-b)) print(ans)
<reponame>Haruki/FilmzRestServer package gl.hb.filmzrestserver.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.dropwizard.auth.Authorizer; /** * Created by Homer on 23.04.2017. */ public class FilmzServiceAuthorizer implements Authorizer<FilmzServiceUser> { private final Logger logger = LoggerFactory.getLogger(FilmzServiceAuthorizer.class); @Override public boolean authorize(FilmzServiceUser user, String role) { logger.debug(user.getName() + " " + role); return user.getName().equals("good-guy") && role.equals("Level0"); } }