content
stringlengths 7
2.61M
|
---|
HOW DO CALENDAR ANOMALIES AFFECT AN INVESTMENT CHOICE? A PROPOSAL OF AN ANALYTIC HIERARCHY PROCESS MODEL In recent years, financial markets changed for globalization. Today, a wide range of investment opportunities is available to investors. In this new scenario, markets are related, but each of them has specific characteristics with particular opportunities for investors. An investment choice can be influenced by numerous qualitative and quantitative factors that often conflict with one other. Thus, portfolio management choice is a multi-criteria decision problem today, so it requires flexible and analytic decision tools for investors. For this task, the Analytic Hierarchy Process (AHP) is suitable. We propose a theoretical model to analyse an investment choice problem taking into account different financial markets. Return of stock market, performance of the government bond and calendar effects in the financial markets considered are the evaluation criteria used in our model. The proposed model has strengths and weaknesses. First, through the AHP methodology the problem can be decomposed into a dominance hierarchy. Then, the subjective judgements expressed by means of pairwise comparisons are cheked in order to verify their consistency. Moreover, it is flexible and allows us to check if the ranking changes based on varying criteria weights. However, in that model we assume that criteria and alternatives are independent. Furthermore, our research lacks of a numerical application to test the model. |
def convertFastaToDict(fastaFile):
if isinstance(fastaFile, list):
files = fastaFile
else:
files = [fastaFile]
currentName = None
currentSequence = None
seqDict = {}
for currentFile in files:
if currentFile.endswith('.gz'):
f = gzip.open(currentFile)
else:
f = open(currentFile)
for line in f:
if not line.strip() == '' and not line.startswith('#'):
if line.startswith('>'):
if not currentName == None:
seqDict[currentName] = currentSequence
currentName = line.strip()[1:].split()[
0]
currentSequence = ''
else:
currentSequence += line.strip()
f.close()
seqDict[currentName] = currentSequence
return seqDict |
/**
* Represent a send work request. Applications create work request and post them onto queue pairs for execution.
*
* Each work request is composed of several scatter/gather elements, each of which referring to one single buffer.
*/
public class IbvSendWR {
public enum IbvWrOcode {
IBV_WR_RDMA_WRITE, IBV_WR_RDMA_WRITE_WITH_IMM, IBV_WR_SEND, IBV_WR_SEND_WITH_IMM, IBV_WR_RDMA_READ, IBV_WR_ATOMIC_CMP_AND_SWP, IBV_WR_ATOMIC_FETCH_AND_ADD
};
public static final int IBV_WR_RDMA_WRITE = 0;
public static final int IBV_WR_RDMA_WRITE_WITH_IMM = 1;
public static final int IBV_WR_SEND = 2;
public static final int IBV_WR_SEND_WITH_IMM = 3;
public static final int IBV_WR_RDMA_READ = 4;
public static final int IBV_WR_ATOMIC_CMP_AND_SWP = 5;
public static final int IBV_WR_ATOMIC_FETCH_AND_ADD = 6;
public static int IBV_SEND_FENCE = 1 << 0;
public static int IBV_SEND_SIGNALED = 1 << 1;
public static int IBV_SEND_SOLICITED = 1 << 2;
public static int IBV_SEND_INLINE = 1 << 3;
protected long wr_id;
protected LinkedList<IbvSge> sg_list;
protected int num_sge;
protected int opcode;
protected int send_flags;
protected int imm_data; /* in network byte order */
protected Rdma rdma;
protected Atomic atomic;
protected Ud ud;
public IbvSendWR() {
rdma = new Rdma();
atomic = new Atomic();
ud = new Ud();
sg_list = new LinkedList<IbvSge>();
}
protected IbvSendWR(Rdma rdma, Atomic atomic, Ud ud, LinkedList<IbvSge> sg_list) {
this.rdma = rdma;
this.atomic = atomic;
this.ud = ud;
this.sg_list = sg_list;
}
/**
* A unique identifier for this work request. A subsequent completion event will have a matching id.
*
* @return the wr_id
*/
public long getWr_id() {
return wr_id;
}
/**
* Allows setting the work request identifier. A subsequent completion event will have a matching id.
*
* @param wr_id the new wr_id
*/
public void setWr_id(long wr_id) {
this.wr_id = wr_id;
}
/**
* Gets the scatter/gather elements of this work request. Each scatter/gather element refers to one single buffer.
*
* @return the sg_list
*/
public LinkedList<IbvSge> getSg_list() {
return sg_list;
}
/**
* Gets a specific scatter/gather element of this work request.
*
* @return the sg element
*/
public IbvSge getSge(int index){
return sg_list.get(index);
}
/**
* Sets the scatter/gather elements of this work request. Each scatter/gather element refers to one single buffer.
*
* @param sg_list the new sg_list
*/
public void setSg_list(LinkedList<IbvSge> sg_list) {
this.sg_list.clear();
this.sg_list.addAll(sg_list);
this.num_sge = sg_list.size();
}
/**
* The number of scatter/gather elements in this work request.
*
* @return the num_sge
*/
public int getNum_sge() {
return num_sge;
}
/**
* Unsupported.
*
* @param num_sge the new num_sge
*/
public void setNum_sge(int num_sge) {
this.num_sge = num_sge;
}
/**
* Returns the opcode of this work request.
*
* A opcode can be either IBV_WR_RDMA_WRITE, IBV_WR_SEND, or IBV_WR_RDMA_READ.
*
* @return the opcode
*/
public int getOpcode() {
return opcode;
}
/**
* Returns the opcode of this work request.
*
* A opcode can be either IBV_WR_RDMA_WRITE, IBV_WR_SEND, or IBV_WR_RDMA_READ.
*
* @param opcode the new opcode
*/
public void setOpcode(int opcode) {
this.opcode = opcode;
}
/**
* Gets the send flags for this work request. Unsupported.
*
* @return the send_flags
*/
public int getSend_flags() {
return send_flags;
}
/**
* Sets the send flags for this work request. Unsupported.
*
* @param send_flags the new send_flags
*/
public void setSend_flags(int send_flags) {
this.send_flags = send_flags;
}
/**
* Unsupported.
*
* @return the imm_data
*/
public int getImm_data() {
return imm_data;
}
/**
* Unsupported.
*
* @param imm_data the new imm_data
*/
public void setImm_data(int imm_data) {
this.imm_data = imm_data;
}
/**
* Gets the RDMA section of of this work request.
*
* The RDMA part is required for one sided-operations such as IBV_WR_RDMA_WRITE, or IBV_WR_RDMA_READ.
*
* @return the rdma
*/
public Rdma getRdma() {
return rdma;
}
/**
* Unsupported.
*
* @return the atomic
*/
public Atomic getAtomic() {
return atomic;
}
/**
* Unsupported.
*
* @return the ud
*/
public Ud getUd() {
return ud;
}
/**
* Specifies the remote buffer to be used in READ or WRITE operations.
*/
public static class Rdma {
protected long remote_addr;
protected int rkey;
protected int reserved;
public Rdma() {
}
/**
* Gets the address of the remote buffer;
*
* @return the remote_addr
*/
public long getRemote_addr() {
return remote_addr;
}
/**
* Sets the address of the remote buffer;
*
* @param remote_addr the new remote_addr
*/
public void setRemote_addr(long remote_addr) {
this.remote_addr = remote_addr;
}
/**
* Gets the key of the remote buffer;
*
* @return the rkey
*/
public int getRkey() {
return rkey;
}
/**
* Sets the key of the remote buffer;
*
* @param rkey the new rkey
*/
public void setRkey(int rkey) {
this.rkey = rkey;
}
/**
* Unsupported.
*
* @return the reserved
*/
public int getReserved() {
return reserved;
}
/**
* Unsupported.
*
* @param reserved the new reserved
*/
public void setReserved(int reserved) {
this.reserved = reserved;
}
public String getClassName() {
return Rdma.class.getCanonicalName();
}
}
/**
* Unsupported.
*/
public static class Atomic {
protected long remote_addr;
protected long compare_add;
protected long swap;
protected int rkey;
protected int reserved;
public Atomic() {
}
public long getRemote_addr() {
return remote_addr;
}
public void setRemote_addr(long remote_addr) {
this.remote_addr = remote_addr;
}
public long getCompare_add() {
return compare_add;
}
public void setCompare_add(long compare_add) {
this.compare_add = compare_add;
}
public long getSwap() {
return swap;
}
public void setSwap(long swap) {
this.swap = swap;
}
public int getRkey() {
return rkey;
}
public void setRkey(int rkey) {
this.rkey = rkey;
}
public int getReserved() {
return reserved;
}
public void setReserved(int reserved) {
this.reserved = reserved;
}
public String getClassName() {
return Atomic.class.getCanonicalName();
}
}
/**
* Unsupported.
*/
public static class Ud {
protected int ah; // 24
protected int remote_qpn; // 28
protected int remote_qkey; // 32
protected int reserved; // 36
public Ud() {
}
public int getAh() {
return ah;
}
public void setAh(int ah) {
this.ah = ah;
}
public int getRemote_qpn() {
return remote_qpn;
}
public void setRemote_qpn(int remote_qpn) {
this.remote_qpn = remote_qpn;
}
public int getRemote_qkey() {
return remote_qkey;
}
public void setRemote_qkey(int remote_qkey) {
this.remote_qkey = remote_qkey;
}
public int getReserved() {
return reserved;
}
public void setReserved(int reserved) {
this.reserved = reserved;
}
public String getClassName() {
return Ud.class.getCanonicalName();
}
}
} |
package com.zoctan.api.controller.admin;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoctan.api.core.jwt.JwtUtil;
import com.zoctan.api.core.response.Result;
import com.zoctan.api.core.response.ResultGenerator;
import com.zoctan.api.model.User;
import com.zoctan.api.service.UserService;
import com.zoctan.api.service.impl.UserDetailsServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.security.Principal;
import java.util.List;
/**
* @author Zoctan
* @date 2018/06/09
*/
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
@Resource
private UserService userService;
@Resource
private UserDetailsServiceImpl userDetailsService;
@Resource
private JwtUtil jwtUtil;
@PostMapping
public Result register(@RequestBody @Valid final User user,
final BindingResult bindingResult) {
// {"username":"123456", "password":"<PASSWORD>", "email": "<EMAIL>"}
if (bindingResult.hasErrors()) {
//noinspection ConstantConditions
final String msg = bindingResult.getFieldError().getDefaultMessage();
return ResultGenerator.genFailedResult(msg);
} else {
this.userService.save(user);
return this.getToken(user);
}
}
@PreAuthorize("hasAuthority('user:delete')")
@DeleteMapping("/{id}")
public Result delete(@PathVariable final Long id) {
this.userService.deleteById(id);
return ResultGenerator.genOkResult();
}
@PostMapping("/password")
public Result validatePassword(@RequestBody final User user) {
final User oldUser = this.userService.findById(user.getId());
final boolean isValidate = this.userService.verifyPassword(user.getPassword(), oldUser.getPassword());
return ResultGenerator.genOkResult(isValidate);
}
@PutMapping
public Result update(@RequestBody final User user) {
this.userService.update(user);
return this.getToken(this.userService.findById(user.getId()));
}
@GetMapping("/{id}")
public Result detail(@PathVariable final Long id) {
final User user = this.userService.findById(id);
return ResultGenerator.genOkResult(user);
}
@GetMapping("/info")
public Result info(final Principal user) {
final User userDB = this.userService.findDetailByUsername(user.getName());
return ResultGenerator.genOkResult(userDB);
}
@GetMapping("/userInfo")
public Result userInfo(final Principal user) {
User userDB = this.userService.findDetailBy("username", user.getName());
if (userDB!=null){
userDB.setPassword(null);
}
return ResultGenerator.genOkResult(userDB);
}
@PreAuthorize("hasAuthority('user:list')")
@GetMapping
public Result list(@RequestParam(defaultValue = "0") final Integer page,
@RequestParam(defaultValue = "0") final Integer size) {
PageHelper.startPage(page, size);
final List<User> list = this.userService.findAllUserWithRole();
//noinspection unchecked
final PageInfo pageInfo = new PageInfo(list);
return ResultGenerator.genOkResult(pageInfo);
}
@PostMapping("/login")
public Result login(@RequestBody final User user) {
// {"username":"admin", "password":"<PASSWORD>"}
// {"email":"<EMAIL>", "password":"<PASSWORD>"}
if (user.getUsername() == null && user.getEmail() == null) {
return ResultGenerator.genFailedResult("username or email empty");
}
if (user.getPassword() == null) {
return ResultGenerator.genFailedResult("password empty");
}
// 用户名登录
User dbUser = null;
if (user.getUsername() != null) {
dbUser = this.userService.findBy("username", user.getUsername());
if (dbUser == null) {
return ResultGenerator.genFailedResult("username error");
}
}
// 邮箱登录
if (user.getEmail() != null) {
dbUser = this.userService.findBy("email", user.getEmail());
if (dbUser == null) {
return ResultGenerator.genFailedResult("email error");
}
user.setUsername(dbUser.getUsername());
}
// 验证密码
//noinspection ConstantConditions
if (!this.userService.verifyPassword(user.getPassword(), dbUser.getPassword())) {
return ResultGenerator.genFailedResult("password error");
}
// 更新登录时间
this.userService.updateLoginTimeByUsername(user.getUsername());
return this.getToken(user);
}
@GetMapping("/logout")
public Result logout(final Principal user) {
return ResultGenerator.genOkResult();
}
/**
* 获得 token
*/
private Result getToken(final User user) {
final String username = user.getUsername();
final UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
final String token = this.jwtUtil.sign(username, userDetails.getAuthorities());
return ResultGenerator.genOkResult(token);
}
}
|
<reponame>kokonafang/FlexibleTransition<filename>FlexibleTransition/FlexibleTransition/Utils/DynamicItem.h
//
// DinamicItem.h
// FlexibleTransition
//
// Created by fang on 11/02/16.
// Copyright © 2016 fang. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DynamicItem : NSObject <UIDynamicItem>
@property(nonatomic, readwrite) CGRect bounds;
@property(nonatomic, readwrite) CGPoint center;
@property(nonatomic, readwrite) CGAffineTransform transform;
- (id)initWithCenter:(CGPoint) center;
@end
|
United kingdom: the prime minister and parliament This article examines the notion of prime ministerial accountability in the United Kingdom. It starts with an examination of the concept of accountability and discusses the role of parliament in holding the prime minister to account. The decline in the power of legislatures is outlined and the particular features that contribute to executive dominance in the UK parliament are examined. This leads into an historical overview of the relationship between parliament and prime minister, with special reference to the post-1945 period. The various factors affecting that relationship are considered, of which personality is but one, and it is argued, increasingly not the most significant. |
package kasa
import (
"bytes"
"encoding/hex"
// "encoding/json"
"fmt"
"github.com/brutella/hc/accessory"
"github.com/brutella/hc/characteristic"
"github.com/brutella/hc/log"
// "github.com/brutella/hc/util"
tfaccessory "github.com/cloudkucooland/toofar/accessory"
"github.com/cloudkucooland/toofar/config"
"github.com/cloudkucooland/toofar/devices"
"github.com/cloudkucooland/toofar/homecontrol"
"github.com/cloudkucooland/toofar/platform"
"net"
"sync"
"time"
)
// https://www.softscheck.com/en/reverse-engineering-tp-link-hs110/#TP-Link%20Smart%20Home%20Protocol
// https://medium.com/@hu3vjeen/reverse-engineering-tp-link-kc100-bac4641bf1cd
// https://machinekoder.com/controlling-tp-link-hs100110-smart-plugs-with-machinekit/
// https://lib.dr.iastate.edu/cgi/viewcontent.cgi?article=1424&context=creativecomponents
// ahttps://github.com/p-doyle/Python-KasaSmartPowerStrip
// see if we can support these...
// https://github.com/brutella/hc/blob/master/characteristic/program_mode.go
// https://github.com/brutella/hc/blob/master/characteristic/set_duration.go
// https://github.com/brutella/hc/blob/master/characteristic/remaining_duration.go
const (
cmd_sysinfo = `{"system":{"get_sysinfo":{}}}`
cmd_countdown = `{"count_down":{"get_rules":{}}}`
)
// Platform is the platform handle for the Kasa stuff
type Platform struct {
Running bool
}
type kmu struct {
mu sync.Mutex
ks map[string]*tfaccessory.TFAccessory
ignore map[string]bool
}
var kasas kmu
var kasaUDPconn *net.UDPConn
// Startup is called by the platform management to start the platform up
func (k Platform) Startup(c *config.Config) platform.Control {
kasas.ks = make(map[string]*tfaccessory.TFAccessory)
kasas.ignore = make(map[string]bool)
udpl, err := net.ListenUDP("udp", &net.UDPAddr{IP: nil, Port: 9999})
if err != nil {
log.Info.Printf("unable to start kasa UDP listener: %s", err.Error())
return k
}
kasaUDPconn = udpl
go func() {
buffer := make([]byte, 1024)
log.Info.Println("starting kasa UDP listener")
for {
n, addr, err := kasaUDPconn.ReadFromUDP(buffer)
if err != nil {
log.Info.Println(err.Error())
break
}
res := decrypt(buffer[0:n])
doUDPresponse(addr.IP.String(), res)
}
// return
}()
broadcastCmd(cmd_sysinfo, 3)
k.Running = true
return k
}
// Shutdown is called by the platform management to shut things down
func (k Platform) Shutdown() platform.Control {
k.Running = false
return k
}
// AddAccessory adds a Kasa device, pulls it for info, then adds it to HC
func (k Platform) AddAccessory(a *tfaccessory.TFAccessory) {
hc, ok := platform.GetPlatform("HomeControl")
if !ok {
log.Info.Println("can't add accessory, HomeControl platform does not yet exist")
return
}
_, ok = k.GetAccessory(a.IP)
if ok {
log.Info.Printf("already have a device with this IP address: %s", a.IP)
return
}
// override the config file with reality
settings, err := getSettingsTCP(a)
if err != nil {
log.Info.Printf("unable to identify kasa device, skipping: %s", err.Error())
kasas.ignore[a.IP] = true
return
}
a.Info.Name = settings.Alias
a.Info.SerialNumber = settings.DeviceID
a.Info.Manufacturer = "TP-Link"
a.Info.Model = settings.Model
a.Info.FirmwareRevision = settings.SWVersion
// convert 12 chars of the deviceId into a uint64 for the ID
mac, err := hex.DecodeString(settings.DeviceID[:12])
if err != nil {
log.Info.Printf("weird kasa devid: %s", err.Error())
}
for k, v := range mac {
a.Info.ID += uint64(v) << (12 - k) * 8
}
switch settings.Model {
case "KP303(US)":
a.Type = accessory.TypeSwitch
kp := devices.NewKP303(a.Info)
a.Device = kp
a.Accessory = kp.Accessory
case "HS200(US)", "HS210(US)":
a.Type = accessory.TypeSwitch
d := devices.NewHS200(a.Info)
a.Device = d
a.Accessory = d.Accessory
case "HS103(US)":
a.Type = accessory.TypeSwitch
d := devices.NewHS103(a.Info)
a.Device = d
a.Accessory = d.Accessory
case "KP115(US)":
a.Type = accessory.TypeSwitch
d := devices.NewKP115(a.Info)
a.Device = d
a.Accessory = d.Accessory
case "HS220(US)":
a.Type = accessory.TypeLightbulb
hs := devices.NewHS220(a.Info)
a.Device = hs
a.Accessory = hs.Accessory
}
log.Info.Printf("adding %s: %s (%s)", a.IP, a.Info.Name, a.Info.Model)
// add to HC for GUI
hc.AddAccessory(a)
a.Accessory.Info.Name.OnValueRemoteUpdate(func(newname string) {
log.Info.Print("setting alias to [%s]", newname)
err := setRelayAlias(a, newname)
if err != nil {
log.Info.Println(err.Error())
return
}
})
// kasas are indexed by IP address
kasas.mu.Lock()
kasas.ks[a.IP] = a
kasas.mu.Unlock()
switch a.Device.(type) {
case *accessory.Switch:
// startup value
sw := a.Device.(*accessory.Switch)
sw.Switch.On.SetValue(settings.RelayState > 0)
// install callbacks: if we get an update from HC, deal with it
sw.Switch.On.OnValueRemoteUpdate(func(newstate bool) {
log.Info.Printf("setting [%s] to [%t] from Kasa generic switch handler", a.Info.Name, newstate)
err := setRelayState(a, newstate)
if err != nil {
log.Info.Println(err.Error())
return
}
})
case *devices.HS200: // and 210
sw := a.Device.(*devices.HS200)
sw.Switch.On.SetValue(settings.RelayState > 0)
sw.Switch.On.OnValueRemoteUpdate(func(newstate bool) {
log.Info.Printf("setting [%s] to [%t] from HS200 handler", a.Info.Name, newstate)
err := setRelayState(a, newstate)
if err != nil {
log.Info.Println(err.Error())
return
}
})
case *devices.KP115:
kp := a.Device.(*devices.KP115)
kp.Outlet.On.SetValue(settings.RelayState > 0)
kp.Outlet.OutletInUse.SetValue(settings.RelayState > 0)
kp.Outlet.On.OnValueRemoteUpdate(func(newstate bool) {
log.Info.Printf("setting [%s] to [%t] from KP115 handler", a.Info.Name, newstate)
err := setRelayState(a, newstate)
if err != nil {
log.Info.Println(err.Error())
return
}
kp.Outlet.OutletInUse.SetValue(newstate)
})
case *devices.HS103:
hs := a.Device.(*devices.HS103)
hs.Outlet.On.SetValue(settings.RelayState > 0)
hs.Outlet.OutletInUse.SetValue(settings.RelayState > 0)
hs.Outlet.On.OnValueRemoteUpdate(func(newstate bool) {
log.Info.Printf("setting [%s] to [%t] from HS103 handler", a.Info.Name, newstate)
err := setRelayState(a, newstate)
if err != nil {
log.Info.Println(err.Error())
return
}
hs.Outlet.OutletInUse.SetValue(newstate)
})
case *devices.HS220:
hs := a.Device.(*devices.HS220)
hs.Lightbulb.On.SetValue(settings.RelayState > 0)
hs.Lightbulb.On.OnValueRemoteUpdate(func(newstate bool) {
log.Info.Printf("setting [%s] to [%t] from HS220 handler", a.Info.Name, newstate)
err := setRelayState(a, newstate)
if err != nil {
log.Info.Println(err.Error())
return
}
})
hs.Lightbulb.Brightness.SetValue(settings.Brightness)
hs.Lightbulb.Brightness.OnValueRemoteUpdate(func(newval int) {
log.Info.Printf("setting [%s] brightness [%d] from HS220 handler", a.Info.Name, newval)
err := setBrightness(a, newval)
if err != nil {
log.Info.Println(err.Error())
return
}
})
hs.Lightbulb.SetDuration.OnValueRemoteUpdate(func(newval int) {
if hs.Lightbulb.ProgramMode.GetValue() != characteristic.ProgramModeNoProgramScheduled {
log.Info.Println("a countdown is already active, ignoring request")
return
}
log.Info.Println("setting up countdown action")
current := hs.Lightbulb.On.GetValue()
err := setProgramState(a, !current, newval)
if err != nil {
log.Info.Println(err.Error())
return
}
hs.Lightbulb.ProgramMode.SetValue(characteristic.ProgramModeProgramScheduled)
})
case *devices.KP303:
kp := a.Device.(*devices.KP303)
for i := 0; i < len(kp.Outlets); i++ {
n := characteristic.NewName()
n.SetValue(settings.Children[i].Alias)
outlet := kp.Outlets[i]
outlet.AddCharacteristic(n.Characteristic)
l := i // local-only copy for this func
n.OnValueRemoteUpdate(func(newname string) {
log.Info.Print("setting alias to [%s]", newname)
err := setChildRelayAlias(a, settings.Children[l].ID, newname)
if err != nil {
log.Info.Println(err.Error())
return
}
})
outlet.On.SetValue(settings.Children[i].RelayState > 0)
outlet.OutletInUse.SetValue(settings.Children[i].RelayState > 0)
outlet.On.OnValueRemoteUpdate(func(newstate bool) {
log.Info.Printf("setting [%s].[%d] to [%t] from KP303 handler", a.Info.Name, l, newstate)
err := setChildRelayState(a, settings.Children[l].ID, newstate)
if err != nil {
log.Info.Println(err.Error())
return
}
})
}
}
if hc.(tfhc.HCPlatform).Running {
log.Info.Println("restarting HomeControl")
hc.(tfhc.HCPlatform).Restart()
}
}
func setRelayState(a *tfaccessory.TFAccessory, newstate bool) error {
state := 0
if newstate {
state = 1
}
cmd := fmt.Sprintf(`{"system":{"set_relay_state":{"state":%d}}}`, state)
err := sendUDP(a.IP, cmd)
if err != nil {
log.Info.Println(err.Error())
return err
}
return nil
}
func setChildRelayState(a *tfaccessory.TFAccessory, childID string, newstate bool) error {
state := 0
if newstate {
state = 1
}
cmd := fmt.Sprintf(`{"context":{"child_ids":["%s"]},"system":{"set_relay_state":{"state":%d}}}`, childID, state)
err := sendUDP(a.IP, cmd)
if err != nil {
log.Info.Println(err.Error())
return err
}
return nil
}
func setProgramState(a *tfaccessory.TFAccessory, target bool, t int) error {
err := sendUDP(a.IP, `{"count_down":{"get_rules":{}}}`)
if err != nil {
log.Info.Println(err.Error())
return err
}
var state uint8
if target {
state = 1
}
cmd := fmt.Sprintf(`{"count_down":{"add_rule":{"enable":1,"delay":%d,"act":%d,"name":"TooFar"}}}`, t, state)
err = sendUDP(a.IP, cmd)
if err != nil {
log.Info.Println(err.Error())
return err
}
return nil
}
func deleteCountdown(a *tfaccessory.TFAccessory) error {
err := sendUDP(a.IP, `{"count_down":{"delete_all_rules":{}}}`)
if err != nil {
log.Info.Println(err.Error())
return err
}
return nil
}
func setRelayAlias(a *tfaccessory.TFAccessory, newname string) error {
cmd := fmt.Sprintf(`{"system":{"set_alias":{"alias":"%s"}}}`, newname)
err := sendUDP(a.IP, cmd)
if err != nil {
log.Info.Println(err.Error())
return err
}
return nil
}
func setChildRelayAlias(a *tfaccessory.TFAccessory, childID string, newname string) error {
cmd := fmt.Sprintf(`{"context":{"child_ids":["%s"]},"system":{"set_alias":{"alias":"%s"}}}`, childID, newname)
err := sendUDP(a.IP, cmd)
if err != nil {
log.Info.Println(err.Error())
return err
}
return nil
}
func setBrightness(a *tfaccessory.TFAccessory, newval int) error {
cmd := fmt.Sprintf(`{"smartlife.iot.dimmer":{"set_brightness":{"brightness":%d}}}`, newval)
err := sendUDP(a.IP, cmd)
if err != nil {
log.Info.Println(err.Error())
return err
}
return nil
}
// GetAccessory looks up a Kasa device by IP address
func (k Platform) GetAccessory(ip string) (*tfaccessory.TFAccessory, bool) {
kasas.mu.Lock()
val, ok := kasas.ks[ip]
kasas.mu.Unlock()
return val, ok
}
func getSettingBroadcast() error {
return broadcastCmd(cmd_sysinfo, 1)
}
func getCountdownBroadcast() error {
return broadcastCmd(cmd_countdown, 1)
}
func broadcastCmd(cmd string, broadcast_sends int) error {
bcast, err := broadcastAddresses()
if err != nil {
return err
}
for i := 0; i < broadcast_sends; i++ {
for _, b := range bcast {
err := sendUDP(b.String(), cmd)
if err != nil {
log.Info.Println(err.Error())
return err
}
}
time.Sleep(time.Second)
}
return nil
}
// Background runs a background Go task verifying HC has the current state of the Kasa devices
func (k Platform) Background() {
kpr := config.Get().KasaPullRate
if kpr == 0 {
log.Info.Println("KasaPullRate is 0, disabling checks")
return
}
go func() {
for range time.Tick(time.Second * time.Duration(kpr)) {
getSettingBroadcast()
getCountdownBroadcast()
}
}()
}
func encrypt(plaintext string) []byte {
n := len(plaintext)
buf := new(bytes.Buffer)
ciphertext := []byte(buf.Bytes())
key := byte(0xAB)
payload := make([]byte, n)
for i := 0; i < n; i++ {
payload[i] = plaintext[i] ^ key
key = payload[i]
}
for i := 0; i < len(payload); i++ {
ciphertext = append(ciphertext, payload[i])
}
return ciphertext
}
func decrypt(ciphertext []byte) string {
n := len(ciphertext)
key := byte(0xAB)
var nextKey byte
for i := 0; i < n; i++ {
nextKey = ciphertext[i]
ciphertext[i] = ciphertext[i] ^ key
key = nextKey
}
return string(ciphertext)
}
// sendUDP sends the command and does not wait for any response.
// Responses are handled by the listener thread.
func sendUDP(ip string, cmd string) error {
if kasaUDPconn == nil {
return fmt.Errorf("udp conn not running")
}
repeats := config.Get().KasaBroadcasts
// unset, 0 (misconfigured) or 1 sends 1 packet
if repeats < 1 {
repeats = 1
}
payload := encrypt(cmd)
for i := uint8(0); i < repeats; i++ {
_, err := kasaUDPconn.WriteToUDP(payload, &net.UDPAddr{IP: net.ParseIP(ip), Port: 9999})
if err != nil {
log.Info.Printf("cannot send UDP command: %s", err.Error())
return err
}
}
return nil
}
|
Effects of Bicarbonate Ingestion on Leg Strength and Power During Isokinetic Knee Flexion and Extension The aim of this experiment was to determine whether sodium bicarbonate ingestion of a 300 mg kg−1 body mass dose improved either total work or peak torque values during isokinetic leg ext/flex exercise in 9 healthy male subjects using a Cybex 340 isokinetic dynamometer under control, alkalotic, and placebo conditions. Basal and pre- and postexercise arterialized venous blood samples were collected and analyzed for lactate, pH, partial pressure of O2 and CO2, base excess, and blood bicarbonate. Preexercise, the bicarbonate increased the blood pH levels, indicating a state of induced metabolic alkalosis. Postexercise in all conditions, blood pH was significantly lower than preexercise values, indicating that metabolic acidosis had occurred. The amount of work and peak torque completed in the control and placebo trials was not significantly different. During the experimental trial, however, more work was completed than in either the control or placebo conditions, and peak torque also increased. This suggests that bicarbonate could be used as an ergogenic aid during isokinetic work and enables the athlete to become more powerful. |
<gh_stars>1-10
package Le3;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class Solution {
public static void main(String[] args) {
// Solution solution=new Solution();
// System.out.println(solution.lengthOfLongestSubstring("abcabcbb"));
System.out.println(5/2);
}
public int lengthOfLongestSubstring(String s) {
if(!s.isEmpty()){
int length=s.length();
HashMap<Character,Integer> repeat=new LinkedHashMap<>();
int start=0,end=0;
int max=0;
while (end<length){
if(repeat.containsKey(s.charAt(end))){
int index=repeat.get(s.charAt(end))+1;
for (int i=start;i<index;i++){
repeat.remove(s.charAt(i));
}
start=index;
}else{
repeat.put(s.charAt(end),end);
max=Math.max(max,end-start+1);
end++;
}
}
return max;
}
return 0;
}
} |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/ui/search/search_ipc_router.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/mock_render_process_host.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_test_sink.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace {
class MockSearchIPCRouterDelegate : public SearchIPCRouter::Delegate {
public:
virtual ~MockSearchIPCRouterDelegate() {}
MOCK_METHOD1(OnInstantSupportDetermined, void(bool supports_instant));
MOCK_METHOD1(OnSetVoiceSearchSupport, void(bool supports_voice_search));
};
} // namespace
class SearchTabHelperTest : public ChromeRenderViewHostTestHarness {
public:
virtual void SetUp() {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableInstantExtendedAPI);
ChromeRenderViewHostTestHarness::SetUp();
SearchTabHelper::CreateForWebContents(web_contents());
}
bool MessageWasSent(uint32 id) {
return process()->sink().GetFirstMessageMatching(id) != NULL;
}
MockSearchIPCRouterDelegate* mock_delegate() { return &delegate_; }
private:
MockSearchIPCRouterDelegate delegate_;
};
TEST_F(SearchTabHelperTest, DetermineIfPageSupportsInstant_Local) {
NavigateAndCommit(GURL(chrome::kChromeSearchLocalNtpUrl));
EXPECT_CALL(*mock_delegate(), OnInstantSupportDetermined(true)).Times(0);
SearchTabHelper* search_tab_helper =
SearchTabHelper::FromWebContents(web_contents());
ASSERT_NE(static_cast<SearchTabHelper*>(NULL), search_tab_helper);
search_tab_helper->ipc_router().set_delegate(mock_delegate());
search_tab_helper->DetermineIfPageSupportsInstant();
}
TEST_F(SearchTabHelperTest, DetermineIfPageSupportsInstant_NonLocal) {
NavigateAndCommit(GURL("chrome-search://foo/bar"));
process()->sink().ClearMessages();
EXPECT_CALL(*mock_delegate(), OnInstantSupportDetermined(true)).Times(1);
SearchTabHelper* search_tab_helper =
SearchTabHelper::FromWebContents(web_contents());
ASSERT_NE(static_cast<SearchTabHelper*>(NULL), search_tab_helper);
search_tab_helper->ipc_router().set_delegate(mock_delegate());
search_tab_helper->DetermineIfPageSupportsInstant();
ASSERT_TRUE(MessageWasSent(ChromeViewMsg_DetermineIfPageSupportsInstant::ID));
scoped_ptr<IPC::Message> response(
new ChromeViewHostMsg_InstantSupportDetermined(
web_contents()->GetRoutingID(),
web_contents()->GetController().GetVisibleEntry()->GetPageID(),
true));
search_tab_helper->ipc_router().OnMessageReceived(*response);
}
TEST_F(SearchTabHelperTest, PageURLDoesntBelongToInstantRenderer) {
// Navigate to a page URL that doesn't belong to Instant renderer.
// SearchTabHelper::DeterminerIfPageSupportsInstant() should return
// immediately without dispatching any message to the renderer.
NavigateAndCommit(GURL("http://www.example.com"));
process()->sink().ClearMessages();
EXPECT_CALL(*mock_delegate(), OnInstantSupportDetermined(false)).Times(0);
SearchTabHelper* search_tab_helper =
SearchTabHelper::FromWebContents(web_contents());
ASSERT_NE(static_cast<SearchTabHelper*>(NULL), search_tab_helper);
search_tab_helper->ipc_router().set_delegate(mock_delegate());
search_tab_helper->DetermineIfPageSupportsInstant();
ASSERT_FALSE(MessageWasSent(
ChromeViewMsg_DetermineIfPageSupportsInstant::ID));
}
|
Review of the status of LiNbO3 devices and technologies In this paper, we review LiNbO3-based devices and technologies from both materials and device processing techniques. However, all the relevant areas cannot possibly be covered; we limit the scope of the paper to electrooptic devices. Also, we mostly focus on our own activities at Sumitomo Metal Mining. First, materials-related issues such as the uniformity and consistency of the substrate crystal as assessed by the variability of directional coupler coupling length are summarized. The photorefractive damage resistance is also reviewed; the dependence on the substrate quality and input laser wavelength. Second, taking the case of the multi-function gyro chip, we review and discuss the use of both Ti-indiffused and proton- exchanged waveguides on a single chip. |
/***********************************************************************************************
* IsInitialIsm *
*--------------*
* Description:
* Checks the next token in the text stream to determine if it is an initialism. Also
* tries to determine whether or not the period at the end of the initialism is the end of
* the sentence.
*
* If match made:
* Advances m_pNextChar to the appropriate position (either the period at the end of the
* abbreviation, or just past that period). Sets the Item in the ItemList at ItemPos to the
* abbreviation.
*
********************************************************************* AH **********************/
HRESULT CStdSentEnum::IsInitialism( CItemList &ItemList, SPLISTPOS ItemPos, CSentItemMemory &MemoryManager,
BOOL* pfIsEOS )
{
SPDBG_FUNC( "CStdSentEnum::IsInitialism" );
HRESULT hr = S_OK;
BOOL fMatchedEOS = false;
if ( (long)(m_pEndOfCurrItem - m_pNextChar) < 4 )
{
hr = E_INVALIDARG;
}
else
{
const WCHAR *pIterator = NULL;
ULONG ulCount = 0;
pIterator = m_pNextChar;
while ( SUCCEEDED(hr) &&
pIterator <= m_pEndOfCurrItem - 2)
{
if ( !iswalpha(*pIterator) ||
*(pIterator + 1) != L'.' )
{
hr = E_INVALIDARG;
}
else
{
pIterator += 2;
ulCount++;
}
}
if ( SUCCEEDED( hr ) &&
!(*pfIsEOS) )
{
const WCHAR *pTempNextChar = m_pEndOfCurrToken, *pTempEndChar = m_pEndChar;
const SPVTEXTFRAG *pTempCurrFrag = m_pCurrFrag;
hr = SkipWhiteSpaceAndTags( pTempNextChar, pTempEndChar, pTempCurrFrag, MemoryManager );
if ( SUCCEEDED( hr ) )
{
if ( !pTempNextChar )
{
*pfIsEOS = true;
fMatchedEOS = true;
}
else if ( IsCapital( *pTempNextChar ) )
{
WCHAR *pTempEndOfItem = (WCHAR*) FindTokenEnd( pTempNextChar, pTempEndChar );
WCHAR temp = (WCHAR) *pTempEndOfItem;
*pTempEndOfItem = 0;
if ( bsearch( (void*) pTempNextChar, (void*) g_FirstWords, sp_countof( g_FirstWords ),
sizeof( SPLSTR ), CompareStringAndSPLSTR ) )
{
*pfIsEOS = true;
fMatchedEOS = true;
}
*pTempEndOfItem = temp;
}
}
}
if ( SUCCEEDED(hr) )
{
CSentItem Item;
Item.pItemSrcText = m_pNextChar;
Item.ulItemSrcLen = (long)(m_pEndOfCurrItem - m_pNextChar);
Item.ulItemSrcOffset = m_pCurrFrag->ulTextSrcOffset +
(long)( m_pNextChar - m_pCurrFrag->pTextStart );
Item.ulNumWords = ulCount;
Item.Words = (TTSWord*) MemoryManager.GetMemory( ulCount * sizeof(TTSWord), &hr );
if ( SUCCEEDED( hr ) )
{
SPVSTATE* pNewState = (SPVSTATE*) MemoryManager.GetMemory( sizeof( SPVSTATE ), &hr );
if ( SUCCEEDED( hr ) )
{
memcpy( pNewState, &m_pCurrFrag->State, sizeof( SPVSTATE ) );
pNewState->ePartOfSpeech = SPPS_Noun;
ZeroMemory( Item.Words, ulCount * sizeof(TTSWord) );
for ( ULONG i = 0; i < ulCount; i++ )
{
Item.Words[i].pXmlState = pNewState;
Item.Words[i].pWordText = &Item.pItemSrcText[ 2 * i ];
Item.Words[i].ulWordLen = 1;
Item.Words[i].pLemma = Item.Words[i].pWordText;
Item.Words[i].ulLemmaLen = Item.Words[i].ulWordLen;
}
Item.pItemInfo = (TTSItemInfo*) MemoryManager.GetMemory( sizeof(TTSItemInfo), &hr );
if ( SUCCEEDED( hr ) )
{
Item.pItemInfo->Type = eINITIALISM;
ItemList.SetAt( ItemPos, Item );
}
}
}
}
}
return hr;
} |
#####################################
import atexit, io, sys, collections
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write(): sys.__stdout__.write(buffer.getvalue())
#####################################
import collections, math
def f(s):
cc = collections.Counter()
ones = collections.Counter(s)[1]
r = [str(e) for e in s if e != 1]
if '2' not in r:
return ''.join(r) + ''.join(['1' * ones])
else:
for i in range(len(r)):
if r[i] == '2':
break
r = r[:i] + ['1' * ones] +r[i:]
return ''.join(r)
print f(map(int, list(raw_input()))) |
/**
* adds all points of all all cellt found to be at the specified frame
* @param frame
*/
public void addToOverlay(int frame) {
for (int i=0;i<allCells.size();i++) {
Cell c= allCells.get(i);
CellT ct = c.getCellTAt(frame);
if (ct!=null) {
addToOverlay(ct);
}
}
} |
def test_yield():
print('start')
yield 1
print('after')
ty = test_yield()
next(ty)
next(ty)
# start
# after
# Traceback (most recent call last):
# File "D:\workspace\python\python-learning-notes\note32\test.py", line 8, in <module>
# next(ty)
# StopIteration |
Determinants of medication withdrawal strategy in the epilepsy monitoring unit SUMMARY Background. Video-EEG (VEEG) monitoring is a vital diagnostic tool, but there are no guidelines for withdrawal of antiepileptic drugs (AEDs). Aim. The main objectives of this study were to understand the different withdrawal strategies used in the EMU, how strategies are chosen, and the efficacy and safety of different withdrawal strategies in producing seizures. Materials and methods. We retrospectively analyzed 95 consecutive patients and measured time to first seizure, incidence of status epilepticus, and need for rescue medications. Results. We found that AED withdrawal strategies can be divided into four categories based on level of aggressiveness. The main factors which impacted choice of strategy was number of AEDs on admission and frequency of pre-admission seizures. Abrupt cessation of medications was correlated with longer time to first seizure compared to other methods (hazard ratio (HR) 0.36, 95% confidence interval (CI) 0.200.65, p = 0.0007). Patients remaining on medications had shorter time to first seizure (HR 2.98, 95% CI 1.227.24, p = 0.016). Withdrawal technique was not correlated with need for rescue medications (OR 5.0, 95% CI 0.7743, p = 0.20). No patients had status epilepticus in the study. Conclusions. Pre-admission seizure frequency and number of AEDs are the main factors which drive choice of withdrawal strategy on the epilepsy monitoring unit (EMU). Counterintuitively, least aggressive strategy is associated with highest risk of seizures. Results of this analysis suggest that disease factors, not choice of withdrawal strategy, determine seizure frequency on the EMU. |
<filename>.spout/utils/logger.ts
import Logger from 'that-logger';
export default new Logger({}); |
Agricultural Revamping via Major Capital Outlay: the Antidote to Food Insecurity Challenges in Nigeria Food insecurity in Nigeria has necessitated this study which emphasizes agricultural revamping as the antidote to the prevailing circumstance of food crisis in the country This study draws the attention of the present administration to the urgent need for significant capital investment in agriculture as a means to proffer a permanent solution to food insecurity in Nigeria This study employs literature review approach and discovers that the factors impeding food safety in Nigeria include farmers' lack of access to the credit facility, insufficient farmlands, security threat on farmers and farmers' lack of education However, relevant econometric techniques and statistical tools are specifically applied to examine the impact of government expenditure and agricultural output on food safety using a secondary source of data spanning from 2008 -2019 From the findings of this study, agricultural output has a considerable influence on food safety, but government expenditure on agriculture is yet to gain momentum in affecting adequate food production in the country Thus, this study concludes that there is an urgent need for the government to invest significantly in agriculture which serves as an antidote to food security challenges in Nigeria |
import logging
from devops_automation_infra.plugins import docker
from pytest_automation_infra.helpers import hardware_config
import tempfile
@hardware_config(hardware={"host": {}})
def test_docker(base_config):
temp = tempfile.NamedTemporaryFile(delete=True)
temp.write(b'Sasha king')
temp.flush()
logging.info("write somethinh to proxy container")
base_config.hosts.host.Docker.copy_file_to_container("automation_proxy", temp.name, "/tmp/test_file")
logging.info("Read from proxy container")
content = base_config.hosts.host.SSH.get_contents("/tmp/test_file")
assert content == b"Sasha king"
temp.close()
ids = base_config.hosts.host.Docker.container_ids_by_name("automation_proxy")
assert len(ids) == 1
|
Kathy Harvey said Anaheim officials did the right thing when they revamped the city’s fireworks program, even if it means her nonprofit could receive nothing.
Nonprofits will have until May 19 to turn in an application for a May 25 lottery to operate fireworks booths in the city. Eight nonprofits will be chosen in the new system, with another eight slots already earmarked for Anaheim high schools. Fireworks sales at the 16 stands will be allowed from June 28 to July 4.
The new process approved by the City Council last month replaces a two-year-old program that gave every Anaheim nonprofit a chance to participate, but brought in very little money for those charities.
The city had prohibited the sale and use of fireworks for nearly 30 years until voters in 2014 overturned the ban to allow the sale of so-called safe and sane fireworks such as sparklers, smoke balls, and fountain fireworks.
Under the former guidelines, Anaheim Arena Management – the operators of the Honda Center – handled the fireworks sale for the city with one mega booth at the Honda Center in exchange for a 60 percent cut of sales. (A second location in West Anaheim was added last year.) The other 30 percent went toward participating nonprofits, and 10 percent to the Anaheim Community Foundation. Anaheim Arena Management also pitched in a $40,000 donation for an annual fireworks show in Anaheim Hills, where fireworks remain prohibited because of wildfire dangers.
Many nonprofits and high school booster clubs found little payoff. For nonprofits to generate income, a customer needed to designate the group at the time of purchase for the charity to receive credit.
Last year, fireworks sales brought in $346,452. The 99 participating nonprofits split a $93,600 pot, another $34,600 went to the community foundation. According to city records, the top earner that wasn’t a high school was St. Boniface Church at $2,953. Fourteen nonprofits received less than $100.
The city will contribute $10,000 toward the annual fireworks show in Anaheim Hills, the community will need raise the rest.
“We handed out flyers, but there weren’t many local places for them to buy fireworks so we didn’t get much support,” said Harvey, whose organization received $1,419 last year.
Harvey said she’s looking forward to the lottery. She plans to turn in the application to operate a booth soon. |
Child Abuse A Review Article Any purposeful act of physical, emotional, or sexual abuse, including acts of neglect, done by a person responsible for the child's care has come to be known as child abuse. Violence against children, according to UNICEF, can take many forms "Neglect or negligent care, exploitation, and sexual assault are all examples of physical and mental abuse. Violence can occur in a variety of settings, including homes, schools, orphanages, residential care facilities, the streets, the workplace, jails, and other detention facilities." Such violence can disrupt a child's normal development, affecting their mental, physical, and social well-being. Abuse of a child might result in death in extreme situations. Child abuse and neglect are defined as "at a minimum, any recent act or failure to act on the part of a parent or caretaker that results in death, serious physical or emotional harm, sexual abuse or exploitation, or an act or failure to act that poses an imminent risk of serious harm" according to the Child Abuse Prevention and Treatment Act1. |
Negotiating and creating intercultural relations: Chinese immigrant children in New Zealand early childhood education centres A MULTIPLE-CASE STUDY INVESTIGATION of the experiences of eight Chinese immigrant children in New Zealand early childhood centres suggested that the immigrant children's learning experiences in their first centre can be understood as a process of negotiating and creating intercultural relations. The children's use of family cultural tools, such as the Chinese language, was a distinctive feature of their learning experiences, simultaneously revealing and extending their exploration of the intercultural practices and their establishment of a sense of belonging. In the presence of Chinese-speaking peers who acted as bridges' and boundary objects, the Chinese language was actively used by the immigrant children in English-speaking early childhood centres and, as a result, they created intercultural relations which: (i) bridged the two cultures; (ii) brought the cultures into convergence; (iii) enabled the children to claim group identity; and (iv) battled intercultural constraints. The absence of Chinese speakers, on the other hand, constrained possibilities for intercultural relations. The focus on intercultural relations in this study is expected to lead to educational initiatives to support the incorporation of diverse cultures in early childhood services. |
import { CreateUserDto } from './create-user.dto';
import { Score } from '../../score/entities/score.entity';
declare const UpdateUserDto_base: import("@nestjs/mapped-types").MappedType<Partial<CreateUserDto>>;
export declare class UpdateUserDto extends UpdateUserDto_base {
sum_score?: number;
scores?: Score[];
}
export {};
|
Helicopter Parenting and Cell-Phone Contact between Parents and Children in College ABSTRACT Using relational dialectics theory as the organizing framework, this study examined helicopter parenting and cell-phone contact among college students (N = 529). Participants had more cell-phone conflict, engaged in more avoidance, and had more rules about cell-phone contact with high- compared to low- and, in some cases, moderate-helicopter mothers. Participants with high-helicopter fathers reported more father-initiated contact and cell-phone conflict than moderate- or low-helicopter fathers. Those with moderate- and high-helicopter fathers reported more rules about cell-phone contact but also higher closeness and relational satisfaction than those with low-helicopter fathers. Overall, participants differed on autonomyconnection issues with their mothers and fathers. |
Greenpeace points out that binge watching Netflix is bad for the environment
Greenpeace recently released a report on how well tech companies are acting as global citizens by reviewing their current carbon footprint. It’s report states that companies such as Google, Facebook and Apple are taking the greatest initiative to move towards renewable energy. It has also stated that large tech companies such as Netflix, Amazon and Samsung continue to languish behind when it comes to adopting an attitude of carbon footprint reduction.
Greenpeace Senior IT Analyst Gary Cook states “Like Apple, Facebook, and Google, Netflix is one of the biggest drivers of the online world and has a critical say in how it is powered. Netflix must embrace the responsibility to make sure its growth is powered by renewables, not fossil fuels and it must show its leadership here”. Out of the 70 companies profiled, Netflix has one of the largest data footprints and accounts for a third of internet traffic just in North America. As it continues to grow within other markets, it’s data needs will continue to grow and how it powers these data centres is critical to its carbon footprint. Netflix has yet to commit to renewable energy.
The energy performance of the tech sector has been monitored by Greenpeace since 2009 and is making a call to all the leaders in the industry to make a commitment to renewable energy. The industry itself accounts for 7% of electricity use and as the continued use of online services such as streaming grow, so will its carbon footprint. Greenpeace has urged the likes of Netflix to become transparent on their energy consumption and to put forward their strategies for transitioning their electricity needs to renewable energy.
This news does leave the many environmentally conscious binge watching people out there with quite the predicament. It also demonstrates that when looking at our own carbon footprint that we need to account for the services that we use. What does such information serve for the everyday person, though? Well hopefully the next time you are lazing about and binge watching the next season of House of Cards or Stranger Things, you consider its impact on the environment. We all might just go and plant a tree for every season we watch.
Source: Greenpeace |
Australia's new A$5 bill is so high-tech vending machines can't handle it, but no problem — here's something else you can do with all that spare cash.
In a video posted by the National Film and Sound Archive (NFSA), NFSA education manager Cris Kennedy uses the new plastic note to play a record of "Brit's Blues" by Red Norvo and his orchestra, rather than a record player stylus.
The NFSA is at pains to point out they are not playing an official collection record — and they can't guarantee it won't damage your own vinyl should you give it a try.
The note also has special tactile features to make it accessible to the Blind community — is there anything this bill can't do (besides buy you a can of Coke)?
(H/T 9News) |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
#import <MediaPlayer/NSCopying-Protocol.h>
#import <MediaPlayer/NSSecureCoding-Protocol.h>
@class MPStoreArtworkRequestToken, NSArray, NSDate, NSDictionary, NSNumber, NSString, NSURL;
@interface MPStoreItemMetadata : NSObject
{
NSDictionary *_downloadAssetDictionary;
NSDictionary *_downloadMetadataDictionary;
NSDictionary *_storeMusicAPIDictionary;
NSDate *_expirationDate;
_Bool _hasOverrideChildStorePlatformDictionaries;
NSNumber *_hasSubscriptionOffer;
NSArray *_overrideChildStorePlatformDictionaries;
NSDictionary *_storePlatformDictionary;
MPStoreItemMetadata *_parentStoreItemMetadata;
}
+ (id)storeServerCalendar;
+ (id)artworkRequestTokenForStorePlatformArtworkValue:(id)arg1;
+ (_Bool)supportsSecureCoding;
@property(readonly, copy, nonatomic) MPStoreItemMetadata *parentStoreItemMetadata; // @synthesize parentStoreItemMetadata=_parentStoreItemMetadata;
- (id)_storePlatformLastModifiedDateFormatter;
- (id)_musicAPIDateFormatter;
- (id)_storePlatformReleaseDateFormatter;
- (id)metadataWithParentMetadata:(id)arg1;
- (id)metadataWithChildStorePlatformDictionaries:(id)arg1;
- (id)metadataByAppendingMetadata:(id)arg1;
- (id)brickEditorialArtworkRequestToken;
- (id)flowcaseEditorialArtworkRequestToken;
- (id)movieArtworkRequestToken;
- (id)tvShowArtworkRequestToken;
- (id)tvEpisodeArtworkRequestToken;
- (id)editorNotesWithStyle:(id)arg1;
- (id)descriptionTextWithStyle:(id)arg1;
- (id)childStorePlatformDictionaryForStoreID:(id)arg1;
- (id)childStorePlatformDictionaryForArtworkTrackID:(id)arg1;
- (id)stationGlyphRequestTokenForStorePlatformDictionary:(id)arg1;
- (id)artworkRequestTokenForStorePlatformDictionary:(id)arg1;
- (id)avatarArtworkRequestToken;
- (id)artworkRequestTokenForUberArtworkKind:(id)arg1;
- (id)artworkRequestTokenForScreenshotArtwork;
- (id)artworkRequestTokenForEditorialArtworkKind:(id)arg1;
@property(readonly, copy, nonatomic) NSArray *radioStationEvents;
@property(readonly, copy, nonatomic) NSString *radioStationProviderName;
@property(readonly, nonatomic) _Bool isChart;
@property(readonly, nonatomic) long long radioStationTypeID;
@property(readonly, nonatomic, getter=isVerifiedPerson) _Bool verifiedPerson;
@property(readonly, nonatomic, getter=isPrivatePerson) _Bool privatePerson;
@property(readonly, copy, nonatomic) NSString *nameRaw;
@property(readonly, copy, nonatomic) NSString *handle;
@property(readonly, copy, nonatomic) NSString *workName;
@property(readonly, copy, nonatomic) NSString *videoSubtype;
@property(readonly, copy, nonatomic) NSString *versionHash;
@property(readonly, copy, nonatomic) NSURL *URL;
@property(readonly, copy, nonatomic) NSURL *shortURL;
@property(readonly, nonatomic) long long seasonNumber;
@property(readonly, nonatomic) long long episodeCount;
@property(readonly, nonatomic) long long trackNumber;
@property(readonly, nonatomic) long long trackCount;
@property(readonly, nonatomic) long long subscriptionAdamID;
@property(readonly, nonatomic) long long purchasedAdamID;
@property(readonly, copy, nonatomic) id socialProfileID;
@property(readonly, copy, nonatomic) NSArray *formerStoreAdamIDs;
@property(readonly, copy, nonatomic) id storeID;
@property(readonly, copy, nonatomic) NSString *cloudUniversalLibraryID;
@property(readonly, nonatomic) _Bool showComposer;
@property(readonly, nonatomic) _Bool shouldReportPlayEvents;
@property(readonly, copy, nonatomic) NSNumber *shouldBookmarkPlayPosition;
@property(readonly, copy, nonatomic) NSString *shortName;
@property(readonly, copy, nonatomic) NSDate *lastModifiedDate;
@property(readonly, copy, nonatomic) NSDate *releaseDate;
@property(readonly, copy, nonatomic) NSNumber *popularity;
@property(readonly, copy, nonatomic) NSArray *playlistIdentifiers;
@property(readonly, copy, nonatomic) NSArray *offers;
@property(readonly, copy, nonatomic) NSString *name;
@property(readonly, copy, nonatomic) NSArray *movieClips;
@property(readonly, nonatomic) long long movieClipsCount;
@property(readonly, nonatomic) long long movementNumber;
@property(readonly, copy, nonatomic) NSString *movementName;
@property(readonly, nonatomic) long long movementCount;
@property(readonly, nonatomic) MPStoreArtworkRequestToken *latestAlbumArtworkRequestToken;
@property(readonly, copy, nonatomic) NSString *iTunesBrandType;
@property(readonly, copy, nonatomic) NSString *playlistType;
@property(readonly, copy, nonatomic) NSString *itemKind;
@property(readonly, nonatomic, getter=isStoreRedownloadable) _Bool storeRedownloadable;
@property(readonly, nonatomic) _Bool isPreorder;
- (_Bool)isMasteredForITunes;
@property(readonly, nonatomic, getter=isCompilation) _Bool compilation;
@property(readonly, nonatomic) long long explicitRating;
@property(readonly, nonatomic, getter=isExplicitContent) _Bool explicitContent;
@property(readonly, copy, nonatomic) NSArray *genreNames;
@property(readonly, nonatomic) _Bool hasSubscriptionOffer;
@property(readonly, nonatomic) _Bool hasSocialPosts;
@property(readonly, nonatomic) _Bool hasTimeSyncedLyrics;
@property(readonly, nonatomic) _Bool hasLyrics;
@property(readonly, nonatomic) _Bool hasArtistBiography;
@property(readonly, copy, nonatomic) NSDictionary *effectiveStorePlatformDictionary;
@property(readonly, copy, nonatomic) NSString *shortEditorNotes;
@property(readonly, nonatomic, getter=isExpired) _Bool expired;
@property(readonly, copy, nonatomic) NSDate *expirationDate;
@property(readonly, copy, nonatomic) NSString *editorNotes;
@property(readonly, nonatomic) double duration;
@property(readonly, nonatomic) long long discNumber;
@property(readonly, nonatomic) long long discCount;
@property(readonly, copy, nonatomic) NSString *descriptionText;
@property(readonly, copy, nonatomic) id curatorID;
@property(readonly, copy, nonatomic) NSString *curatorName;
@property(readonly, copy, nonatomic) NSString *copyrightText;
@property(readonly, copy, nonatomic) NSString *composerName;
@property(readonly, copy, nonatomic) id collectionStoreID;
@property(readonly, copy, nonatomic) NSString *collectionName;
@property(readonly, nonatomic) unsigned long long cloudID;
@property(readonly, copy, nonatomic) NSString *cloudAlbumID;
@property(readonly, copy, nonatomic) NSArray *childStoreItemMetadatas;
@property(readonly, copy, nonatomic) NSArray *childrenStoreIDs;
@property(readonly, nonatomic, getter=isBeats1) _Bool beats1;
@property(readonly, copy, nonatomic) NSArray *artworkTrackIDs;
@property(readonly, nonatomic) MPStoreArtworkRequestToken *stationGlyphRequestToken;
@property(readonly, nonatomic) MPStoreArtworkRequestToken *artworkRequestToken;
@property(readonly, copy, nonatomic) NSString *artistUploadedContentType;
@property(readonly, copy, nonatomic) id artistStoreID;
@property(readonly, copy, nonatomic) NSString *artistName;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)description;
- (id)initWithStorePlatformDictionary:(id)arg1 parentStoreItemMetadata:(id)arg2 expirationDate:(id)arg3;
- (id)initWithStorePlatformDictionary:(id)arg1 parentStoreItemMetadata:(id)arg2;
- (id)initWithStorePlatformDictionary:(id)arg1 expirationDate:(id)arg2;
- (id)initWithStorePlatformDictionary:(id)arg1;
- (id)initWithStoreMusicAPIDictionary:(id)arg1;
- (id)initWithDownloadAssetDictionary:(id)arg1;
- (_Bool)hasMetadataForRequestReason:(unsigned long long)arg1;
@property(readonly, copy, nonatomic) NSString *cacheableItemIdentifier;
@end
|
Image caption The Colombian military have been clearing land mines but many of them were laid by the Farc who have the records and maps of their locations.
The Colombian army and Farc guerrillas have begun working together to clear landmines sown during 50 years of war, the government says.
Officials said they had identified four areas for clearance in the northern region of Antioquia using maps provided by the Farc.
Peace talks have been faltering since the left-wing rebel group suspended a unilateral ceasefire last week.
Colombia is one of the most mine-ridden countries in the world.
There have been almost 11,000 recorded deaths and injuries from landmines since 1990.
The government's chief peace negotiator in Havana, Humberto de la Calle, said: "Farc handed over a map and actively contributed in the process."
He said decommissioning anti-personnel mines "had become a reality".
The mission, which took place over the course of a week, was the first step in a March agreement towards de-commissioning mines placed during the conflict.
The work focused on a region severely affected by mines.
Mr de la Calle said: "Work started in Antioquia, because it is the department historically with the most incidents of explosions from these objects."
He said the area they had begun to search contained "more mines than inhabitants".
The joint operation which had been agreed during the last round of peace talks taking place in Havana had been due to begin sooner, but the suspension of a unilateral ceasefire by Farc last week and the deaths of both army and Farc personnel in various attacks had delayed the start.
Image caption Colombian soldiers have been practising with fake mines in preparation for demining in Cocorna municipality, in Antioquia.
Image caption Soldiers need patience and to be highly organised.
The Farc killed 11 soldiers in an ambush last month, causing President Juan Manuel Santos to order new air strikes on rebel positions.
Around 40 rebel fighters have been killed since last week, including two high-ranking commanders.
Mr de la Calle said that he hoped the joint de-mining operation would bring hope for the peace talks.
"Who would have imagined an army sergeant and a Farc explosive expert spending days together exchanging opinions?" he asked. |
Cheiloscopy in gender determination: A study on 2112 individuals Background: Lip prints are seen to remain the same for an individual throughout his/her life. Cheiloscopy can be used as an effective tool in the identification of the persons from pieces of evidence that may be left behind from lip prints. Aim and Objectives: The aim of the current research was to evaluate the predominant lip groove pattern among Calicut population, Kerala. Materials and Methods: The study involved 2112 individuals (1056 males and 1056 females) in the Department of Oral Medicine and Radiology, KMCT Dental College, Calicut, Kerala. Lipstick was used to record the lip groove patterns and the patterns were visualized by magnifying lens after the institutional ethical clearance and informed consent from the individual. Statistical analysis was done using SPSS software 22.0. Results: Among the study population, Type 1, Type 1, Type 4, and Type 5 were found to be common lip groove patterns. Males showed predominance on Type 1 and Type 1 lip groove patterns, whereas females showed predominance on Type 4 and Type 5 lip groove patterns. The results were similar when analyzed on upper and lower lips separately on males and females. Conclusion: Cheiloscopy is a reliable tool in personal identification and gender determination of an individual. The geographical prevalence of lip groove patterns was reported in the current research and is added to the database of the anthropological data. Studies in different geographical regions will add lip groove patterns on the database in the future and henceforth the potential of cheiloscopy could be further utilized. Introduction The identification of human beings is a process based on certain scientific principles. There are many methods used in personal identification rather than traditional methods for anthropometry, age estimation, gender determination, differentiation by blood groups, fingerprints, and DNA analysis. The branch of dentistry that deals with the identification of individuals based on evidence in the court of law is termed forensic dentistry. It includes rugoscopy, cheiloscopy, bite mark analysis, tooth prints, radiographs, photographic study, and molecular methods. Identification in civil and criminal cases requires scientific evidence and support. Cheiloscopy is the technique in which individuals are identified based on the lip groove patterns. It is possible to identify the lip groove patterns as early as the sixth week of intrauterine life. Lip groove pattern once formed is permanent and does not change permanently following climatic variations, pathology, minor trauma, inflammation, and infections. The salivary and sebaceous secretions from glands located at vermillion border aid in the formation of a latent lip groove pattern. Lip groove patterns aiding in criminal investigations have been well documented. It is an adjunctive mode of identification accepted in the court of law. The pattern produced by lip grooves on mechanical surface is termed lip print. Lip groove patterns are unique and do not change during the entire life of an individual and are invariable and permanent. In postmortem analysis, lip groove patterns have to be obtained within 24 h of death to prevent any possible postmortem mechanical degradation of lip mucosa. Apart from forensic medicine, particular types of lip print patterns have been associated with the occurrence of non-syndromic cleft lip with or without cleft palate and numerous studies are underway to establish facts. Parents of patients affected with cleft lip and/or palate have been shown to have a particular lip print pattern. The study of lip prints in understanding the inheritance of various congenital anomalies can, therefore, be a useful tool in primary care of diseases. This provides a cost-effective, noninvasive screening method to evaluate the occurrence of clefts in the offspring. There are reported studies on the gender differences among the lip groove patterns of individuals. Lack of comprehensive database is a major roadblock in the progression and establishment of cheiloscopy as a distinctive supporting branch in forensic dentistry. The aim of the current research is to determine the common lip groove pattern among Calicut population, evaluate the variation in lip groove patterns and gender-wise comparison of lip groove patterns. Methodology The study was carried out from January 2017 to January 2019 on 2112 individuals (1056 males and 1056 females) aged from 15 to 60 years in KMCT Dental College, Calicut. Excluded criteria are 1) persons with lip scar, 2) lip lesions, 3) lip congenital deformities, and 4) persons with hypersensitivity to lipsticks. The study protocol and objectives were thoroughly explained to the participants and informed consent was taken from them. The Institutional Ethics Committee of KMCT Dental College has approved the research. Materials used to record the lip groove patterns were: red-colored lipstick, cellophane tape, white paper, and magnifying lens. Costa and Caldas technique was used to record the lip groove pattern. The individuals' lips were cleaned with a wet tissue before starting the procedure. The lipstick was gently applied to both lips and the individuals were asked to roll the lips in a uniform manner from center to the corner of lips. The individual was asked to stop moving the lips during the procedure and to keep the lips in relaxed state. The lip groove patterns were lifted by cellophane scotch tape on upper lip from one side to another; following which the tape was pasted on a white bond paper as a permanent record. The same process was repeated for lower lips. After pasting the lip groove patterns on the bond paper, the remaining lipstick was cleaned on the lips with a tissue and washed properly. Lip groove patterns were categorized into four regions predominantly by dropping a perpendicular from the philtrum of lips: upper right (UR) region, upper left (UL) region, lower right (LR) region, and lower left (LL) region. The obtained lip groove patterns were carefully examined under the magnifying lens. The analysis was done as per the Suzuki and Tsuchihashi classification. The classification is as follows: Type I: clear cut grooves running vertically across the lips; Type I': grooves are straight but disappear halfway instead of covering the entire breadth of the lip; Type II: grooves fork in their course; Type III: grooves intersect; Type IV: grooves are reticular; Type V: groves do not fall into any of the Type I to IV and cannot be differentiated morphologically. Statistical analysis The collected data was statistically analyzed using SPSS 22.0 software. Results The results noted from the study were the following: Type I (61.5%), Type V (59.5%), Type I' (56.4%), and Type IV (53.1%) form the predominant lip groove patterns in the four regions of lips in the population. Type III (24.7%) and Type II (29.0%) form the least common lip groove patterns in the four regions of lips in the population. Table 1]. Lip groove patterns were taken for 2112 males and females and were assessed for the presence of patterns separately in upper lip and lower lip. Mean and standard deviation is also calculated . Lip groove patterns were taken for 1056 males and were assessed for the presence of patterns separately in upper lip and lower lip. Mean and standard deviation is also calculated . Lip groove patterns were taken for 1056 females and were assessed for the presence of patterns separately in upper lip and lower lip. Mean and standard deviation is also calculated . Discussion Different prevalence of lip groove patterns has been reported worldwide. Cheiloscopy could be a useful adjunct in crime scenes, mass disasters, and accidents. It is considered the most important and advisable form of transfer of evidence. Lip prints could be retrieved from glass, cigarette butts, clothes, food material, etc., and it could be done by using aluminum powder and magnetic powder. The current research revealed a uniqueness of lip groove pattern and predominance of Type IV and Type V patterns among females and Type I' and Type I patterns among males. Costa and Caldas and Kumar et al. stated that lip groove patterns can be used as a potential aid in gender determination which is in accordance with the results of current research. Lip groove patterns vary in different parts of lips and it reiterates the fact of uniqueness of lip groove patterns. According to other studies Type IV lip groove pattern was found to be predominant among Kerala population which is in accordance with the predominant pattern among females in the current research. A cheiloscopic study on Rajasthan population revealed a significant difference among gender, which is in accordance with the current research results. Type IV and Type I lip groove patterns were found to be predominant among Karnataka and Punjab population, which is again consistent with the results of current research. Type V lip groove pattern was found least common among Indian students and Portuguese population when compared to Yemeni population. Maheswari and Gnanasundaram reported predominant Type II lip groove pattern among Indian population. A study in Egypt which is equally hot like Somalia showed dominance of Type I and IV patterns. Manikya S reported Type IV lip groove pattern as predominant among their samples. Conclusion Lip groove pattern is unique to an individual and there are predominant patterns based on the gender of an individual. The anthropological database needs to be established on a wider background with further studies in this regard on other geographical areas of the world also. The missing links regarding the establishment of cheiloscopy as a distinctive branch can be completed with more update on the database regarding the lip groove patterns. |
#import <UIKit/UIKit.h>
FOUNDATION_EXPORT double AWMarkupStripperVersionNumber;
FOUNDATION_EXPORT const unsigned char AWMarkupStripperVersionString[];
|
// (c) 2019-2020, <NAME>, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package rpc
import (
"bytes"
"fmt"
"net/http"
"strings"
"time"
rpc "github.com/gorilla/rpc/v2/json2"
)
type Requester interface {
SendJSONRPCRequest(endpoint string, method string, params interface{}, reply interface{}) error
}
type jsonRPCRequester struct {
uri string
client http.Client
}
func NewRPCRequester(uri string, requestTimeout time.Duration) Requester {
return &jsonRPCRequester{
uri: uri,
client: http.Client{
Timeout: requestTimeout,
},
}
}
func (requester jsonRPCRequester) SendJSONRPCRequest(endpoint string, method string, params interface{}, reply interface{}) error {
// Golang has a nasty & subtle behaviour where duplicated '//' in the URL is treated as GET, even if it's POST
// https://stackoverflow.com/questions/23463601/why-golang-treats-my-post-request-as-a-get-one
endpoint = strings.TrimLeft(endpoint, "/")
requestBodyBytes, err := rpc.EncodeClientRequest(method, params)
if err != nil {
return fmt.Errorf("problem marshaling request to endpoint '%v' with method '%v' and params '%v': %w", endpoint, method, params, err)
}
url := fmt.Sprintf("%v/%v", requester.uri, endpoint)
resp, err := requester.client.Post(url, "application/json", bytes.NewBuffer(requestBodyBytes))
if err != nil {
return fmt.Errorf("problem while making JSON RPC POST request to %s: %s", url, err)
}
statusCode := resp.StatusCode
// Return an error for any non successful status code
if statusCode < 200 || statusCode > 299 {
// Drop any error during close to report the original error
_ = resp.Body.Close()
return fmt.Errorf("received status code '%v'", statusCode)
}
if err := rpc.DecodeClientResponse(resp.Body, reply); err != nil {
return err
}
return resp.Body.Close()
}
type EndpointRequester interface {
SendRequest(method string, params interface{}, reply interface{}) error
}
type avalancheEndpointRequester struct {
requester Requester
endpoint, base string
}
func NewEndpointRequester(uri, endpoint, base string, requestTimeout time.Duration) EndpointRequester {
return &avalancheEndpointRequester{
requester: NewRPCRequester(uri, requestTimeout),
endpoint: endpoint,
base: base,
}
}
func (e *avalancheEndpointRequester) SendRequest(method string, params interface{}, reply interface{}) error {
return e.requester.SendJSONRPCRequest(
e.endpoint,
fmt.Sprintf("%s.%s", e.base, method),
params,
reply,
)
}
|
The need to protect sensitive electronic components and computer boards from electrostatic discharge during handling, shipping, and assembly provided the driving force for development of an entire new class of antistatic packaging materials. Key developments in polymers -- notably conductive polyethylene and sophisticated laminates with very thin metallized films -- have created a multi-million dollar packaging industry. This enterprise undoubtedly saves many hundreds of millions of dollars each year for the electronics and computer industries, and it dwarfs all other commercial and industrial antistatic abatement activity.
This page describes a simple demonstration of the shielding effect provided by the antistatic bags used to store and ship electronic components and assembled boards. Click here if you wish to review another demonstration of the phenomenon of electrostatic shielding. The apparatus required for the demonstration includes a TESV that is, the tonal electrostatic voltmeter, preferably mounted on a tripod, various antistatic bags large enough to cover the instrument, plus a plastic tube or rod and a rubbing cloth. PVC pipe, Teflon, or Nylon work well with cloths of wool or silk.
The demonstration is conducted by setting up the TESV instrument on the tripod, turning on and zeroing the instrument, and then bringing the plastic rod, charged up by rubbing, close to the sensing head. As expected, the instrument responds by indicating the presence of charge. The TESV is then covered by one of the antistatic plastic bags and the experiment repeated. Refer to the photograph shown above. Now, the instrument registers little or no charge. Even when a charged conducting object is discharged directly to the bag, the instrument registers little or nothing. The explanation of this phenomenon is that the instrument has been shielded from the electrostatic field of the charged object by the conductive bag.
Note that it is not necessary to ground the bag. If grounding were necessary, antistatic bags would be much less convenient and effective than they are. Grounding is unnecessary here because electric charge abhors the inside surface of any void enclosed by conductive material. For an ungrounded bag, the charge simply stays on the outside where it harmlessly remains. Now consider the problem of removing a sensitive electronic component or board from a charged bag. If the bag is handled by a person, contact with the hand serves to ground the bag and remove the charge. However, if the person wears insulating gloves, then the component may draw a strong electrical spark as it is withdrawn from the bag and may be damaged.
Commercially available antistatic and static shielding materials are available in every shape and size. In addition to thickness, abrasion resistance, and so forth, the technical specifications usually refer to either MIL specs or some measure of the rate of charge dissipation. Definitions for antistatic materials abound and sometimes can be confusing. For a summary of these, please click here.
Refer to the advertisement shown just below. This bag has a metallic layer which provides "Faraday Cage" shielding, in reference to the above cited fact that charge abhors the inside surface of a conductor (as long as there is no charge within the bag).
A somewhat different type of bag is described in the advertisement below. This bag has no metal layer, but instead is made from a conductive polyethylene film. Note the claim that this bag will dissipate 5000 volts in 2 seconds. This claim is made in reference to a standardized test where the bag is charged up to a preset voltage, the source is disconnected and the voltage is monitored with the bag connected to ground. In fact it is electric charge that is dissipated; however, the voltage, being far easier to measure and also being directly proportional to the charge for a fixed capacitance geometry, provides a convenient, indirect measure of the rate of charge dissipation.
For a set of photographs showing a very impressive demonstration of shielding, where a Faraday cage is used to protect a person from the deadly electrostatic spark of the very large van de Graaff generator at the Museum of Science in Boston, please CLICK HERE.
H.A. Haus and J.R. Melcher, Electromagnetic fields and energy," (Prentice-Hall, Englewood Cliffs, NJ), 1989, pp. 27-28. |
/**
* Add a date sequence value to the list.
*
* @param seqName
* The name of the sequence property, it must include the namespace prefix, e.g. "pdf:Keywords"
* @param date
* The date to add to the sequence property.
*/
public void addUnqualifiedSequenceDateValue(String seqName, Calendar date)
{
addUnqualifiedSequenceValue(
seqName,
getMetadata().getTypeMapping().createDate(null, XmpConstants.DEFAULT_RDF_LOCAL_NAME,
XmpConstants.LIST_NAME, date));
} |
def is_valid_data(entity):
if "type" not in entity.keys() or "attributes" not in entity.keys():
return False
attr_keys = entity["attributes"].keys()
if entity["type"] != "Event":
return False
if "studip_id" not in attr_keys or entity["attributes"]["studip_id"] is None:
return False
return True |
Granulocytic differentiation of the human myelomonocytic leukaemia cell line ME1 in serumfree culture We have recently established ME1, a human myelomonocytic leukaemia cell line derived from acute myelomonocytic leukaemia with eosinophilia (M4E0). When ME1 cells were cultured in serumfree medium, they stopped proliferating and began to differentiate morphologically, functionally and phenotypically to mature granulocytelike cells. The protein kinase inhibitor, 1(5isoquinolinylsulphonyl)2methylpiperazine (H7) enhanced this differentiation dosedependently. Upon addition of fetal calf serum (FCS) to the serumfree medium, the differentiation of ME1 cells into granulocytelike cells was inhibited and they resumed cell growth. We have recently reported that the differentiation of ME1 cells into macrophagelike cells induced by IL3 and GMCSF involved the activation of protein kinase C. The present results indicate that ME1 is a bipotential cell line that can differentiate into granulocytelike cells or macrophagelike cells, and that protein kinase C is closely related to each form of differentiation. |
Culture of Tatarstan
Education
The education system in Tatarstan is secular. The literacy rate for the total population is about 100%. Elementary and secondary education is compulsory (grades 1–10). Students must pass graduation exams at the end of the 10th grade in order to continue their education in colleges and universities. Most schools are public along with a small number of parochial schools run by churches or mosques. The school year begins in September. Kazan State University is one of the major centers of higher education in Russia. There are several colleges, institutes, and technical schools in Kazan and other cities of the republic.
Libraries
Major libraries include the Science Library of Kazan State University and the National Library of the Republic of Tatarstan. There are two museums of republican significance, as well as 90 museums of local importance. In the past several years new museums appeared throughout the Republic.
Music
Traditional (folk) Tatar music is based on the pentatonic scale. The first Tatar opera was staged in 1925. It was composed by Sultan Gabyashi in collaboration with Vasili Vinogradov. Farit Yarullin was the creator of the first Tatar ballet, known as Surale. Modern Tatar music includes practically all existing musical genres.
Theater
There are 16 professional and dozens of amateur theaters in Tatarstan performing plays in Tatar, Russian, and other local languages.
Religion
In Tatarstan, religion and the state are separate from each other, although as in the rest of Russia, religious authorities are subordinated to the state. The most common faith are Sunni Islam and Russian Orthodoxy. As of 2004, there were 1,208 buildings used for religious purposes in Tatarstan; 1,014 of which were Islamic, and 176—Russian Orthodox. |
<filename>source/utopian/utility/Utility.cpp
#include "utility/Utility.h"
glm::vec4 ColorRGB(uint32_t r, uint32_t g, uint32_t b)
{
return glm::vec4(r / 255.0f, g / 255.0f, b / 255.0f, 1.0f);
}
std::string ReadFile(std::string filename)
{
std::string text;
std::ifstream is(filename.c_str(), std::ios::binary | std::ios::in | std::ios::ate);
if (is.is_open())
{
size_t size = is.tellg();
is.seekg(0, std::ios::beg);
char* data = new char[size];
is.read(data, size);
is.close();
text = data;
delete[] data;
assert(size > 0);
}
return text;
}
namespace Utopian
{
std::string ExtractFilename(std::string path)
{
std::size_t found = path.rfind("/");
if (found != std::string::npos)
path.replace(0, found + 1, "");
return path;
}
std::string ExtractFileDirectory(std::string path)
{
size_t found = path.find_last_of("/\\");
return path.substr(0, found+1);
}
std::string GetFileExtension(std::string filename)
{
std::string::size_type index = filename.rfind('.');
if(index != std::string::npos)
{
std::string extension = filename.substr(index);
return extension;
}
else
{
assert(0);// No extension found
}
}
}
|
import {MigrationInterface, QueryRunner, Table} from "typeorm";
export class CreateCategories1643334962570 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
'CREATE TABLE IF NOT EXISTS categories (categoryId INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(45), description VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);'
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("categories");
}
}
|
def model_changed(self, old_fields, new_fields, is_new):
raise NotImplementedError("Missing method `model_changed`") |
Energy efficient torque vectoring control Tire forces are at the heart of the dynamic qualities of vehicles. With the advent of electric vehicles the precise and accurate control of the traction and braking forces at the individual wheel becomes a possibility and a reality outside test labs and virtual proving grounds. Benefits of individual wheel torque control, or torque-vectoring, in terms of vehicle dynamics behavior have been well documented in the literature. However, very few studies exist which analyze the individual wheel torque control integrated with vehicle efficiency considerations. This paper focuses on this aspect and discusses the possibilities and benefits of integrated, energy efficient torque vectoring control. Experiments with a four-wheel-drive electric vehicle show that considerable energy savings can be achieved by considering drivetrain and tire power losses through energy efficient torque vectoring control. |
Constitutively active Notch1 signaling promotes endothelial-mesenchymal transition in a conditional transgenic mouse model Endothelial-mesenchymal transition (EndoMT) is a process in which endothelial cells lose their cell-type-specific characteristics and gain a mesenchymal cell phenotype. The Notch signaling pathway is crucial in the regulation of EndoMT; however, its roles have not been fully studied in vivo. In a previous study, we reported the generation of transgenic mice with a floxed -geo/stop signal between a CMV promoter and the constitutively active intracellular domain of Notch1 (IC-Notch1) linked with a human placental alkaline phosphatase (hPLAP) reporter (ZAP-IC-Notch1). In this study, we examined the results of activating IC-Notch1 in endothelial cells. ZAP-IC-Notch1 mice were crossed with Tie2-Cre mice to activate IC-Notch1 expression specifically in endothelial cells. The ZAP-IC-Notch1/Tie2-Cre double transgenic embryos died at E9.510.5 with disruption of vasculature and enlargement of myocardium. VE-cadherin expression was decreased and EphrinB2 expression was increased in the heart of these embryos. Mesenchymal cell marker -smooth muscle actin (SMA) was expressed in IC-Notch1-expressing endothelial cells. In addition, upregulation of Snail, the key effector in mediating EndoMT, was identified in the cardiac cushion of the double transgenic murine embryo heart. The results of the present study demonstrate that constitutively active Notch signaling promotes EndoMT and differentially regulates endothelial/mesenchymal cell markers during cardiac development. Introduction Endothelial-mesenchymal cell transdifferentiation (EndoMT) is the process in which endothelial cells lose their celltype-specific characteristics and gain a mesenchymal or myofibroblastic phenotype. EndoMT may be initiated by cytokines or growth factors secreted by peri-vascular cells. The basement membrane under the endothelial cells is likely to be degraded by matrix metalloproteinases (MMPs), then the transitioning endothelial cells become motile and invade the surrounding tissues. During EndoMT, endothelial cells lose the expression of their markers, such as vascular endothelial (VE)-cadherin and von Willebrand factor (vWF), and gain the expression of mesenchymal cell markers including vimentin, -smooth muscle actin (SMA) and type I collagen. EndoMT was first observed in studies on cardiac development. EndoMT has emerged as a possible mechanism in the pathogenesis of various diseases, including diabetic nephropathy, cardiac fibrosis, intestinal fibrosis, pulmonary hypertension and systemic sclerosis. Despite the notable importance of EndoMT for embryonic development and pathologic conditions, the underlying molecular mechanisms involved in EndoMT have yet to be fully elucidated. Substantial evidence has indicated the crucial role of TGF- signaling in the initiation of EndoMT. A number of signaling transduction pathways, including VEGF, NFAT, BMP, Wnt/-catenin, ErbB, and NF1/Ras, play a role in EndoMT during cardiac development. In addition, EndoMT can be modulated in response to manipulations of the Notch pathways in many different endothelial cell types. It is also suggested that a number of signaling pathways interact with TGF- and Notch to mediate EndoMT during heart valve development. The Notch signaling pathway is evolutionarily conserved and plays a fundamental role in a number of mechanisms. Activation of Notch signaling is initiated through ligand-receptor interactions which lead to proteolytic cleavage of the receptor. Mammals have four receptors (Notch1, 2, 3, 4) and five ligands (Jagged 1 and 2, and -like 1, 3 and 4). Following activation, the intracellular domain of Notch (IC-Notch) translocates into the nucleus and binds the Constitutively active Notch1 signaling promotes endothelial-mesenchymal transition in a conditional transgenic mouse model DNA-binding protein CSL (CBF1/suppressor of hairless/Lag-1) through its RAM23 domain. The CSL protein (also known as CBF-1/RBP-J) binds to the DNA sequence GTGGGAA in the promoter region of Notch-regulated genes. The components of the Notch signaling pathway are crucial for cell fate decisions during morphogenesis and embryonic development. Notch signaling was thought to be involved in the regulation of vascular smooth muscle differentiation during heart valve and cardiac cushion development. Subsequent studies have confirmed the involvement of Notch signaling in the EndoMT process. Notch proteins are expressed in most cell types and are involved in a broad spectrum of disorders. Studies of the Notch pathway in mice using gain-and loss-of-function approaches have been restricted due to the development of embryonic lethal phenotypes. To investigate the function of Notch signaling in specific tissues, we established ZAP-IC-Notch1 transgenic mice to take advantage of the Cre recombinase-expressing system to tailor IC-Notch1 expression to particular cell types. The ZAP-IC-Notch1 construct utilizes a CMV enhancer-chicken -actin promoter followed by a loxP-flanked -geo fusion gene and three polyadenylation (pA) sequences. Downstream of the pA sequence is the coding sequence for the IC-Notch1 protein with an internal ribosomal entry site (IRES)-linked human placental alkaline phosphatase (hPLAP). Therefore, IC-Notch1 is silent in the transgenic mice but can be activated by the introduction of Cre recombinase and excision of the stop signal. IC-Notch1 expression can be monitored by the co-expression with hPLAP following Cre excision. In this study, ZAP-IC-Notch1 mice were crossed with Tie2-Cre mice, which drive Cre recombination in the entire vascular endothelium. The expression of IC-Notch1 was activated in endothelial cells during early development. Constitutively active Notch1 signaling induced disruption of the vasculature, enlargement of myocardium and embryonic lethality at E9.5-10.5. VE-cadherin expression was decreased while EphrinB2 expression was increased. Mesenchymal cell marker -SMA was expressed in IC-Notch1-expressing cells. In addition, Snail, the key effector in mediating EndoMT, was upregulated in the ZAP-IC-Notch1/Tie2-Cre double transgenic mouse embryo heart. Results of this study therefore support the role of Notch signaling in the promotion of EndoMT. Materials and methods Mice. ZAP-IC-Notch1 transgenic mice were previously generated in our laboratory. Tie2-Cre transgenic mice were generously provided by Dr Yanagisawa (University of Texas Southwestern Medical Center, Dallas, TX, USA). The ZAP IC-Notch1 transgene was genotyped by staining ear clips for lacZ expression and by pCCALL PCR using genomic DNA isolated from mouse ear biopsies. The Tie2-Cre mice were genotyped by Cre PCR as previously described. Western blot analysis. The mouse embryo hearts were lysed in ice-cold RIPA buffer (20 mM Tris pH 7.5, 150 mM NaCl, 50 mM NaF, 1% NP-40, 0.1% DOC, 0.1% SDS, 1 mM EDTA and supplemented with 1 mM PMSF and 1 g/ml leupeptin). The protein concentration was determined using the BCA assay (Bio-Rad, Hercules, CA, USA). Equal amounts of protein were separated by a 10% SDS-PAGE and transferred onto a PVDF membrane. The membranes were blocked with 2.5% BSA, and incubated with the primary antibodies at 4C overnight in PBS-T. Primary antibodies used were: rabbit anti-VE-cadherin antibody (Abcam, Cambridge, MA, USA), rabbit anti-EphrinB2 antibody, rabbit anti-Snail antibody (both from Santa Cruz Biotechnology, Inc.), and mouse anti--actin antibody (Sigma-Aldrich). Immunoreactivity was visualized with HRP-linked secondary antibodies and chemiluminescence. Semi-quantitative PCR analysis. Total RNA isolation from mouse embryo hearts was performed using TRIzol reagent (Invitrogen, Carlsbad, CA, USA) according to the manufacturer's instructions. An aliquot of 2 g total RNA from each sample was used for the synthesis of cDNA using a High-Capacity cDNA Reverse Transcription kits (Applied Biosystems Inc., Foster City, CA, USA). The cDNA was amplified in a final volume of 20 l with 1 unit of Taq DNA polymerase (Invitrogen) and 10 pmol of each primer. Oligonucleotide primer sequences are shown in Table I. The PCR products were visualized by ethidium bromide staining following a 1.2% agarose gel electrophoresis. Results Embryos with endothelial cell-specific expression of IC-Notch1 exhibit disorganized vasculature. ZAP-IC-Notch mice were crossed with Tie2-Cre mice to activate IC-Notch1 expression in endothelial cells (Fig. 1). The embryos were taken at various stages, dissected and photographed. The genotypes of the embryos were determined by PCR of yolk sac samples. Double transgenic ZAP-IC-Notch1/Tie2-Cre embryos died at E9. 5-10.5 showing pale yolk sacs with fewer blood vessels than the littermates ( Fig. 2A and B). These embryos also exhibited an enlarged heart and hemorrhaging around the vessels (Fig. 2D). After whole-mount AP staining, ZAP-IC-Notch1/Tie2-Cre embryos exhibited purple/blue color on the blood vessels in the embryos and yolk sacs (Fig. 2F), indicating that Cre excision of the STOP signal successfully activated constitutive Notch1 signaling together with hPLAP expression. The embryos were sectioned and stained with a monoclonal antibody to PECAM-1, a marker for VE cells (Fig. 3). We observed that blood vessels were collapsed in ZAP-IC-Notch1/Tie2-Cre double transgenic embryos, leading to bleeding and the death of the embryos. In the trunk of wild-type embryos at E9.5, intersomitic blood vessels were apparent along the boundaries between adjacent somites (Fig. 3A), but in ZAP-IC-Notch1/Tie2-Cre embryos intersomitic vessels were severely disorganized and irregularly positioned ( Figure 3B). Yolk sacs demonstrated the presence of a well-organized capillary bed in wild-type embryos (Fig. 3C), whereas ZAP-IC-Notch1/Tie2-Cre yolk sacs exhibited a disorganized vascular plexus lacking intact blood vessels (Fig. 3D). IC-Notch1 promotes cardiac cushion formation and EndoMT in embryo heart. During cardiac cushion formation from the heart tube, endothelial cells of the endocardium lead to interstitial mesenchymal cells through EndoMT. In the ZAP-IC-Notch1/Tie2-Cre mouse embryos, the endocardium of the embryonic heart was intact; however, the cardiac cushion showed hypercellularity and advanced development of heart valves ( Fig. 4A and B). On the sections, cells with positive AP staining were observed in the endocardium and myocardium, suggesting that IC-Notch1-expressing endothelial cells migrated into the myocardium (Fig. 4B). -SMA is expressed in mesenchymal cells such as myofibroblasts, and is not normally expressed in endothelial cells. However, endothelial cells of the ZAP-IC-Notch1/Tie2-Cre mouse embryos, which express IC-Notch1 as shown by AP staining, were stained positive for antibody against -SMA ( Fig. 4C and D). Therefore, these endothelial cells underwent transdifferentiation and gained the characteristics of mesenchymal cells IC-Notch1 promotes Snail expression in embryo heart. Snail, a Zinc-finger-containing transcriptional repressor, has been identified as a key promoter of EMT (Fig. 6A). Results of semi-quantitative PCR and western blot analysis, revealed that the mRNA and protein levels of Snail were elevated in the ZAP-IC-Notch1/Tie2-Cre mouse embryo hearts ( Fig. 5A and B). The expression of endothelial cell markers was also examined. VE cadherin is an endothelial cell-specific junction molecule and its expression is reduced during EMT. EphrinB2, together with its receptor EphB4, are known to play a crucial role in arteriovenous differentiation. In the ZAP-IC-Notch1/Tie2-Cre mouse embryo hearts, VE-cadherin expression was decreased while EphrinB2 expression was increased, suggesting that IC-Notch1 differentially regulated endothelial cell markers during EndoMT. Moreover, a strong increase in the Snail protein expression was observed in mesenchymal cells in the cardiac cushion by immunohistochemistry ( Fig. 6B and C), and the upregulation of Snail was accompanied by an increase in EphrinB2 expression ( Fig. 6D and E). Discussion The Notch signaling pathway is essential for cardiovascular development and is involved in the pathogenesis of many cardiovascular diseases. Recently, Notch signaling has been shown to regulate cardiac cushion formation and EndoMT. However, its roles have not been well studied through gain-of-function mouse models. Using the Cre/loxP system, we were able to establish transgenic mouse lines carrying a silent transgene for constitutively active IC-Notch1 (ZAP-IC-Notch1). Expression of the IC-Notch1 transgene can be activated in a tissue-specific manner and monitored by an hPLAP reporter. In this study, ZAP-IC-Notch1 mice were crossed with Tie2-Cre mice and constitutively active Notch signaling was triggered specifically in endothelial cells. This unique conditional expression model During embryonic development, endothelial precursors assemble in a primitive network through vasculogenesis, and the network expands through angiogenesis. Angiogenesis is a process of sprouting new capillaries from pre-existing vessels, and is tightly controlled by various cell signaling cascades. The Notch signaling pathway plays crucial roles in angio genesis during embryonic development. In mice, the targeted deletion of Notch family genes including Notch receptors or their ligands lead to vascular defects and embryonic lethality at E9.5-10.5 43). The gain-of-function studies of Notch signaling are relatively limited. The IC-Notch14 expressed under the flk-1 locus caused embryonic lethality at E9.5 with a disorganized vascular network. In the current study, the Notch signaling pathway was activated specifically in endothelial cells by crossing ZAP-IC-Notch1 mice with Tie2-Cre mice. The double transgenic embryos died before E10.5 with disruption of vasculature in both embryos and yolk sacs. The same outcome was observed for another line of conditional IC-Notch mice ZEG-IC-Notch1 crossed with Tie2-Cre mice (data not shown). The disruption in vasculature produced by constitutively active Notch signaling was similar to the defects in angiogenesis produced by deficient Notch signaling in mouse embryos, suggesting a balance of Notch signaling is required for correct vessel formation during development. EndoMT is required for embryonic heart development and frequently observed in adult cardiac fibrosis. Previous studies have demonstrated an essential role for Notch signaling in the control of endocardial cushion EndoMT. In human, mutations of the Notch1 gene are associated with mitral valve anomalies, bicuspid aortic valve disease and tetralogy of fallot. Patients with mutations of the Jagged1 gene develop Alagille syndrome with cardiac cushion defects. In mice, the targeted deletion of Notch1 or its key nuclear partner CSL results in cardiac cushion EndoMT defects. Additionally, the targeted deletion of the downstream Notch effector Hairy/enhancer-of-split associated with the YRPW motif 2 (Hey2) or double-deficiency of Hey1 and Hey2 results in various congenital heart anomalies including cardiac cushion defects. Notch inhibition in zebrafish embryos similarly prevents cardiac valve development, whereas the transient ectopic expression of activated Notch1 leads to hypercellular valves. Similar to zebrafish embryos, results of the present study show that constitutively active Notch1 in endothelial cells increased EndoMT in the mouse embryo heart. In addition, IC-Notch1-expressing cells exhibited the expression of myoblast marker -SMA and downregulation of the endothelial cell marker VE cadherin. These findings provide further evidence of the involvement of Notch signaling in embryonic development by regulating EndoMT. The Snail family proteins are zinc finger-containing transcriptional repressors that trigger EndoMT during embryonic development by regulating the expression of junctional proteins such as cadherins. In mice, Snail is expressed in the cardiac cushions after E9.5. Mouse embryos with targeted deletion of Notch1 or CSL lack cardiac Snail expression, and show abortive endocardial EndoMT with abnormal maintenance of intercellular adhesion complexes. In the embryo heart, Notch functions via lateral induction to promote Snail-mediated EndoMT which leads to the cellularization of the developing cardiac valvular primordium. In this study, we found that ZAP-IC-Notch1/Tie2-Cre mouse embryo hearts showed a higher expression of Snail in the mRNA and protein levels. In addition, an increase in Snail protein expression was observed in mesenchymal cells of cardiac cushion. These findings confirm that Notch signaling promotes Snail expression in embryo heart through the gain-of-function mouse model. VE cadherin is a strictly endothelial-specific adhesion molecule located at junctions between endothelial cells. During EndoMT, VE-cadherin expression is reduced in endothelial cells undergoing transdifferentiation. The expression of cadherin 5 gene, which encodes VE-cadherin protein, can be suppressed by Snail transcription factor and Notch signaling components. Our results indicate that the mRNA and protein levels of VE cadherin is decreased in ZAP-IC-Notch1/Tie2-Cre mouse embryo heart, which confirms that constitutively active Notch signaling downregulates VE-cadherin expression. EphrinB2 and its receptor EphB4 are involved in determining the boundaries between arteries and veins. Although its expression is known to be arterial endothelial cell-specific, EphrinB2 is also expressed in perivascular mesenchymal cells. Dll4/Notch1 is upstream of EphB4/ephrinB2 signaling during cardiovascular development. In this study, EphrinB2 expression was upregulated in ZAP-IC-Notch1/Tie2-Cre mouse embryo heart and immunostaining showed an increased EphrinB2 expression in cardiac mesenchymal cells, suggesting that Notch signaling differentially regulates endothelial cell markers during EndoMT. In summary, we employed a Cre/loxP conditional mouse model and specifically activated IC-Notch1 expression in endothelial cells. The results demonstrate that constitutively active Notch signaling inhibits angiogenesis and promotes EndoMT in mouse embryos through the gain-of-function mouse model. In addition, IC-Notch1 promotes Snail expression and differentially regulates endothelial/mesenchymal cell markers. The present study provides insights into the role of Notch signaling in EndoMT and cardiovascular development. |
Effect of Plant Extracts and Biological control agents on Rhizoctonia solani Kuhn This study aims to examined antagonistic ability of some Plant Extracts and bio agents against of Rhizoctonia solani. The aqueous Extracts of plants used in study (Common Hornwort, Sage and Thorn apple) had against effect on the growth of pathogen in PSA medium. The Common Hornwort and Sage at rate 15% was superior inhibits fungal growth, it was 100.0 %. The results showed that alcoholic extract of plants (in concentrate 10 and 15%) was also effective and caused highly activity to inhibit radial growth of pathogen. In addition to the concentrates 1 and 5% were inhibited at rates 40.8-69.6% and 63.0-3838%. Thorn apple (Datura) extract was superior on Sage then Common Hornwort respectively. In the other hand the results appeared that Effective Microorganisms (EM-1) reduced growth of fungus more than organic fertilizer, Sea Bloom 29 which was 100.0% at both rates 10 and 15% whereas, the concentration 1 and 5% have inhibition influence which was 48.5 and 76.3% respectively. These results showed for the first time that ability of using the plant extracts and bioagents as alternative methods to control of the most serious plant pathogen and reduce using of chemicals and their problems. Introduction The fungus Rhizoctonia solani kuhn, which is one of the most important pathogens on many economic crops, causing significant damage and losses in production both in terms of quantity and quality. The fungus attacks the plant at all stages of its growth, causing seed rot, seedling death, and root rot. The primary symptoms of the disease appear in the form of light brown spots along the main and secondary roots. As the infection progresses, all the roots become rotten and dark brown. The use of chemical methods to control plant diseases has led to many environmental and health problems and disturbed the natural balance of life. In addition, many of them have lost their effective control effect due to the development of new strains of pathogens tolerant of these chemicals. Researchers have increased interest in using plant extracts to combat many plant pathogenic fungi, as these extracts contain effective secondary metabolic compounds and possess environmentally desirable characteristics such as their rapid decomposition, low toxicity, and high specialization. Many of them have been used in the control of R. solani. In the midst of the search for alternatives to chemicals in agriculture, research has shown the efficacy of the biological combination of Effective Microorganisms (EM-1) in controlling many diseases and improving growth and production of Plant. In view of the importance of this pathogen in Iraq and the attempt to control disease by using biological agents and plant extracts, this study was conducted with the aim of trying to control the pathogen with some plant extracts and biological control agents. Preparation of aqueous and alcoholic extracts of Common Hornwort, Sage and Thorn apple Three plants were selected (Table 1) to study their effect against the pathogen R. solani (a pure isolate was obtained from the Laboratory of Plant Diseases-Technical College of Al-Mussaib). They included Common Hornwort Ceratophylum demereni, Sage Salvia officinalis and Thorn apple Datura stramonium. Common Hornwort plants were collected from rivers, washed well to remove the impurities and mud from them while the Sage were obtained from the markets and the Thorn apple plant was collected from some fields at the Technical Institute / Al-Mussaib, after which the plant samples were dried in the open air under the sun's rays, by brushing them in the form of thin layers over wide surfaces of cloth and exposing them to the rays of the sun. For an appropriate period of time with continuous stirring of samples to prevent them from rotting and to speed up their drying. The plant specimens were crushed with a grinder containing a fine-mesh sieve. The powder of each plant was placed in polyethylene bags with the name of the plant and the weight of the form written on it and kept in the refrigerator until use. The extraction was done using Shekhawat and Prasada method with some 2 modification, where a certain volume of each powder from the used plants was taken and placed in a 1 liter glass flask and distilled water was added (70% ethyl alcohol in the case of an alcoholic extract) in a ratio of 1: 2 ( Volume / volume) The flask was closed and placed in a Julabo Sw20 electric shaker for 24 hours at room temperature (24 + 1 ° C). The solution was filtered with a clean cloth to get rid of large particles, then the extract was filtered through Whatman No.1 filter paper placed in a Buechner funnel with a vacuum. The total filtrate obtained from the extraction was concentrated in a water bath at a temperature of 50 ° C to get rid of the water, and a thick liquid was obtained. The extracts were weighed and stored in marked and sealed glass bottles and placed in the refrigerator until use. Inhibitory activity of the aqueous and alcoholic extracts of Common Hornwort, Sage and Thorn apple in the growth of Rhizoctonia solani in PSA The effect of plant extracts on the growth of R. solani was tested by food poisoning method. The concentrations (1, 5, 10, 15%) of the extract of the plants prepared for the test were prepared with sterile and cooled PSA medium respectively, while the medium was left without adding the extract as a control, the media was poured into sterile dishes (9 cm in diameter) and after the medium hardened The plates were inoculated in the center with a disc of diameter (0.5 cm) from the culture medium containing the growths of the pathogen R. solani at 5 days old. The experiment was carried out using a completely random design, and three plates were used for each treatment as replicates. The plates were incubated at a temperature of 25 + 1 ° C, and after the diameter of the fungal culture in the control treatment (without extract) to reached to the edge of the plate, the results were taken by calculating the rate of measurement of two perpendicular diameters from the growth of each colony and the percentage of inhibition was calculated according to the following equation: Inhibition (%)= x 100. Evaluation of the inhibitory effect of EM-1 and Sea Bloom29 on the growth of Rhizoctonia solani under laboratory conditions. The EM-1 bioactive preparation was activated by mixing the stock material with molasses and warm sterile distilled water in a ratio of 5: 5: 95, respectively. Dissolve the molasses well with warm water, then add the stock solution and mix well and put in a small plastic 5-liter barrel sealed with a plastic cover to prevent air contact with the solution and put in the incubator at a temperature of 37 + 1 m for 10 days with opening the barrel 2-3 times to leak gas When a layer of sediment is formed at the bottom of the barrel. The effect of EM-1 and Sea Bloom (obtained from the College of Agriculture, University of Baghdad) on the growth of R. solani was tested by food poisoning method. The same concentrations mentioned in the previous paragraph were prepared by adding a certain volume of each solution to a specific volume of the culture medium, where 1, 5, 10, and 15 ml of the solution were added to 99, 95, 90, 85 ml of sterile and cooled PSA medium, Then the medium was shaken to distribute the solution homogeneously in the medium and poured into sterile dishes (9 cm in diameter). Three dishes were used for each treatment in addition to the control treatment, which contained only the PSA medium. As for the chemical pesticide Beltanol, a concentration of 0.5 ml / liter of sterilized and cooled PSA was added. The dishes were incubated at a temperature of 25 + 1 ° C. After the fungal culture was reached to the edge of the plate in control treatment, the results were taken as followed in the previous paragraph3 The effect of the aqueous extracts of Common Hornwort, Sage and Thorn apple on the growth of R. solani in the PSA medium The results (Figures 1 and 2) showed the difference in the efficiency of the aqueous extract of the plants used in inhibiting the growth of R. solani according to the used concentrations, as the concentration of 15% of the extract of the Common Hornwort 3 and Sage achieved the highest reduction in the growth rate of the pathogen fungus by 0.0 cm and the rate of inhibition of 100% while it appeared A slight growth in Thorn apple extract at the same concentration reached 1.2 cm, with an inhibition rate of 78.3%, with a significant difference from the control treatment, in which the growth rate of the fungus was 9.0 cm and the inhibition rate was zero. It was followed by a concentration of 10%, as the fungus growth rate was 1.8, 1.3 and 2.7 cm for Common Hornwort, Sage and Thorn apple extract, respectively, with a significant superiority for a Sage extract over a Thorn apple extract, as it achieved a high inhibition rate of 85.2%, while the concentrations 1 and 5% achieved significant inhibition ratios except for concentration 1 % of Thorn apple that grew the fungus well and did not differ from the control treatment. The results of the current study showed, for the first time in the world, that the aqueous extract of the Common Hornwort plant, with the concentrations mentioned above, has an inhibitory effect on the pathogen R. solani, which is one of the most dangerous fungi living in the soil and the most pathogenic for the plant. The results are consistent with what Fareed et al have shown regarding the effectiveness of extracts of some plants, including the Common Hornwort plant, in inhibiting the growth of a number of bacterial and fungal pathogen species. And with Ismail results, which proved that Sage extract with concentrations of 250-1000ppm was the best among the plants tested in inhibiting the growth of the pathogen Fusarium oxysporum that causes Fusarium wilt in the medium, with an inhibition rate ranging between 17.2 -40.8%. And with what San Aye and Matsumoto found that the aqueous and alcoholic extract of Sage and some other plants inhibit the ability of some pathogenic fungi, including the pathogen R.solani Jalander and Gachande demonstrated the effectiveness of the aqueous extract of the Thorn apple plant in inhibiting the growth of some pathogenic fungi. This inhibitory activity of Thorn apple is due to the fact that it contains many antifungal compounds such as tigloidine (3B-tigloyloxytropane), tropine (3ahydroxy tropane), apoatropine, hyoscyamine and others. The effect of the alcohol extract of some plants and the chemical pesticide Beltanol on the growth of R. solani The results ( Fig. 3 and 4) showed the effectiveness of the alcoholic extract of the tested plants in inhibiting the growth of the pathogen R. solani. Inhibition was 92.6% compared to the control treatment in which the fungus growth was 9cm and the inhibition rate was 0%. Concentrations 1 and 5% achieved good inhibition rates ranging between 40.8-69.6% and 63-83.3%, respectively, with a significant superiority for the Thorn apple plant extract, followed by the Sage plant extract and then the Common Hornwort plant extract. On the other hand, the results showed the efficiency of the treatment of the chemical fungicide Beltanol with a concentration of 0.05% in completely inhibiting the pathogenic fungus, which is one of the most efficient chemical pesticides in controlling the pathogen, as it completely prevented the growth of the fungus with an inhibition rate of 100%. The results are consistent with what was found by many studies of the efficacy of the pesticide Beltanol in controlling the disease fungus, which is attributed to it being an effective pesticide against a wide range of pathogenic fungi and this efficacy is due to the formation of chelating compounds with copper in the host's tissues. This facilitates its way into the pathogen cells, and then it is liberated and kills the pathogen. The inhibitory effect of the Common Hornwort plant extract may be attributed to a change in the properties of the growing medium because the extract contains some inhibitory substances, and due to the lack of studies on the subject, we recommend conducting studies on the subject and identifying the active substances. Whereas studies have shown that the inhibitory action of Sage plant is due to its containment of many essential oils, Tannis, Oestrogens, Organic acids, Terpenhydroxides, Myrecine, Cymene and other substances that have an inhibitory action for microorganisms, including fungi 3 The effect of EM-1 and Bloom 29 Sea on the growth of R. solani in PSA culture. The results (Figures 5 and 6) showed a significant superiority of EM-1 product over Sea Bloom and the different concentrations used, thus achieving high inhibition ratios reaching a maximum of (100%) at concentrations of 10 and 15% respectively, which is recommended to use a concentration of 10% as there is no difference in the result Concentration to 15%, while concentration 1 and 5% brought about a clear reduction in the rate of fungal growth, causing inhibition rates of 48.5 and 76.3%, respectively. The results were consistent with what Castro et al. found when testing the effect of EM-1 on many pathogenic fungi of the plant in a laboratory, where he observed inhibition of fungi and bacteria in the PDA medium with an addition of EM-1 at a concentration of 5% with different inhibition rates and that the most sensitive fungi was Pythium sp. It obtained 100% inhibition, while R. solani was inhibited by 50%. The results also agreement with what the surgeon found that the EM-1 product has good levels of inhibition of the pathogen R. solani amounted to 88.67% at concentration 10%, but the percentages of inhibition that the researcher reached do not agree with the percentages of inhibition in the current study, and this difference may be due to different working conditions and different fungal isolates, as the fungus isolates vary in their toxicity and speed of growth between plant hosts, different geographical areas. Sea Bloom29 bio fertilizer contains many nutrients from seaweed, growth regulators, and amino acids, and helps stimulate systemic resistance and increase plant growth. The effect of EM-1 biosynthesis is due to the components of this product, which is composed of a biological combination that includes many bacterial species, yeasts and selected fungi compatible with each other that are beneficial to plants and soil and that have efficiency in inhibiting the activity of many plant pathogens. Conclusions We can concluded from The results of the current study for the first time in the world, the possession of aqueous and alcoholic extract of Common Hornwort, Sage and Thorn apple have a inhibitory effect on the pathogen R. solani, which is one of the most dangerous fungi inhabit in the soil and the most pathogenic for the plant. We also conclude the biological effectiveness of EM-1 and Sea Bloom against pathogenic fungi, which gives a new distance for the use of these environmentally safe materials as an alternative to harmful chemical pesticides3 |
<filename>26-Implementing-a-better-Newlib/main.c
/** ***************************************************************************
* @file main.c
* @brief Simple LED Blink Demo for EFM32GG_STK3700
* @version 1.0
******************************************************************************/
#include <stdint.h>
/*
* Including this file, it is possible to define which processor using command line
* E.g. -DEFM32GG995F1024
* The alternative is to include the processor specific file directly
* #include "efm32gg995f1024.h"
*/
#include <stdint.h>
#include <stdio.h>
#include "em_device.h"
#include "clock_efm32gg2.h"
#include "led.h"
#include "lcd.h"
/*****************************************************************************
* @brief SysTick interrupt handler
*
* @note Called every 1/DIVIDER seconds (1 ms)
*/
//{
#define SYSTICKDIVIDER 1000
#define SOFTDIVIDER 1000
static uint64_t ticks = 0;
void SysTick_Handler(void) {
static int counter = 0; // must be static
ticks++;
if( counter != 0 ) {
counter--;
} else {
counter = SOFTDIVIDER-1;
LED_Toggle(LED1);
}
}
//}
/*****************************************************************************
* @brief Delay function based on SysTick
*****************************************************************************/
void
Delay(uint32_t v) {
uint64_t lim = ticks+v; // Missing processing of overflow here
while ( ticks < lim ) {}
}
/*****************************************************************************
* @brief Main function
*
* @note Using default clock configuration
* HFCLK = HFRCO
* HFCORECLK = HFCLK
* HFPERCLK = HFCLK
*/
#include "uart2.h"
#define DELAYVAL 2
int main(void) {
char line[100];
int tryn = 0;
/* Configure LEDs */
LED_Init(LED1|LED2);
// Set clock source to external crystal: 48 MHz
(void) SystemCoreClockSet(CLOCK_HFXO,1,1);
/* Turn on LEDs */
LED_Write(0,LED1|LED2);
/* Configure SysTick */
SysTick_Config(SystemCoreClock/SYSTICKDIVIDER);
// Message
printf("Starting......");
/* Configure LCD */
LCD_Init();
LCD_SetAll();
Delay(DELAYVAL);
LCD_ClearAll();
Delay(DELAYVAL);
LCD_WriteString("hello");
// Enable IRQs
__enable_irq();
printf("Hello\n");
while (1) {
LED_Toggle(LED2);
printf("Try %d\n",tryn++);
printf("\nYour name: ");
fgets(line,99,stdin);
printf("Hello %s\n",line);
Delay(100);
}
}
#if 0
int main(void) {
//uint32_t v;
const uint32_t DELAYVAL = 2;
/* Configure Pins in GPIOE */
LED_Init(LED1|LED2);
LED_On(LED1|LED2);
// Set clock source to external crystal: 48 MHz
(void) SystemCoreClockSet(CLOCK_HFXO,1,1);
/* Configure SysTick */
SysTick_Config(SystemCoreClock/SYSTICKDIVIDER);
// Message
printf("Starting......");
/* Configure LCD */
LCD_Init();
LCD_SetAll();
Delay(DELAYVAL);
LCD_Clear_All();
Delay(DELAYVAL);
LCD_WriteString("hello");
// Configure ADC for temperature measurement
Temperature_Init(500000);
/* Blink loop */
__enable_irq();
while (1) {
// v = Temperature_GetRawValue();
//printf("t=%u\n",(unsigned) v);
Delay(DELAYVAL);
LED_Toggle(LED1); // Toggle LED1
}
}
#endif
|
/// Display the results in a human readable format.
pub fn display(&self, powers: &[Float], top_amount: usize, precision: u32) {
let win_rates: Vec<_> = self
.wins
.iter()
.map(|w| Float::with_val(precision, w) / Float::with_val(precision, self.rounds))
.collect();
println!("Results (top {} validators) :", top_amount);
println!("power win rate wins diff");
for i in 0..top_amount {
let diff = Float::with_val(precision, &win_rates[i] - &powers[i]);
println!(
"{:0.8} {:0.8} {:>8} {:+0.8}",
powers[i].to_f64(),
win_rates[i].to_f64(),
self.wins[i],
diff.to_f64()
);
}
println!();
println!("blocks: {}", self.rounds);
println!("max multi shard win : {}", self.max_win_across_shards);
println!("min winner score : {:0.8}", self.min_win_weight.to_f64());
println!("max winner score : {:0.8}", self.max_win_weight.to_f64());
println!(
"avr winner score : {:0.8}",
Float::with_val(
precision,
&self.sum_win_weight / Float::with_val(precision, self.rounds)
)
.to_f64()
);
} |
Characterization of the power line carrier communications environment of the American home The growing interest in user installable home automation has prompted a considerable interest in the use of the AC power line for intrahome communications. The author describes an approach to characterize the ability of all types of American homes to support this power line carrier (PLC) communication. The effort described involves a considerable amount of field data acquisition, data reduction and extensive characterization of commonly found power line operated devices. The general approach chosen, the type of measurements made, and the type of information being distilled from the field data is discussed.<<ETX>> |
BODIPY derivatives as fluorescent reporters of molecular activities in living cells Fluorescent compounds have become indispensable tools for imaging molecular activities in the living cell. 4,4-Difluoro-4-bora-3a,4a-diaza-s-indacene (BODIPY) is currently one of the most popular fluorescent reporters due to its unique photophysical properties. This review provides a general survey and presents a summary of recent advances in the development of new BODIPY-based cellular biomarkers and biosensors. The review starts with the consideration of the properties of BODIPY derivatives required for their application as cellular reporters. Then review provides examples of the design of sensors for different biologically important molecules, ions, membrane potential, temperature and viscosity defining the live cell status. Special attention is payed to BODPY-based phototransformable reporters. The bibliography includes 339 references. |
<filename>src/subject.ts
import {areHookInputsEqual, isFunction, isKindOf} from './utils';
export interface Observer<TValue> {
next(value: TValue): void;
error(error: Error): void;
complete(): void;
}
export type Unsubscribe = () => void;
export type MainHook<TValue> = () => TValue;
export type CleanUpEffect = () => void;
export type Effect = () => CleanUpEffect | void;
export type CreateInitialState<TState> = () => TState;
export type CreateState<TState> = (previousState: TState) => TState;
export type SetState<TState> = (state: TState | CreateState<TState>) => void;
interface EffectMemoryCell {
readonly kind: 'EffectMemoryCell';
outdated: boolean;
effect: Effect;
dependencies: unknown[] | undefined;
cleanUpEffect?: CleanUpEffect;
}
interface StateMemoryCell<TState> {
readonly kind: 'StateMemoryCell';
readonly setState: SetState<TState>;
state: TState;
stateChanges: (TState | CreateState<TState>)[];
}
interface MemoMemoryCell<TValue> {
readonly kind: 'MemoMemoryCell';
value: TValue;
dependencies: unknown[];
}
type MemoryCell = EffectMemoryCell | StateMemoryCell<any> | MemoMemoryCell<any>;
type Result<TValue> =
| {readonly type: 'value'; readonly value: TValue}
| {readonly type: 'error'; readonly error: Error}
| {readonly type: 'completed'};
export class Subject<TValue> {
private static active: Subject<unknown> | undefined;
public static getActive(): Subject<unknown> {
if (!Subject.active) {
throw new Error(
'Hooks can only be called inside the body of the main hook.'
);
}
return Subject.active;
}
private readonly memory: MemoryCell[] = [];
private observers: Set<Observer<TValue>> | undefined = new Set();
private memoryAllocated = false;
private memoryPointer = 0;
private latestResult?: Result<TValue>;
public constructor(private readonly mainHook: MainHook<TValue>) {}
public subscribe(observer: Observer<TValue>): Unsubscribe {
this.observers?.add(observer);
if (!this.latestResult) {
this.run();
} else if (this.latestResult.type === 'value') {
observer.next(this.latestResult.value);
} else if (this.latestResult.type === 'error') {
observer.error(this.latestResult.error);
} else {
observer.complete();
}
return () => this.observers?.delete(observer);
}
public complete(): void {
const observers = this.observers;
if (!observers) {
return;
}
this.observers = undefined;
this.latestResult = {type: 'completed'};
this.cleanUpEffects(true);
for (const observer of observers) {
try {
observer.complete();
} catch (error) {
// @ts-ignore
console.error('Error while completing.', error);
}
}
}
public useEffect(effect: Effect, dependencies?: unknown[]): void {
if (this !== Subject.active) {
throw new Error(
'Please use the separately exported useEffect() function.'
);
}
const memoryCell = this.getMemoryCell<EffectMemoryCell>('EffectMemoryCell');
if (!memoryCell) {
this.memory[this.memoryPointer] = {
kind: 'EffectMemoryCell',
outdated: true,
effect,
dependencies
};
} else if (
!areHookInputsEqual(memoryCell.dependencies, dependencies) ||
memoryCell.outdated
) {
memoryCell.outdated = true;
memoryCell.effect = effect;
memoryCell.dependencies = dependencies;
}
this.memoryPointer += 1;
}
public useState<TState>(
initialState: TState | CreateInitialState<TState>
): [TState, SetState<TState>] {
if (this !== Subject.active) {
throw new Error(
'Please use the separately exported useState() function.'
);
}
let memoryCell = this.getMemoryCell<StateMemoryCell<TState>>(
'StateMemoryCell'
);
if (!memoryCell) {
this.memory[this.memoryPointer] = memoryCell = {
kind: 'StateMemoryCell',
setState: state => {
memoryCell!.stateChanges = [...memoryCell!.stateChanges, state];
Promise.resolve().then(() => this.run());
},
state: isFunction<CreateInitialState<TState>>(initialState)
? initialState()
: initialState,
stateChanges: []
};
}
this.memoryPointer += 1;
return [memoryCell.state, memoryCell.setState];
}
public useMemo<TValue>(
createValue: () => TValue,
dependencies: unknown[]
): TValue {
if (this !== Subject.active) {
throw new Error('Please use the separately exported useMemo() function.');
}
let memoryCell = this.getMemoryCell<MemoMemoryCell<TValue>>(
'MemoMemoryCell'
);
if (!memoryCell) {
this.memory[this.memoryPointer] = memoryCell = {
kind: 'MemoMemoryCell',
value: createValue(),
dependencies
};
} else if (!areHookInputsEqual(memoryCell.dependencies, dependencies)) {
memoryCell.value = createValue();
memoryCell.dependencies = dependencies;
}
this.memoryPointer += 1;
return memoryCell.value;
}
private run(): void {
try {
if (!this.memoryAllocated || this.applyStateChanges()) {
do {
this.execute();
while (this.applyStateChanges()) {
this.execute();
}
this.cleanUpEffects();
this.triggerEffects();
} while (this.applyStateChanges());
}
} catch (error) {
const observers = this.observers;
if (!observers) {
return;
}
this.observers = undefined;
this.cleanUpEffects(true);
this.latestResult = {type: 'error', error};
for (const observer of observers) {
try {
observer.error(error);
} catch (error) {
// @ts-ignore
console.error('Error while publishing error.', error);
}
}
}
}
private execute(): void {
if (!this.observers) {
return;
}
Subject.active = this;
try {
this.memoryPointer = 0;
const value = this.mainHook();
if (this.memoryPointer !== this.memory.length) {
throw new Error('The number of hook calls must not change.');
}
this.memoryAllocated = true;
this.latestResult = {type: 'value', value};
for (const observer of this.observers) {
try {
observer.next(value);
} catch (error) {
// @ts-ignore
console.error('Error while publishing value.', error);
}
}
} finally {
Subject.active = undefined;
}
}
private cleanUpEffects(force = false): void {
for (const memoryCell of this.memory) {
if (isKindOf<EffectMemoryCell>('EffectMemoryCell', memoryCell)) {
if ((memoryCell.outdated || force) && memoryCell.cleanUpEffect) {
try {
memoryCell.cleanUpEffect();
} catch (error) {
// @ts-ignore
console.error('Error while cleaning up effect.', error);
}
memoryCell.cleanUpEffect = undefined;
}
}
}
}
private triggerEffects(): void {
for (const memoryCell of this.memory) {
if (isKindOf<EffectMemoryCell>('EffectMemoryCell', memoryCell)) {
if (memoryCell.outdated) {
memoryCell.outdated = false;
memoryCell.cleanUpEffect = memoryCell.effect() || undefined;
}
}
}
}
private applyStateChanges(): boolean {
let changed = false;
for (const memoryCell of this.memory) {
if (isKindOf<StateMemoryCell<unknown>>('StateMemoryCell', memoryCell)) {
for (const stateChange of memoryCell.stateChanges) {
const state = isFunction<CreateState<unknown>>(stateChange)
? stateChange(memoryCell.state)
: stateChange;
if (!Object.is(memoryCell.state, state)) {
memoryCell.state = state;
changed = true;
}
}
memoryCell.stateChanges = [];
}
}
return changed;
}
private getMemoryCell<TMemoryCell extends MemoryCell>(
kind: TMemoryCell['kind']
): TMemoryCell | undefined {
const memoryCell = this.memory[this.memoryPointer];
if (!memoryCell && this.memoryAllocated) {
throw new Error('The number of hook calls must not change.');
}
if (memoryCell && !isKindOf<TMemoryCell>(kind, memoryCell)) {
throw new Error('The order of hook calls must not change.');
}
return memoryCell;
}
}
|
Need for comprehensive standardization strategies for marketed Ayurveda formulations Ayurveda is known for the use of poly-herbal formulations and multi-component therapeutics for the management of health and diseases. Several pharmaceutical companies are manufacturing and marketing different Ayurvedic formulations, prepared as per the classical texts and the regulatory standards. However, on a cursory glance, marked variations are observed amongst the same formulations manufactured by different companies. This raises questions on the quality standards. Drugs or formulations are expected to exert a desired biological activity at particular concentrations of their chemical constituents. The overall aim of drug standardization is to ensure the quality, efficacy and uniformity of the products, in terms of their chemical and biological properties, across the manufactures. In this article, the authors intend to open up a discussion on the need for comprehensive standardization strategies for marketed Ayurveda formulations taking Lodhrasavam (a classical Ayurveda preparation) as an example. Lodhrasavam procured from six reputed Ayurveda drug manufacturers showed significant variations in their sensorial, physico-chemical, chromatographic as well as biological properties. This is a matter of serious concern and need to be addressed effectively to derive better standardization strategies for Ayurvedic formulations. Introduction Ayurveda is one of the Indian Systems of Medicine (ISM), wherein the concepts of 'holism' are logically and intelligently used to understand the wellness (Svasthya) and illness (Asvasthya) of living organisms. Ayurveda predominantly uses herbal products/ formulations for the maintenance of health and management of diseases. These formulations are designed and manufactured based on unique principles of Ayurveda pharmacology (Dravyagunashasthra), which are epistemologically different from the modern pharmacology concepts of molecular medicines. They are expected to exert a 'network pharmacology' (multi-drug-multi-target mode of action) effect, due to the presence of several bioactive molecules, that is different from the well known and widely studied single-drug-single-target action of molecular drugs (lock and key hypothesis). This is considered as one of the strengths of Ayurveda, and perhaps for all other complementary and alternative medicines (CAMs) across the globe. However, complexity of the herbal formulations is a major challenge in Ayurveda drug industry, making standardization of Ayurveda formulation a difficult task. Even a cursory glance of several generic Ayurveda formulations produced and marketed by different companies show enormous variations amongst the same product. This raises questions on their quality standards. Ayurveda as a science and drug industry, it is very important to follow stringent and non-compromising quality control parameters to ensure uniformity and standards of the formulations/products across the industry. In this context, this article intends to bring out a discussion on the need for better and comprehensive standardization strategies for Ayurveda formulations taking the example of the variations observed in marketed samples of Lodhrasavam. The authors are working on the formulation Lodhrasavam, focusing on its anti-diabetic and anti-obesity potentials. Lodhrasavam is a complex, poly-herbal formulation prepared from 29 plant drugs, with self generated alcohol in it. Ayurveda mentions Lodhra (Symplocos racemosa Roxb.) as the major ingredient in the formulation, which is referred as a medo-hara (anti-obesity) plant and is the prime member of Lodhradi-gana plants (a group of plants having medo-hara and kapha-hara properties) described in Ayurveda. Besides the anti-diabetic and anti-obesity applications, Lodhrasavam is also indicated for various other diseases such as aneamia, skin diseases, anorexia, hemorrhoids etc. As part of the sample collection the team collected six marketed samples of Lodhrasavam, manufactured by well-known Ayurveda drug manufacturers in India. The samples are labeled as LOD A e F. Though our focus was on antidiabetic and anti-obesity effects of Lodhrasavam, the drastic variations in the visual appearance of these marketed samples ( Fig. 1A) urged us to do a comparative analysis for their physico-chemical properties as well as biological activities. Lodhrasavam is a classical Ayurveda product that is expected to follow a definite method of preparation as indicated by the formulary. According to the product descriptions, all samples are marketed with the product name Lodhrasavam and claimed to be prepared in a similar manner as per the classical texts of Ayurveda. However, variations are seen in the final products right from simple sensorial parameters. This is large enough to cast doubt on the quality, genuinely and authenticity of the product by the consumers and physicians. Hedonicity and physicochemical properties In view of the visual differences observed, the marketed samples were compared for the degree of likeness (hedonicity), from a consumer perspective, based on taste, odour and palatability. A small amount of the sample was given to 20 healthy volunteers and instructed to report their degree of likeness under any one of the seven classifications given (Fig. 1B). Out of the six samples tested, only sample B and C were found to be appealing by participants wherein 11 people liked sample B and 7 people liked sample C. All other samples were found to be not appealing (Fig. 1B). The samples were also analyzed and compared for their physicochemical properties viz. alcohol content, total reducing sugars and tannins, density, suspended particles, optical density, brix value, refractive index and pH value. The results showed drastic variations in the physicochemical parameters studied and the variations are found to be random and not following any sample-specific pattern (Fig. 1D). Some of the samples are not complying with the prescribed pharmacopoeial limits like alcohol content. Similarly a simple thin layer chromatography (TLC) comparison of the six samples also showed considerable differences in the banding pattern (Fig. 1C), that further substantiates the visual, hedonicity and physicochemical differences observed with the samples. Although it is too early to draw a direct correlation between the hedonicity and physicochemical parameters, it is important to note that the variations are reflected both at the consumer preference level as well as at the physicochemical content level. Profiling and comparison based on sensory properties Sensorial profiling is an important aspect for a product as it evaluates the consumer's level of acceptability of the product based on the organoleptic properties. It is more relevant from the consumer perspective as the differences in physicochemical and biological properties are too technical for the consumers to understand. Lodhrasavam is an oral medicine and the marketed samples were analyzed and compared for their sensorial properties viz. visual, olfactory, tactile and taste attributes. Substantiating the hedonicity and physico-chemical variations, all attributes/subattributes studied, except tactile attributes, were found to be varying between the samples (Table 1). Comparison of biological activity Lodhrasavam being an anti-diabetic and anti-obesity formulation prescribed in Ayurveda, comparison of biological activity of marketed samples was focused on their alpha-amylase and alphaglucosidase inhibition effects. The variations observed with sensorial, organoleptic and chemical properties are naturally expected to reflect in the biological activity of the formulation as well. Although all the samples showed inhibition of digestive enzymes (alpha-amylase and alpha-glucosidase), there are considerable differences in the percentage of inhibition at specific concentrations of the samples tested (Fig. 2). The variations observed with biological activity is more concerning as it raises questions on the credibility and authenticity of the formulation. Conclusion Drugs and formulations are expected to exert desired biological activities at desired concentrations of its chemical constituents. The overall aim of drug standardization is to have uniformity, across the manufactures, with respect to its chemical and biological properties. Our study basically intend to highlight the variations observed in marketed samples of Ayurveda formulations, using Lodhrasavam as an example. It is an unbiased study and have no intentions to claim any one of the samples (Lod AeF) is superior to the other. Lodhrasavam is just an example, and similar issues are there with other formulations as well. Though there are several factors that make the standardization of Ayurveda formulation a great challenge, drastic variations within the same product will raise questions on the authenticity and credibility of the product. The need of the hour is better standardization protocols and quality measures for uniformity of formulations across the Ayurveda drug industry. In the era of globalization of Ayurveda, it is necessary to have utmost attention on the quality control parameters for the therapeutic formulations. Our observations are expected to open up discussions on the need of consistency and uniformity of formulations across the Ayurvedic drug manufacturing industry. Conflicts of interest None. |
Picnics are the essential summer bucket list to-do. We interviewed the picnic pros (yes, these are the people who literally wrote the books on picnicking) who provided us with the perfect checklists so you can raise your picnic up a notch and have the best.picnic.ever.
Insulated bag It's important to keep hot foods hot and cold foods cold, said DeeDee Stovel, California-based author of Picnic. But, Stovel said, she also brings other fancier picnic baskets for the other items. "For many picnics, I bring an antique market basket lined with a pretty dishtowel for all the non-perishable items," she said. "If a little hike is involved, a picnic backpack containing dishes with insulated pockets for food is great."
Reusable water bottle You're sitting on the earth, so you should show it some love. Lori Popkewitz Alper, founder and editor-in-chief of Groovy Green Livin, a Web site dedicated to sharing green ideas based just outside of Boston, said she's been using Klean Kanteen stainless steel bottles (price varies at Kleankanteen.com for years, but she also likes the Lifefactory water bottles (starts at $14.99 for a 9 oz bottle at Lifefactory.com) which are made of high quality soda lime glass, and are wrapped in a protective silicone sleeve.
Reusable napkins Not only do they reduce paper waste, but they also make your picnic look so much fancier. Alper said she's found great ones on Etsy.
Freezer pack You spent the time cooking (or shopping), and you want the food to taste good. Alper recommended the non-toxic ice packs from Kids Konserve ($9.95 at Amazon.com), which come with a sweat-free cover.
Bandanas These become make-shift hats, napkins, splits, diapers, SOS flats, wine stoppers, props for Capture the Flat and even an air-conditioner if you wet one and put it around your neck, said Hilary Heminway, of Heminway Interiors in Stonington, Connecticut.
Cover the knife If you're tossing sharp objects into the basket like knives and corkscrews, make sure they're covered with a shield of some sort so that when you blindly stick you hand in to reach for them – or even for something else – that you don't cut yourself, Stovel said.
Individual lunch box Fill each one ahead of time, zip it up and place it into the picnic basket, ready to be handed out to guests, Heminway said, recommending that you skip the adorable wicker baskets, which look cute but invite ants to join the picnic.
Tablecloth, flowers and candles These always adds a festive touch, and go a long way toward setting the mood of the picnic, Heminway said.
Choosing a spot Sit by a stream, a lake or a shore, and use the water to double as a fridge for the drinks, Heminway said.
Keep a bag ready to go Sometimes, the best picnics are those that are planned on the spur of the moment. "I have a picnic basket in the garage filled with tablecloths, ground cover, tableware and dishes that I can just grab for a picnic anytime instead of rummaging around the house looking for things to pack," Stovel said.
Everyday Napkins, $25 at birchlane.com.
The Movable Feast Cooler Cart, $199.95 at hammacher.com. |
Ghrelin secretion is not reduced by increased fat mass during diet-induced obesity. Ghrelin is a stomach hormone that stimulates growth hormone (GH) secretion, adiposity, and food intake. Gastric ghrelin production and secretion are regulated by caloric intake; ghrelin secretion increases during fasting, decreases with refeeding, and is reduced by diet-induced obesity. The aim of the present study was to test the hypotheses that 1) an increase in body adiposity will play an inhibitory role in the reduction of gastric ghrelin synthesis and secretion during chronic ingestion of a high-fat (HF) diet and 2) chronic ingestion of an HF diet will suppress the rise in circulating ghrelin levels in response to acute fasting. Adult male Sprague-Dawley rats were fed a standard AIN-76A (approximately 5-12% of calories from fat) or an HF (approximately 45% of calories from fat) diet. The effect of increased adiposity on gastric ghrelin homeostasis was assessed by comparison of stomach ghrelin production and plasma ghrelin levels in obese and nonobese rats fed the HF diet. HF diet-fed, nonobese rats were generated by administration of triiodothyronine to lower body fat accumulation. Our findings indicate that an increased fat mass per se does not exert an inhibitory effect on ghrelin homeostasis during ingestion of the HF diet. Additionally, the magnitude of change in plasma ghrelin in response to fasting was not blunted, indicating that a presumed, endogenous signal for activation of ingestive behavior remains intact, despite excess stored calories in HF-fed rats. |
def if_hexagon_enabled(a):
return select({
"//micro:hexagon_enabled": a,
"//conditions:default": [],
})
def if_not_hexagon_enabled(a):
return select({
"//micro:hexagon_enabled": [],
"//conditions:default": a,
})
def new_local_repository_env_impl(repository_ctx):
echo_cmd = "echo " + repository_ctx.attr.path
echo_result = repository_ctx.execute(["bash", "-c", echo_cmd])
src_path_str = echo_result.stdout.splitlines()[0]
source_path = repository_ctx.path(src_path_str)
work_path = repository_ctx.path(".")
child_list = source_path.readdir()
for child in child_list:
child_name = child.basename
repository_ctx.symlink(child, work_path.get_child(child_name))
build_file_babel = Label("//:" + repository_ctx.attr.build_file)
build_file_path = repository_ctx.path(build_file_babel)
repository_ctx.symlink(build_file_path, work_path.get_child("BUILD"))
# a new_local_repository support environment variable
new_local_repository_env = repository_rule(
implementation = new_local_repository_env_impl,
local = True,
attrs = {
"path": attr.string(mandatory = True),
"build_file": attr.string(mandatory = True),
},
)
|
Perrin Kaplan: Has social networking improved or hurt productivity in your company?
As former Vice President of Marketing and Corporate Affairs for Nintendo of America Inc., Perrin oversaw many aspects of internationally recognized marketing and public relations programs. She oversaw all public relations, public and government affairs, investor relations, internal communications, international communications and community relations for the global company. She is a well-known spokesperson and has brought great personality to many of her interviews. |
/******************************************************************************
* User-Defined Class: vSDKSparkHelper
* Author: John Tanner @ Veeva
* Date: 2020-02-03
*-----------------------------------------------------------------------------
* Description: Useful Methods to help with Spark Integration between Vaults
*
*-----------------------------------------------------------------------------
* Copyright (c) 2020 Veeva Systems Inc. All Rights Reserved.
*
* This code is based on pre-existing content developed and
* owned by Veeva Systems Inc. and may only be used in connection
* with the deliverable with which it was provided to Customer.
*--------------------------------------------------------------------
*
*******************************************************************************/
@UserDefinedClassInfo()
public class vSDKSparkHelper {
/**
* Returns whether an active version of the specified 'integrationName'
* is configured against this (source) Vault.
*
* @param integrationName
*/
public static boolean isIntegrationActive(String integrationName) {
QueryService queryService = ServiceLocator.locate(QueryService.class);
StringBuilder query = new StringBuilder();
query.append("SELECT id, name__v, status__v ");
query.append("FROM integration__sys ");
query.append("WHERE name__v = '").append(integrationName).append("' ");
query.append("AND status__v = 'active__v' ");
QueryResponse integration = queryService.query(query.toString());
if (integration.getResultCount() == 0) {
return false;
} else {
return true;
}
}
/**
* Creates a User exception message
*
* @param integrationApiName
* @param integrationPointApiName
* @param errorMessage
* @param messageProcessor
* @param messageBody stores the message identifier so it can be re-run
*/
public static void createUserExceptionMessage(String integrationApiName,
String integrationPointApiName,
String errorMessage,
String messageProcessor,
String messageBody) {
LogService logService = ServiceLocator.locate(LogService.class);
RecordService recordService = ServiceLocator.locate(RecordService.class);
String integrationId = getIntegrationId(integrationApiName);
String integrationPointId = getIntegrationPointId(integrationPointApiName);
// Construct the user exception message
Record userExceptionMessage = recordService.newRecord("exception_message__sys");
List<String> errorTypePicklistValues = VaultCollections.newList();
errorTypePicklistValues.add("message_processing_error__sys");
userExceptionMessage.setValue("integration__sys", integrationId);
userExceptionMessage.setValue("integration_point__sys", integrationPointId);
userExceptionMessage.setValue("error_type__sys", errorTypePicklistValues);
userExceptionMessage.setValue("error_message__sys", errorMessage);
userExceptionMessage.setValue("name__v", integrationPointApiName);
userExceptionMessage.setValue("message_processor__sys", messageProcessor);
userExceptionMessage.setValue("message_body_json__sys", messageBody);
List<Record> recordsToSave = VaultCollections.newList();
recordsToSave.add(userExceptionMessage);
// Save the User Exception
recordService.batchSaveRecords(recordsToSave)
.rollbackOnErrors()
.execute();
StringBuilder logMessage = new StringBuilder();
logMessage.append("Created User exception message: ").append(errorMessage);
logService.info(logMessage.toString());
}
/**
* Returns the ID of the specified 'integrationName'
*
* @param integrationAPIName of the integration
*/
public static String getIntegrationId(String integrationAPIName) {
QueryService queryService = ServiceLocator.locate(QueryService.class);
StringBuilder query = new StringBuilder();
query.append("SELECT id ");
query.append("FROM integration__sys ");
query.append("WHERE integration_api_name__sys = '").append(integrationAPIName).append("'");
QueryResponse intQueryResponse = queryService.query(query.toString());
List<String> ids = VaultCollections.newList();
intQueryResponse.streamResults().forEach(qr -> {
ids.add(qr.getValue("id", ValueType.STRING));
});
return ids.get(0);
}
/**
* Returns the ID of the specified 'integrationPointAPIName'
*
* @param integrationPointAPIName of the integration
*/
public static String getIntegrationPointId(String integrationPointAPIName) {
QueryService queryService = ServiceLocator.locate(QueryService.class);
StringBuilder query = new StringBuilder();
query.append("SELECT id ");
query.append("FROM integration_point__sys ");
query.append("WHERE integration_point_api_name__sys = '").append(integrationPointAPIName).append("'");
QueryResponse intQueryResponse = queryService.query(query.toString());
List<String> ids = VaultCollections.newList();
intQueryResponse.streamResults().forEach(qr -> {
ids.add(qr.getValue("id", ValueType.STRING));
});
return ids.get(0);
}
/**
* Returns the ID of the specified 'connectionName'
*
* @param connectionAPIName of the integration
*/
public static String getConnectionId(String connectionAPIName) {
QueryService queryService = ServiceLocator.locate(QueryService.class);
StringBuilder query = new StringBuilder();
query.append("SELECT id ");
query.append("FROM connection__sys ");
query.append("WHERE api_name__sys = '").append(connectionAPIName).append("'");
QueryResponse intQueryResponse = queryService.query(query.toString());
List<String> ids = VaultCollections.newList();
intQueryResponse.streamResults().forEach(qr -> {
ids.add(qr.getValue("id", ValueType.STRING));
});
return ids.get(0);
}
/**
* Return a list of objects which haven't been migrated
* This uses a callback to the source vault to check for records in the integration_transaction__c object
* for the object/integration point, which have a processed status of pending and a last modified date
* greater than 10 seconds before. This wait is to allow for the job already being processed on a separate thread.
*
* @param connectionName to the source Vault
* @param objectName of the object name to be migrated from the source Vault
* @param targetIntegrationPoint for the source record
* @param runImmediately if true it doesn't wait for the 10 seconds before processing
*/
public static List<String> getUnprocessedObjects(String connectionName, // e.g. vsdk_connection_to_warranties
String objectName, // e.g. vsdk_warranty__c
String targetIntegrationPoint, // e.g. send_to_claims_pending__c
Boolean runImmediately) {
String reprocessBeforeDate = java.time.Clock.systemUTC().instant().minusSeconds(10).toString();
LogService logService = ServiceLocator.locate(LogService.class);
List<String> unprocessedObjectsList = VaultCollections.newList();
StringBuilder query = new StringBuilder();
query.append("SELECT source_key__c ");
query.append("FROM integration_transaction__c ");
query.append("WHERE transaction_status__c = 'pending__c' ");
query.append("AND source_object__c = '").append(objectName).append("' ");
query.append("AND target_integration_point__c = '").append(targetIntegrationPoint).append("' ");
if (!runImmediately) {
query.append("AND modified_date__v < '").append(reprocessBeforeDate).append("' ");
}
StringBuilder logMessage = new StringBuilder();
logMessage.append("Unprocessed Callback query: ").append(query.toString());
logService.info(logMessage.toString());
//This is a vault to vault Http Request to the source connection
HttpService httpService = ServiceLocator.locate(HttpService.class);
HttpRequest request = httpService.newHttpRequest(connectionName);
//The configured connection provides the full DNS name.
//For the path, you only need to append the API endpoint after the DNS.
//The query endpoint takes a POST where the BODY is the query itself.
request.setMethod(HttpMethod.POST);
request.appendPath("/api/v19.3/query");
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setBodyParam("q", query.toString());
//Send the request to the source vault via a callback. The response received back should be a JSON response.
//First, the response is parsed into a `JsonData` object
//From the response, the `getJsonObject()` will get the response as a parseable `JsonObject`
// * Here the `getValue` method can be used to retrieve `responseStatus`, `responseDetails`, and `data`
//The `data` element is an array of JSON data. This is parsed into a `JsonArray` object.
// * Each queried record is returned as an element of the array and must be parsed into a `JsonObject`.
// * Individual fields can then be retrieved from each `JsonObject` that is in the `JsonArray`.
httpService.send(request, HttpResponseBodyValueType.JSONDATA)
.onSuccess(httpResponse -> {
JsonData response = httpResponse.getResponseBody();
if (response.isValidJson()) {
String responseStatus = response.getJsonObject().getValue("responseStatus", JsonValueType.STRING);
if (responseStatus.equals("SUCCESS")) {
JsonArray data = response.getJsonObject().getValue("data", JsonValueType.ARRAY);
logService.info("HTTP Query Request: SUCCESS");
//Retrieve each record returned from the VQL query.
//Each element of the returned `data` JsonArray is a record with it's queried fields.
for (int i = 0; i < data.getSize();i++) {
JsonObject queryRecord = data.getValue(i, JsonValueType.OBJECT);
String sourceId = queryRecord.getValue("source_key__c", JsonValueType.STRING);
unprocessedObjectsList.add(sourceId);
}
data = null;
}
response = null;
}
else {
logService.info("getUnprocessedObjects error: Received a non-JSON response.");
}
})
.onError(httpOperationError -> {
logService.info("getUnprocessedObjects error: httpOperationError.");
}).execute();
request = null;
return unprocessedObjectsList;
}
/**
* Return a list of Integration Transaction Record Ids, associated with the given
* composite key which consists of source_record_id, source_object, target_integration_point
* and processed_status of pending
*
* @param connectionName to the source Vault
* @param objectName of the object name to be migrated from the source Vault
* @param targetIntegrationPoint for the source record
*/
public static List<String> getIntTransIds(String connectionName, // i.e. vsdk_connection_to_warranties
List<String> sourceRecordIds,
String objectName, // i.e. vsdk_warranty__c
String targetIntegrationPoint) { // i.e. send_to_claims_pending__c
LogService logService = ServiceLocator.locate(LogService.class);
List<String> idList = VaultCollections.newList();
StringBuilder query = new StringBuilder();
query.append("SELECT id ");
query.append("FROM integration_transaction__c ");
query.append("WHERE transaction_status__c = 'pending__c' ");
query.append("AND source_object__c = '").append(objectName).append("' ");
query.append("AND source_key__c contains ('").append(String.join("','", sourceRecordIds)).append("') ");
query.append("AND target_integration_point__c = '").append(targetIntegrationPoint).append("' ");
StringBuilder logMessage = new StringBuilder();
logMessage.append("Int Transactions Ids Callback query: ").append(query.toString());
logService.info(logMessage.toString());
//This is a vault to vault Http Request to the source connection
HttpService httpService = ServiceLocator.locate(HttpService.class);
HttpRequest request = httpService.newHttpRequest(connectionName);
//The configured connection provides the full DNS name.
//For the path, you only need to append the API endpoint after the DNS.
//The query endpoint takes a POST where the BODY is the query itself.
request.setMethod(HttpMethod.POST);
request.appendPath("/api/v19.3/query");
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setBodyParam("q", query.toString());
httpService.send(request, HttpResponseBodyValueType.JSONDATA)
.onSuccess(httpResponse -> {
JsonData response = httpResponse.getResponseBody();
if (response.isValidJson()) {
String responseStatus = response.getJsonObject().getValue("responseStatus", JsonValueType.STRING);
if (responseStatus.equals("SUCCESS")) {
JsonArray data = response.getJsonObject().getValue("data", JsonValueType.ARRAY);
logService.info("HTTP Query Request: SUCCESS");
//Retrieve each record returned from the VQL query.
//Each element of the returned `data` JsonArray is a record with it's queried fields.
for (int i = 0; i < data.getSize();i++) {
JsonObject queryRecord = data.getValue(i, JsonValueType.OBJECT);
String sourceId = queryRecord.getValue("id", JsonValueType.STRING);
idList.add(sourceId);
}
data = null;
}
response = null;
}
else {
logService.info("getIntTransIds error: Received a non-JSON response.");
}
})
.onError(httpOperationError -> {
logService.info("getIntTransIds error: httpOperationError.");
}).execute();
request = null;
return idList;
}
/**
* Sets the status of the source objects that have been migrated
* This uses a callback to the source vault for the object, based on the unprocessed status field/value
*
* @param recordsUpdateSourceRecordIds is a list parameter containing the affected source record Ids
* @param connectionName to the source Vault
* @param objectName of the object name to be migrated from the source Vault
* @param targetIntegrationPoint for the source record
* @param processSuccess for the source record
*/
//The recordsUpdate list parameter contains the affected source Ids.
//The source Ids are used to build a batch of vsdk_bike_store__c updates for the source system.
//The Update Record API takes JSON data as the body of the HttpRequest, so we can
// build a Json request with the `JsonObjectBuilder` and `JsonArrayBuilder`
public static void setIntTransProcessedStatuses(List<String> recordsUpdateSourceRecordIds,
String connectionName, // i.e. vsdk_connection_to_warranties
String objectName, // i.e. vsdk_warranty__c
String targetIntegrationPoint,
Boolean processSuccess) { // i.e. receive_warranties__c
HttpService httpService = ServiceLocator.locate(HttpService.class);
LogService logService = ServiceLocator.locate(LogService.class);
String processValue = "process_success__c";
if (!processSuccess) {
processValue = "process_failure__c";
}
// Get a list of Integration Transaction Record Ids, associated with the given
// composite key which consists of source_record_id, source_object, target_integration_point
// and processed_status of pending
List<String> recordUpdateIds = getIntTransIds(connectionName,
recordsUpdateSourceRecordIds,
objectName,
targetIntegrationPoint);
HttpRequest request = httpService.newHttpRequest(connectionName);
JsonService jsonService = ServiceLocator.locate(JsonService.class);
JsonObjectBuilder jsonObjectBuilder = jsonService.newJsonObjectBuilder();
JsonArrayBuilder jsonArrayBuilder = jsonService.newJsonArrayBuilder();
//The Update Object Record API takes JSON data as input.
//The input format is an array of Json objects.
//Use the `JsonObjectBuilder` to build the individual Json Objects with the necessary updates.
//Then add the resulting `JsonObject` objects to the `JsonArrayBuilder`
for (String value : recordUpdateIds) {
JsonObject inputJsonObject = jsonObjectBuilder.setValue("id", value)
.setValue("transaction_status__c", processValue)
.build();
jsonArrayBuilder.add(inputJsonObject);
}
//Once all the Json objects are added to the `JsonArray`, use the `build` method to generate the array.
JsonArray inputJsonArray = jsonArrayBuilder.build();
if (inputJsonArray.getSize() > 0) {
request.setMethod(HttpMethod.PUT);
request.appendPath("/api/v19.1/vobjects/integration_transaction__c");
request.setHeader("Content-Type", "application/json");
request.setBody(inputJsonArray);
httpService.send(request, HttpResponseBodyValueType.JSONDATA)
.onSuccess(httpResponse -> {
JsonData response = httpResponse.getResponseBody();
if (response.isValidJson()) {
String responseStatus = response.getJsonObject().getValue("responseStatus", JsonValueType.STRING);
if (responseStatus.equals("SUCCESS")) {
JsonArray data = response.getJsonObject().getValue("data", JsonValueType.ARRAY);
//Retrieve the results for each record that was updated.
//Each element of the returned `data` JsonArray is the results of a single updated record.
for (int i = 0; i <= data.getSize()-1;i++) {
JsonObject recordResponse = data.getValue(i, JsonValueType.OBJECT);
String recordStatus = recordResponse.getValue("responseStatus", JsonValueType.STRING);
JsonObject recordData = recordResponse.getValue("data", JsonValueType.OBJECT);
String recordId = recordData.getValue("id", JsonValueType.STRING);
StringBuilder logMessage = new StringBuilder();
logMessage.append("HTTP Update Request ").append(recordStatus)
.append(": ").append(recordId);
logService.info(logMessage.toString());
}
data = null;
}
response = null;
}
else {
logService.info("v2vHttpUpdate error: Received a non-JSON response.");
}
})
.onError(httpOperationError -> {
logService.info(httpOperationError.getMessage());
logService.info(httpOperationError.getHttpResponse().getResponseBody());
}).execute();
request = null;
inputJsonArray = null;
}
}
// Move to the Spark Queue AFTER the record has successfully been inserted.
public static void moveMessagesToQueue(String queueName, String objectName, String targetIntegrationPointAPIName, String recordEvent, List vaultIds) {
QueueService queueService = ServiceLocator.locate(QueueService.class);
LogService logService = ServiceLocator.locate(LogService.class);
RecordService recordService = ServiceLocator.locate(RecordService.class);
QueryService queryService = ServiceLocator.locate(QueryService.class);
Message message = queueService.newMessage(queueName)
.setAttribute("object", objectName)
.setAttribute("event", recordEvent)
.setAttribute("integration_point", targetIntegrationPointAPIName);
PutMessageResponse response = queueService.putMessage(message);
// Check that the message queue successfully processed the message.
// If it's successful, create an integrationTransaction record setting the `transaction_status__c` flag to 'pending__c',
// as long as it doesn't already exist, as there is no point duplicating it.
// Otherwise if there is an error, create an integrationTransaction record setting the `transaction_status__c` flag to 'send_failure__c'.
List<Record> intTransactionsToSave = VaultCollections.newList();
List<PutMessageResult> messageResultList = response.getPutMessageResults();
for (PutMessageResult messageResult : messageResultList) {
logService.info("Sent to Connection: " + messageResult.getConnectionName());
String connectionId = vSDKSparkHelper.getConnectionId(messageResult.getConnectionName());
logService.info("connectionId: " + connectionId);
logService.info("integrationPointAPIName: " + targetIntegrationPointAPIName);
// Query to see if any intTransactions already exist in pending state
StringBuilder query = new StringBuilder();
query.append("SELECT source_key__c ");
query.append("FROM integration_transaction__c ");
query.append("WHERE source_key__c contains ('" + String.join("','", vaultIds) + "') ");
query.append("AND source_object__c = '").append(objectName).append("' ");
query.append("AND connection__c = '").append(connectionId).append("' ");
query.append("AND target_integration_point__c = '").append(targetIntegrationPointAPIName).append("' ");
query.append("AND transaction_status__c = 'pending__c'");
QueryResponse queryResponse = queryService.query(query.toString());
logService.info("Query existing pending integration transactions by ID: " + query);
// Any pending integration transactions records that already exist will be removed from the list
// so they don't get recreated
queryResponse.streamResults().forEach(qr -> {
String source_key__c = qr.getValue("source_key__c", ValueType.STRING);
logService.info("Found existing pending record with Source Key: " + source_key__c);
vaultIds.remove(source_key__c);
});
queryResponse = null;
for (Object vaultId : vaultIds) {
Record integrationTransaction = recordService.newRecord("integration_transaction__c");
integrationTransaction.setValue("source_object__c", objectName);
integrationTransaction.setValue("source_key__c", vaultId);
integrationTransaction.setValue("target_integration_point__c", targetIntegrationPointAPIName);
integrationTransaction.setValue("connection__c", connectionId);
if (response.getError() != null) {
integrationTransaction.setValue("transaction_status__c", VaultCollections.asList("send_failure__c"));
StringBuilder err = new StringBuilder();
err.append("ERROR Queuing Failed: ").append(response.getError().getMessage());
integrationTransaction.setValue("message__c", err.toString().substring(1,1500));
} else {
integrationTransaction.setValue("transaction_status__c", VaultCollections.asList("pending__c"));
}
StringBuilder recordName = new StringBuilder();
recordName.append(recordEvent).append(" ")
.append(vaultId)
.append(" to ")
.append(targetIntegrationPointAPIName);
integrationTransaction.setValue("name__v", recordName.toString());
intTransactionsToSave.add(integrationTransaction);
}
logService.info("Completed connection: " + messageResult.getConnectionName());
}
// Save the Integration Transactions for the connection
if (intTransactionsToSave.size() > 0) {
recordService.batchSaveRecords(intTransactionsToSave)
.onErrors(batchOperationErrors -> {
//Iterate over the caught errors.
//The BatchOperation.onErrors() returns a list of BatchOperationErrors.
//The list can then be traversed to retrieve a single BatchOperationError and
//then extract an **ErrorResult** with BatchOperationError.getError().
batchOperationErrors.stream().findFirst().ifPresent(error -> {
String errMsg = error.getError().getMessage();
int errPosition = error.getInputPosition();
StringBuilder err = new StringBuilder();
String name = intTransactionsToSave.get(errPosition).getValue("source_key__c", ValueType.STRING);
err.append("Unable to create '")
.append(intTransactionsToSave.get(errPosition).getObjectName())
.append("' record: '")
.append(name)
.append("' because of '")
.append(errMsg)
.append("'.");
throw new RollbackException("OPERATION_NOT_ALLOWED", err.toString());
});
})
.execute();
StringBuilder logMessage = new StringBuilder();
logMessage.append("Created Integration Transaction for integration point : ").append(targetIntegrationPointAPIName).append(".");
logService.info(logMessage.toString());
}
}
} |
The Federal Trade Commission today finally voiced concern about the long-known problem of data leaking into criminal hands via LimeWire, BearShare, Kazaa and dozens of other peer-to-peer (P2P) file sharing networks.
The FTC put nearly 100 companies and agencies on notice that their employees appear to be regularly leaking large amounts of sensitive customer and employee data on popular P2P networks
The FTC did not name names, either of the victimized organizations or of the P2P networks. But the problem is well-known in tech-security circles. And it appears to be exacerbated by rising d0-more-with-less demands on being placed on employees.
“Companies should take a hard look at their systems to ensure that there are no unauthorized P2P file-sharing programs and that authorized programs are properly configured and secure,” says FTC Chairman Jon Leibowitz. “Just as important, companies that distribute P2P programs, for their part, should ensure that their software design does not contribute to inadvertent file sharing.â€Â
Data leaking from home PCs
This is a long-debated concern on which studies have been done and for which Congressional hearings have been held. The basic problem has to do with well-meaning employees taking company files home and loading them on their personal PCs to work on.
If that PC is subsequently used to download free music or videos at LimeWire, Kazaa or dozens of other P2P networks — and the user is not careful about configuring the download — work files can get exposed to all users of the network.
“It sounds preposterous, but sensitive information leaking out unintentionally like this is amazingly common,” says Eric Johnson, director of digital strategies at Dartmouth’s Tuck School of Business. “Look at the file sharing networks and you’ll find people exposing things all the time.”
In fact, data leakage via P2P networks has become so commonplace that there are cybercrime gangs who specialize in continually searching P2P sites for sensitive work documents. FTC investigators easily found health-related information, financial records, drivers’ license and social security numbers accessible on P2P networks — “the kind of information that could lead to identity theft,” says Leibowitz.
The FTC is conducting “non-public investigations” of other companies whose data are turning up on P2P networks. It also today released new education materials to help companies deal with the problem.
Doing more with less
A big driver of the problem is the fact that many employees today are under intense pressure to take on tasks previously assigned to others who’ve been laid off in the down economy.
Striving to produce more, employees feel compelled to take work home and use their own equipment and network hookups to complete assignments, says Lisa Sotto, head of privacy and information management at New York law firm Hunton & Williams.
Sotto says companies need to establish and enforce policies relating to the access and use of sensitive company data, and train employees on best security practices.
“Awareness is critical,” she says. “A lot of people don’t know that there is a problem.”
The FTC is calling on the roughly 100 organizations whose data it found littering p2p sites to identify affected customers and employees and “consider whether to notify them that their information is available on P2P networks.” The agency pointed out that most states and federal regulatory agencies have data breach notification laws requiring such disclosure.
By Byron Acohido
February 22nd, 2010 | For consumers | Imminent threats |
Soilborne root disease pathogen complexes drive widespread decline of subterranean clover pastures across diverse climatic zones Abstract. Subterranean clover (Trifolium subterraneum L.) is an important pasture legume in many regions of Australia, and elsewhere. A survey was undertaken in 2014 to define the levels of soilborne disease and associated pathogens in annual subterranean clover pastures across southern Australia. Most of the 202 samples processed had very severe levels of taproot rot disease (disease index 6080%) and extremely severe lateral root rot disease (disease index 80100%). A complex of soilborne root pathogens including Aphanomyces trifolii, Phytophthora clandestina, and one or more of Pythium, Rhizoctonia and Fusarium spp. was found responsible for severe pre- and post-emergence damping-off and root disease. This is the first study to highlight the high incidence of A. trifolii across southern Australian pastures and the first to highlight the existence of natural synergistic associations in the field between Rhizoctonia and Pythium spp., Pythium and Fusarium spp., Pythium spp. and A. trifolii, and P. clandestina and A. trifolii. Nodulation was generally poor, mainly only in the 2040% nodulation index range. There was no relationship between rainfall zone and tap or lateral root disease level, with root disease equally severe in lower (330mm) and higher (1000mm) rainfall zones. This dispels the previous belief that severe root disease in subterranean clover is an issue only in higher rainfall zones. Although overall the relationship between tap and lateral root disease was relatively weak, these two root-disease components were strongly positively expressed within each pathogens presence grouping, providing explanation for variability in this relationship across different field situations where soilborne root disease is a major problem. Most producers underestimated the levels and effect of root disease in their pastures. This study established that tap and lateral root diseases are widespread and severe, having devastating impact on the feed gap during autumnearly winter across southern Australia. Severe root disease was independent of the highly variable complex of soilborne pathogens associated with diseased roots, geographic location and rainfall zone. It is evident that soilborne root diseases are the primary factor responsible for widespread decline in subterranean clover productivity of pastures across southern Australia. Implications for disease management and options for extension are discussed. |
Saudi Arabia is seeking foreign investment in its healthcare industry as it plans to turn hundreds of government-owned hospitals and thousands of primary care centres into better-run corporations, Health Minister Tawfig Al-Rabiah said.
Nearly 80 percent of health care in Saudi Arabia is provided by the government, Al-Rabiah said in an interview in Boston. But the kingdom “is trying to move the private sector to invest more,” he said at a gathering that attracted executives including General Electric Co CEO Jeffrey Immelt.
Saudi Arabia is moving to privatize entire industries as part of a plan to overhaul its economy, shrink its budget deficit and wean itself off oil, which accounts for more than 70 percent of government revenue. The center piece of Deputy Crown Prince Mohammed bin Salman’s so-called Vision 2030 is selling a stake in oil giant Aramco in 2018 and investing the proceeds domestically and overseas.
So far, plans for the health care sector are more conservative. Starting next year, authorities intend to create multiple corporations to manage 279 hospitals and 2,300 primary care centres. The process will separate regulation from operations, but the government will retain ownership, Al-Rabiah said.
“At least for the time being, we don’t have any revenue aim,” he said. “The aim is efficiency and quality.” Officials haven’t decided if the corporations will eventually be spun out of the government, Al-Rabiah said.
In an interview broadcast Tuesday on Saudi television, Prince Mohammed hinted that could happen in the future.
Saudi Arabia hasn’t stopped or slowed orders for medical devices, Al-Rabiah added. Medtronic Plc Chief Executive Officer Omar Ishrak had previously said that the company was facing a decline in Saudi business. The issue largely had “to do with built-up inventory of implantable devices in the Saudi system itself,” which they’re cleaning out now, Ishrak said in a February 2017 earnings call.
“I just had a meeting with the chairman and CEO of Medtronic and there were no complaints at all,” Al-Rabiah said. Orders “are as scheduled and everything is going smooth as it is,” he said. |
DETROIT - Detroit Mayor Dave Bing announced Wednesday that he will implement pay and benefit cuts to union workers - effective immediately.
One Tuesday, Detroit City Council voted against the proposed cuts five to four.
The plan calls for the implementation of $102 million in annual savings. Included in the savings is a 10 percent wage cut, as well as significant changes to health care and work rules.
UNCUT VIDEO: Detroit mayor says he's implementing union contracts with cuts
READ: Summary of Detroit city employment terms 2012
READ: Detroit city employment fact sheet
Union concessions are a big part of the city's budget. On July 1st, the budget for the fiscal year began, which called for $250 million in savings. Due to the savings, about 2,600 jobs will be cut.
About the concessions
All city workers will be forced to take a 10 percent pay cut and they will no longer get furlough days in exchange. Under work rule change, Detroit Police Chief Ralph Godbee could put officers on 12-hour shifts.
The new contract also calls for about $52 million in savings by changing the city's health care plan. This includes cutting dental and vision coverage for retirees and increasing co-pays on insurance, according to the release.
Other changes include the increase of contributions from employees on prescription drugs and changes to pension and work rules.
Mayor Bing's statement
Mayor Bing released the following statement on the 2012 City Employment Terms:
For the past several years our City has spent approximately $150 million per year in excess of the cash we received. This difference was covered by annual multi-million dollar borrowing. The City can no longer borrow, hoping to cover this deficit spending. Without action the City will shut down.
This is a tough day for me, a tough day for City workers and a tough day for all of Detroit. However, it is a necessary day – but it's still a tough day.
Last night, following the process outlined by the Financial Stability Agreement, and after the Detroit Council voted against the City Employment Terms, I directed my administration to impose the CETs to continue the process to fiscally stabilize the city. This means the City Employment Terms, including wage reductions and work rule changes, are effective immediately.
The City will save $102 million dollars annually from the implementation of these terms. These savings are a key component of my administration's plan to stabilize the City's financial condition. And I want to thank the four council members who took a tough vote yesterday and were consistent in their efforts to restore financial stability to the City.
Let me say again, none of us – not me or anyone in my administration – takes any pleasure in this decision. I know this represent a hardship and sacrifices for many city workers. But as I've said before, I must make the best decisions for all Detroiters.
COMPLETE COVERAGE: Detroit City in Crisis
Copyright 2012 by ClickOnDetroit.com. All rights reserved. This material may not be published, broadcast, rewritten or redistributed. |
#include<stdio.h>
int main()
{
int t,n,i,a[10000],k,flag,c,tc;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
i=0;
k=0;
flag=1;
tc=0;
while(1)
{
if(n>=10000)
{
c=n/1000;
a[i]=c*1000;
n=n-(c*1000);
tc=tc+1;
i++;
k++;
//printf("n10000=%d\n",n);
}
if(n>=1000)
{
c=n/1000;
a[i]=c*1000;
n=n-(c*1000);
tc=tc+1;
i++;
k++;
//printf("n1000=%d\n",n);
}
if(n>=100)
{
c=n/100;
a[i]=c*100;
n=n-(c*100);
tc=tc+1;
i++;
k++;
//printf("n100=%d\n",n);
}
if(n>10 && n<100)
{
c=n/10;
a[i]=c*10;
n=n-(c*10);
tc=tc+1;
i++;
k++;
//printf("n10>=%d\n",n);
}
if(n<=10)
{
if(n!=0)
{
c=1;
a[i]=n;
tc=tc+1;
flag=1;
i++;
k++;
//printf("n10=%d\n",n);
}
break;
}
}
printf("%d\n",tc);
for(i=0; i<k; i++)
printf("%d ",a[i]);
printf("\n");
}
return 0;
} |
// handleError handles the given error by logging it and then returning the
// error. If the err is nil or is a GracefulExit error then the method will
// return nil without logging anything.
func handleError(err error) error {
if err == nil || err == beat.GracefulExit {
return nil
}
logp.Critical("Exiting: %v", err)
fmt.Fprintf(os.Stderr, "Exiting: %v\n", err)
return err
} |
def _compute_rec_score(predictions, trues, score_window, smooth_window, rec_error_type):
if (rec_error_type == "point"):
errors = [abs(y_h - y) for y_h, y in zip(predictions, trues)]
errors_smoothed = pd.Series(errors).rolling(
smooth_window, center=True, min_periods=smooth_window // 2).mean().values
z_scores = stats.zscore(errors_smoothed)
z_scores = np.clip(z_scores, a_min=0, a_max=None) + 1
elif (rec_error_type == "area"):
pd_true = pd.Series(np.asarray(trues).flatten())
pd_pred = pd.Series(np.asarray(predictions).flatten())
score_measure_true = pd_true.rolling(score_window, center=True,
min_periods=score_window // 2).apply(integrate.trapz)
score_measure_pred = pd_pred.rolling(score_window, center=True,
min_periods=score_window // 2).apply(integrate.trapz)
errors = abs(score_measure_true - score_measure_pred)
errors_smoothed = pd.Series(errors).rolling(smooth_window, center=True,
win_type='triang',
min_periods=smooth_window // 2).mean().values
z_scores = stats.zscore(errors_smoothed)
z_scores = np.clip(z_scores, a_min=0, a_max=None) + 1
elif (rec_error_type == "dtw"):
i = 0
similarity_dtw = list()
length_dtw = (score_window // 2) * 2 + 1
hafl_length_dtw = length_dtw // 2
true_pad = np.pad(trues, (hafl_length_dtw, hafl_length_dtw),
'constant', constant_values=(0, 0))
predictions_pad = np.pad(
predictions,
(hafl_length_dtw,
hafl_length_dtw),
'constant',
constant_values=(
0,
0))
while i < len(trues) - length_dtw:
true_data = np.zeros((length_dtw, 2))
true_data[:, 0] = np.arange(length_dtw)
true_data[:, 1] = true_pad[i:i + length_dtw]
preds_data = np.zeros((length_dtw, 2))
preds_data[:, 0] = np.arange(length_dtw)
preds_data[:, 1] = predictions_pad[i:i + length_dtw]
dtw, _ = sm.dtw(true_data, preds_data)
similarity_dtw = similarity_dtw + [dtw]
i += 1
similarity_dtw = [0] * int(length_dtw / 2) + similarity_dtw + [0] * (
len(trues) - len(similarity_dtw) - int(length_dtw / 2))
errors = similarity_dtw
errors_smoothed = pd.Series(errors).rolling(smooth_window, center=True,
min_periods=smooth_window // 2).mean().values
z_scores = stats.zscore(errors_smoothed)
z_scores = np.clip(z_scores, a_min=0, a_max=None) + 1
return z_scores |
It started off innocently enough.
When Sun first came to Blake asking if he could sit in on Professor Port's class, Blake thought he was making some sick joke. She couldn't imagine any sane person who would voluntarily suffer through one minute of Port's mind-numbing anecdotes, much less an entire hour. Even Weiss, the most academically-inclined member of Team RWBY had trouble staying awake during his lectures. Then, when it became apparent Sun was serious, Blake thought his request had some ulterior motive, most likely a prank he and Neptune concocted. No surprise then that she was initially hesitant about becoming an accessory to the mischief.
Sun must have sensed her reluctance, so he explained that all Haven students, during their stay in Vale for the Vytal Festival, were required to audit at least one non-combat course at a local academy. The faculty at Haven did not want their students to fall behind, after all.
"But why Professor Port's class?" Blake asked him as they walked together in the hallways of Beacon. "I'm sure you've heard how boring it is."
Sun shrugged. "Hey, it's not like I'm gonna pay attention in any class I audit. Plus, if I'm bored I'd rather be bored with friends," he replied with a nudge. Blake felt the corners of her mouth bending upwards even as she rolled her eyes. Smiles were not commonplace for her, but she found them gracing her usually-stoic face more frequently around Sun. Ever since the dance, she discovered he had an uncanny talent for brightening her day, a fact that did not displease Blake. Nor was she disappointed how she and Sun were spending more time together - usually in the library or outside under a tree - or how they shared friendly physical contact every now and then. Her heart grew warm as she reflected on the pleasant feeling of his company.
When she remained silent, he sighed and clasped his hands together. "C'mon, please?" he begged. "I promise I'll behave."
Blake regarded him for a moment, studying those puppy-dog eyes. He was being sincere, she could tell. Plus, it would be a welcome distraction amidst the boredom...
"Fine," she replied. "But no funny business, okay?"
He gave her a wink, earning him a playful elbow from her.
True to his word, Sun accompanied Team RWBY the next morning to Grimm Studies and sat quietly next to Blake. And true to his reputation, Professor Port was delivering one of the dullest lectures ever devised by an educator.
Blake scribbled in her notebook, as was her routine. She looked around the room, her eyes passing over the clock and wondering if Port's voice actually made time stand still. Her gaze found her teammates. Ruby was zonked out on her desk, her drowsiness Blake attributed to a late night reading of her newest weapon magazine subscription. Their fearless leader tried her best, Blake decided, but she still had some growing up to do. Weiss was, to nobody's surprise, scribbling down the exact details of how Professor Port managed to, allegedly, scale the side of the Goliath and ride it for six miles before felling the fearsome elephant-Grimm with a single swing of his axe. At least Ruby could get the notes from Weiss later.
Yang rested her head on her open hand, listening intently. At least, that's how it would appear to an unknowing observer. Blake was well-aware that Yang had an earpiece hidden in her palm and was currently listening to her newest playlist. Blake allowed herself a small grin as she glanced between Ruby and Yang, both equally inattentive. Definitely sisters.
She turned back to her sketch, her preferred method of time-killing in Port's godforsaken class. After a cautious glance to either side, she continued shading in some of the finer details of the subject's facial features. A little darker on the left, as if he was caught by candlelight... She gave a small nod of approval, liking the soft motif. She made to extend the shading down the side of his bare torso, but a small piece of folded paper slid in front of her and interrupted the flow of her pencil. A look to her right found Sun starting sideways at her with a sly smile. She raised an eyebrow, and he motioned discreetly with his hands for her to open the paper.
Blake bit her lip, wondering if she should indulge his game, but she quickly caved as curiosity got the better of her. She unfolded the note to find a crude stick-figure drawing of Professor Port barely hanging onto the side of a giant Goliath for dear life with a comically terrified expression on his face.
She snorted and covered her mouth, trying to hold back her laughter. This became even more difficult when she looked back up to find Sun mimicking the illustration in his seat by surreptitiously flailing his arms while mouthing a scream. She lowered her forehead against the desk, trying to pass her laughter off as a stifled cough. He beamed, proud he was able to elicit such a reaction. That rapscallion, she thought. Always making me laugh at times like these.
After she regained her composure, Sun went back to resting his head on his forearms and pretending to listen to the lesson, his face now bearing a lively smile. Blake wore a pleased grin as well. That was the most fun she'd ever had in this cursed lecture hall, she decided.
She turned back to her sketch for a moment and darkened some of the lines on the subject's body, paying particular attention to the exposed abdomen and thighs. This one was turning out nicely, and she only lacked a few more details until her creation was complete. But her gaze found its way back to Sun after a short time, and she soon found herself tearing out an unused sheet from her notebook.
A couple of scribbles later and she was sliding her own note across the desk to Sun. It was his turn to be curious as he stared back at Blake, took the note from her hand and unfolded it. His grin grew even wider as he quietly cackled at Blake's drawing: Professor Port manically running from an enraged Goliath, bug-eyed with sweat droplets pouring down his face. Their shoulders heaved as they tried to contain themselves.
"Ahem!"
Immediately their backs straightened and their laughter ceased. Port was staring right at them, apparently displeased at their inattentiveness. Blake reacted with remarkable slight-of-hand, sliding the notes into her notebook, snapping it closed and nudging it off the desk and into her bag all in one swift motion. Her heart raced.
"Ms. Belladonna, Mr. Wukong, is there anything you care to add to my heroic account?" Port inquired with the 'gotcha'-tone of a watchful authority figure.
Blake gulped. "N-No, sorry Professor."
Please, please, don't take up the book...
Professor Port's reputation extended beyond his intolerable lectures. His secondary claim to infamy around Beacon was his tendency to, whenever he confiscated off-topic doodles or notes passed between students, show off the contents to the entire class. Blake paled as she imagined Port waving her notebook around, its forbidden drawings made known to Beacon's student body. She swore she saw her social life flash before her eyes.
Sun at least had the sense to act shameful in order to avoid further scolding, though Blake knew the little head-bow he gave was a facade. "Yeah, sorry Boss. Won't happen again."
Port raised an eyebrow at the unorthodox honorific, and the pounding in Blake's chest grew faster. She didn't care about the notes. She didn't care about the embarrassment of being called out in front of the entire class. She didn't even care about receiving punishment for mocking a Professor. But if he took up her notebook, her life was over. No way she would ever live it down, much less adequately explain it.
Port let them stew for a while longer before returning to his lecture, and Blake gave a long exhale of relief. She made a mental note to thank Sun later for his good behavior. Her ears ached to hear the ring of the dismissal bell.
Sun gave a quiet 'psh' and gestured to Port with his thumb. He made a cross-eyed expression and shook his fist mockingly in the air, another obvious jab at the Professor's disciplinary remarks. Blake gave an unamused frown and turned her gaze away, still panicked at her close call. Her secret wasn't safe here, she needed to avoid drawing attention to herself, and Sun acting childish was certainly not going to accomplish that.
Out of the corner of her eye, she saw Sun visibly deflate and sink down onto the desk, dejected at her suddenly aloof attitude. Her stomach twisted with guilt. This wasn't the first time she'd been unnecessarily curt with him. He was only trying to brighten her boring day, a fact that was not lost on her.
She sighed. She'd apologize to Sun later. Right now, her first priority was surviving this class. Still shaken up, Blake decided it was not safe to resume her sketches. She would have to suffer through the lecture without her usual means of mitigation, but she could bear it.
An eternity later, the bell of salvation sounded and Blake was out the door before Sun could even address her. A glance back saw him mopily gathering his belongings and swinging his bag over his shoulder, his downtrodden demeanor speaking volumes about his hurt feelings. Another sting in Blake's chest. It was exceptionally rude of her to abandon Sun after agreeing to escort him through the class, and she knew he probably thought it was something abhorrent he did that triggered her speedy and unceremonious exit.
She took out her Scroll and start composing a message, knowing she owed Sun at least that much. She refused to repeat the callous behavior she displayed when Sun asked her to the dance weeks ago.
'Sun, sorry I had to run. There's something I need to take care of. I'll meet you for lunch later, okay?'
She pressed send and continued walking down the hall, torn between self-preservation and treating Sun fairly. Her guarded, detached nature sometimes caused her to come off as cold, not because she wanted to, but because willingly keeping people at arm's length for so many years turned the action into a reflex she had yet to break. It was a habit she was consciously trying to rectify, not only with Sun, but with all her friends. And Blake felt she'd been doing well lately; one less passive-aggressive comment towards Weiss here, one more bit of encouragement for Jaune there, and then she went and ruined her streak with the one person who deserved her good grace the most. She cursed herself for being such an ingrate.
Her Scroll buzzed, and she read Sun's reply:
'No sweat, everything okay?'
Blake replied with a quick affirmative, thankful he didn't sound upset. Her reply was mostly true, she knew everything would be okay once she shoved her notebook away in the deepest, darkest corner of her bookshelf where nobody but her would ever know of its existence. Sun would have to wait just a little longer. After the incident in Port's class, Blake knew she couldn't maintain a level head around Sun with her damnable notebook burning a hole in her bag. She needed to hide it away before she could feel even remotely comfortable around him.
He was the absolute last person who should know what laid inside.
After a particularly long and tense walk back to her dorm room, Blake swiped herself in with her scroll, slipped inside and locked the door behind her. A cautious examination found the room to be empty. She hoisted her bag onto her bottom bunk and shook her head at the unnecessary paranoia. Of course her teammates weren't back yet, she'd all but scampered away from the lecture hall. There was nothing to worry about.
She drew the curtains closed, just to be safe.
Blake plopped down onto her bed and let her head fall until it hit the soft pillow. Absolute stillness was what she needed. She steadied herself internally, closed her eyes, took a deep breath and exhaled slowly. Her shoulders relaxed slightly. To think she learned that little zen-trick from Weiss of all people.
She was fine. Everything was fine. She had plenty of time before Ruby came bursting through the door for a nap with Weiss and Yang in tow. Plenty of time to sit up, unzip her bag, rifle through it for her notebook and file it away in the deep recesses of...
She froze. Her fingers leafed through the books in her bag, but she did not see the one she was looking for. The notebook was nowhere to be found.
With a sharp inhale, Blake wrestled the bag into her lap and all but tore it open. Her eyes darted around, frantically searching the inside. No luck. She began throwing books out of her bag one by one, checking each one in vain. Her pulse pounded. This couldn't be happening, it should be right there!
Now hyperventilating, she jumped up and dumped out the entirety of her bag onto her bed and scouted the pile of loose papers, writing utensils and paperback volumes for the item she so desperately wanted to keep secret. But no matter how many times her Faunus eyes combed over the contents of the bag, Blake could not find her notebook. Slowly, she sank down onto her bed and buried her face in her hands.
Her notebook was lost.
She felt sick.
Really sick.
Like she'd just ingested battery acid-level sick.
She growled in a mix of anguish and frustration, clenching her hands and closing her eyes. How was this possible? For the past several weeks, ever since she found herself sketching those... those less than appropriate images, Blake had treated the notebook containing them as an extension of her own body, never letting it leave her sight or person when it wasn't hidden away. And now, it was anyone's guess where the scandalous tome was...
She stood quickly and began gathering her belongings back into her bag. It wasn't the end of the world just yet. She still had time to avoid any trouble. She just had to figure out where she'd left it and retrieve it before anyone had a chance to discover it first. She closed her eyes and racked her brain.
Think! she mentally screamed at herself. You were in class. When was the last instance you saw it?
Sun. The notes. Port. That's right, she'd shoved the notes into her notebook and slid them off the desk in order to prevent Professor Port from seeing them. But if that was true, then the book should have been in her bag, which it clearly was not. Blake bit her finger. This was not good. Had another student taken it off her person while she was walking back? Doubtful, but what other explanation was there? She had been distracted...
No, Blake decided, it had to be during class. She replayed the events in her mind once more, making sure to include the smallest of details. Notes into the notebook. Sliding them off the desk, straight into the open bag. More boring class. Bell. Grabbing her bag. Unzipping it and shoving her pencils inside. Closing it. Leaving class. Walking...
Her eyes widened.
Sliding the notebook into the open bag. But she always kept her bag closed during class. And Sun's bag had been right next to hers.
She had dropped her notebook into Sun's bag.
"Oh... Oh my God," Blake whispered. In the course of a few seconds, she tore out the door and was in a full-out sprint back toward the lecture hall. She passed the rest of Team RWBY down the corridor but made no attempt to acknowledge their greetings. At this point, Blake was fighting back tears, wondering which force of nature she pissed off to deserve this fate. It couldn't be true, the notebook had to still be in the classroom.
After crossing the academy in record time, pushing through crowds and colliding with a few students along the way, Blake finally reached the lecture hall. Her head was on a swivel as she descended the steps to her usual seat, searching frantically for the missing item. She flew into the chair and checked inside, on top of and under the desk in front of her. Nothing. An examination of Sun's desk yielded similar results.
Blake paused, out of breath and stupefied. Sun had her notebook in his bag. He was undoubtedly back in his guest dormitory with Neptune by now. Soon he would find it among his own books, and once he opened it...
She stood and clenched her fists. No, she couldn't let that happen. She would tackle Sun to the ground and wrestle it from his hands if necessary.
With even greater haste than her run to the lecture hall, Blake once again sprinted full-throttle towards Sun's room. The guest dormitories were only a short distance away from the regular dorms, which unfortunately for Blake meant another cross-campus trek and more precious time lost. Just when she was about to round the corner to the hallway that would allow her to enter the correct guest dormitory, something grabbed the back of her shirt and pulled her to a screeching halt.
"Whoa there, partner," a familiar voice said. "Who lit a fire under your butt?"
She whirled around to face Yang, incensed that her progress had been impeded. Her partner stood there with that cocky little grin she always wore, staring Blake down with her hands on her hips.
Blake was not amused. "What do you want, Yang?" she asked.
Yang shrugged. "Just wondering what's got you in such a hurry," she replied. "You might've even given Ruby a run for her money in a foot race back there."
"That's because I need to be somewhere fast," she replied and began walking once more.
"Ah, come on," Yang chirped, matching her strides. "That wasn't your average, everyday, late-to-class running. You're really worried about something, huh?"
Blake sighed, trying to appear calm despite the turmoil in her gut. "I'm fine. I have to go," she said, picking up the pace.
"Hey," Yang said, catching Blake by the shoulder. The two girls stopped and faced each other again. "You know you can talk to me, right? If anything's wrong, I want to help." She winked. "Partners, remember?"
Blake nodded slowly. She almost considered spilling everything to Yang but decided against it. She knew she would probably never be as close to Yang as Ruby, but Blake felt like she and Yang had become sisters of sorts since they found each other in the Emerald Forest. She trusted her partner, but it would still be best if she kept this to herself. Less messy that way. "Thank you, Yang," she replied. "I know you're concerned, but I'm not going to go off the deep end like last time when we were after the White Fang. I just need to handle this alone. It's nothing bad, just... something personal." She rubbed her left arm with her right at this, her actions betraying her insecurity.
Yang considered her for a moment before nodding. "Well then, I'll be with Weiss and Rubes. If you need us, just call," she said. She gave a short wave and departed.
Blake breathed a sigh of relief and began jogging once more. Good ol' Yang. If anyone understood the need to handle some things personally, it was her. Blake knew that her partner preferred to keep the details of her occasional nighttime crusades into Vale's less than reputable establishments under the rug, and she knew not to ask about it unless Yang brought it up first. Thankfully, Yang was principled enough to extend others the same courtesy.
After ascending several flights of stairs and navigating the hallways, Blake found herself in front of Team SSSN's room. Though she'd never actually been inside, a few late-night library reading sessions over the past few weeks had ended with Blake walking Sun back to his dorm. It was an unspoken protocol between them; they each took turns walking the other back to their respective rooms after spending evenings together. But Blake never had a need to enter before, and she was now mentally reeling.
What if he was already looking at it? What if someone else was looking at it? Oh God, what if they were all looking at it?
Just as she reached forward to knock, the door swung open, causing Blake to jump back and tense her muscles on reflex. Out walked Neptune, combing his hair into place. He gave his blue mane a dainty little flip before pocketing his comb. As the door swooshed shut, he finally took notice of her.
He flashed his sparkling smile. "Sup, Blake?" For some reason, he looked rather pleased with himself. "Here to see Sun?"
Some of Blake's fears dissipated. Judging by Neptune's attitude, everything seemed to be normal. "Hey Neptune," she replied. "And yeah, I am. I, um... forgot something, and he, ah-"
"Hey, no sweat," he remarked. "I know you and Sun have your thing going. It's cool, you don't have to hide it from me." He crossed his arms and nodded. "I won't gossip," he added jovially.
Her initial reflex was to vehemently deny... whatever Neptune seemed to be implying. But time was of the essence, so she decided to roll with it. "Yeah..." she tediously chuckled. "We're... having lunch together. So, is he alone in there?"
She immediately regretted her phrasing when she saw the bawdy glint in Neptune's eye. Whatever, she could clear up any misconceptions later. Right now, she had to get inside. Let Neptune believe what he would. "Yup, I'm heading out for some combat training," he answered. "I'll swipe you in before I leave." He ran his Scroll across the door lock and gave his signature double-finger point to her upon hearing it beep. "Have fun you crazy kids."
She cringed as he walked away, and down the hall she heard him mutter something about Sun owing him for being such an awesome wingman. She shook her head. As obviously insecure as Neptune was about maintaining his cool persona, she had to admit he was a good guy for helping her out. For the first time since class, she felt relaxed. Everything was fine. She just had to walk in, get the notebook from Sun with some lame excuse about how she needed it to study and walk back out. Easy. Then, she could enjoy lunch with Sun like normal.
Blake took a deep breath and opened the door.
What she found mortified her.
Hello, all. Thank you for taking interest in my story. BlackSun does not get nearly enough love, so I felt I should try to rectify that and support my ship. I would very much like to continue with this, but I would also appreciate some feedback. Please take just one minute leave me a review or PM me with your thoughts/likes/criticisms, it would mean a lot.
Until next time,
RobotFish |
<gh_stars>0
const ns = 'bull_monitor:';
export const StorageConfig = {
ns,
persistNs: ns + 'store:',
closeableTipNs: ns + 'hide_tip:',
};
|
<gh_stars>0
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbTestMain.h"
void RegisterTests()
{
REGISTER_TEST(otbImageFileWriterWithExtendedOptionBox);
REGISTER_TEST(otbImageFileReaderONERAComplex);
REGISTER_TEST(otbImageFileReaderRADComplexFloat);
REGISTER_TEST(otbShortRGBImageIOTest);
REGISTER_TEST(otbPipelineMetadataHandlingWithUFFilterTest);
REGISTER_TEST(otbImageMetadataFileWriterTest);
REGISTER_TEST(otbImageScalarFileWriterTestWithoutInputShort);
REGISTER_TEST(otbImageScalarFileWriterTestWithoutInputInt);
REGISTER_TEST(otbImageScalarFileWriterTestWithoutInputFloat);
REGISTER_TEST(otbImageScalarFileWriterTestWithoutInputDouble);
REGISTER_TEST(otbImageComplexFileWriterTestWithoutInputShort);
REGISTER_TEST(otbImageComplexFileWriterTestWithoutInputInt);
REGISTER_TEST(otbImageComplexFileWriterTestWithoutInputFloat);
REGISTER_TEST(otbImageComplexFileWriterTestWithoutInputDouble);
REGISTER_TEST(otbVectorImageStreamingFileWriterScalarTestWithoutInputShort);
REGISTER_TEST(otbVectorImageStreamingFileWriterScalarTestWithoutInputInt);
REGISTER_TEST(otbVectorImageStreamingFileWriterScalarTestWithoutInputFloat);
REGISTER_TEST(otbVectorImageStreamingFileWriterScalarTestWithoutInputDouble);
REGISTER_TEST(otbVectorImageStreamingFileWriterComplexTestWithoutInputShort);
REGISTER_TEST(otbVectorImageStreamingFileWriterComplexTestWithoutInputInt);
REGISTER_TEST(otbVectorImageStreamingFileWriterComplexTestWithoutInputFloat);
REGISTER_TEST(otbVectorImageStreamingFileWriterComplexTestWithoutInputDouble);
REGISTER_TEST(otbReadingComplexDataIntoComplexImageTest);
REGISTER_TEST(otbImageFileReaderRADInt);
REGISTER_TEST(otbImageFileReaderRGBTest);
REGISTER_TEST(otbImageMetadataStreamingFileWriterTest);
REGISTER_TEST(otbFloatImageIOTest);
REGISTER_TEST(otbImageFileReaderMSTAR);
REGISTER_TEST(otbGDALDriverDoubleWritingTest);
REGISTER_TEST(otbDoubleImageIOTest);
REGISTER_TEST(otbImageFileWriterTestCalculateNumberOfDivisions);
REGISTER_TEST(otbImageFileReaderRADComplexFloatExtract);
REGISTER_TEST(otbImageFileReaderRADComplexInt);
REGISTER_TEST(otbImageScalarStreamingFileWriterTestWithoutInputShort);
REGISTER_TEST(otbImageScalarStreamingFileWriterTestWithoutInputInt);
REGISTER_TEST(otbImageScalarStreamingFileWriterTestWithoutInputFloat);
REGISTER_TEST(otbImageScalarStreamingFileWriterTestWithoutInputDouble);
REGISTER_TEST(otbImageComplexStreamingFileWriterTestWithoutInputShort);
REGISTER_TEST(otbImageComplexStreamingFileWriterTestWithoutInputInt);
REGISTER_TEST(otbImageComplexStreamingFileWriterTestWithoutInputFloat);
REGISTER_TEST(otbImageComplexStreamingFileWriterTestWithoutInputDouble);
REGISTER_TEST(otbScalarBufferToImageFileWriterTest);
REGISTER_TEST(otbImageFileWriterONERAComplex);
REGISTER_TEST(otbPipelineMetadataHandlingTest);
REGISTER_TEST(otbMultiResolutionReadingInfo);
REGISTER_TEST(otbImageFileReaderTestFloat);
REGISTER_TEST(otbVectorImageComplexFloatTest);
REGISTER_TEST(otbVectorImageComplexDoubleTest);
REGISTER_TEST(otbImageComplexFloatTest);
REGISTER_TEST(otbImageComplexDoubleTest);
REGISTER_TEST(otbVectorImageComplexIntoRealFloatTest);
REGISTER_TEST(otbVectorImageComplexIntoRealDoubleTest);
REGISTER_TEST(otbImageFileReaderRADChar);
REGISTER_TEST(otbShortImageIOTest);
REGISTER_TEST(otbImageSeriesFileReader);
REGISTER_TEST(otbStreamingShortImageFileWriterTest);
REGISTER_TEST(otbImageFileWriterStreamingONERAComplex);
REGISTER_TEST(otbImageFileReaderWithComplexPixelTest);
REGISTER_TEST(otbVectorImageFileReaderWithComplexPixelTest);
REGISTER_TEST(otbImageFileReaderRADFloat);
REGISTER_TEST(otbVectorImageFileReaderWriterTest);
REGISTER_TEST(otbIntImageIOTest);
REGISTER_TEST(otbImageFileReaderONERATest);
REGISTER_TEST(otbPNGIndexedNbBandsTest);
REGISTER_TEST(otbImageFileReaderTest);
REGISTER_TEST(otbVectorImageFileWriterScalarTestWithoutInputShort);
REGISTER_TEST(otbVectorImageFileWriterScalarTestWithoutInputInt);
REGISTER_TEST(otbVectorImageFileWriterScalarTestWithoutInputFloat);
REGISTER_TEST(otbVectorImageFileWriterScalarTestWithoutInputDouble);
REGISTER_TEST(otbVectorImageFileWriterComplexTestWithoutInputShort);
REGISTER_TEST(otbVectorImageFileWriterComplexTestWithoutInputInt);
REGISTER_TEST(otbVectorImageFileWriterComplexTestWithoutInputFloat);
REGISTER_TEST(otbVectorImageFileWriterComplexTestWithoutInputDouble);
REGISTER_TEST(otbWritingComplexDataWithComplexImageTest);
REGISTER_TEST(otbImageFileWriterWithFilterTest);
REGISTER_TEST(otbImageFileReaderRADComplexDouble);
REGISTER_TEST(otbPipeline);
REGISTER_TEST(otbStreamingImageFilterTest);
REGISTER_TEST(otbStreamingImageFileWriterTest);
REGISTER_TEST(otbImageFileWriterRGBTest);
REGISTER_TEST(otbMonobandScalarToImageComplexFloat);
REGISTER_TEST(otbMonobandScalarToImageComplexDouble);
REGISTER_TEST(otbMonobandScalarToImageComplexInt);
REGISTER_TEST(otbMonobandScalarToImageComplexShort);
REGISTER_TEST(otbMonobandComplexToImageScalarFloat);
REGISTER_TEST(otbMonobandComplexToImageScalarDouble);
REGISTER_TEST(otbMonobandComplexToImageScalarInt);
REGISTER_TEST(otbMonobandComplexToImageScalarShort);
REGISTER_TEST(otbMonobandComplexToImageComplexFloat);
REGISTER_TEST(otbMonobandComplexToImageComplexDouble);
REGISTER_TEST(otbMonobandComplexToImageComplexInt);
REGISTER_TEST(otbMonobandComplexToImageComplexShort);
REGISTER_TEST(otbMonobandComplexToVectorImageScalarFloat);
REGISTER_TEST(otbMonobandComplexToVectorImageScalarDouble);
REGISTER_TEST(otbMonobandComplexToVectorImageScalarInt);
REGISTER_TEST(otbMonobandComplexToVectorImageScalarShort);
REGISTER_TEST(otbMonobandComplexToVectorImageComplexFloat);
REGISTER_TEST(otbMonobandComplexToVectorImageComplexDouble);
REGISTER_TEST(otbMonobandComplexToVectorImageComplexInt);
REGISTER_TEST(otbMonobandComplexToVectorImageComplexShort);
REGISTER_TEST(otbMultibandScalarToImageComplexFloat);
REGISTER_TEST(otbMultibandScalarToImageComplexDouble);
REGISTER_TEST(otbMultibandScalarToImageComplexInt);
REGISTER_TEST(otbMultibandScalarToImageComplexShort);
REGISTER_TEST(otbMultibandScalarToVectorImageComplexFloat);
REGISTER_TEST(otbMultibandScalarToVectorImageComplexDouble);
REGISTER_TEST(otbMultibandScalarToVectorImageComplexInt);
REGISTER_TEST(otbMultibandScalarToVectorImageComplexShort);
REGISTER_TEST(otbMultibandComplexToVectorImageScalarFloat);
REGISTER_TEST(otbMultibandComplexToVectorImageScalarDouble);
REGISTER_TEST(otbMultibandComplexToVectorImageScalarInt);
REGISTER_TEST(otbMultibandComplexToVectorImageScalarShort);
REGISTER_TEST(otbMultibandComplexToVectorImageComplexFloat);
REGISTER_TEST(otbMultibandComplexToVectorImageComplexDouble);
REGISTER_TEST(otbMultibandComplexToVectorImageComplexShort);
REGISTER_TEST(otbMultibandComplexToVectorImageComplexInt);
REGISTER_TEST(otbMonobandScalarToVectorImageComplexFloat);
REGISTER_TEST(otbMonobandScalarToVectorImageComplexDouble);
REGISTER_TEST(otbMonobandScalarToVectorImageComplexShort);
REGISTER_TEST(otbMonobandScalarToVectorImageComplexInt);
REGISTER_TEST(otbMultibandComplexToImageScalarFloat);
REGISTER_TEST(otbMultibandComplexToImageScalarDouble);
REGISTER_TEST(otbMultibandComplexToImageScalarShort);
REGISTER_TEST(otbMultibandComplexToImageScalarInt);
REGISTER_TEST(otbImageFileWriterTest);
REGISTER_TEST(otbCompareWritingComplexImageTest);
REGISTER_TEST(otbImageFileReaderOptBandTest);
REGISTER_TEST(otbImageFileWriterOptBandTest);
REGISTER_TEST(otbMultiImageFileWriterTest);
REGISTER_TEST(otbWriteGeomFile);
}
|
Homeowners insurance NEVER includes flood insurance. However, federal law says, and EVERY mortgage lender requires, that home owners carry flood insurance if their home is in a flood zone. If your home is paid for, Derb, and you are in a flood zone you are still required by law to carry flood insurance.
It is sold by virtually all insurance carriers, the price is federally mandated so the cost is the same no matter who you purchase it from. |
from __future__ import annotations
import abc
import functools
import typing as ty
class EasyDecorator(abc.ABC):
"""Легкий способ создать класс-декоратор"""
def __new__(cls, __handler: ty.Optional[ty.Callable] = None, **kwargs) -> ty.Union[EasyDecorator, ty.Callable[..., EasyDecorator]]:
self = object.__new__(cls)
if __handler is None:
self.__kwargs = kwargs
return self.__partail_init
return self
def __partail_init(self, __handler: ty.Callable) -> EasyDecorator:
self.__init__(__handler, **self.__kwargs)
return self
def easy_func_decorator(func: ty.Callable):
"""
Args:
func: ty.Callable:
func: ty.Callable:
Returns:
"""
@functools.wraps(func)
def wrapper_args(__handler: ty.Optional[ty.Callable] = None, **kwargs):
"""
Args:
__handler: ty.Optional[ty.Callable]: (Default value = None)
**kwargs:
__handler: ty.Optional[ty.Callable]: (Default value = None)
Returns:
"""
if __handler is None:
def wrapper_handler(__handler: ty.Callable):
"""
Args:
__handler: ty.Callable:
__handler: ty.Callable:
Returns:
"""
return func(__handler, **kwargs)
return wrapper_handler
return func(__handler, **kwargs)
return wrapper_args
def easy_method_decorator(func: ty.Callable):
"""
Args:
func: ty.Callable:
func: ty.Callable:
Returns:
"""
@functools.wraps(func)
def wrapper_args(
self, __handler: ty.Optional[ty.Callable] = None, **kwargs
):
"""
Args:
__handler: ty.Optional[ty.Callable]: (Default value = None)
**kwargs:
__handler: ty.Optional[ty.Callable]: (Default value = None)
Returns:
"""
if __handler is None:
def wrapper_handler(__handler: ty.Callable):
"""
Args:
__handler: ty.Callable:
__handler: ty.Callable:
Returns:
"""
return func(self, __handler, **kwargs)
return wrapper_handler
return func(self, __handler, **kwargs)
return wrapper_args
|
#include "bittybuzz/BittyBuzzUserFunctions.h"
#include "bbzvm.h"
#include "bittybuzz/BittyBuzzSystem.h"
#include "bittybuzz/BittyBuzzUtils.h"
#include <LockGuard.h>
#include <Task.h>
struct ForeachFunctionContext {
bool m_err = false;
std::array<FunctionCallArgumentDTO, FunctionCallRequestDTO::FUNCTION_CALL_ARGUMENTS_MAX_LENGTH>
m_arguments = {};
uint16_t m_length = 0;
};
void foreachFunctionCallback(bbzheap_idx_t key, bbzheap_idx_t value, void* params) {
ForeachFunctionContext* context = (ForeachFunctionContext*)params;
bbzobj_t* keyObj = bbzheap_obj_at(key); // NOLINT
bbzobj_t* valueObj = bbzheap_obj_at(value); // NOLINT
if (!bbztype_isint(*keyObj) || keyObj->i.value > (int16_t)context->m_arguments.size() ||
keyObj->i.value < 0 || context->m_err) {
context->m_err = true;
return;
}
switch (bbztype(*valueObj)) {
case BBZTYPE_INT:
context->m_arguments[(uint8_t)keyObj->i.value] =
FunctionCallArgumentDTO((int64_t)valueObj->i.value);
context->m_length++;
break;
case BBZTYPE_FLOAT:
context->m_arguments[(uint8_t)keyObj->i.value] =
FunctionCallArgumentDTO(bbzfloat_tofloat(valueObj->f.value));
context->m_length++;
break;
default:
context->m_err = true;
}
}
struct ArgNameAndType {
bbzheap_idx_t m_key;
bbzheap_idx_t m_value;
};
// We know that the size is 1, so the value will be written once
void foreachNameAndType(bbzheap_idx_t key, bbzheap_idx_t value, void* params) {
ArgNameAndType* context = (ArgNameAndType*)params;
context->m_key = key;
context->m_value = value;
}
FunctionDescriptionArgumentTypeDTO getbbzObjType(bbzobj_t* bbzObj) {
switch (bbztype(*bbzObj)) {
case BBZTYPE_INT:
return FunctionDescriptionArgumentTypeDTO::Int;
case BBZTYPE_FLOAT:
return FunctionDescriptionArgumentTypeDTO::Float;
default:
return FunctionDescriptionArgumentTypeDTO::Unknown;
}
}
void BittyBuzzUserFunctions::log() {
// Get the number of args
uint16_t nArgs = bbzvm_locals_count();
LockGuard lock(BittyBuzzSystem::g_ui->getPrintMutex());
constexpr uint16_t objStrSize = 256;
char objStr[objStrSize];
// Iterate through args, we start a arg 1 up to the nb of
BittyBuzzSystem::g_ui->print("BBZ USER: ");
for (uint16_t i = 1; i <= nArgs; i++) {
bbzobj_t* obj = bbzheap_obj_at(bbzvm_locals_at(i)); // NOLINT
if (BittyBuzzUtils::logObj(obj, objStr, objStrSize) >= 0) {
BittyBuzzSystem::g_ui->print("%s", objStr);
} else {
BittyBuzzSystem::g_ui->print("Fail to log");
}
}
BittyBuzzSystem::g_ui->flush();
bbzvm_ret0();
}
void BittyBuzzUserFunctions::registerClosure() {
bbzvm_assert_lnum(4); // NOLINT
bbzobj_t* bbzFunctionName = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzheap_idx_t bbzClosureHeapIdx = bbzvm_locals_at(2); // NOLINT
bbzheap_idx_t bbzArgsDescHeapIdx = bbzvm_locals_at(3); // NOLINT
bbzheap_idx_t bbzSelfHeapIdx = bbzvm_locals_at(4); // NOLINT
bbzobj_t* bbzClosure = bbzheap_obj_at(bbzClosureHeapIdx); // NOLINT
bbzobj_t* bbzArgsDesc = bbzheap_obj_at(bbzSelfHeapIdx); // NOLINT
if (!bbztype_isstring(*bbzFunctionName) && !bbztype_isclosure(*bbzClosure) &&
!bbztype_istable(*bbzArgsDesc)) {
BittyBuzzSystem::g_logger->log(LogLevel::Error,
"BBZ: Invalid type when registering function");
bbzvm_seterror(BBZVM_ERROR_TYPE);
return;
}
std::optional<const char*> functionNameOpt =
BittyBuzzSystem::g_stringResolver->getString(bbzFunctionName->s.value);
if (!functionNameOpt) {
BittyBuzzSystem::g_logger->log(LogLevel::Error,
"BBZ: String id not found when registering function");
bbzvm_seterror(BBZVM_ERROR_STRING);
return;
}
// Store the function name
BittyBuzzFunctionDescription argsDescription(functionNameOpt.value());
uint8_t argsSize = bbztable_size(bbzArgsDescHeapIdx);
for (uint8_t i = 0; i < argsSize; i++) {
bbzheap_idx_t key = bbzint_new(i);
bbzheap_idx_t subTable;
// Fetching the object in the table by index
if (bbztable_get(bbzArgsDescHeapIdx, key, &subTable) == 0) {
BittyBuzzSystem::g_logger->log(LogLevel::Error,
"BBZ: Invalid args description on closure registration");
bbzvm_seterror(BBZVM_ERROR_TYPE);
return;
}
// Getting the subtable
if (!bbztype_istable(*bbzheap_obj_at(subTable)) || bbztable_size(subTable) != 1) {
BittyBuzzSystem::g_logger->log(LogLevel::Error,
"BBZ: Invalid args description on closure registration");
bbzvm_seterror(BBZVM_ERROR_TYPE);
return;
}
ArgNameAndType keyValue;
// We know that the subtable has a size of 1, so no overwrite on the foreach
bbztable_foreach(subTable, foreachNameAndType, &keyValue);
bbzobj_t* bbzArgName = bbzheap_obj_at(keyValue.m_key);
bbzobj_t* bbzArgType = bbzheap_obj_at(keyValue.m_value);
// Getting the string name
std::optional<const char*> argNameOpt =
BittyBuzzSystem::g_stringResolver->getString(bbzArgName->s.value);
if (!argNameOpt) {
BittyBuzzSystem::g_logger->log(LogLevel::Error,
"BBZ: Arg name could not be found on registration");
bbzvm_seterror(BBZVM_ERROR_STRING);
return;
}
// Adding to the arg description
const char* argName = argNameOpt.value();
FunctionDescriptionArgumentTypeDTO argType = getbbzObjType(bbzArgType);
argsDescription.addArgument(argName, argType);
}
bool ret = BittyBuzzSystem::g_closureRegister->registerClosure(
functionNameOpt.value(), bbzClosureHeapIdx, bbzSelfHeapIdx, argsDescription);
if (!ret) {
BittyBuzzSystem::g_logger->log(LogLevel::Error, "BBZ: Could not register closure");
bbzvm_seterror(BBZVM_ERROR_MEM);
return;
}
bbzvm_ret0();
}
void BittyBuzzUserFunctions::callHostFunction() {
bbzvm_assert_lnum(3); // NOLINT
bbzobj_t* bbzId = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzobj_t* bbzFunctionName = bbzheap_obj_at(bbzvm_locals_at(2)); // NOLINT
bbzheap_idx_t bbzArgsTableHeapIdx = bbzvm_locals_at(3); // NOLINT
ForeachFunctionContext context;
std::optional<const char*> functionName =
BittyBuzzSystem::g_stringResolver->getString(bbzFunctionName->s.value);
bbztable_foreach(bbzArgsTableHeapIdx, foreachFunctionCallback, &context);
if (context.m_err) {
BittyBuzzSystem::g_logger->log(LogLevel::Error,
"BBZ: Error parsing argument list, host FCall");
bbzvm_seterror(BBZVM_ERROR_TYPE);
return;
}
bool ret = BittyBuzzSystem::g_messageService->callHostFunction(
(uint16_t)bbzId->i.value, functionName.value(), context.m_arguments.data(),
context.m_length);
if (!ret) {
BittyBuzzSystem::g_logger->log(LogLevel::Warn, "BBZ: could not call host FCall");
}
bbzvm_ret0();
}
void BittyBuzzUserFunctions::callBuzzFunction() {
bbzvm_assert_lnum(3); // NOLINT
bbzobj_t* bbzId = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzobj_t* bbzFunctionName = bbzheap_obj_at(bbzvm_locals_at(2)); // NOLINT
bbzheap_idx_t bbzArgsTableHeapIdx = bbzvm_locals_at(3); // NOLINT
ForeachFunctionContext context;
std::optional<const char*> functionName =
BittyBuzzSystem::g_stringResolver->getString(bbzFunctionName->s.value);
bbztable_foreach(bbzArgsTableHeapIdx, foreachFunctionCallback, &context);
if (context.m_err) {
BittyBuzzSystem::g_logger->log(LogLevel::Error,
"BBZ: Error parsing argument list, buzz FCall");
bbzvm_seterror(BBZVM_ERROR_TYPE);
return;
}
bool ret = BittyBuzzSystem::g_messageService->callBuzzFunction(
(uint16_t)bbzId->i.value, functionName.value(), context.m_arguments.data(),
context.m_length);
if (!ret) {
BittyBuzzSystem::g_logger->log(LogLevel::Warn, "BBZ: could not call buzz FCall");
}
bbzvm_ret0();
}
void BittyBuzzUserFunctions::isNil() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* bbzObj = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzvm_pushi(bbztype_isnil(*bbzObj));
bbzvm_ret1();
}
void BittyBuzzUserFunctions::isInt() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* bbzObj = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzvm_pushi(bbztype_isint(*bbzObj));
bbzvm_ret1();
}
void BittyBuzzUserFunctions::isFloat() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* bbzObj = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzvm_pushi(bbztype_isfloat(*bbzObj));
bbzvm_ret1();
}
void BittyBuzzUserFunctions::isString() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* bbzObj = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzvm_pushi(bbztype_isstring(*bbzObj));
bbzvm_ret1();
}
void BittyBuzzUserFunctions::isTable() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* bbzObj = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzvm_pushi(bbztype_istable(*bbzObj));
bbzvm_ret1();
}
void BittyBuzzUserFunctions::isClosure() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* bbzObj = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzvm_pushi(bbztype_isclosure(*bbzObj));
bbzvm_ret1();
}
void BittyBuzzUserFunctions::isLambdaClosure() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* bbzObj = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
bbzvm_pushi(bbztype_isclosurelambda(*bbzObj));
bbzvm_ret1();
}
void BittyBuzzUserFunctions::toInt() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* o = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
if (bbztype_isfloat(*o)) {
bbzvm_pushi((int16_t)bbzfloat_tofloat(o->f.value));
} else if (bbztype_isint(*o)) {
bbzvm_pushi(o->i.value);
} else {
bbzvm_pushnil();
}
bbzvm_ret1();
}
void BittyBuzzUserFunctions::toFloat() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* o = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
if (bbztype_isfloat(*o)) {
bbzvm_pushf(o->f.value);
} else if (bbztype_isint(*o)) {
bbzvm_pushf(bbzfloat_fromint(o->i.value));
} else {
bbzvm_pushnil();
}
bbzvm_ret1();
}
void BittyBuzzUserFunctions::delay() {
bbzvm_assert_lnum(1); // NOLINT
bbzobj_t* o = bbzheap_obj_at(bbzvm_locals_at(1)); // NOLINT
if (bbztype_isint(*o) && o->i.value >= 0) {
Task::delay(static_cast<uint16_t>(o->i.value));
bbzvm_ret0();
} else {
bbzvm_seterror(BBZVM_ERROR_TYPE);
}
}
|
<gh_stars>1-10
import { EditorState, QueryMethods } from '@craftjs/core';
import forIn from 'lodash/forIn';
import pickBy from 'lodash/pickBy';
// Wrap any orphaned Slate child nodes with a new Slate node
// This happens when you drag a Slate child node (ie: a Typography node) into a non-Slate parent node
export const wrapRogueElement = (
state: EditorState,
rootType: any,
acceptableElements: any[]
) => {
const rogueNodes = pickBy(state.nodes, (node) => {
return (
acceptableElements.includes(node.data.type) &&
[rootType, ...acceptableElements].includes(
state.nodes[node.data.parent].data.type
) === false
);
});
forIn(rogueNodes, (node) => {
const newSlateNode = QueryMethods(state)
.parseFreshNode({
data: {
type: rootType,
nodes: [node.id],
parent: node.data.parent,
},
})
.toNode();
const currentParentNode = state.nodes[node.data.parent];
const indexInParentNode = currentParentNode.data.nodes.indexOf(node.id);
if (indexInParentNode > -1) {
currentParentNode.data.nodes.splice(
indexInParentNode,
1,
newSlateNode.id
);
}
node.data.parent = newSlateNode.id;
state.nodes[newSlateNode.id] = newSlateNode;
});
return state;
};
|
Sensorless current sharing in digitally controlled multiphase buck DC-DC converters This paper describes a current sharing technique for digitally controlled multiphase buck DC-DC converters. The effective duty cycle mismatches and resistance mismatches are digitally compensated to achieve equal current sharing without sensing currents. Effects of various non-idealities on the current sharing performance are discussed. Experimental results are shown for a four-phase synchronous buck converter with 9V input voltage, and 1.5 V, 01.5A output. |
package com.unittesting.awaitility;
import static org.apache.commons.lang3.StringUtils.countMatches;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.unittesting.awaitlity.AwaitilityWrapper;
public class AwaitilityWrapperTest {
private static final Logger logger = LoggerFactory.getLogger(AwaitilityWrapperTest.class);
@Rule public StandardOutputStreamLog outLog = new StandardOutputStreamLog();
private int counter;
@Before public void beforeEveryTest() {
outLog.clear();
}
@Test public void
givenDefaultWait_whenWeOverrideWaitMinutesToSecondsAndLogSomeMsg_shouldOutputToConsoleCorrectNumTimes() {
counter = 3;
AwaitilityWrapper.defaultAwait().atMost(47, TimeUnit.SECONDS).until(new Callable<Boolean>() {
public Boolean call() throws Exception {
logger.info("Some msg: {}", counter);
return counter-- == 1;
}
});
int numTimesMsgLogged = countMatches(outLog.getLog(), "Some msg");
assertThat(numTimesMsgLogged, is(equalTo(3)));
}
@Test public void
givenDefaultWait_whenWeOverrideWaitAndPollIntervalndLogSomeMsg_shouldOutputToConsoleCorrectNumTimes() {
counter = 10;
AwaitilityWrapper.defaultAwait(1, 2).until(new Callable<Boolean>() {
public Boolean call() throws Exception {
logger.info("Some msg2: {}", counter);
return counter-- == 1;
}
});
int numTimesMsgLogged = countMatches(outLog.getLog(), "Some msg2");
assertThat(numTimesMsgLogged, is(equalTo(10)));
}
}
|
Facebook is no stranger to dropping the ball when it comes to user privacy.
Facebook's latest privacy blunder is just the latest in a long line of SNAFUs for the world's largest social network. Here are some of the social network's greatest privacy faux pas.
In the latest episode of the gang that couldn't get privacy straight, it was revealed by the Wall Street Journal that many of Facebook's popular applications were unintentionally transmitting the names of the social network's members and, in some cases, their friends' names to dozens of advertising and Internet tracking companies.
While acknowledging concern over the issue, Facebook maintained that the significance of the problem is being exaggerated by the press. "Knowledge of a UID [User ID] does not enable anyone to access private user information without explicit user consent," Facebook platform engineering lead Mike Vernal wrote in a blog.
Nevertheless, Facebook was concerned enough about the issue to block last week the playing of games made by LOLApps on the social network. After Facebook discovered the the information leak was browser-related and not intentional by the game maker, LOL's Facebook privileges were restored.
The app leak comes on the heels of criticism of the network's revamped group feature rolled out earlier this month. It allows members to create groups and invite friends to join the group. From a privacy point of view, however, the feature leaves much to be desired. While members can control who they invite to the group, they can't control who their friends invite to join the group. That means there's no way to really keep the group private. It also makes a group vulnerable to spammers. In fact, one blogger called Facebook Groups "the worst spam loophole in the world."
Another Facebook feature, Places, set privacy advocates buzzing as soon as it was announced in August. Once again, integration with third-party websites was cited as a flaw. "Your friends' apps may be able to access information about your most recent check-in by default as soon as you start using Places," the American Civil Liberties Union warned Facebook members. "Even if you've already gone through your settings to limit the info that apps can access, you should do it again--you may find that you've been defaulted into sharing your location info with apps."
In April, Facebook was rapped for its new "Instant Personalization" feature. It allowed websites who partnered with the socnet to peek at members' personal information when they arrive at a site. Using that info, the site could then display a personalized page for the member. So if you stumbled across a restaurant site that cut a deal with Facebook, for example, eateries recommended by your friends could be splashed on the web page you landed on. "While going to a brand-new website that instantly knows who you are might ultimately be useful, the first time it happens you're going to freak out," observed Liz Gannes at GigaOm.
Other changes introduced in April, led to a complaint being filed with the Federal Trade Commission in May. At that time, the Electronic Privacy Information Center maintained that the changes revealed more information to third parties about Facebook members that it did before the changes were made. The Center asserted: "These changes violate user expectations, diminish user privacy, and contradict Facebook's own representations. These business practices are Unfair and Deceptive Trade Practices."
Even the simplest changes at the social networking site can spur mountains of privacy protests, as it found out in February when it tinkered with language in its terms of usage agreement. It removed a clause in the pact that barred Facebook from using a member's information if the member removed it from the service. Under the rescinded change, members complained that Facebook would have control over their information forever.
At the end of last year, Facebook, in an attempt to stimulate sharing, lowered the default controls on its members' accounts allowing more personal information to be displayed on their home pages. What the network stimulated was howls of protest. "Things get downright ugly when it comes to controlling who gets to see personal information such as your list of friends," groused an attorney for the Electronic Frontier Foundation. "Under the new regime, Facebook treats that information along with your name, profile picture, current city, gender, networks and the pages that you are a ‘fan' of--as ‘publicly available information' or ‘PAI.' Before, users were allowed to restrict access to much of that information." |
package com.capgemini.client;
import com.capgemini.contentfulServices.ContentfulService;
import com.capgemini.contentfulServices.impl.ContentfulClient;
import com.contentful.java.cda.CDAArray;
import com.contentful.java.cda.CDAClient;
import com.contentful.java.cda.CDAEntry;
import com.contentful.java.cda.CDASpace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ContentfulServiceClient implements ContentfulService {
@Autowired
ContentfulClient clientService;
CDAClient client;
@Override
public CDASpace getSpace() {
return this.getClient().fetchSpace();
}
public CDAEntry getIntro() {
CDAArray entries = getClient().fetch(CDAEntry.class).withContentType("introduction").all();
CDAEntry intro = (CDAEntry) entries.entries().values().toArray()[0];
return intro;
}
public CDAEntry getArticle(String articleID) {
return getClient().fetch(CDAEntry.class).one(articleID);
}
private CDAClient getClient() {
if (this.client == null) {
this.client = this.clientService.getClient();
}
return this.client;
}
}
|
Sandstone diapirism and clastic intrusion in the Tertiary submarine fans of the Bruce-Beryl Embayment, Quadrant 9, UKCS Abstract Submarine fans of Late Palaeocene and Early Eocene age form important hydrocarbon reservoirs in the Bruce-Beryl Embayment, northern North Sea. The Early Eocene fans are the main reservoirs in the Forth-Gryphon oilfields and in the giant Frigg gasfield. Significant oil discoveries have also been made in Late Palaeocene fans. Forth and Gryphon lie on the flanks of the Crawford Anticline, a drape structure that developed during the Palaeocene above the crest of a Mesozoic tilted fault block. The Early Eocene fans pinchout against the flanks of the anticline implying continued growth of the structure throughout the Eocene. Growth was accompanied by the development of major gravity slides that detached in a sequence of altered, basaltic tephras at the base of the Eocene sequence. Seismic-scale, post-depositional deformation (sandstone diapirism and the intrusion of clastic sills and dykes) connected with this sliding dramatically modified the original depositional geometries of the fans. A detailed account of the deformation features, illustrated with core, wireline log and three-dimensional seismic data is presented together with a discussion of their exploration/appraisal significance. |
Hope for the globe Rebecca Hope, a medical student at Leeds, is coordinator of Alma Mata, a global health network for healthcare graduates (www.almamata.net). She has a bachelors degree in international health from University College London and is author of The Elective Pack, available on Student BMJ.com, a guide to international health and development for medical students. She spoke to Tiago Villanueva about the future for Alma Mata and global health |
<filename>src/main/java/onethreeseven/trajsuite/core/view/controller/TrajsuiteWWMainViewController.java<gh_stars>10-100
package onethreeseven.trajsuite.core.view.controller;
import gov.nasa.worldwind.BasicModel;
import gov.nasa.worldwind.Configuration;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.awt.WorldWindowGLJPanel;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.globes.EarthFlat;
import gov.nasa.worldwind.globes.FlatGlobe;
import gov.nasa.worldwind.terrain.ZeroElevationModel;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.embed.swing.SwingNode;
import javafx.stage.Stage;
import onethreeseven.trajsuite.core.model.TrajSuiteProgram;
import onethreeseven.trajsuite.core.settings.TrajSuiteSettings;
import onethreeseven.trajsuite.core.util.ViewChanger;
import onethreeseven.trajsuite.core.view.CheapAWTInputHandler;
import onethreeseven.trajsuitePlugin.view.controller.MainViewController;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Controller for the main view in TrajSuite.
* @author <NAME>
*/
public class TrajsuiteWWMainViewController extends MainViewController {
private final ObjectProperty<WorldWindow> wwdView =
new SimpleObjectProperty<>(null);
public TrajsuiteWWMainViewController(TrajSuiteProgram program, Stage stage){
super(program, stage);
}
protected TrajSuiteProgram getProgram(){
return (TrajSuiteProgram) program;
}
@Override
protected void initialize(){
super.initialize();
//load worldwind into center of border pane
final SwingNode swingNode = new SwingNode();
createSwingContent(swingNode);
topLevelPane.setCenter(swingNode);
}
private void createSwingContent(final SwingNode swingNode) {
//try get last latlon
Position startupPos = TrajSuiteSettings.LAST_POSITION.getSetting();
Configuration.setValue(AVKey.INITIAL_LATITUDE, startupPos.latitude.degrees);
Configuration.setValue(AVKey.INITIAL_LONGITUDE, startupPos.longitude.degrees);
Configuration.setValue(AVKey.INITIAL_ALTITUDE, startupPos.elevation);
WorldWindowGLJPanel wwd = new WorldWindowGLJPanel();
wwd.setInputHandler(new CheapAWTInputHandler());
//wwd.setPreferredSize(preferredWwdSize);
swingNode.setContent(wwd);
ZeroElevationModel zeroElevationModel = new ZeroElevationModel();
zeroElevationModel.setNetworkRetrievalEnabled(false);
FlatGlobe earth = new FlatGlobe(EarthFlat.WGS84_EQUATORIAL_RADIUS, EarthFlat.WGS84_POLAR_RADIUS, EarthFlat.WGS84_ES, zeroElevationModel);
ViewChanger.setupWorldLayers(getProgram().getLayers().getRenderableLayers());
BasicModel model = new BasicModel(earth, getProgram().getLayers().getRenderableLayers());
wwd.setModel(model);
pollGlobeUntilReady(wwd);
//when entity changes, re-draw
getProgram().getLayers().numEditedEntitiesProperty.addListener((observable, oldValue, newValue) -> {
if(wwd.getView().getGlobe() != null){
wwd.redraw();
}
});
}
private void pollGlobeUntilReady(final WorldWindow wwd){
ThreadFactory factory = r -> new Thread(r, "Poll for WorldWindow.");
ExecutorService service = Executors.newSingleThreadExecutor(factory);
CompletableFuture.runAsync(()->{
while(wwd.getView().getGlobe() == null){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, service).thenRun(()-> {
getProgram().setWwd(wwd);
wwdView.setValue(wwd);
});
}
public void addOnViewReadyListener(ChangeListener<? super WorldWindow> listener){
this.wwdView.addListener(listener);
}
}
|
<reponame>diouman/web-application
package managers;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import dbConnection.DatabaseConnection;
public class OrderManager {
private Connection connection = null;
private static SessionFactory sessionFactory;
public OrderManager() {
// sessionFactory = new Configuration().configure().buildSessionFactory();
Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
sessionFactory = config.buildSessionFactory(servReg);
}
public String addOrder(int oId, Date date, Time time, double total, int cId) throws ClassNotFoundException, SQLException {
connection = DatabaseConnection.getDBConnection();
String sql = "insert into orders values (?,?,?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, oId);
pstmt.setDate(2, date);
pstmt.setTime(3, time);
pstmt.setDouble(4, total);
pstmt.setInt(5, cId);
int exe = pstmt.executeUpdate();
if (exe >= 1) {
return "Order has been saved successfully!";
}
else {
return "Order has not been saved!!!";
}
}
public int haddOrder(int oId, Date date, Time time, double total, int cId) {
Session session = sessionFactory.openSession();
session.beginTransaction();
SQLQuery insertQuery = session.createSQLQuery("insert into orders values (?,?,?,?,?)");
insertQuery.setParameter(0, oId);
insertQuery.setParameter(1, date);
insertQuery.setParameter(2, time);
insertQuery.setParameter(3, total);
insertQuery.setParameter(4, cId);
int exe = insertQuery.executeUpdate();
session.getTransaction().commit();
session.close();
if (exe >= 1) {
return 1;
}
else {
return 0;
}
}
public int getLastOrderId() throws ClassNotFoundException, SQLException {
connection = dbConnection.DatabaseConnection.getDBConnection();
int oId = 0;
String sql = "select max(oId) as maxId from orders";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
oId = rs.getInt("maxId");
}
return oId;
}
@SuppressWarnings("unchecked")
public int hgetLastOrderId() {
Session session = sessionFactory.openSession();
String sql = "select max(oId) as maxId from orders";
SQLQuery query = session.createSQLQuery(sql);
List<Integer> results = query.list();
int oId = results.get(0);
session.close();
return oId;
}
}
|
/**
* FIXME: needs proper description
*
* saves secondary tab and makes sure the record is still open afterwards
*
* REQUIRED: to be in secondary tab with all the required fields filled out
*
* @param secondaryType
* @param secondaryID
* @param selenium
* @throws Exception
*/
public static void saveSecondary(int secondaryType, String secondaryID, Selenium selenium) throws Exception {
selenium.click("css=.csc-relatedRecordsTab-" + Record.getRecordTypeShort(secondaryType) + " .saveButton");
if (selenium.isElementPresent("css=.csc-confirmationDialog .saveButton")){
selenium.click("css=.csc-confirmationDialog .saveButton");
}
textNotPresent("Select number pattern", selenium);
textPresent(secondaryID, selenium);
openRelatedOfCurrent(secondaryType, secondaryID, selenium);
} |
/**
* ============================================================================
*
* Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved.
*
* 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,
* this list of conditions and the following disclaimer.
*
* 2 Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3 Neither the names of the copyright holders nor the names of the
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*/
#pragma once
#include<list>
#include "acl/acl.h"
#include "acl/ops/acl_dvpp.h"
#include "thread_safe_queue.h"
#include "atlas_error.h"
#include "dvpp_mem_mgr.h"
namespace {
const uint32_t kLevelNum = 9;
const uint32_t kPerLevelPoolsNum = 4;
}
enum MallocType {
MEM_ACL_MALLOC = 0,
MEM_POOL_MALLOC,
UNKNOW_MALLOC_TYPE,
};
struct MallocInfo {
uint32_t level;
uint32_t poolId;
uint32_t size;
MallocType mallocType;
};
class DvppMemPool {
public:
DvppMemPool();
~DvppMemPool();
void* MallocMem(uint32_t size, bool& isNewBlock);
void FreeMem(void* ptr);
uint32_t BlockNum() { return blockNum_; }
uint32_t FreeBlockNum() { return freeList_.Size(); }
uint32_t UsedBlockNum() { return usedList_.size(); }
private:
uint32_t blockNum_;
ThreadSafeQueue<void*> freeList_;
std::list<void*> usedList_;
mutable std::mutex mutex_lock_;
};
struct PoolLevel {
uint32_t size;
uint32_t maxBlockNum;
uint32_t totalBlockNum = 0;
DvppMemPool poolTbl[kPerLevelPoolsNum];
};
class DvppMemPoolMgr {
public:
DvppMemPoolMgr();
DvppMemPoolMgr(const DvppMemPoolMgr&) = delete;
DvppMemPoolMgr& operator=(const DvppMemPoolMgr&) = delete;
static DvppMemPoolMgr& GetInstance() {
static DvppMemPoolMgr instance;
return instance;
}
~DvppMemPoolMgr() {};
void* MallocMem(uint32_t size);
void FreeMem(void* ptr);
void StatisticMalloc() { totalMallocTimes_++; }
void StatisticFree() { totalFreeTimes_++; }
void PrintPoolInfo();
private:
uint32_t ChooseLevel(uint32_t size);
uint32_t ChoosePool(uint32_t level);
void* MallocDvppMemory(uint32_t size);
void* WrapMem(void* buffer, uint32_t level,
uint32_t poolId, MallocType mallocType, uint32_t size);
private:
PoolLevel levelList_[kLevelNum];
uint32_t totalMallocTimes_;
uint32_t totalFreeTimes_;
};
void* AtlasDvppMalloc(uint32_t size);
void AtlasDvppFree(void* ptr);
void PrintDvppMgrInfo();
|
N, M = map(int, input().split())
A = [int(x) for x in input().split()]
matches = [2, 5, 5, 4, 5, 6, 3, 7, 6]
A.sort()
min_match = 8
max_number = 0
for i, a in enumerate(A):
if min_match > matches[a - 1]:
min_match = matches[a - 1]
max_number = a
ans = list()
for i in range(N // min_match):
ans.append(max_number)
surplus = N % min_match
upper = 0
lower = N // min_match - 1
matches = list(map(lambda x: x - min_match, matches))
A.reverse()
for a in A:
if surplus >= matches[a - 1] and matches[a - 1] != 0:
for i in range(surplus // matches[a - 1]):
if a > max_number:
ans[upper] = a
upper += 1
else:
ans[lower] = a
lower -= 1
surplus %= matches[a - 1]
print("matches : {}".format(matches))
print("surplus : {}".format(surplus))
print(str(ans))
|
package ca.ulaval.glo4002.theproject.domain.creditcard;
import ca.ulaval.glo4002.theproject.domain.creditcard.value.CreditCardExpirationDate;
import ca.ulaval.glo4002.theproject.domain.creditcard.value.CreditCardNumber;
import ca.ulaval.glo4002.theproject.service.transaction.InvalidCreditCardException;
import org.junit.Before;
import org.junit.Test;
import java.time.YearMonth;
import static org.junit.Assert.*;
public class GenericCreditCardTest {
private final CreditCardNumber A_CARD_NUMBER = new CreditCardNumber("1234 5678 9012 3456");
private final CreditCardNumber AN_INVALID_CARD = new CreditCardNumber("123");
private final CreditCardExpirationDate AN_EXPIRATION_DATE = new CreditCardExpirationDate("02/10");
private final YearMonth A_MONTH = YearMonth.of(2015, 8);
private final CreditCardExpirationDate A_SAME_MONTH = new CreditCardExpirationDate("08/15");
private final CreditCardExpirationDate A_PAST_MONTH = new CreditCardExpirationDate("07/15");
private final CreditCardExpirationDate A_FUTURE_MONTH = new CreditCardExpirationDate("09/15");
private CreditCard creditCard;
@Before
public void init() {
creditCard = new GenericCreditCard(A_CARD_NUMBER, AN_EXPIRATION_DATE);
}
@Test
public void aCreditCard_GetCardNumber_ReturnsCardNumber() {
CreditCardNumber cardNumber = creditCard.getCardNumber();
assertEquals(A_CARD_NUMBER, cardNumber);
}
@Test
public void aCreditCard_GetExpirationDate_ReturnsExpirationDate() {
CreditCardExpirationDate expirationDate = creditCard.getExpirationDate();
assertEquals(AN_EXPIRATION_DATE, expirationDate);
}
@Test
public void aPastMonthCreditCard_IsExpired_ReturnsTrue() {
creditCard = new GenericCreditCard(A_CARD_NUMBER, A_PAST_MONTH);
boolean expired = creditCard.isExpired(A_MONTH);
assertTrue(expired);
}
@Test
public void aSameMonthCreditCard_IsExpired_ReturnsFalse() {
creditCard = new GenericCreditCard(A_CARD_NUMBER, A_SAME_MONTH);
boolean expired = creditCard.isExpired(A_MONTH);
assertFalse(expired);
}
@Test
public void aFutureMonthCreditCard_IsExpired_ReturnsFalse() {
creditCard = new GenericCreditCard(A_CARD_NUMBER, A_FUTURE_MONTH);
boolean expired = creditCard.isExpired(A_MONTH);
assertFalse(expired);
}
@Test(expected = InvalidCreditCardException.class)
public void aVisaCreditCardNotValid_Validate_ShouldThrowInvalidCreditCardException() {
creditCard = new VisaCreditCard(AN_INVALID_CARD, A_SAME_MONTH);
creditCard.validate();
}
@Test
public void aCreditCard_SetExpirationDate_ReturnsExpirationDate() {
creditCard.setExpirationDate(AN_EXPIRATION_DATE);
CreditCardExpirationDate theExpirationDate = creditCard.getExpirationDate();
assertEquals(AN_EXPIRATION_DATE, theExpirationDate);
}
}
|
package org.ovirt.engine.core.common.queries;
import org.ovirt.engine.core.compat.Guid;
public class GetVmsRunningOnOrMigratingToVdsParameters extends VdcQueryParametersBase {
private static final long serialVersionUID = 5129010056629518621L;
private Guid id;
public GetVmsRunningOnOrMigratingToVdsParameters() {
}
public GetVmsRunningOnOrMigratingToVdsParameters(Guid id) {
this.id = id;
}
public Guid getId() {
return id;
}
public void setId(Guid id) {
this.id = id;
}
}
|
Spatial mapping of ices in the Oph-F core: A direct measurement of CO depletion and the formation of CO2 Aims: Ices in dense star-forming cores contain the bulk of volatile molecules apart from H2 and thus represent a large fraction of dark cloud chemistry budget.To directly constrain the freeze-out profile of CO, the formation route of CO2 and the carrier of the 6.8 micron band, the spatial distribution of the CO/CO2 ice system and the 6.8 micron band carrier are measured in a nearby dense core. Methods: VLT-ISAAC, ISOCAM-CVF and Spitzer-IRS archival mid-infrared (3-20 micron) spectroscopy of young stellar objects is used to construct a map of the abundances of CO and CO2 ices in the Oph-F star-forming core, probing core radii from 2 10^3 to 14 10^3 AU or densities from 5 10^4 to 5 10^5 cm^-3 with a resolution of ~ 3000 AU. Results: The line-of-sight averaged abundances relative to water ice of both CO and CO2 ices increase monotonously with decreasing distance to the core center. The map traces the shape of the CO abundance profile between freeze-out ratios of 5-60% and shows that the CO2 ice abundance increases by a factor of 2 as the CO freezes out. It is suggested that this indicates a formation route of CO2 on a CO ice surface to produce a CO2 component dilute in CO ice, in addition to a fraction of the CO2 formed at lower densities along with the water ice mantle. It is predicted that the CO2 bending mode band profile should reflect a high CO:CO2 number ratio in the densest parts of dark clouds. In contrast to CO and CO2, the abundance of the carrier of the 6.8 micron band remains relatively constant throughout the core. A simple freeze-out model of the CO abundance profile is used to estimate the binding energy of CO on a CO ice surface to 814+/-30 K. Introduction Theory has long predicted that molecules freeze out onto dust grains in dense molecular clouds causing gas-phase abundances to drop by orders of magnitude. A series of recent measurements of the gas-phase abundances of volatile molecules such as CO and N 2 H + in dense cores have corroborated this conjecture (e.g. ;;). CO ice has also been observed directly along a growing sample of isolated lines of sight toward both embedded young stellar objects as well as background stars, showing that the CO molecules taken from the gas-phase reappears in the solid phase (;). CO ice is an excellent tracer of freeze-out processes because it is the only abundant ice species known to form initially in the gas-phase before adsorbing to a grain surface. Send offprint requests to: K. M. Pontoppidan Pontoppidan et al. introduced the technique of ice mapping at high (∼ 1000 AU) spatial resolution -comparable to that of gas-phase maps. The procedure was demonstrated by constructing a map of the distribution of water and methanol ices in the outer envelope of the class 0 protostar SMM 4 in the Serpens star-forming cloud. The ice map of SMM 4 was used to show that the water ice abundace remained constant over a relatively wide range of densities, while the methanol abundance increased sharply by at least a factor of ten within 10 000 AU of the center of SMM 4. In principle, ices are best mapped toward field stars located behind the cloud. However, such background stars are typically extremely faint in the midinfrared wavelength region. Therefore, disk sources embedded in their parent molecular cloud core offer a convenient infrared continuum against which the ices in the core can be mapped, with appropriate caveats on the interpretation of the derived ice abundances. Direct mapping of CO ice abundances is highly complementary to mapping of gas phase abundances, because ice maps are sensitive to depletion fractions as low as 5%, while gas-phase abundance maps trace high depletion factors (n(ice)/n(gas)) of 50% (). Furthermore, the depletion fraction as a function of gas density in a core is strongly dependent on the properties of the dust grain surfaces. Direct maps of CO ice in a dense core therefore enables an independent measure of surface binding energies. This letter presents the first spatial map of CO and CO 2 ices in a dense molecular core. It will be demonstrated that by directly measuring the relation between ice abundances and gas densities, the following quantities can be constrained: 1) the dependence of CO depletion on gas density with a large dynamical range, 2) the CO-CO binding energy, 3) the formation route of CO 2 and the 6.8 m band carrier. The case study is the F core in the Ophiuchus molecular cloud complex (Motte et al. ). Embedded within this region, are at least 8-10 infrared-bright young stars. The lines of sight toward 5 of these young stars are used to probe the ices in front of each star in order to obtain a cross section of ice abundances across the minor axis of the core. Observations The individual spectra are taken from van Dishoeck et al. and Pontoppidan et al. of the 3.08 m and 4.67 m stretching modes of solid H 2 O and CO, obtained with the Infrared Spectrometer And Array Camera (ISAAC) on the Very Large Telescope (VLT) 1. The solid CO 2 component is probed along the same lines of sight using the InfraRed Spectrograph (IRS) on the Spitzer Space Telescope (AOR IDs 0009346048 and 0009829888 2 ) (;) as well as 5-16.3 m spectra obtained with ISOCAM-CVF (TDTs 29601715 and 29601813) () 3. The Spitzer spectra were taken as part of the Cores to Disks Legacy program (). Combining these facilities, high quality 3-16 m spectra are available for 5 sources within a radius of 15 000 AU from the center of the pre-stellar core, defined to be the 850 m peak of Oph-F MM2 (=16 h 27 24.3, =-24 40 35, J2000) (). Only IRS 46 has no suitable spectrum between 5 and 10 m. To determine the optical depths of the various ice bands continua were fitted using low-order polynomia. The CO and CO 2 bands are sufficiently narrow to make the continuum determination relatively straight-forward and unbiased. For the 3.08 m water ice band a continuum is fitted to points between 3.8 to 4.0 m and a K-band photometric point from the 2MASS catalogue. Finally, a local continuum between 5.5 and 8.0 m is used to extract optical depth spectra of the 6.8 m band. In consideration of the uncertainties in the continuum determination, care was taken to use the same "ice-free" regions and 2-order polynomia for all sources. Further discussion of the determination of continua for extracting ice optical depth spectra can be found in e.g. Gerakines et al. ; Dartois et al. ; Keane et al.. The ice spectra are shown on an optical depth scale in Fig. 1, while the locations of the sources relative to an 850 m JCMT-SCUBA map obtained by the COMPLETE collaboration () are shown in Fig. 2. Abundance profiles of CO and CO 2 ice The basic ice map is constructed by determining the ice column densities along each line of sight and ratioing with the water ice column density. The implicit assumption is that the 3.08 m water ice band traces the total H 2 column density (see Pontoppidan et al. for a discussion). This yields CO and CO 2 line-of-sight averaged ice abundances relative to H 2 O ice as a function of projected distance to the center of the core. The radial map is shown in Fig. 3. It is seen that the abundances of pure CO, water-rich CO and CO 2 all increase toward the center of the core, while the 6.8 m band carrier decreases slightly in abundance. The sharp rise in CO ice abundance is expected for CO freezing out from the gas-phase at high densities in the central parts of the core. Fig. 1. Overview of the H 2 O, CO, 6.8 m and CO 2 ice bands (ordered left to right) used to construct the ice map of the Oph-F core. The 3.08 m water ice bands shown on the left-most panel are ordered according to optical depth, for clarity, as indicated in the panel. In the remaining panels, the sources are ordered according to projected distance to the core center, with the source furthest from the center (IRS 46) at the top. No 5-8 m spectrum is available for IRS 46. Note also that the 6.8 m band of IRS 42 is filled in by emission likely due to PAHs. All the spectra have been shifted vertically, for clarity. Pontoppidan et al., the average abundance of pure CO ice is seen to rise from 4.5 10 −6 to 7.0 10 −5, and the total CO and CO 2 abundances from 2.3 10 −5 to 12 10 −5. This corresponds to a total CO depletion ranging from 12% to 60%, assuming an initial CO gas-phase abundance of 2 10 −4. The increase by roughly a factor two in CO 2 ice abundance is particularly interesting. Since CO 2 molecules are formed on the grain surfaces, the increase in CO 2 ice abundance along with the CO freeze out is a direct indication of a formation route associated with CO. A significant amount of CO 2 is present in the outer parts of the Oph-F core where the densities are not yet high enough for the CO to freeze out. This can be interpreted as evidence for two distinct eras for CO 2 ice formation: The first takes place at roughly the same time as the bulk of the water ice is formed, which is known to happen as soon as the extinction, A V, into the cloud reaches a specific, relatively low, threshold of roughly 3-5 magnitudes (). This domain is not probed by the Oph-F ice map. The second takes place during the catastrophic freeze-out of CO that occurs at densities of a few 10 5 cm −3 () in which an almost pure CO ice mantle forms. This second phase of CO 2 molecules should be easily detectable in the shape of the 15.2 m CO 2 bending mode absorption band, which is highly sensitive to the molecular environment of the CO 2 molecules. Specifically, the new CO 2 molecules should be found to be dilute in the CO ice with an average fraction of 1:5, as determined by the relative CO and CO 2 abundance increases in the Oph-F core. Since the CO freeze-out rate is a very strongly increasing function of density, it is expected that the CO 2 :CO ratio will decrease in denser parts of the core. Thus, one would expect to find a range of components in the CO 2 bending mode in the centers of dense clouds. The spectral resolution of the ISOCAM-CVF spectra (/∆ ∼ 50) is not sufficiently high to search for such band shape changes in the current data. Since the young stars that are used to estimate ice abundances in the core material are embedded in the core, significant caveats apply. Heating of the core material may desorb CO ice within a radius of a few hundred AU of each source, depending on the luminosity. However, since the projected size of the core is 30 000 AU, desorption is likely to play only a minor role. A possible exception to this is IRS 46, which contains a significant component of warm molecular gas along the line of sight (). Also, the sources may be surrounded by remnant envelopes with different ice abundances than the surrounding core. The ice absorption toward CRBR 2422.8-3423 was shown by Pontoppidan et al. to be dominated Fig. 3. Radial map of CO and CO 2 ices of the Oph-F core. Ice abundances relative to H 2 O ice toward young stars are plotted as functions of projected distance to the center of the core as described in the text. The CO ice has been split into a "pure" and "water-rich" component following Pontoppidan et al.. by cold core material, although a fraction of the water, CO 2 and 6.8 m ices are likely located in the disk. However, it was found that the CO ice observed in this line of sight could not originate in the disk. Empirical determination of the CO-CO binding energy The CO depletion profile in Fig. 3 is modeled using a simplified freeze-out model, assuming a static core and that only thermal desorption occurs. For the purposes of this letter, the model presented is intended as a demonstration of the method, rather than achieving very accurate results. The rate of ice mantle build-up is then given by: Where R des = 0 exp n CO,ice is the desorption rate and R ads = n CO,gas n dust d 2 √ 3kT/m CO f is the adsorption rate. is a factor taking into account that CO only desorbs from the top monolayer (i.e. 1st order desorption for sub-monolayer coverage and 0th order desorption for multilayers). d = 0.05 m is the grain radius, f = 1 is the sticking coefficient, 0 is the frequency of the CO stretching mode and n CO,gas and n dust are the number densities of CO gas and dust particles. Solving for n ice yields a time dependent ice density given a gas density and (assumed identical) gas and dust temperature. This rate equation reaches an equilibrium on relatively short time scales (<< 10 6 years). Therefore, given a temperature and density structure, one can in principle solve for the binding energy of CO, dH. For the density profile of the core, a Bonnor-Ebert sphere with a central density of 5.5 10 5 cm −3 is used with a temperature of 15 K as suggested by Motte et al. and references therein. This simple procedure yields a CO on CO binding energy of 814 ± 30 K. The Fig. 4. Observed and modeled CO ice abundance for Oph-F. The curve shows the simple freeze-out model for the bestfitting CO binding energy of dH/k = 814 K. The "solid CO" abundance is the sum of the pure CO, CO in water and the CO 2 ice excess abundances. This assumes that one CO molecule is used to produce each CO 2 molecule. The error bars indicate a 20% uncertainty. uncertainty reflects different results obtained if varying the central density and water ice abundance by 50%. Additionally, the derived binding energy scales linearly with the assumed dust temperature. Considering the simplified analysis, this result is consistent with that recently found by Bisschop et al. from laboratory experiments. The radial map constitutes the first direct observation of the freeze-out profile of CO on dust grains in a prestellar core previously inferred indirectly from observations of millimetre lines of molecules. Additionally the observed increase in CO 2 ice abundance toward the center is the first quantitative observational evidence of the formation of CO 2 from CO on the surfaces of dust grains. These are observations that would not have been possible with single lines of sight. |
Polyphenolic promiscuity, inflammation-coupled selectivity: Whether PAINs filters mask an antiviral asset The Covid-19 pandemic has elicited much laboratory and clinical research attention on vaccines, mAbs, and certain small-molecule antivirals against SARS-CoV-2 infection. By contrast, there has been comparatively little attention on plant-derived compounds, especially those that are understood to be safely ingested at common doses and are frequently consumed in the diet in herbs, spices, fruits and vegetables. Examining plant secondary metabolites, we review recent elucidations into the pharmacological activity of flavonoids and other polyphenolic compounds and also survey their putative frequent-hitter behavior. Polyphenols, like many drugs, are glucuronidated post-ingestion. In an inflammatory milieu such as infection, a reversion back to the active aglycone by the release of -glucuronidase from neutrophils and macrophages allows cellular entry of the aglycone. In the context of viral infection, virions and intracellular virus particles may be exposed to promiscuous binding by the polyphenol aglycones resulting in viral inhibition. As the mechanisms scope would apply to the diverse range of virus species that elicit inflammation in infected hosts, we highlight pre-clinical studies of polyphenol aglycones, such as luteolin, isoginkgetin, quercetin, quercetagetin, baicalein, curcumin, fisetin and hesperetin that reduce virion replication spanning multiple distinct virus genera. It is hoped that greater awareness of the potential spatial selectivity of polyphenolic activation to sites of pathogenic infection will spur renewed research and clinical attention for natural products antiviral assaying and trialing over a wide array of infectious viral diseases. Introduction Therapies with demonstrated efficacy for infection by SARS-CoV-2, the etiological agent of the COVID-19 pandemic, include small molecule antivirals such as molnupiravir and nirmatrelvir, monoclonal antibodies (U.S. Food and Drugs Administration, 2021), and repurposed drugs such as dexamethasone and fluvoxamine (). Monoclonal antibody therapy suffers from challenging logistics to administer. Dexamethasone has only modest effect on disease outcome (The RECOVERY Collaborative Group, 2021). Fluvoxamine remains prescribable but not yet mandated with agency approvals for COVID-19 (Leo and Erman, 2022). Researchers have called for mutagenicity studies of molnupiravir (Malone and Campbell, 2021;). As SARS-CoV-2 variants continue to evolve, nirmatrelvir's future efficacy could be impacted, including under its own selection pressure on the main protease (). Persistently low worldwide vaccination rates, the potential for breakthrough infections, and the ability for vaccinated individuals to achieve viral loads sufficient to infect others (), suggest that there remains ample scope for additional safe, replication-inhibiting antivirals in the panoply of pandemic-alleviating healthcare tools. Natural products may present a potentially untapped source of antiviral activity. Plants must resist viruses whose constituent peptides are restricted to the same repertoire of proteinogenic amino acids as peptides in mammals. Plant virus proteins share similar fundamental constraints on protein secondary and tertiary structure as viruses with mammalian hosts. Plants' secondary metabolites are known particularly for plantprotection. Prevalent among the secondary metabolites are polyphenols. One of the three primary polyphenol classes are flavonoids (). extract were shown to inhibit H1N1 infection by binding to the viral envelope blocking entry into host cells (). Quercetin demonstrated anti-infective and anti-replicative activity in four different virus species. Quercetin also blocks viral binding and penetration to the host cell in HSV (). In a recent paper on the antiviral effects of flavonoids, Liskova et al. review the antiviral mechanisms of action for several flavonoids. For example, caflanone (from Cannabis sativa L.--Cannabaceae) pleiotropically inhibits viral entry factors such as ABL-2, cathepsin L, PI4Kiii and AXL-2, which facilitate mother-to-fetus transmission of coronavirus (). In addition, caflanone shows multi-modal anti-inflammatory activity through the inhibition of IL-1, IL-6, IL-8, TNF- and Mip-1 (). Other flavonoids show antiinflammatory activity through direct inhibition of NFB (). Caflanone, and other flavonoids such as equivir, hesperetin, and myricetin also bind at high affinity to the helicase spike protein of SARS-CoV-2, as well as protease cleavage sites on the ACE2 receptor (). The antiviral effect of Pelargonium sidoides DC. , also known as umckaloaba, has been found to predominantly depend on the polyphenols, namely the flavonoids and oligomeric proanthocyanidins (). These compounds have been shown to directly interfere with the infectivity of HIV-1 particles before they interact with the host cell in a polyvalent manner. For instance, the flavonoid/anthocyanidin fraction of P. sidoides inhibited attachment of virus particles to cells by inhibiting the early viral proteins of Tat and Rev (positive regulators of gene expression) and inhibited the release of infectious virions. In addition, P. sidoides extracts demonstrated a strong reduction of input viral RNA levels in virus-exposed cells. In addition, the previously mentioned flavonoids target HIV-1 envelope proteins (X4 (LAI) and R5 (AD8 and JRFL), thereby inhibiting HIV-1 entry by interfering with the function of the envelope proteins (). In ex-vivo investigations in rhinovirus-infected cells isolated from patients with severe asthma, moderate COPD, and diseasefree controls, a P. sidioides extract (standardized to oligomeric prodelphinidins, a type of flavonoid) concentration-dependently demonstrated significantly increased human bronchial epithelial cell survival and decreased expression of inducible co-stimulator (ICOS) and its ligand ICOSL, as well as cell surface calreticulin. In both infected and uninfected, rhinovirus B-defensin-1 and suppressor of cytokine signaling-1 (SOCS1) were up-regulated suggesting a mode of activity for these flavonoid-rich extracts (). Besides the discussed anti-inflammatory activity, there is other immunomodulatory activity of flavonoids which has been reviewed elsewhere (;;). Besides the cytokine inhibition, cytokines have other roles that may significantly affect immune function. For example, the ubiquitous occurring quercetin and its glycoside rutin, have been found to facilitate the shift of macrophages from a proinflammatory to an antiinflammatory phenotype (Bispo da ;). Additionally, apigenin, luteolin, and quercetin show significant immunomodulatory actions on natural killer cell cytotoxicity activity and granule secretion (). Quercetin has also demonstrated a decreased in the expression levels of the major histocompatibility complex class two (MHC II) and costimulatory molecules resulting in a marked reduction of T cell activation (). Finally, human peripheral blood mononuclear cells treated with quercetin preferentially induced interferon gamma (IFN-) expression and synthesis while inhibiting IL-4 production resulting in a differential activation of Th1 cells, suggesting potential antitumor activity (). A frequent target of coronavirus antivirals is the SARS-CoV-2 main protease, owing especially to the successful history of protease inhibitors on reducing HIV replication. Several polyphenols showed potent antiviral activity to SARS-CoV's main protease (;;;;). Among these, the polyphenolic flavonoid hesperetin was unique in potently inhibiting the action of the main protease in cell-based assay (). Hesperetin dose-dependently inhibited cleavage activity of the 3CLpro in expressed in Vero E6 cells with an IC50 of 8.3 M (). However, polyphenols like hesperetin are disfavored by industrial medicinal chemists for proceeding through the hitto-lead (H2L) stage of the drug discovery pipeline (Lowe, 2020;. Polyphenols are categorized among the Pan-Assay INterference compounds (PAINs) , and are suggested to obscure the results of various assays. They also bind broadly to assays' protein targets themselves. Selected examples of polyphenol aglycones are provided in Figure 1. Due to the ongoing pressing need for further COVID treatment strategies, we review the pharmacokinetic and putative frequent-hitting behavior of polyphenols' as a class with an eye toward ascertaining 1) their potential as an antiviral 2) whether or not polyphenols simultaneously should pose risks to ordinary healthy cellular processes. What defines a polyphenol? While IUPAC has defined the term "phenols", a definition of polyphenols remains yet to be formally accepted. Quideau explored definitions of polyphenols extensively, providing an applicable description: "The term "polyphenol" should be used to define plant secondary metabolites derived exclusively from the shikimate-derived phenylpropanoid and/or the polyketide pathway(s), featuring more than one phenolic ring and being devoid of any nitrogen-based functional group in their most basic structural expression." () Describing polyphenols in part based on their provenance provides excellent exclusivity. However, one could question whether it is helpful to exclude phenols such as acacetin which have only one phenolic ring. For large-scale cheminformatic purposes, which challenge the application of biosynthesis pathway criteria, an applicable definition may be to treat polyphenols as any molecule with more than one phenolic ring but lacking elements other than C, H, and O. Poor polyphenol PK perception The therapeutic efficacy of any antiviral whose purpose is to reduce viral replication requires maintaining an efficacious concentration of the ligand at its putative target for an extended period of time. Conservatively, this period should ideally be of long duration relative to a virus's replication time to reach peak viral load. An interval typically measured in days in the case of SARS-CoV-2 infection in humans (). However, polyphenolic compounds' potential for efficacy for any particular pathology is criticized due to a prima facie poor pharmacokinetic ADMET profile. Consider, for example, diosmetin. A primary intermediate metabolite of the pharmaceutical formulation known as Daflon (comprised of 90% diosmin, and 10% other flavonoids expressed as hesperidin, diosmetin, linarin, and isorhoifolin), and similarly proportioned formulations are prescribed in many countries around the world for chronic venous insufficiency (CVI). Note that a similar metabolic pathway can be described for other flavonoid aglycones. In the case of hesperidin, it is hydrolyzed to hesperetin, ultimately primarily becoming Figures 3A,B, respectively. Yet to our knowledge 1) no quantitative bioavailability assays of diosmetin have taken place in non-plasma compartments such as extracellular fluid and tissue in humans; 2) tissue distribution studies of flavonoids in animal models are few. More in vivo distribution data to support therapeutic insights into polyphenols would be valuable. Therefore, if any particular pharmaceutical candidate's PK profile achieves significant distribution in organs other than those associated with either the GI tract or renal tract, it would be unascertainable from serum analysis alone. Further, if any particular pathology has an effect on a compound's tissue distribution (whether by causing sequestering in sanctuary sites, or adduct formation with the target in tissue both of which represent an increase in the volume of distribution), then plasma analysis alone remains poorly positioned to provide the relevant readout. Rather, tissue analysis in sacrificed animal models, or comprehensive radiolabeled elimination quantitation in humans, would be required. Walle et al. demonstrated such a radiolabeled analysis. Notably, they found that carbon dioxide was a major metabolite of quercetin in humans, () suggesting a rarer elimination pathway than typically encountered by pharmacological analysis. Even with this exotic elimination route taken into account, the full dose of quercetin was not always fully representative of the dose given. One can speculate that sequestration of quercetin products in tissue compartments was maintained past the 72-hr study period. Moreover, while de Boer et al. and Bieger et al. demonstrated that quercetin reaches certain tissues other than those associated with GI and renal tracts in healthy animal Toward resolving the "flavonoid paradox" To begin addressing these pharmacokinetic challenges, we examine them through the lens of a subtle but critically important feature of the pharmacokinetic profile of polyphenols, such as flavonoids, as elucidated by the literature. Menendez et al. and Perez-Vicaino et al. frame flavonoids' pharmacokinetic challenges in the context of a "flavonoid paradox" (;). The paradox can be summarized as the observation that several flavonoid polyphenols have been shown to demonstrate therapeutic effects for various pathologies in vivo, and yet their pharmacological profiles suggest poor bioavailability, including the difficulty of glucuronide metabolites to pass through cell membranes, along with rapid plasma clearance. Investigators (;;O';;Shimoi and Nakayama, 2005;;;;;;;;) of the following deconjugation mechanism offer a resolution to the flavonoid paradox: During inflammation (as happens during infection of several etiologies), phagocytes arrive at the extracellular fluid surrounding the sites of inflammation. The phagocytes express -glucuronidase which accomplishes deglucuronidation (also known as deconjugation) of the flavonoid glucuronide into its aglycone form. The deconjugated flavonoid aglycone subsequently diffuses through the cell membrane where they can reach their target. The mechanism is summarized in Table 1. For purposes of this review, the mechanism steps are labeled stages B, C, D, E, and F. While the deglucuronidation-through-inflammation hypothesis has been reviewed extensively by others, (;;Kawai, 2014;;Terao, 2017;Kawai, 2018) to our knowledge, this review is the first to unify the body of work into one cohesive, accessible evidentiary framework. Demonstration of the evidence generated through the deglucuronidation-through-inflammation body of work, (;;O';;Shimoi and Nakayama, 2005;;;;;;;;) is provided against the model's labeled stages C-F in Figure 4. Figure 4 illustrates the body of deglucuronidation-throughinflammation literature thusly: Original research investigators produced results demonstrating any one of the four stages of the mechanism (which we refer to here as steps C, D, E, F), the entire mechanism (CDEF), or consecutive combinations of steps (such as CD, CDE). We highlight whether evidence for an individual step has been produced, or instead over multiple consecutive steps end-to-end (without isolated verification of any intermediate step). Consecutive step verifications are illustrated by highlighting in bold the top and bottom of the relevant cells. The figure annotates whether experiments have been performed in vitro (using mice, rat, or human cell lines) or in vivo in mice models, rat models, or humans. While steps of the pathway were verified across the polyphenols luteolin (;;Shimoi and Nakayama, 2005), We believe the figure also adds value as it makes clear which steps are already demonstrated so that they can undergo simpler replication studies, as well as identifying which steps, such as in vivo human verification work at stages DEF, could be better elucidated with fresh original research. We propose standardizing the mechanism's naming to the technical term "deglucuronidation-through-inflammation" or DTI. The term 'Shimoi pathway' further serves as a convenient shorthand that recognizes the lead researcher to first propose and study this mechanism with specific attention to inflammation with polyphenols. The promiscuous inhibition of polyphenols Promiscuous inhibition poses two primary implications for medicinal chemistry assaying. The first is the non-specific binding of protein/enzyme targets themselves. The second is the disruption of assay integrity by inhibiting non-target enzymes used for assay readout. As it can be difficult to distinguish between these two, orthogonal assays are sometimes performed to verify a target binding interaction. Promiscuity could take any of several forms. A promiscuous ligand could simply be highly conforming to a protein surface's geometry, with a high number of hydrogen donors & acceptors to more likely "stick" nonspecifically to any given protein site's own set of H-donors and H-acceptors. Another mechanism sees promiscuous inhibition take the form of colloidal aggregations. In this mechanism, upon reaching a certain concentration, the ligand forms tightly-packed spherical aggregates with itself, even inside the cell (;Shoichet, 2021) as illustrated in Figure 5. Proteins and enzymes non-specifically bind to the surface of the aggregation and are inhibited in the process (). Often seen as a nuisance originally, it is now also seen as a source of opportunity in drug discovery as well (;;). Deliberate study of aggregation in cell-based assays is a nascent sub-field, () thus cataloguing of non-specific aggregation among polyphenols in cells merits further investigation. Of 123,844 assay records hosted by Pubchem and compiled by Gilberg et al. (), their isolation of the most promiscuous 466 of them (99.6% percentile) contains 13 polyphenols based on our cheminformatic-oriented definition. The catechol functional group, while not the exclusive province of polyphenols (and nor do polyphenols all contain catechol), certainly correlates with polyphenols. Bael and Holloway, highlights catechol as a prominent PAINS functional group (Baell and Holloway, 2010) even as Capuzzi et al. cautions against blind application of PAINS filters. (). And yet Jasial et al. demonstrates that the catechol functional group is in the top ten percentile (9.5) of primary activity assays in Pubchem, and in the top seven percentile (6.9) of functional groups in Pubchem confirmatory assay activity (). Therapeutic role of a promiscuous binder? The final step of a putative polyphenol deglucuronidation-based antiviral mechanism requires that a promiscuous-binding compound once inside a virus-infected human cell will arrest viable virion production. The complete proposed mechanism is presented in Table 2. Table 2 is illustrated graphically in Figure 6-by way of one of the most studied flavonoids in the pharmacokinetic literature, quercetin. Inhibitory mechanisms of viral replication could be due to direct inhibition of viral proteins and enzymes, or by slowing ordinary cellular metabolic mechanisms such as respiration, translation, <35 M Clementi et al. a One phenol only. Frontiers in Pharmacology frontiersin.org Frontiers in Pharmacology frontiersin.org 10 transcription as co-opted by the infecting virus. In one case, that of fisetin applied to Dengue fever, (a) fisetin showed no direct activity against DENV virions outside the cell yet effectively inhibited replication in-cell. The study's authors suggest it could be due to forming complexes with RNA or inhibition of RNA polymerases. While inhibition of the dengue RdRp would represent a virus-specific inhibition, it remains intriguing to consider that the replication inhibition could also be due to general non-selective inhibition in a weakened cell. Application of deglucuronidationthrough-inflammation to antiviral assaying and clinical trialing Given that many forms of viral infections are known to induce inflammation, it would be a logical extension to study whether consumption of certain flavonoids of sufficient quantity and in bioavailable forms could serve to reduce the rate of viral replication in the early stages of viral infection. The mechanism FIGURE 7 Additionally referenced polyphenols: luteolin ; Isoginkgetin ; baicalein ; curcumin ; fisetin ; quercetagetin ; naringenin. Frontiers in Pharmacology frontiersin.org of action could be by inhibition of viral entry to cells, direct inhibitory action on viral enzymes in-cell, or non-specific promiscuous disruption of the co-opted metabolism of infected cells. The literature provides early in vitro evidence of achievable inhibition by phenolic flavonoids spanning across Dengue virus, Influenza-A virus (IAV), Chikungunya virus, Foot-and-mouth disease virus (FMDV), Japaneses Encephalitus Virus (JEV) and SARS-CoV-2, presented in Table 3. Corresponding ligand structures are available in Figure 1 and Figure 7. Much care must be applied in interpreting in vitro viral replication inhibition results. Where an IC50 value is defined against a measure of viral RNA copies/mL, then qRT-PCR will show a difference of a single unit of Ct. For comparison, SARS-CoV-2 infection typically presents a Ct range between 10 and 40 for acute infection vs. non-detectable viral load, respectively (). However, in vitro and in vivo Ct values are not directly comparable, as in vitro reduction of viral replication may exhibit nonlinear effects at the in vivo scale, especially when the effects of the innate and specific immune system are considered. Where due analysis of toxicity allows, a higher IC value can be targeted, such as IC90 or even IC99 (). Viral inhibitory assays typically report the Selectivity Index (SI), defined as the ratio of the cytotoxicity (CC50) to the inhibitory concentration (IC50). A SI < 1 means that the ligand's cytotoxicity to cells occurs at a lower concentration than its inhibition of the target. Selectivity indices of 5 or greater are preferred. Ligand candidates suffering from lower selectivity indices may be excluded from further investigation. However, the deglucuronidation-through-inflammation mechanism would suggest that dismissing polyphenol ligands with a low selectivity index could be overly conservative. Given that polyphenols circulate in plasma primarily as glucuronides, (;;;;O';;;;;;Bajraktari and Weiss, 2020;) a low selectivity index for the aglycone may not only be acceptable but may even be preferable. This of course will depend on how efficiently the deglucuronidation process discriminates between the localities of healthy and infected cells that induce the inflammatory process. Given the selectivity that deglucuronidation-throughinflammation affords, and the putative validity of aggregation-based non-selective binding mechanisms, the standard practice of applying aggregatedissociating detergents such as Triton X-100 is called into question for antiviral assays of phenols that are known or expected to act through the DTI mechanism. A revisiting of relevant results of in vitro assays in the literature where such a detergent was applied would be appropriate. However, such a modification to laboratory practice should be considered carefully as the tendency for an aggregation to bind assayspecific enzymes could still benefit from detergent application. Non-selective inhibition can be a double-edged sword. Dong demonstrates that the aglycone kaempferol increased IAV viral titers by log-2 compared with untreated mice, hastening their loss (). This was attributed to attenuation of antiviral host-defense factor expression such as IFN, IFN, IFN. By contrast, hesperidin was protective of the mice. Further laboratory and clinical investigation of demonstrably promiscuous-binding polyphenols utilizing in vitro viral infection culture and in vivo models will continue to be valuable. Attention would be particularly appropriate against those viruses that are known to induce inflammatory responses such as influenza A (IAV-A), dengue (DENV), chikungunya (CHIKV), and coronavirus (SARS-CoV-2). Additional observations on antivirals trialing of polyphenols While it is important to maintain ligand concentration at the target for a period sufficient to exert the relevant mechanism of action, it is worth noting that this period can be extremely short. Although not a polyphenol, artemisinin enjoys enormous efficacy against the malaria parasite Plasmodium falciparum with a T max at less than 2 h and a half-life of 2-5 h (;de Vries and Dien, 2021). Also, the dosage is of utmost importance. Following due analysis of toxicity, protease inhibitors can target a C min dose (minimum concentration between consecutive doses) of many multiples of the IC50 value () to achieve faster viral clearance. Indirect antiviral effects of certain polyphenols may also be possible, such as non-specific upregulation of immunosurveillance, as well as modulation of specific immune cells (;;). Also, as promiscuous binders, due attention should be applied to inhibition of liver enzymes for drug-drug interactions (Bajraktari and Weiss, 2020), especially of drugs that study subjects might concomitantly consume for the same or unrelated conditions. For example, among the polyphenols studied are those known to bind to CYP1A2 (Bajraktari and Weiss, 2020), CYP3A4 (Bajraktari and Weiss, 2020) and OATP1A2, the latter giving rise to the famous "grapefruit effect" (). Conversely, this P450 or other liver enzyme inhibition may be advantageous to increase serum concentrations of verified pharmaceuticals, such as fluvoxamine, in context of combination therapy (James Duke, personal communication, 28 November 2009) for superior joint bioavailability. Finally, as a given polyphenol can demonstrate differing bioavailabilities between different dosage forms, () consideration should also be given to oral delivery type, such as aqueous, softgel, dry tablet form, and degree of micronization. Further, owing to strong Frontiers in Pharmacology frontiersin.org bioavailability and/or release rate, delivery in the form of original plant matter while controlling for phytochemical content should also be considered (;;). Evolutionary role A BLAST search demonstrates that the gene coding for glucuronidase is extensively common across the animal kingdom (data not shown). Its homolog -galactosidase (40% identity) is also commonly expressed in bacteria (data not shown). -glucuronidase has several documented purposes (). It targets glucuronic acid in the gut, (;) and is associated with the degradation of glucuronatecontaining glycosaminoglycan (). But its extensive expression on, and release from, neutrophils attracted in response to inflammatory signals is a mechanism whose genetic etiology and species prevalence will require further work to elucidate. Given the long history of herbivory in animals (and associated polyphenolic compound ingestion), and the high prevalence frequency of the -glucuronidase-coding gene GUSB across vertebrates, this mechanism could be a long-ago evolved broad response under selection pressure of viral pathologies in ancestral species. It would be worthwhile for future investigators to probe the genetic basis for neutrophilic -glucuronidase expression and its orthology across vertebrate species in order to better localize how this response evolved. Conclusion In this paper, we add to the body of evidence in the literature that polyphenols are a frequent-binding class of chemicals produced by plants. We show that the pharmacology of polyphenols may allow for viral infection-fighting potential due to the human body's inflammatory response and provide conjecture as to the evolutionary basis for a putative inflammation-induced antiviral function. Future work could include quantifying the effect of in vitro antiviral studies under inflammation with neutrophils present for such viral targets as SARS-CoV-2, CHIKV, DENV, and IAV/IBV. Author contributions RS and KS contributed to conception of the review. RS wrote the first draft of the manuscript. KS wrote sections of the manuscript. All authors contributed to manuscript revision, read, and approved the submitted version. Funding This work was supported by EMSKE Phytochem. the preparation of this manuscript; and Yu Wai Chen PhD, Francisco Perez-Vizcaino PhD, and Erik de Clercq PhD for encouragement, and would especially like to recognize and appreciate Stephen Molnar PhD for insights and reviewing drafts of this manuscript. We are indebted to Fabiola de Marchi PhD for expert chemical structure graphic drafting. Finally, we would like to thank Priyanshu Jain for unflagging support and encouragement in the course of preparation. Conflict of interest Author RS was employed by EMSKE Phytochem. The remaining author declares that the research was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest. Publisher's note All claims expressed in this article are solely those of the authors and do not necessarily represent those of their affiliated organizations, or those of the publisher, the editors and the reviewers. Any product that may be evaluated in this article, or claim that may be made by its manufacturer, is not guaranteed or endorsed by the publisher. |
Several hundred yards away on a neighboring ranch, a man with a high-powered rifle with telescopic sights had started his morning by nudging his ATV up a hill through knee-high dried grass to reach a 16-foot tower rising over the landscape. It was a comfortable perch once the ladder climb was conquered, a comfortably-cushioned, camouflaged seat with a padded rest for one’s weapon.
The tower, sold under names like “Sniper Outlaw Deer Stand,” was one of several stationed around the man’s property. This one offered a sweeping view of endless acres of wide open land, which the man scanned through his telescope. Then, in the distance, a large dog appeared in his crosshairs, and the man’s finger tightened on the rifle’s trigger.
Teesee Murray, a global vice president of a major software corporation who travels frequently, was home and on a business phone call that morning when she heard the distinct retort of a large-caliber rifle. She noted the time, almost subconsciously — 8:15 a.m. — and felt a fleeting chill before dismissing the moment; gunfire in the rural area is not uncommon. But shortly thereafter, Snoop Dogg failed to return home.
With husband David on a business trip in Colorado, Teesee and her three teenage children spent the day and part of the next searching for their missing friend. Then she noticed an ominous gathering of turkey vultures circling over one edge of their property. She walked, alone and apprehensive, to the site. There she found Snoop Dogg, shot through the heart, his big, strong body already ravaged by night predators.
Almost exactly two years earlier, the Murrays had finally located and purchased the latest of the numerous Ridgebacks they had owned over two decades, a huge, playful, friendly puppy they simply called “Snoop.” He never let his AKC pedigree papers go to his head, the Murrays said.
In his brief Creston residency, Snoop already had sired one litter of pups, helping earn about $25,000. At their birth, Snoop was so excited about his new little family that he awakened the Murrays and heralded the news by dancing happily as he ushered them to the delivery site.
The two Murray daughters were planning to fund their college education with the Ridgebacks’ continuing enthusiastic procreation. Snoop’s mate, Pepper, is now pregnant with litter number two.
Snoop’s pleasant and gentle temperament made him a perfect companion, David recalled as he drove a reporter in an ATV to view the sniper tower where the shooter had perched.
David could barely suppress his emotions as he pointed up the hill, at the tower.
David Murray and Pepper, Snoop Dogg’s pregnant mate.
After showing Snoop’s body to sheriff’s deputies, the Murray’s 18-year-old son Spencer carried out the wrenching job of burying “our cherished family member,” David said. Until that point, David did not know what was happening back home on the family ranch. Teecee placed the difficult call to her husband only after Snoop was interred.
Sheriff’s deputies interviewed a neighbor, Stephen William Almond, 65. David said deputies told him Almond admitted shooting Snoop Dogg, thinking the Ridgeback was a stray, was on his property, and that it might have been chasing a deer.
Such a shooting would have been illegal under those circumstances. California law prohibits killing a domestic dog unless it is threatening livestock or humans. Even if Snoop Dogg was chasing wildlife, that would not be grounds for pulling the trigger, deputies told the Murrays.
Sheriff’s investigators have turned their findings over to District Attorney Dan Dow, suggesting that criminal charges be filed against Almond.
“We want Mr. Almond criminally prosecuted for animal cruelty,” David said.
Almond did not return a reporter’s phone calls and text requests for comment.
Spencer entered Cal Poly’s College of Engineering earlier this month with Snoop Dogg’s demise weighing heavily on his mind. The Murray daughters aren’t sure if they will follow their breeding plans. Teecee is awakened at night by the sound of gunshots in her nightmares. David seethes with anger over what he calls Snoop Dogg’s “murder,” and like his family he’s numbed by grief. All are talking with therapists.
And now, the family has agreed that they no longer can live on the ranch with lingering memories of Snoop Dogg, and will be selling the property, David said.
The Murrays said they haven’t heard from Almond.
Almond violated California Animal Cruelty Laws period. Only a heartless person would cage a dog.
Any responsible dog owner would keep control of their dog, either caged or leashed.
I had heard about this shooting. But after reading this, there is so much more to this than I thought. I can’t believe that someone can get away with a shoot like this. How do you not know what your neighbors dog looks like? Even if it had been a stray and even if it had been chasing deer around. Shooting makes ZERO sense. I mean the dog could have been out for a walk with it’s owner. Hell, he could have missed and hit someone near by. Pets are expensive. Not only in time and money, but mostly in love. I know that if someone was to kill a part of my family, that person should always look over his/her shoulder.
This shooter sure lives up to the brand name of his tower: Sniper Outlaw Deer Stand. High in his tower this outlaw sniper, who shot the neighbor’s dog, has the ability to view and fire directly into their house with his high power telescopic rifle. I can see why these neighbors can’t sleep. It would take a long time, if ever, to get rid of their grief and palpable fear for their future safety. The shooter seems to ignore their situation. Not helpful. Most shooters go to remote areas for their activities. One who chooses to menace his neighbors should himself be put in a facility with guard towers to keep him away from harming others. I hope and pray that he is charged with the felony he admitted to. Let’s all hope the law will act to restore peace.
I don’ t know where to begin except that I am heartbroken over the loss of the beautiful dog. I live in the Pomar Junction area on 16 acres, unfenced. My dogs stay here just protecting the property. If anyone, anyone ever shot my dog – OMg I just can’t. The sheriffs would have to restrain me.
This man needs to be account able as far as it can go. i know that Dan Dow and the County of San Luis Obispo will do the right thing as we take our family/ranch/winery dogs quite seriously. |
<reponame>ericyao2013/idlcpp
#include "ImportDirectory.h"
#include "Platform.h"
#include <Windows.h>
ImportDirectories g_importDirectories;
ImportDirectories::ImportDirectories()
{
m_hasCurrentDirectory = false;
}
void ImportDirectories::calcImportDirectories(const char* fileName)
{
const char* lastSlash = strrchr(fileName, '\\');
if (0 == lastSlash)
{
return;
}
std::string path(fileName, lastSlash + 1);
::SetCurrentDirectory(path.c_str());
auto it = m_directories.begin();
auto end = m_directories.end();
for (; it != end; ++it)
{
std::string fullName;
normalizeFileName(fullName, it->c_str());
if(fullName.length() > 0 && fullName.back() != '\\')
{
fullName.push_back('\\');
}
*it = fullName;
}
}
void ImportDirectories::addImportDirectory(const char* dir)
{
m_directories.insert(m_directories.begin(), dir);
}
void ImportDirectories::setCurrentDirectory(const char* dir)
{
std::string str;
normalizeFileName(str, dir);
if(str.length() > 0)
{
if(str.at(str.length() - 1) != '\\')
{
str += '\\';
}
if(m_hasCurrentDirectory)
{
m_directories.pop_back();
}
m_directories.push_back(str);
m_hasCurrentDirectory = true;
}
}
|
Former staffers of the far-right website sum up Trump’s campaign chief with the words ‘fear and bullying’ – but say he’s too calculating to dare cross his new boss
“Egomaniacal.” “Purely Machiavellian.” A man summed up by three words: “fear and bullying”.
Former employees do not lack for words to describe Donald Trump’s new campaign chief, a Wall Street veteran who found his flock on the far right, with a site associated with conspiracy theories, provocation and notions unspoken on cable TV. For staffers of Breitbart News, Steve Bannon’s words were law.
READING BREITBART FOR 48 HOURS WILL CONVINCE YOU THE WORLD IS TERRIBLE Read more
A former Goldman Sachs banker with an MBA from Harvard, Bannon was appointed this week by Trump to help channel the populist tide that drove him to the top of the Republican ticket. Bannon has no experience running a campaign, but a number of employees who left Breitbart under his stewardship had warnings for campaign staff: expect expletive-laced phone calls at all hours of the night.
“There will be screaming matches between Steve and every other person in the office,” said Ben Shapiro, a former editor at Breitbart News.
“But there will be no screaming matches between Steve and Trump. Steve knows where his bread is buttered.”
A steady stream of emails leaked in the days following Trump’s hiring of Bannon paint a picture of a shrewd businessman with a scorched-earth approach to the Republican establishment. Former Breitbart staffers interviewed by the Guardian recall a man driven less by an ideological crusade than the desire to emerge on top – not unlike the candidate who now employs him.
To some, the Trump-Bannon partnership simply marks the consummation of a long, happy rapport. During his tenure as the executive chairman of Breitbart, Bannon spent the greater part of the last year promoting Trump’s candidacy: where others fled or scolded Trump’s declaration that Mexican immigrants were “rapists” and “killers”, Breitbart News echoed the call.
Bannon was a presence in the newsroom, often hopping on daily editorial calls and making his views clear. Staff present for the discussions, including Shapiro and Kurt Bardella, who previously served as a media consultant to Breitbart, said Bannon aggressively pushed stories against immigrants, and supported linking minorities to terrorism and crime.
It was catnip for the site’s growing audience of the so-called “alt-right”, a far-right group that merges race and nationalism and has largely embraced Trump. For all his antagonism toward the media, the Republican nominee has publicly lavished praise on Breitbart, even though his former campaign manager Corey Lewandoski was charged with battery against one of the website’s reporters, Michelle Fields, when she tried to ask Trump a question.
Bannon, rather than defend Fields, used Breitbart as a vehicle to discredit her story and her character. Fields resigned, as did Shapiro and Bardella.
“That was really a crystallization of how his pursuit of a relationship with Trump superseded the welfare of his reporters,” Bardella said. “It was that moment of clarity where they’re so in for Trump that they’re willing to throw one of their own overboard even when that person is the victim of the situation.”
Shapiro soon rebranded Breitbart as “Trump Pravda”, and said that many staffers were increasingly concerned about their future. The site was spinning away from its crusade to hold liberal media and establishment Republicans to account, they felt. They worried about instead turning into shills for the Trump campaign.
It was not just the obvious support for Trump that troubled employees, but also the clear objective of Bannon to diminish the former reality TV star’s opponents in the Republican primary. The website ran overwhelmingly unfavorable coverage of Marco Rubio and Jeb Bush, both established Florida politicians, especially with articles about the bilingual candidates’ support for immigration reform.
“His whole mindset in general was: ‘We need to go after Rubio, we need to go after Bush,’” said Bardella.
The focus on Rubio was particularly relentless, as the Florida senator emerged as one of the final candidates in the race. Stories ran near daily with headlines asserting that, if Rubio were elected president, immigrants and terrorists would stream across the US border.
Facebook Twitter Pinterest Marco Rubio: a friend to immigrants and terrorists, according to Steve Bannon’s Breitbart. Photograph: Lynne Sladky/AP
“He hates Marco,” said one former employee, who requested anonymity to speak freely. “There was definitely a decision to promote the work of writers with an extreme anti-Rubio bent.”
Similar treatment has been directed toward House speaker Paul Ryan in recent months, with Bannon working behind the scenes to push his long-shot primary challenger, Paul Nehlen. One story criticized Ryan for having a fence around his home in Wisconsin, with the implication that the speaker was willing to wall off his own house but not the US border.
Bannon was “absolutely fuelling the energy” behind Nehlen, a former staffer said.
Spokespeople for Ryan and Rubio declined to comment.
Even Ted Cruz, an ultraconservative senator once covered favorably by Breitbart, was not spared the site’s acidic treatment of Trump’s opponents. A report published by the Hill detailed how Bannon slowly turned against the Texas senator. In particular, Breitbart seized on Trump’s attacks on Cruz’s citizenship – the senator was born to an American mother in Canada – much in the way it spread false “birther” ideas against Barack Obama.
It was a remarkable turnaround, given that just under a year prior, Breitbart reporter Matthew Boyle had been invited to observe Cruz’s bedtime ritual with his children – and subsequently produced a report portraying the senator in a glowing light.
Although they criticized his methods, those who worked under Bannon acknowledged a tireless devotion to creating an empire too influential to ignore, and his success so far.
Given its popularity among grassroots conservatives and Bannon’s “take-no prisoners” approach, few Republican candidates or lawmakers are brazen enough to pick a fight with the website.
Both Rubio and Bush continued to engage with Breitbart during the Republican primary, for example, even as they were targeted by much of its coverage.
At the height of the primary, a visibly frustrated Rubio mocked Breitbart’s credibility on Fox News, accusing them of publishing “conspiracy theories”. He has nonetheless continued to provide at least some of their reporters with interviews dubbed exclusives.
Bannon “has taken where the Breitbart brand essentially was before the election – considered by many as outliers – and made it a sheer force of will”, Bardella said. “He’s been able to advance an agenda.
“And now he’s the right-hand person to a would-be president.”
Though Bannon has only had a few days in charge of Trump’s campaign, his former employees said he would stand in stark contrast to former chairman Paul Manafort, who resigned on Friday. While Manafort tried to steer Trump toward a more moderate general election strategy, little will be off limits for Bannon, they said.
His motto, as Shapiro put it, will be simple: “Let Trump be Trump.” |
New insights on early evolution of spiny-rayed fishes (Teleostei: Acanthomorpha) The Acanthomorpha is the largest group of teleost fishes with about one third of extant vertebrate species. In the course of its evolution this lineage experienced several episodes of radiation, leading to a large number of descendant lineages differing profoundly in morphology, ecology, distribution and behavior. Although Acanthomorpha was recognized decades ago, we are only now beginning to decipher its large-scale, time-calibrated phylogeny, a prerequisite to test various evolutionary hypotheses explaining the tremendous diversity of this group. In this study, we provide new insights into the early evolution of the acanthomorphs and the euteleost allies based on the phylogenetic analysis of a newly developed dataset combining nine nuclear and mitochondrial gene markers. Our inferred tree is time-calibrated using 15 fossils, some of which have not been used before. While our phylogeny strongly supports a monophyletic Neoteleostei, Ctenosquamata (i.e., Acanthomorpha plus Myctophiformes), and Acanthopterygii, we find weak support (bootstrap value < 48%) for the traditionally defined Acanthomorpha, as well as evidence of non-monophyly for the traditional Paracanthopterygii, Beryciformes, and Percomorpha. We corroborate the new Paracanthopterygii sensu Miya et al. including Polymixiiformes, Zeiformes, Gadiformes, Percopsiformes, and likely the enigmatic Stylephorus chordatus. Our timetree largely agrees with other recent studies based on nuclear loci in inferring an Early Cretaceous origin for the acanthomorphs followed by a Late Cretaceous/Early Paleogene radiation of major lineages. This is in contrast to mitogenomic studies mostly inferring Jurassic or even Triassic ages for the origin of the acanthomorphs. We compare our results to those of previous studies, and attempt to address some of the issues that may have led to incongruence between the fossil record and the molecular clock studies, as well as between the different molecular timetrees. |
Relaxnews
Even if Uber's latest autonomous automobile accident is a timely reminder that we're still some way off truly self-driving cars, a new Harris Poll gauging the opinions of 3,000 U.S. drivers finds that most people are already dreaming about what to do with all the spare time they'll have when their cars are capable of driving themselves.
The study, commissioned by Erie Insurance finds that dream is an apt description as 51 per cent think that they'll be able to catch up on much needed sleep, or at least not worry about becoming drowsy and inattentive, especially on longer journeys.
Texting (34 per cent), reading (27 per cent) and playing video games (11 per cent) are also popular potential pastimes with 2 per cent believing that they'd actually be able to exercise while on the go.
Despite years of steady improvement, in 2015 (the most recent year for accurate figures) the number of traffic fatalities on U.S. roads jumped to 38,300 while 4.4 million were also seriously injured -- even though the modern automobile has never been safer.
U.S. authorities suggest that cheaper gas prices, more people driving for work, and increases in distracted driving behavior are the driving forces behind these figures. And when asked about the risks of distracted driving, 59 per cent of respondents said that they believe self-driving cars will be the key to eliminating this behavior and making roads safer for all.
And as cars start to go on general sale that are capable of self-steering and maintaining lane discipline on the highway, such as the Volvo S90, Mercedes E Class and Tesla Model S, it can seem to some that the age of the autonomous automobile is already here.
"Current technology is going a long way to keep us safer on the road, but the last thing we want is for people to become over-confident as this technology continues to evolve," said Cody Cook, Erie Insurance vice president. "Unfortunately, our survey finds that many people are getting ahead of themselves -- making plans for what they'll do in the car instead of paying attention to the road."
Huge gains in development are being made every day but as shown by Uber's accident last week in Arizona, where one of its self-driving cars was flipped on its side when an oncoming car that should have given way, refused to yield, much work needs to be done on the issue of how autonomous cars interact with those driven by unpredictable humans.
"The interaction between robot cars and human-driven cars is an area of serious concern and requires research," said John M. Simpson, Privacy Project Director for U.S. not-for-profit public interest group Consumer Watchdog.
The incident has also raised questions about transparency, regulation and one of the biggest single issues surrounding autonomous driving tech -- who is responsible when a car in autonomous mode has an accident?
"Self-driving car manufactures and developers must accept responsibility when their automated and autonomous technologies fail," said Simpson. "There must be complete transparency and accountability about what they are doing, which clearly can threaten public safety." |
Q-switched erbium-doped fiber lasers based on copper nanoparticles saturable absorber We reported a generation of passively Q-switching pulses in an erbium-doped fiber laser by exploiting copper nanoparticles polyvinyl alcohol polymer composite (CuNP-PVA) based saturable absorber (SA). The modulation depth and the saturation power intensity of the CuNP-PVA film are calculated as 18 % and 0.021 kW/cm2, respectively. A maximum repetition rate of 104.2 kHz, the shortest pulse width of 5.1 s and pulse energy up to 20.4 nJ was observed at 1558 nm wavelength. Introduction The evolution of 1-, 2-and 3-Dimensional material in the field of material sciences has allowed the realization of a multitude of new devices, called saturable absorber (SAs). These SAs are the key to generate passively Q-switched fiber lasers. Passively Q-switched fiber lasers have been extensively used in optical communications, range finding and material processing due to its flexible and compact advantages. Essentially, Q-switched laser has its convenience especially in terms of relatively high pulse energy and tunable repetition rate. Originally, saturable absorber begins with semiconductor saturable absorber mirrors (SESAMs) to generate pulsed outputs in laser cavities. However, due to their complex procedure, limited bandwidth and expensive costs lead the researchers to explore material which acquires high laser damage threshold, good fiber compatibility and low optical saturable intensity. Two-dimensional (2D) layered materials including graphene and transition metal dichalcogenides (TMDCs) have been employed as SA considering their simplicity of manufacture and inexpensive cost contrasting to SESAMs. Graphene normally has a low optical saturation which is 2.3% per layer and TMDCs are progressively available in the visible region because of their substantial bandgaps. Still, 2D materials in specific, are acknowledged as a strong prospect for the cutting-edge photonics innovation in light of their ultrafast carrier elements and wideband responses. Next, black phosphorus (BP) has been regained as one of the next SA for optoelectronic applications. However, they are also vulnerable to high laser optical damage threshold and easily oxidized to oxygen and moisture environment. Quite recently, metal nanomaterial such as silver and copper attract many researchers as the next generation of SAs as it has high potential in the optic application. Copper especially has broad saturable absorption, large third-order nonlinearity and ultrafast response time. Muhammad et al. proposed a Q-switched fiber laser with copper-PVA at the 1.5 wavelength region. The laser operated at a repetition rate and pulse width of 101.2 kHz and 4.28 s respectively, while the maximum average output power was obtained at 1.86 mW. Sinan et al. reported Q-switch pulse using copper oxide-. In the present work, a passively Q-switched EDFL was successfully realized at C-band region by incorporating a copper nanoparticles polymer composite based SA into a ring fiber laser cavity. The modulation depth and the saturation power intensity of the CuNP-PVA film are 18% and 0.021 kW/cm 2 respectively. The laser generates a Q-switching pulse train with the shortest pulse width of 5.1 s, a repetition rate of 104.2 kHz and an output power of 2.1 mW at the maximum input pump power of 198.0 mW. Preparation and optical characterization of the CuNP-PVA based SA. The copper nanoparticles PVA film fabricated in this work is utilized as SA to generate laser pulses in erbium-doped fiber laser (EDFL). Commercially available copper nanoparticle powder from Sigma Aldrich are used to fabricate the SA. The copper nanoparticles are obtained in a powder consist of an average of 25 nm particles size. The film based SA is prepared by first dissolving 25 mg of copper nanoparticles powder in tetrahydrofuran (THF) and undergone ultrasonic bath for 6h to ensure the dispersion of the copper nanoparticles. Apart from that, the polymer host is prepared by dissolving 1g of PVA powder into 120 ml DI water. The mixture is stirred for 6 hours to ensure the homogeneous solution at 500 rpm at 145 °C. Then, 10 ml of the dispersed copper nanoparticles in THF solution is added into approximately 10 ml of the dissolved PVA solution to form a CuNP-PVA composite solution with a composition ratio of 1:1. The prepared CuNP-PVA composite solution is stirred for another 1 hour at room temperature to ensure the good binding of the composite as well as to allow any excess solvent to evaporate. Finally, about 20% of the resulting CuNP-PVA composite solution is taken for analysis while the remainder is poured into a petri dish and dried in room temperature for 3 days to produce the desired free-standing film of CuNP-PVA film. Figure 1(a) shows the transmission electron microscope (TEM) of copper nanoparticles a 50 nm scale bar. Figure 1(b) demonstrates the nonlinear transmission profile of twin detector measurement. According to data fitting as shown in the figure below, the modulation depth and the saturation power intensity of the CuNP-PVA film calculated as 18% and 0.021 kW/cm 2, respectively. The measured modulation depth of CuNP-PVA thin film is comparable to that of other materials such as Cu-PVA at 36 %, CuO-PVA at 3.5 % and silver nanoparticles-PVA at 19%. Figure 2 illustrates the experimental set-up of the proposed passively Q-switched EDFL with the CuNP-PVA thin film. The cavity is composed of a 975 nm laser diode (LD) as the pump sources and is associated with a 980/1550 nm wavelength division multiplexer (WDM) port. The normal port of the WDM is currently connected to a 3.0 m long erbium-doped fiber (EDF). The EDF has a numerical aperture (NA) of 0.16 and erbium ion absorption of 23 dB/m at 980 nm with a core and cladding diameters of 4 m and 125 m respectively. To secure unidirectional propagation of light in the ring cavity, a polarization-independent isolator was used. Then, the end of the isolator is associated with a fiber-based 90:10 optical coupler, which is utilized to remove roughly 90% of the proliferating signal for examination. The 90% port of the coupler then again is associated with an integration of the SA between the two fiber ferrules. At last, the end of the SA is connected back with the 1550 nm port of the WDM. The end coupler of 10% port is associated with another 3 dB optical coupler to monitor simultaneously the results of the Q-switching performance. With one end of 50%, the coupler is associated with a Yokogawa AQ6370B optical range analyzer (OSA) for optical spectrum range. The opposite end of the coupler is associated with an InGaAs photodetector (1. Result and discussion The laser operates within the continuous wave laser (CW) at 32.76 mW input pump power. After the integration of the SA in the cavity, Q-switched operation is realized at the increasing input pump power of 83.61 mW up to the maximum input pump power of 198.0 mW. The relatively high threshold for the CW operation indicated too high overall cavity loss and high insertion loss of the SA device. The SA presented intracavity loss modulation and transformed the working from CW to Q-switching operation. When the pump power is increasing to 83.61 mW, a self-starting stable Q-switch pulse is observed with a repetition rate of 52.74 kHz and a pulse-width of 9.44 s. It remains noticeable until the pump power extent to 198.0 mW. The output spectrum of the Q-switched laser operates at a wavelength of 1558 nm is shown in Figure 3. The stability of the generated Q-switched output is confirmed by monitoring the pulse in the radio frequency spectrum analyser at the maximum LD pump power. Figure 4 Figure 5(a) illustrates the Q-switching performance of calculated pulse energy and output power of the pulse against the input pump power. As expected, both pulse energy and output power show an increasing trend against the input pump power. Over the input pump power range of 83.61-198.0 mW, the output power of the Q-switched laser is seen to increase from 0.74 mW to 2.13 mW. Similarly, the pulse energy also increases from 14.12 nJ to 20.44 nJ over the same power range, although at a pump power above 153.53 mW, the pulse energy is seen to decrease slightly. This is attributed to insufficient The relationship between the repetition rate and pulse width is shown in Figure 5(b). It can be seen the detailed evolution of the repetition rate increased steadily from 52.74 kHz to 104.2 kHz from input pump power of 83.61 mW to 198.0 mW, while the pulse width, on the other hand, decreases from 9.44 to 5.08 s. This is the trendline behaviour for passively Q-switching operation where when the increasing input pump power is almost linearly with increasing repetition rate and decreasing the pulse width. Figure 5. Q-switching performances (a) Average output power and output pulse energy against power (b) Repetition rate and pulse width against pump power Conclusion In this work, a passively Q-switched EDFL is proposed and demonstrated. The system employs a CuNP-PVA SA in the ring cavity and provides the desired pulse output. The system is capable of generating pulsed outputs with a maximum repetition rate of 104.2 kHz, the narrowest pulse width of 5.1s and pulse energy of 20.44 nJ at the maximum input pump power of 198.0 mW. The RF spectrum showed the signal noise to a ratio of about 54 dB. |
General toxicity of the new calcium antagonist felodipine in dogs. Felodipine 4-(2,3-dichlorophenyl)-1,4-dihydropyridine-2,6-dimethyl-3,5- dicarboxylic 3-ethyl ester and 5-methyl ester, CAS 72509-76-3) is a new selective calcium antagonist for use in the management of hypertension or other cardiovascular disease, which requires reduction of peripheral vascular resistance. A combined 6- and 12-month study in dogs has been performed as a part of the preclinical safety program. 30 dogs, 5 males and 5 females per group, were treated with felodipine for 12 months. Additional 18 dogs, 3 males and 3 females per group, were interim-sacrificed after 6-month treatment. The dose levels were 2 x 0.38, 2 x 1.2 and 2 x 2.3 mg/kg daily. Initially, 2 x 3.8 mg/kg/d was used as a high dose. At this dose level 2 animals died preterminally after 4 days of dosing. They were replaced and the high dose level was reduced. Two similar control groups were given a placebo formulation for 12 and 6 months, respectively. All animals were treated b.i.d. using a 4-h time interval. Mucosal hyperemia and tachycardia, as an expression of the vasodilating properties of felodipine, were observed in a somewhat variable but dose-related manner. Noninflammatory gingival hyperplasia, similar to that after treatment with phenytoin and the calcium antagonist nifedipine, occurred with a propensity for the males after 12 months of treatment. Slight-degree gingival hyperplasia was also noted after 6 months of treatment. This change occurred dose- and time related in the medium and high dose groups but was absent in the low dose group.(ABSTRACT TRUNCATED AT 250 WORDS) |
package org.freedom.econnoisseur.announcement.task;
import org.freedom.econnoisseur.announcement.service.DingTalkService;
import org.freedom.econnoisseur.announcement.util.FileUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* 爬取公告推荐可以for freedom的公告
*
* @author <NAME>
* @since version
* 2018年06月29日 16:50:00
*/
@Service
public class AnnouncementTask {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnouncementTask.class);
@Autowired
private DingTalkService dingTalkService;
@Scheduled(fixedDelayString="60000")
private void run() throws IOException {
LOGGER.info("start...");
Elements announcements = Jsoup.connect("https://mytoken.io/announcement").get().getElementsByClass("announcement-item");
int lastId = Integer.valueOf(FileUtil.readFromFile());
LOGGER.info("lastId: " + lastId);
int maxId = lastId;
// for
for (Element announcement : announcements) {
// get url 交易所 发布时间 title 链接 更新上次id
String url = announcement.attr("href");
String title = announcement.getElementsByClass("title").get(0).text();
String[] sub = announcement.getElementsByClass("sub").get(0).text().split("\\|");
String exchange = sub[0].trim();
String time = sub[1].trim();
int id = Integer.valueOf(url.split("/")[1]);
LOGGER.info("current id: " + id);
// 条件判断
if (id <= lastId) {
break;
} else {
if (maxId < id) {
maxId = id;
}
// 需要处理
// 获取原文链接
if (title.contains("送") || title.contains("享") || title.contains("空投") || title.contains("上线")) {
String link = Jsoup.connect("https://mytoken.io/" + url).get().getElementById("link").attr("href");
this.dingTalkService.send(new DingTalkService.DingTalkMsg("貌似出现可以薅羊毛的活动,请关注", "#### For Freedom\n\n"
+ " * 标题: **" + title + "**\n"
+ " * 交易所: **" + exchange + "**\n"
+ " * 发布时间: **" + time + "**\n"
+ " * 链接: **" + "https://mytoken.io/" + url + "**\n"
+ " * 原文链接: **" + link + "**"));
}
}
}
FileUtil.writeToFile(String.valueOf(maxId));
LOGGER.info("end...");
}
}
|
<filename>nemo/app/loader.py
"""
Mako templates for django >= 1.2.
"""
from django.conf import settings
from django.template import TemplateDoesNotExist
from django.template.context import Context
from django.template.loaders.filesystem import Loader as FSLoader
from mako.exceptions import MakoException, TopLevelLookupException
from mako.template import Template
from mako.lookup import TemplateLookup
def context_to_dict(ctxt):
res = {}
for d in reversed(ctxt.dicts):
# sometimes contexts will be nested
if isinstance(d, Context):
res.update(context_to_dict(d))
else:
res.update(d)
return res
def _get_start_and_end(source, lineno, pos):
start = 0
for n, line in enumerate(source.splitlines()):
if n == lineno:
start += pos
break
else:
start += len(line) - 1
return start, start
class MakoExceptionWrapper(Exception):
def __init__(self, exc, origin):
self._exc = exc
self._origin = origin
self.args = self._exc.args
def __getattr__(self, name):
return getattr(self._exc, name)
@property
def source(self):
return (self._origin,
_get_start_and_end(self._exc.source,
self._exc.lineno,
self._exc.pos))
class MakoTemplate(object):
def __init__(self, template_obj, origin=None):
self.template_obj = template_obj
self.origin = origin
def render(self, context):
try:
return self.template_obj.render_unicode(**context_to_dict(context))
except MakoException, me:
if hasattr(me, 'source'):
raise MakoExceptionWrapper(me, self.origin)
else:
raise me
_lookup = None
def get_lookup():
global _lookup
if _lookup is None:
opts = getattr(settings, 'MAKO_TEMPLATE_OPTS', {})
_lookup = TemplateLookup(directories=settings.MAKO_TEMPLATE_DIRS,
**opts)
return _lookup
class MakoLoader(FSLoader):
is_usable = True
def load_template(self, template_name, template_dirs=None):
lookup = get_lookup()
try:
real_template = lookup.get_template(template_name)
return MakoTemplate(real_template, template_name), template_name
except TopLevelLookupException:
raise TemplateDoesNotExist(
'mako template not found for name %s' % template_name)
except MakoException, me:
if hasattr(me, 'source'):
raise MakoExceptionWrapper(me, template_name)
raise me
|
<reponame>lywsbcn/Jtool<gh_stars>0
//
// JHPickView.h
// Analog
//
// Created by Apple on 2017/7/14.
// Copyright © 2017年 Apple. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "JpickData.h"
@protocol JpickViewDelegate <NSObject>
@optional
//-(void)JHPickViewDidSelected:(UITextField *)betModel;
-(void)pickViewDidSelected:(UIPickerView *)pickView row:(NSInteger)row;
@end
@interface JpickView : UIView
@property(nonatomic,weak)id<JpickViewDelegate> delegate;
@property(nonatomic,weak)UITextField *textField;
@property(nonatomic,strong)NSArray <JpickData * > * data;
//-(void)setPickSelectRow:(NSInteger)row;
@property(nonatomic,assign)NSInteger selectRow;
-(void)reload;
@end
|
Nine Poisons and a Broken Promise This paper traces the formation, dissemination, and impact of a corpus of narratives about an alchemical icon of the god Muruka. It was purportedly crafted by Bhogar, a Siddhar-alchemist, at the Tamil temple site of Palani in ancient times. These narratives, beginning in the early twentieth century, asserted that any object coming into direct contact with the icon was imbued with miraculous healing properties. Such lore placed Palani as a unique pilgrimage site, attracting pilgrims from the world over, and stimulating its economy to an unprecedented degree, making it the second wealthiest temple in India. Eventually, the demand for icon-touched substances and the assertion of the icons healing properties reached its terminal limit, whereby the body of the god itself became available for sale, first as scrapings and then, in a complicated conspiracy of bait and switch, in its entirety. This article explores how recent myths respond to the challenges of late colonial modernity in the 1930s and Tamil identity politics in the twenty-first century. |
What new cell biology findings could bring to therapeutics: is it time for a phenome-project in Toxoplasma gondii? 'If you know the enemy and know yourself, you need not fear the result of a hundred battles. If you know yourself but not the enemy, for every victory gained you will also suffer a defeat' (SunTzu the Art of War, 544-496 BC). Although written for the managing of conflicts and winning clear victories, this basic guideline can be directly transferred to our battle against apicomplexan parasites and how to focus future basic research in order to transfer the gained knowledge to a therapeutic intervention strategy. Over the last two decades the establishment of several key-technologies, by different groups working on Toxoplasma gondii, made this important human pathogen accessible to modern approaches in molecular cell biology. In fact more and more researchers get attracted to this easy accessible model organism to study specific biological questions, unique to apicomplexans. This fascinating, unique biology might provide us with new therapeutic options in our battle against apicomplexan parasites by finding its Achilles' heel. In this article we argue that in the absence of a powerful high throughput technology for the characterisation of essential gene of interests a coordinated effort should be undertaken to convert our knowledge of the genome into one of the phenome. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.definition.builder;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.metadata.definition.util.ClassUtils;
import org.apache.dubbo.metadata.definition.util.JaketConfigurationUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.common.utils.ClassUtils.isSimpleType;
/**
* 2015/1/27.
*/
public final class DefaultTypeBuilder {
public static TypeDefinition build(Class<?> clazz, Map<Class<?>, TypeDefinition> typeCache) {
// final String canonicalName = clazz.getCanonicalName();
final String name = clazz.getName();
TypeDefinition td = new TypeDefinition(name);
// Try to get a cached definition
if (typeCache.containsKey(clazz)) {
return typeCache.get(clazz);
}
// Primitive type
if (!JaketConfigurationUtils.needAnalyzing(clazz)) {
return td;
}
// Custom type
TypeDefinition ref = new TypeDefinition(name);
ref.set$ref(name);
typeCache.put(clazz, ref);
if(!clazz.isPrimitive() && !isSimpleType(clazz)){
List<Field> fields = ClassUtils.getNonStaticFields(clazz);
for (Field field : fields) {
String fieldName = field.getName();
Class<?> fieldClass = field.getType();
Type fieldType = field.getGenericType();
TypeDefinition fieldTd = TypeDefinitionBuilder.build(fieldType, fieldClass, typeCache);
td.getProperties().put(fieldName, fieldTd);
}
}
typeCache.put(clazz, td);
return td;
}
private DefaultTypeBuilder() {
}
}
|
As a huge fan of competitive ultimate, I love watching the college season inch closer to the spring series, where teams fight for and earn places at the national championships, this year over Memorial Day Weekend in Milwaukee, WI. Almost as much, I look forward to the debates and discussion over the bid allocation – how many teams each of the ten geographic regions gets to send to nationals. Rather than just have the top two teams from each region qualify, USA Ultimate – ultimate’s national governing body – decided to make the process a bit more complicated, but hopefully more fair given the talent disparity across regions.
The system works like this: there are 20 bids to nationals for 10 regions1, and each region automatically gets one bid. The top team in each region is then removed from the rankings, and the top 10 remaining teams earn a bid for their region. Thus, those second 10 teams occupy hugely important spots in the rankings – an extra bid for your region means an easier road to nationals, and the difference between playing in Milwaukee or staying at home.
Obviously the rankings themselves are important – but how does USAU get them in the first place? Unlike college football, there are no polls or playoff committee. The rankings are purely numerical in nature, and hopefully avoid human biases and our inability to process complex networked relationships. I won’t explain the details of the algorithm here2 but the important takeaway is that the only inputs into the algorithms are games and scores. The algorithm does not explicitly account for total win-loss record, net goal differential, or any other statistic. Because the algorithm is focused only on games, the single most important criterion to ensure its accuracy is connectivity between the teams. As of right now, there are 346 men’s teams with 4,136 games played and 228 women’s teams with 2,840 games played.
With that in mind, I thought it would be interesting to see how the connectivity between teams changes over the course of the season, and if we could draw some conclusions about whether or the regular season is structured effectively to ensure connectivity between teams.
Women
The gif below shows the connectivity for women’s teams as time goes on. Each dot represents a team, and each line represents a game. The teams are colored according to their current ranking, not their ranking as of each date.
The first thing I noticed is that, for several weeks, there are two distinct groups of highly ranked teams connected by one purple team. This is the east coast and midwest vs. the west coast, and the team connecting them is Texas. The distinctness of the grouping diminishes substantially between March 17 and 24, but it’s still there if you look closely:
The other noticeable thing on the women’s side is how (relatively) loosely connected Clemson, Notre Dame, and Vriginia – all top 10 teams – are to the action. Is it enough to make me doubt the accuracy of their ranking? I’m not sure.
One other question I wanted to answer was, “Which teams are the most important?” The measure for this is called centrality3. The graph below shows all of the teams colored by centrality – the brighter the team, the more important they are to making connections through the network. Here is a PDF version which should have better resolution.
So if you beat Maryland, the most central team in the women’s division, it’s likely to mean that much more for your overall ranking than the average win because of their unique connections to the rest of the field.
Men
Here’s the men’s season, with the same scheme as the women’s division:
The first thing I noticed here were the outliers at the end – Amherst and maybe Michigan and Maryland. Unlike the women’s side, these teams aren’t in the top 20 so they aren’t directly affecting nationals bid allocations.
Finally, here’s the men’s teams colored by centrality (PDF here):
—
Alright, time for me to get back to work. If anyone wants the raw data, look for the .csv files here.
—
1. This is true for DI. DIII has 16 bids for 10 regions, but otherwise the ranking and allocation processes are the same.↩
2. Here’s USAU’s explanation . It’s essentially a pairwise comparison scheme that solves by iteration until convergence, with a few tweaks like weighting individual games by recency and choosing preference values based on the score of the game.↩
3. I used betweenness centrality as it seems most appropriate for this situation. Someone please correct me if I’m wrong!↩
4. Figures were generated using the NetworkX and matplotlib Python packages.
Advertisements
Share this: Twitter
Facebook
Google
Like this: Like Loading... |
OPTIMIZATION OF BALANCING IN A BRIDGE MEASURING CIRCUIT WITH A DIFFERENTIAL CONDUCTOMETRIC SENSOR The article is devoted to solving the problem of the occurrence of an additive error in determining local changes in the electrical conductivity of electrolyte solutions under conditions of changes in the background electrical conductivity of the measurement medium, which often occurs in biosensor and other systems with a differential pair of conductometric transducers, if their electrical parameters are not identical. The goal is to provide a deep suppression of the influence of background changes with significant differences in both reactance and active resistance in the transducers of a pair of sensor. The essence of the issue, the causes and mechanism of this type of error, as well as the methods and means of its reduction, developed earlier, are briefly considered. A diagram and description of the structure of a differential conductometric channel of a biosensor system based on an AC bridge, an algorithm for its balancing operations by controlling the module and phase of the test voltage, as well as a vector diagram of currents and voltages in the bridge circuit during this process. The balancing of the bridge has been was modeled analytically, bringing it to a quasi-equilibrium state, in which changes in the background electrical conductivity do not change its output signal. Additional operations for balancing the bridge are determined to achieve such a state with significant differences in both capacitances and active resistances in the impedances of a pair of conductometric transducers of a differential sensor. The results of experimental studies of the suppression of the influence of changes in the background electrical conductivity of a solution in a differential conductometric channel with using its computer model and experimental sample of a conductometric instrument with an electrical equivalent of a differential sensor are presented. A comparison of the results obtained and the corresponding data for balancing bridge circuits by previously developed methods is given. References 16, figures 3, tables 3. |
Every Team Makes Mistakes: An Initial Report on Predicting Failure in Teamwork Voting among different agents is a powerful tool in problem solving, and it has been widely applied to improve the performance in machine learning. However, the potential of voting has been explored only in improving the ability of finding the correct answer to a complex problem. In this paper we present a novel benefit in voting, that has not been observed before: we show that we can use the voting patterns to assess the performance of a team and predict their final outcome. This prediction can be executed at any moment during problem-solving and it is completely domain independent. We present a preliminary theoretical explanation of why our prediction method works, where we show that the accuracy is better for diverse teams composed by different agents than for uniform teams made of copies of the same agent. We also perform experiments in the Computer Go domain, where we show that we can obtain a high accuracy in predicting the final outcome of the games. We analyze the prediction accuracy for 3 different teams, and we show that the prediction works significantly better for a diverse team. Since our approach is completely domain independent, it can be easily applied to a variety of domains, such as the video games in the Arcade Learning Environment. |
<reponame>wizmea/twing
/* istanbul ignore next */
import {TwingSource} from "./source";
export interface TwingLoaderInterface {
/**
* Returns the source context for a given template logical name.
*
* @param {string} name The template logical name
* @param {TwingSource} from The source that initiated the template loading
*
* @returns {Promise<TwingSource>}
*
* @throws TwingErrorLoader When name is not found
*/
getSourceContext(name: string, from: TwingSource): Promise<TwingSource>;
/**
* Gets the cache key to use for the cache for a given template name.
*
* @param {string} name The name of the template to load
* @param {TwingSource} from The source that initiated the template loading
*
* @returns {Promise<string>} The cache key
*
* @throws TwingErrorLoader When name is not found
*/
getCacheKey(name: string, from: TwingSource): Promise<string>;
/**
* Returns true if the template is still fresh.
*l
* @param {string} name The template name
* @param {number} time Timestamp of the last modification time of the cached template
* @param {TwingSource} from The source that initiated the template loading
*
* @returns {Promise<boolean>} true if the template is fresh, false otherwise
*
* @throws TwingErrorLoader When name is not found
*/
isFresh(name: string, time: number, from: TwingSource): Promise<boolean>;
/**
* Check if we have the source code of a template, given its name.
*
* @param {string} name The name of the template to check if we can load
* @param {TwingSource} from The source that initiated the template loading
*
* @returns {Promise<boolean>} If the template source code is handled by this loader or not
*/
exists(name: string, from: TwingSource): Promise<boolean>;
/**
* Resolve the path of a template, given its name, whatever it means in the context of the loader.
*
* @param {string} name The name of the template to resolve
* @param {TwingSource} from The source that initiated the template loading
*
* @returns {Promise<string>} The resolved path of the template
*/
resolve(name: string, from: TwingSource): Promise<string>;
}
|
<reponame>henrylee2cn/aster
// Copyright 2018 henrylee2cn. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package aster
import (
"go/types"
)
//go:generate Stringer -type ObjKind,TypKind -output kind_string.go
// ObjKind describes what an object statement represents.
// Extension based on ast.ObjKind: Buil and Nil
type ObjKind uint32
// The list of possible object statement kinds.
const (
Bad ObjKind = 1 << iota // for error handling
Pkg // package
Con // constant
Typ // type
Var // variable
Fun // function or method
Lbl // label
Bui // builtin
Nil // nil
)
// TypKind describes what an object type represents.
type TypKind uint32
// The list of possible object type kinds.
const (
Invalid TypKind = 1 << iota // type is invalid
Basic
Array
Slice
Struct
Pointer
Tuple
Signature // non-builtin function or method
Interface
Map
Chan
named
)
// any kinds
const (
AnyObjKind = ^ObjKind(0) // any object kind
AnyTypKind = ^TypKind(0) // any type kind
)
// In judges whether k is fully contained in set.
func (k ObjKind) In(set ObjKind) bool {
return k&set == k
}
// In judges whether k is fully contained in set.
func (k TypKind) In(set TypKind) bool {
return k&set == k
}
// GetObjKind returns what the types.Object represents.
func GetObjKind(obj types.Object) ObjKind {
switch obj.(type) {
case *types.PkgName:
return Pkg
case *types.Const:
return Con
case *types.TypeName:
return Typ
case *types.Var:
return Var
case *types.Func:
return Fun
case *types.Label:
return Lbl
case *types.Builtin:
return Bui
case *types.Nil:
return Nil
}
return Bad
}
// GetTypKind returns what the types.Type represents.
func GetTypKind(typ types.Type) TypKind {
switch typ.(type) {
case *types.Basic:
return Basic
case *types.Array:
return Array
case *types.Slice:
return Slice
case *types.Struct:
return Struct
case *types.Pointer:
return Pointer
case *types.Tuple:
return Tuple
case *types.Signature:
return Signature
case *types.Interface:
return Interface
case *types.Map:
return Map
case *types.Chan:
return Chan
case *types.Named:
return named
}
return Invalid
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.