content
stringlengths 10
4.9M
|
---|
/**
* Implementation of method to draw marker on the map.
*/
public void draw(PGraphics pg, float x, float y) {
pg.pushStyle();
Float h = 5.0f;
Float b = (float) Math.sqrt(3) * h;
pg.fill(255, 0, 0, 100);
pg.triangle(x, y - 0.66f * h, x - 0.5f * b, y + 0.33f * h, x + 0.5f * b, y + 0.33f * h);
pg.popStyle();
} |
<reponame>johngreyland262/Stealth
// Copyright (c) 2019 2020 The Stealth Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef _EXPLOREDESTINATION_H_
#define _EXPLOREDESTINATION_H_ 1
#include "serialize.h"
#include "json/json_spirit_utils.h"
class ExploreDestination
{
public:
std::vector<std::string> addresses;
int required;
int64_t amount;
std::string type;
void SetNull();
ExploreDestination();
ExploreDestination(const std::vector<std::string>& addressesIn,
const int requiredIn,
const int64_t& amountIn,
const std::string& typeIn);
void AsJSON(json_spirit::Object& objRet) const;
IMPLEMENT_SERIALIZE
(
READWRITE(addresses);
READWRITE(required);
READWRITE(amount);
READWRITE(type);
)
};
#endif /* _EXPLOREDESTINATION_H_ */
|
/**
* Leaf node of scanning tree that allows global menu to be shown. TODO: Consider removing
* suppression and overriding hashCode()
*/
@SuppressWarnings("EqualsHashCode")
public class ShowGlobalMenuNode extends OverlayActionNode {
public ShowGlobalMenuNode(OverlayController overlayController) {
super(overlayController);
}
@Override
public Rect getRectForNodeHighlight() {
return mOverlayController.getMenuButtonLocation();
}
@Override
public List<MenuItem> performActionOrGetMenuItems() {
return GlobalMenuItem.getGlobalMenuItemList(
(AccessibilityService) mOverlayController.getContext());
}
@Override
public boolean equals(Object other) {
return other instanceof ShowGlobalMenuNode;
}
@Override
public List<CharSequence> getSpeakableText() {
List<CharSequence> speakableText = new LinkedList<>();
speakableText.add(
mOverlayController.getContext().getString(R.string.option_scanning_menu_button));
return speakableText;
}
} |
The Manyas fault zone (southern Marmara region, NW Turkey): active tectonics and paleoseismology
The Manyas fault zone (MFZ) is a splay fault of the Yenice Gönen Fault, which is located on the southern branch of the North Anatolian Fault System. The MFZ is a 38 km long, WNW–ESE-trending and normal fault zone comprised of three en-echelon segments. On 6 October 1964, an earthquake (Ms = 6.9) occurred on the Salur segment. In this study, paleoseismic trench studies were performed along the Salur segment. Based on these paleoseismic trench studies, at least three earthquakes resulting in a surface rupture within the last 4000 years, including the 1964 earthquake have been identified and dated. The penultimate event can be correlated with the AD 1323 earthquake. There is no archaeological and/or historical record that can be associated with the oldest earthquake dated between BP 3800 ± 600 and BP 2300 ± 200 years. Additionally, the trench study performed to the north of the Salur segment demonstrates paleoliquefaction structures crossing each other. The surface deformation that occurred during the 1964 earthquake is determined primarily to be the consequence of liquefaction. According to the fault plane slip data, the MFZ is a purely normal fault demonstrating a listric geometry with a dip of 64°–74° to the NNE.
The Manyas earthquake caused extensive liquefaction and lateral spreading around the Salur, Hamamlı, Yeniköy and Kızılköy villages to the south of Lake Manyas. There are different interpretations of the origin of the surface deformation and the seismotectonic features of the earthquake.
The first macro seismic study on the Manyas earthquake was performed by Erentöz and Kurtman (1964). They observed a series of fractures in the Gönen plain, in the area south of Lake Manyas and in the vicinity of the towns Susurluk, Mustafakemalpaşa and Karacabey. These fractures were up to 200 cm long and 5-10 cm wide and indicate that the surface deformation might have occurred due to liquefaction and/or lateral spreading (Erentöz & Kurtman, 1964). The strike of the fractures were reported as N-S in the Gönen plain, E-W in the area south of Lake Manyas, N-S to NNW-SSE partly and WNW-ESE in the Susurluk region and E-W in the regions of Mustafakemalpaşa and Karacabey. Erentöz and Kurtman (1964) stated that during the Manyas earthquake although the northern coastal plain of Lake Manyas was stable, the southern part of the lake subsided. According to Erentöz and Kurtman (1964), the source of earthquake was likely located along E-W-trending faults.
Another macro seismic study on the Manyas earthquake was carried out by Ketin (1969), who mapped a series of NW-trending en-echelon fractures in the vicinity of the villages of Hamamlı, Salur, Kızılköy and Yeniköy. These fractures were interpreted as tension cracks that developed as a result of dextral strike-slip faulting (Ketin, 1969).
There are many different seismological results associated with the source parameters of Manyas earthquake. The first seismological study, which was performed by Canıtez (1968), stated that the vertical component was much larger than the horizontal component associated with the Manyas earthquake. Another seismological study was performed by Öcal et al. (1968) whose focal mechanism solution shows that the Manyas earthquake originated from a WNW-trending reverse fault. According to Öcal et al. (1968) the coordinates of the epicentre were 40.10°N, 27.90°E (south of the MFZ), with a focal depth of 24 km. According to the focal mechanism solution of McKenzie (1972), however the 1964 earthquake originated along a NW-trending normal fault with epicentral coordinates of 40.30°N, 28.23°E (NE of Lake Manyas) and 10-24 km for the focal depth. Kıyak (1986) suggested that the coordinates of the epicentre were 40.18°N, 28.12°E (NE of Lake Manyas) and that the earthquake was sourced by an oblique-slip normal fault. Taymaz, Jackson, and McKenzie (1991) indicated that the Manyas earthquake originated from WNW-trending normal fault and that the coordinates of the epicentre were 40.30°N, 28.23°E (NE of Lake Manyas), with a focal depth of 14 ± 2 km. These differences are primarily associated with the use of different crustal models, initial depths for the moment tensor solutions and the scarcity of avaliable seismological stations.
The structural features and the fault type within the MFZ are controversial in the literature. Şaroğlu, Emre, and Boray (1987) defined the Manyas Fault as an approximately 70-km-long, dextral strike-slip fault extending between the towns of Gönen and Mustafakemalpaşa. Emre, Doğan, Özalp, and Yıldırım (2011) and Emre et al. (2013) described the MFZ as a 38-km-long, dextral strike-slip fault zone also extending between the towns of Gönen and Mustafakemalpaşa and identified a 16-km-long Salur segment that generated a surface rupture during the 1964 Manyas earthquake. Although the MFZ was defined based on its morphological properties, none of those studies presented fault plane slip data.
In this study, we aim to determine the structural and paleoseismological features of the MFZ and identification of the surface deformation structures.
2. Tectonic setting and regional geology
The NAFS is seismologically one of the most active fault systems in the Eastern Mediterranean Region. It begins at the Karlıova Triple Junction and extends to the east of Adapazarı. The NAFS bifurcates into two main branches at the east of Adapazarı as northern and southern branches and forms a large-scale horse tail structure (Barka, 1992;Barka & Gülen, 1988) (Figure 1).
The southern branch of the NAFS extends between the east of Adapazarı and Gemlik Gulf. This branch, which extends parallel to the southern shoreline of the Marmara Sea from the Gemlik Gulf to the Kapıdağ Peninsula, forms a restraining bend towards the southwest. This branch is represented by numerous dextral strike-slip faults such as the Edincik Fault, Sarıköy Fault, Yenice Gönen Fault and Edremit Fault Zone in a wide deformation zone between the Kapıdağ Peninsula and Gulf of Edremit ( Figure 2).
Recent GPS studies demonstrate that plate motions in and around the Marmara Region are principally accommodated by the northern branch of the NAFS, the data for which suggest a velocity of 24 ± 1 mm/year along this branch (McClusky, Reilinger, Mahmoud, Ben Sari, & Tealeb, 2003;Reilinger et al., 2006). The northern branch of the NAFS facilitates approximately four times as much right-lateral motion (~24 mm/year) as the southern branch does (Meade et al., 2002). In the Southern Marmara Region where the NAFS bifurcates into fault segments across a wide zone, the faults are suggested as dextral with extensional slip rates as varying from 0.9-6.8 mm/year to 0.8-5.5 mm/year (Aktuğ et al., 2009;Ergintav et al., 2014;Flerit, Armijo, King, & Meyer, 2004;Meade et al., 2002;Reilinger et al., 2006).
Regional geology
The basement rocks in the region are composed of Kazdağ metamorphics and the Kalabak Group. Kazdağ metamorphics consist of the pre-Triassic Fındıklı formation (Trf) and Altınoluk marble member (Trfa). These units are tec- tonically overlain by the Upper Paleozoic Sazak formation (Pzks) of the Kalabak Group (Duru, Pehlivan, Okay, Şentürk, & Kar, 2012). These metamorphic units are well exposed to the southeast of Manyas and belong to the Sakarya Zone but unconformably overlain by the Karakaya Complex (Trkk) (Figure 3). The Karakaya Complex consists of metaconglomerate, metasandstone, sandy limestone, tuff, metavolcanite and limestone blocks of Devonian -Permian ages (Duru et al., 2012). These units are well exposed to the west of Manyas and the village of Eşen ( Figure 3). It is unconformably overlain by Callovian-Hauterivian Bilecik limestone (Jkb). The basement units are tectonically overlain by the Upper Cretaceous Yayla Melange (Ky) (Figure 3). Basement units are cut by Upper Oligocene -Lower Miocene Hallaçlar Volcanics (Toh), which comprise andesite, dacite and pyroclastic rocks. This formation is comformably overlain by Lower Miocene Şapçı Volcanics (Tmş), which is represented by white tuff and by acidic and andesitic lavas (Genç et al., 2012).
The Hallaçlar Volcanics are unconformably overlain by the Middle-Upper Miocene Göbel Formation (Tmg) and the Mudamköy Volcanic member of this formation (Pehlivan, Duru, Kanar, & Kandemir, 2011 Formation consists of fluvial conglomerate, sandstone and lacustrine claystone in addition to, clayey limestone. The Mudamköy volcanic member is represented by andesite, dacite, basalt, tuff and agglomerate (Pehlivan et al., 2011). The Göbel Formation and Mudamköy volcanite member are exposed in the vicinity of the Eşen segment ( Figure 3). These units are unconformably covered by the Pliocene Bayramiç Formation, which is characterised by the alternation of fluvial conglomerate, sandstone, claystone and siltstone. It is exposed around the Dereköy and Salur segment.
The segment characteristics of the Manyas fault zone (MFZ) and its relation to the North Anatolian fault system
The Southern Marmara Region is primarily deformed by the active dextral strike-slip and normal faults belonging to the southern branch of the NAFS. The Yenice Gönen Fault and MFZ are active fault segments within the southern branch of the NAFS in the Southern Marmara Region. Both the 1953 Yenice Gönen earthquake (Ms = 7.2) and the 1964 Manyas earthquake (Ms = 6.9) were produced by these active faults. A 1-km-long part of the surface ruptures that occurred during both the Yenice Gönen and Manyas earthquakes overlapped each other. The NE-trending Yenice Gönen Fault and WNW-ESE-trending MFZ present a horse tail structure in the Southern Marmara Region (Figure 4).
The MFZ is a 38-km-long normal fault zone that extends in the WNW-ESE direction between the Yenice Gönen Fault to the west and the Mustafa Kemal Paşa fault to the east. The MFZ consists of three en-echelon geometric fault segments, named Dereköy, Salur and Eşen from SW to NE (Figure 3).
The 1964 Manyas earthquake caused surface deformation around the western part of the Dereköy and Salur segments. The Salur segment is a 16-km-long, WNWtrending normal fault segment that extends between Bayramiç in the west and Bölceağaç in the east. In this area, the Salur segment cuts the Bayramiç Formation and Quaternary deposits (Figure 3).
Paleoseismic trenching along the Manyas fault zone (MFZ)
In this study, paleoseismic trenching was performed in two different locations, named the Bayramiç and Hamamlı trench sites. The Bayramiç trench site is located to the west of the Salur segment (UTM Coordinates: 569807 E, 4440636 N) (Figure 3). The Hamamlı trench site is situated north of the Salur segment (NE of Hamamlı village) (GPS Coordinates: 35 0578972 E, 4440811 N) (Figure 3). In this locality, an observation pit was excavated to understand the surface deformation pattern documented by Erentöz and Kurtman (1964) and Ketin (1969).
Six charcoal, organic sediment and bone samples gathered from the Bayramiç trench site were dated at Beta Analytical Laboratories (USA) ( Table 3). Additionally, two Optically Stimulated Luminescence (OSL) samples and two Thermo Luminescence (TL) samples were analysed in the Luminescence Dating Research Laboratory of Ankara University (Turkey) ( Table 4). Trench walls were logged with a photomosaic technique using GIS software.
Bayramiç Trench site
Bayramiç Trenches were excavated on old fluvial deposits (Q1) (Figure 3). The fault trace is characteristic with a several-hundred-meter long linear fault scarp. Bayramiç trenches were excavated on local depressions formed by back-tilting.
Three trenches parallel to each other were excavated across to the Salur segment. They were named Bayramiç Trench 1, 2 and 3 ( Figure 3). Bayramiç Trench 1 is 26 m-long, 3 m-deep and 5 m-wide, Bayramiç Trench 2 is 14 m-long, 3 m-deep and 4 m-wide and Bayramiç Trench 3 is 26 m-long, 3 m-deep and 5 m-wide. Kürçer et al. (2015) Whereas the paleoseismological results were obtained from Bayramiç Trench 1, fault plane slip data were collected and interpreted from the other two trenches. Three different stratigraphic packages were identified at Bayramiç Trenches 1 and 2. The oldest units are Late Pleistocene-Holocene fluvial sediments ( Figure 5, Unit 1 -9). This sequence was incised by late Holocene fluvial chan-nel deposits comprising shards (Figures 5 and 6, Unit 10a and 10b). All of these units are unconformably overlain by modern soil (Figures 5 and 6, Unit 11).
Based on paleoseismological criteria such as stratigraphic and structural relations and upwards termination of fault strands, at least three events in the last 4000 years that resulted in a surface rupture, including the 1964 earthquake were identified and dated at Bayramiç trenches.
Event 3
Event 3 is well identified between 21 and 22 meters in the west wall of Bayramiç Trench 1 ( Figure 5). The earthquake horizon for this event was identified as the base of Unit 10a because Unit 2 was cut by the fault and covered by Unit 10a. Based on the OSL method, Unit 2 was dated to 19100 ± 2500 BP years. The radiocarbon age of Unit 10a is 2300 ± 200 BP. Because approximately 17 000 years of the sediment package (Units between 3 and 9) were eroded by fluvial channel Unit 10a, the age of Event 3 is unclear.
Event 2
Event 2 can be seen in both walls of Bayramiç trench 1 ( Figure 5 and 6). Because the upward termination of the fault strand is covered by Unit 11, the earthquake horizon is defined as the base of Unit 11. The youngest radiocarbon age, obtained from Unit 10b below the earthquake horizon, is 820 ± 30 BP. The age of Unit 11 covering the earthquake horizon is dated to 320 ± 30 BP. According to these data, Event 2 should have occurred between 820 ± 30 BP and 320 ± 30 BP. Based on historical records, earthquakes occurred in both 1323 AD and 1556 AD (Ambraseys & Finkel, 1991) (Figure 2). Because of the epicenteral location of the 1323 AD earthquake, Event 2 seems to be associated with the MFZ. Therefore, Event 2 could be correlated with the 1323 AD earthquake.
Event 1 (6 October 1964. Manyas Earthquake -Ms=6.9) The 1964 earthquake surface rupture is clearly seen on Bayramiç trench walls and is represented by normal fault characteristics in a narrow deformation zone between 2 and 4 mtrs on the east and west walls of Bayramiç Trench 1 (Figures 5 and 6). The age of Unit 11 is 320 ± 30 BP, which is the youngest unit. Because this unit is cut by a fault, this fault is interpreted as a 1964 (Allmendinger, Cardozo, & Fisher, 2012;Marrett & Allmendinger, 1990;V 6.6.3). Arrows show tensional axis. surface rupture. An interpretation of the earthquakes identified from Bayramiç Trenches is presented in (Figure 7).
Hamamlı Trench site
The most intensive surface deformation occurred around the Salur segment during the 1964 earthquake. However, the features of the surface deformation, particularly between the villages of Salur and Hamamlı are controversial. Erentöz and Kurtman (1964) suggested that the fractures occurred due to liquefaction and/or lateral spreading. Conversely, Ketin (1969) interpreted the NW-SE trending fractures as tension cracks resulting from, dextral strike-slip faulting.
We excavated a cross trench to the northeast of Hamamlı village (GPS Coordinates: 35 0578972 E,4440811 N) to understand the origin of these surface deformational features (Figure 3).
The Hamamlı Trench site is located on the flood plain of the Manyas River (Qfp) (Figure 3). The groundwater table lies approximately 2 m below the surface. According to trench microstratigraphy, there is yellowish, water-saturated, fine sand at the bottom (approx. −4 m) Just above this unit, there is a yellowish-green, water-saturated, fine sand and silt alternation. Above the fine sand and silt alternation, there is yellowish clay, which is relatively more plastic. The recent soil level covers all of the units (Figure 8).
The crosscutting paleoliquefaction structures were observed at Hamamlı Trench (Figure 8). The model of earthquake-induced paleoliquefaction structures is illustrated in Figure 9.
The relatively older sand blow determined in Hamamlı Trench at −2 m is interpreted as a paleoliquefaction structure related to the penultimate event of 1964 earthquake. This event can be correlated with the 1323 AD earthquake.
Kinematic features of the Manyas fault zone (MFZ)
The MFZ consists of WNW-ESE-trending and northward-dipping normal faults. The general structural features of the fault zone are presented in Figure 10.
Kinematic data of the MFZ are limited. We were able to collect fault plane slip-data of the Eşen segment approximately 1.5 km northeast of the Eşen Village (Allmendinger et al., 2012;Marrett & Allmendinger, 1990;V 6.6.3). Arrows show tensional axis.
( Figure 11). According to the fault plane slip-data, the Eşen segment is a normal fault with a minor dextral strike-slip component.
The structural data, which reveals the recent kinematic features of the MFZ, was gathered from Bayramiç Trenches 2 and 3 (Table 5; Figures 12-15). According to the fault plane slip-data measured from the trench walls, the MFZ is a pure normal fault trending WNW-ESE and dipping 65°-75°towards to north.
Discussion and conclusion
The deformation of the Southern Marmara region is primarily controlled by the westernmost segments of the NAFS. To the east of Adapazarı, the NAFS splits into two main branches that extend towards the Marmara Sea and the Southern Marmara Region, forming a horse-tail structure (Barka, 1992;Barka & Gülen, 1988) (Figure 2). The northern and southern branches of the NAFS form an approximately 100-km-wide dextral shear zone in noertwestern Turkey (Figure 4). This shear zone is bordered by the Ganos and Saros segments to the north and the Havran-Balıkesir fault zone (HBFZ) and Edremit Fault Zone (EFZ) to the south (Figure 4).
The southern branch of the NAFS consists of several dextral strike-slip faults (e.g. the Yenice Gönen Fault and Sarıköy Fault), reverse faults (e.g. the Bekten fault; Özalp, Kürçer, Özdemir, & Duman, 2016) and normal faults (e.g. the Manyas Fault Zone and Uluabat Fault) associated with the dextral strike-slip faulting mechanism in the area of study. The 1944The , 1953 were produced by the EFZ, YGF and MFZ, respectively (Figure 4).
The YGF is one of the most active dextral strike-slip faults in the Southern Marmara Region. A 70-km-long surface rupture occurred between Yenice and Gönen during the 18 March 1953, Yenice Gönen earthquake (Mw = 7.2). Eleven years after the Yenice Gönen earthquake, the Manyas earthquake (Ms = 6.9) occurred along the MFZ, on 6 October 1964. An 18-km-long surface rupture occurred as a result of the 1964 event along the Dereköy and Salur segments of the MFZ. 1-km-long part of surface rupture that was occurred both during the Yenice Gönen and Manyas earthquakes overlapped each other.
The MFZ is a WNW-ESE-trending 38-km-long normal fault zone that consists of three en-echelon fault segments, named Dereköy, Salur and Eşen from SW to NE. The MFZ is interpreted as a normal fault zone associated with dextral Equal-angle lower-hemisphere plots of fault slip data collected from the trenches. Fault and striae are superposed on a fault plane solution derived using the FaultKin program (V 6.6.3, Allmendinger et al., 2012;Marrett & Allmendinger, 1990). Arrows show tensional axis. strike-slip faulting (see Figure 4). The NE-trending YGF and WNW-ESE-trending MFZ presents as horse-tail structure in the Southern Marmara region (Figure 4).
On 6 October 1954, an earthquake (Ms = 6.9) occurred along the MFZ. Although some surface deformation occurred around the Salur segment, there is
In this study, paleoseismologic trench studies performed on the Salur segment of the MFZ resulted in the gathering of new and substantial data to overcome the discussions outlined above. At least three large earthquakes within the last 4000 years that resulted in surface ruptures, including the 1964 earthquake, have been identified and dated.
The ante-penultimate event was dated to between 3800 ± 600 BP and 2300 ± 200 BP, but there are no archaeological data or historical records associated with this earthquake.
To understand the origin of the surface deformations that occurred during the Manyas earthquake along the Salur segment a trench was excavated to the north of Hamamlı village. Paleoliquefaction structures crossing each other were observed in the Hamamlı trench. We concluded that the surface deformations that occurred during the 1964 earthquake are primarily the consequence of liquefaction.
Based on the fault plane slip-data, the MFZ is a purely normal fault that trends WNW-ESE and dips 64°-74°to the NNE. The Eşen segment of the fault zone has a minor dextral strike-slip component.
The seismotectonic features of the 1964 Manyas earthquake (Ms = 6.9) are controversial in the literature. There are substantially different views about the epicenter, focal depth and the faulting type of the earthquake.
We suggest a new seismotectonic model for the Manyas earthquake (Figure 16). In this model, a surface rupture is assumed to have occurred along the Salur segment of the MFZ during the Manyas earthquake. Fault plane slip-data collected from Bayramiç Trenches show that the MFZ is a purely normal fault trending to the WNW-ESE and dipping 64°-74°NNE (Table 5). We assume that the focal depth of the Manyas earthquake was 14 ± 2 km and that the dip of the fault plane at the hypocenter was 40°NNE (Taymaz et al., 1991).
According to these data, the MFZ should have a listric geometry. The epicentral location for the Manyas earthquake should be somewhere within Manyas Lake ( Figure 16).
Because of the local geological conditions and the proximity of the epicentre, the surface deformations, including liquefaction and lateral spreading, are concentrated between the villages of Salur and Hamamlı. |
<reponame>FedorUporov/gridgain
/*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* 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.ignite.examples.ml.inference;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.ml.IgniteModel;
import org.apache.ignite.ml.inference.Model;
import org.apache.ignite.ml.inference.ModelDescriptor;
import org.apache.ignite.ml.inference.ModelSignature;
import org.apache.ignite.ml.inference.builder.SingleModelBuilder;
import org.apache.ignite.ml.inference.parser.IgniteModelParser;
import org.apache.ignite.ml.inference.reader.ModelStorageModelReader;
import org.apache.ignite.ml.inference.storage.descriptor.ModelDescriptorStorage;
import org.apache.ignite.ml.inference.storage.descriptor.ModelDescriptorStorageFactory;
import org.apache.ignite.ml.inference.storage.model.ModelStorage;
import org.apache.ignite.ml.inference.storage.model.ModelStorageFactory;
/**
* This example demonstrates how to work with {@link ModelStorage}.
*/
public class ModelStorageExample {
/** Run example. */
public static void main(String... args) throws IOException, ClassNotFoundException {
try (Ignite ignite = Ignition.start("examples/config/example-ignite-ml.xml")) {
System.out.println(">>> Ignite grid started.");
ModelStorage storage = new ModelStorageFactory().getModelStorage(ignite);
ModelDescriptorStorage descStorage = new ModelDescriptorStorageFactory().getModelDescriptorStorage(ignite);
System.out.println("Saving model into model storage...");
byte[] mdl = serialize((IgniteModel<byte[], byte[]>)i -> i);
storage.mkdirs("/");
storage.putFile("/my_model", mdl);
System.out.println("Saving model descriptor into model descriptor storage...");
ModelDescriptor desc = new ModelDescriptor(
"MyModel",
"My Cool Model",
new ModelSignature("", "", ""),
new ModelStorageModelReader("/my_model"),
new IgniteModelParser<>()
);
descStorage.put("my_model", desc);
System.out.println("List saved models...");
for (IgniteBiTuple<String, ModelDescriptor> model : descStorage)
System.out.println("-> {'" + model.getKey() + "' : " + model.getValue() + "}");
System.out.println("Load saved model descriptor...");
desc = descStorage.get("my_model");
System.out.println("Build inference model...");
SingleModelBuilder mdlBuilder = new SingleModelBuilder();
try (Model<byte[], byte[]> infMdl = mdlBuilder.build(desc.getReader(), desc.getParser())) {
System.out.println("Make inference...");
for (int i = 0; i < 10; i++) {
Integer res = deserialize(infMdl.predict(serialize(i)));
System.out.println(i + " -> " + res);
}
}
}
}
/**
* Serialized the specified object.
*
* @param o Object to be serialized.
* @return Serialized object as byte array.
* @throws IOException In case of exception.
*/
private static <T extends Serializable> byte[] serialize(T o) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(o);
oos.flush();
return baos.toByteArray();
}
}
/**
* Deserialized object represented as a byte array.
*
* @param o Serialized object.
* @param <T> Type of serialized object.
* @return Deserialized object.
* @throws IOException In case of exception.
* @throws ClassNotFoundException In case of exception.
*/
@SuppressWarnings("unchecked")
private static <T extends Serializable> T deserialize(byte[] o) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(o);
ObjectInputStream ois = new ObjectInputStream(bais)) {
return (T)ois.readObject();
}
}
}
|
University of Birmingham: Stop the Clampdown on Protests
Defend E. started this petition to University of Birmingham started this petition to
The University of Birmingham has started an unprecedented clampdown on protest this year. Two students, Kelly Rogers and Simon Furse, have been suspended from the University for their Part in an occupation in November. Hattie Craig was given a 6 month suspended sentence, meaning that if she breaks any university regulation she will immediately be suspended.
The university currently have a possession order over the whole campus for an entire year, meaning that they can evict anyone from the campus at any time. Their definition of the campus includes university halls meaning that the possession order could be used to evict students who they deem to have breached their tenancy agreements. The university used this possession order to evict a peaceful occupation in two days with no legal process.
The universities procedures are unfair and unlawful: they deny students the right to legal representation in disciplinaries, which goes against the human right to a fair hearing. The procedures use a criteria of balance of probabilities, meaning that decisions can be made on hunches and suspicion rather than evidence. Finally there are no guidelines for what constitutes an offence, or on what sentence should be applied in which situation.
We call on the University of Birmingham to:
1. Immediately lift the nine month suspensions of Kelly Rogers and Simon Furse.
2. Lift the onerous and inhibitive restrictions on the activity of Hattie Craig.
3. Lift the draconian year long possession order of the whole university campus.
4. Reform their disciplinary procedures to include: the right to legal representation, a sentencing criteria of proven beyond reasonable doubt rather than the balance of probabilities, and sentencing guidelines. |
<reponame>navikt/k9-produksjonsstyring
import React, { FunctionComponent } from 'react';
import { injectIntl, WrappedComponentProps, FormattedMessage } from 'react-intl';
import { Row, Column } from 'nav-frontend-grid';
import { Hovedknapp, Knapp } from 'nav-frontend-knapper';
import { Normaltekst } from 'nav-frontend-typografi';
import Image from 'sharedComponents/Image';
import Modal from 'sharedComponents/Modal';
import advarselImageUrl from 'images/advarsel.svg';
import { Driftsmelding } from '../driftsmeldingTsType';
import styles from './sletteDriftsmeldingerModal.less';
type TsProps = Readonly<{
intl: any;
valgtDriftsmelding: Driftsmelding;
closeSletteModal: () => void;
fjernDriftsmelding: (driftsmelding: Driftsmelding) => void;
}>;
/**
* SletteDriftsmeldingModal
*
* Presentasjonskomponent. Modal som lar en avdelingsleder fjerne tilgjengelige saksbehandlere.
*/
const SletteDriftsmeldingModal: FunctionComponent<TsProps & WrappedComponentProps> = ({
intl,
valgtDriftsmelding,
closeSletteModal,
fjernDriftsmelding,
}: TsProps) => (
<Modal
className={styles.modal}
closeButton={false}
isOpen
contentLabel={intl.formatMessage({ id: 'SletteDriftsmeldingModal.SletteModal' })}
onRequestClose={closeSletteModal}
>
<Row>
<Column xs="1">
<Image
className={styles.image}
alt={intl.formatMessage({ id: 'SletteDriftsmeldingModal.SletteModal' })}
src={advarselImageUrl}
/>
<div className={styles.divider} />
</Column>
<Column xs="6" className={styles.text}>
<Normaltekst>
<FormattedMessage id="SletteDriftsmeldingModal.SletteDriftsmelding" />
</Normaltekst>
</Column>
<Column xs="4">
<Hovedknapp
className={styles.submitButton}
mini
htmlType="submit"
onClick={() => fjernDriftsmelding(valgtDriftsmelding)}
autoFocus
>
{intl.formatMessage({ id: 'SletteDriftsmeldingModal.Ja' })}
</Hovedknapp>
<Knapp
className={styles.cancelButton}
mini
htmlType="reset"
onClick={closeSletteModal}
>
{intl.formatMessage({ id: 'SletteDriftsmeldingModal.Nei' })}
</Knapp>
</Column>
</Row>
</Modal>
);
export default injectIntl(SletteDriftsmeldingModal);
|
n = int(input())
mas = list(map(int, input().split()))
maxx = 1
d = 0
t = True
for i in range(n - 1):
if mas[i + 1] <= 2 * mas[i]:
d += 1
t = False
else:
if d > maxx:
maxx = d
d = 0
if d > maxx:
maxx = d
if t == False:
print(maxx + 1)
else:
print(maxx)
|
import argparse
import os
import sys
from fabric.api import *
from fabric.colors import red
from fabric.contrib import files
from fabric.network import disconnect_all
from playback import __version__, common
from playback.templates.local_settings_py import conf_local_settings_py
class Horizon(common.Common):
"""
Install horizon
:param user(str): the user for remote server to login
:param hosts(list): this is a second param
:param key_filename(str): the ssh private key to used, default None
:param password(str): the password for remote server
:param parallel(bool): paralleler execute on remote server, default True
:returns: None
:examples:
.. code-block:: python
# create a horizon instance
horizon = Horizon(user='ubuntu', hosts=['controller1', 'controller2'])
horizon.install(
openstack_host='192.168.1.1',
memcached_servers='controller1',
time_zone='America/New_York'
)
"""
def _install(self, openstack_host, memcached_servers, time_zone):
print red(env.host_string + ' | Install the packages')
sudo('apt-get update')
sudo('apt-get -y install openstack-dashboard')
print red(env.host_string + ' | Update /etc/openstack-dashboard/local_settings.py')
with open('tmp_local_settings_py_' + env.host_string, 'w') as f:
f.write(conf_local_settings_py)
files.upload_template(filename='tmp_local_settings_py_' + env.host_string,
destination='/etc/openstack-dashboard/local_settings.py',
use_jinja=True,
use_sudo=True,
backup=True,
context={'openstack_host': openstack_host,
'memcached_servers': memcached_servers,
'time_zone': time_zone})
os.remove('tmp_local_settings_py_' + env.host_string)
def install(self, *args, **kwargs):
"""
Install horizon
:param openstack_host: configure the dashboard to use OpenStack services on the controller node e.g. `CONTROLLER_VIP`
:param memcached_servers: django memcache e.g. `CONTROLLER1:11211,CONTROLLER2:11211`
:param time_zone: the timezone of the server. This should correspond with the timezone of your entire OpenStack installation e.g. `America/New_York`
:returns: None
"""
return execute(self._install, *args, **kwargs)
|
Metalocalypse crossover time! I wanted to do this for so long... And it took a lot of my free time to finish this. About 5 hours to make the sketch and... I guess 30+ hours of work in photoshop. Yeah, I'm a patient oneSo, who is who?Twilight Sparkle = Nathan Explosion (cause she's some kind of a leader, right?)Applejack = William Murderface (well, AJ is the strongest one, and Murderface is a bassist...)Rarity = Pickles (no paritcular reason, honestlyFluttershy = Toki Wartooth (do I really need to explain why?)Rainbow Dash = Skwisgaar Skwigelf (fast flying/fast playing)Pinkie Pie = Dr. Rockso (she does coc... Um, sugar)And I suppose that now Deththeme [link] should sound like this:Do anything for friendship!Do anything for friendship!Do anything for friendship!Do anything for friendship!FRIENDSHIP, FRIENDSHIP, FRIENDSHIP, FRIENDSHIP!You're...All...My very best...Friends!FRIENDSHIP, FRIENDSHIP!Rainbow Dash is flying freeFluttershy is not a treeAJ, AJ, AJ, AJRarity and Pinkie Pie, shining, laughing all the timeAnd Twilight Sparkle! |
// Method to invoke methods called through reflection. If method doesn't exist, display error
@Override
protected void invokeMethod(Method method) {
try {
method.invoke(SimulatorChoiceDialogBoxFactory.this);
} catch (Exception e) {
new GenerateError(myLanguageResources, INVALID_METHOD);
}
} |
<filename>filer_addons/tests/settings_admin_styles.py
from .settings import * # noqa
INSTALLED_APPS.insert(0, 'admin_styles') # noqa
|
// runDiagnosticsService is like runMetricService, but uses the
// insecure port and supports both trace and metrics.
func (ms *testServer) runDiagnosticsService(ts *traceServer) {
listener, err := net.Listen("tcp", "127.0.0.1:19000")
if err != nil {
log.Fatalf("failed to listen: %s", err)
}
grpcServer := grpc.NewServer()
metricService.RegisterMetricsServiceServer(grpcServer, ms)
if ts != nil {
traceService.RegisterTraceServiceServer(grpcServer, ts)
}
ctx, cancel := context.WithCancel(context.Background())
ms.stops <- cancel
go func() {
if err := grpcServer.Serve(listener); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}()
go func() {
<-ctx.Done()
grpcServer.Stop()
}()
} |
/* A simple test for CompositeTransformReader on its own. See
* CompositeTransformWriterAndReaderTest for a test that checks
* actual writing and then reading for errors. */
int itkCompositeTransformReaderTest(int , char *[] )
{
const unsigned int NDimensions = 2;
typedef itk::CompositeTransformReader<double, NDimensions> ReaderType;
ReaderType::Pointer reader = ReaderType::New();
bool caughtException = false;
try
{
reader->Update();
}
catch (itk::ExceptionObject &ex)
{
caughtException = true;
std::cout << "Exception caught as expected:" << std::endl;
std::cout << ex << std::endl;
}
if( !caughtException )
{
std::cout << "No error generated for no filename." << std::endl;
return EXIT_FAILURE;
}
try
{
reader->SetFileName( "junkfile!@#$%^&*()" );
}
catch (itk::ExceptionObject &ex)
{
std::cout << "Unexpected Exception caught:" << std::endl;
std::cout << ex << std::endl;
}
caughtException = false;
try
{
reader->Update();
}
catch (itk::ExceptionObject &ex)
{
caughtException = true;
std::cout << "Exception caught as expected:" << std::endl;
std::cout << ex << std::endl;
}
if( !caughtException )
{
std::cout << "No error generated for bad filename." << std::endl;
return EXIT_FAILURE;
}
std::cout << reader;
return EXIT_SUCCESS;
} |
package numbersix
import (
"database/sql"
"testing"
"time"
"hawx.me/code/assert"
)
func TestFor(t *testing.T) {
assert := assert.New(t)
sqlite, _ := sql.Open("sqlite3", "file::memory:")
a, err := For(sqlite, "a")
assert.Nil(err)
b, err := For(sqlite, "b")
assert.Nil(err)
assert.Nil(a.Set("x", "y", "z"))
assert.Nil(b.Set("x", "y", "q"))
atriples, err := a.List(About("x"))
assert.Nil(err)
btriples, err := b.List(About("x"))
assert.Nil(err)
var avalue string
atriples[0].Value(&avalue)
assert.Equal("z", avalue)
var bvalue string
btriples[0].Value(&bvalue)
assert.Equal("q", bvalue)
}
func insertMap(db *DB, id string, properties map[string][]interface{}) error {
for key, value := range properties {
if err := db.SetMany(id, key, value); err != nil {
return err
}
}
return nil
}
func triplesToMap(triples []Triple) (map[string][]interface{}, error) {
properties := map[string][]interface{}{}
for _, triple := range triples {
var value interface{}
if err := triple.Value(&value); err != nil {
return properties, err
}
properties[triple.Predicate] = append(properties[triple.Predicate], value)
}
return properties, nil
}
func TestMicroformat(t *testing.T) {
assert := assert.New(t)
type Microformat struct {
Type []string
Properties map[string][]interface{}
}
microformat := Microformat{
Type: []string{"h-entry"},
Properties: map[string][]interface{}{
"content": {"test content"},
"category": {"cool", "tag"},
},
}
postID := "some-uuid"
db, _ := Open("file::memory:")
assert.Nil(db.SetMany(postID, "type", microformat.Type))
assert.Nil(insertMap(db, postID, microformat.Properties))
triples, err := db.List(About(postID))
assert.Nil(err)
properties, err := triplesToMap(triples)
assert.Nil(err)
assert.Equal("h-entry", properties["type"][0])
assert.Equal("test content", properties["content"][0])
assert.Equal("cool", properties["category"][0])
assert.Equal("tag", properties["category"][1])
}
func TestPossibleUsage(t *testing.T) {
assert := assert.New(t)
db, _ := Open("file::memory:")
insertPost := func(postID, title string, createdAt time.Time) {
assert.Nil(db.Set(postID, "title", title))
assert.Nil(db.Set(postID, "createdAt", createdAt))
}
insertPost("1", "My first post", time.Date(2019, time.January, 1, 12, 0, 0, 0, time.UTC))
insertPost("2", "My third post", time.Date(2019, time.March, 1, 12, 0, 0, 0, time.UTC))
insertPost("3", "My second post", time.Date(2019, time.February, 1, 12, 0, 0, 0, time.UTC))
insertPost("4", "My final post", time.Date(2019, time.April, 1, 12, 0, 0, 0, time.UTC))
type Post struct {
Title string
CreatedAt time.Time
}
triples, err := db.List(
After("createdAt", time.Date(2019, time.January, 5, 12, 0, 0, 0, time.UTC)).Limit(2),
)
assert.Nil(err)
posts := map[string]Post{}
for _, triple := range triples {
post, ok := posts[triple.Subject]
if !ok {
post = Post{}
}
switch triple.Predicate {
case "title":
assert.Nil(triple.Value(&post.Title))
case "createdAt":
assert.Nil(triple.Value(&post.CreatedAt))
}
posts[triple.Subject] = post
}
_, ok := posts["1"]
assert.False(ok)
_, ok = posts["4"]
assert.False(ok)
second, ok := posts["3"]
assert.True(ok)
assert.Equal("My second post", second.Title)
assert.Equal(time.Date(2019, time.February, 1, 12, 0, 0, 0, time.UTC), second.CreatedAt)
third, ok := posts["2"]
assert.True(ok)
assert.Equal("My third post", third.Title)
assert.Equal(time.Date(2019, time.March, 1, 12, 0, 0, 0, time.UTC), third.CreatedAt)
}
|
// Based on https://stackoverflow.com/questions/45667415/how-to-receive-bitcoin-payments-using-bitcoinjs-lib-in-node-js
export function subscribePaymentAtAddress(
address: string,
onPayment,
onError = (err) => {}
) {
const btcWS = new WebSocket('wss://ws.blockchain.info/inv')
// NOTIFY ON ADDRESS UPDATE
btcWS.onopen = () => {
btcWS.send(JSON.stringify({ op: 'addr_sub', addr: address }))
console.log('[INFO] btc connection opened')
}
// WE GOT AN UPDATE
btcWS.onmessage = (msg) => {
const response = JSON.parse(msg.data)
const getOuts = response.x.out
// LET'S CHECK THE OUTPUTS
getOuts.map(function (out, i) {
if (address == out.addr) {
const amount = out.value
const calAmount = amount / 100000000
console.log('[INFO] amount received:', calAmount + ' BTC')
onPayment(calAmount)
}
})
}
btcWS.onerror = (error) => {
console.log('connection.onerror', error)
onError(error)
}
return btcWS
}
|
<reponame>jayvdb/django-outputs<filename>outputs/filters.py
import django_filters
from crispy_forms.bootstrap import InlineRadios
from crispy_forms.layout import Layout, Row, Div, Fieldset, Field
from django.contrib.contenttypes.models import ContentType
from django.forms import HiddenInput
from django.utils.translation import ugettext_lazy as _
from django_select2.forms import Select2Widget
from django.contrib.auth import get_user_model
from outputs.models import Export, Scheduler
from pragmatic.forms import SingleSubmitFormHelper
from pragmatic.filters import SliderFilter
class ExportFilter(django_filters.FilterSet):
created = django_filters.DateFromToRangeFilter()
total = SliderFilter(label=_('Total items'), step=10, has_range=True, segment='outputs.Export.total')
creator = django_filters.ModelChoiceFilter(queryset=get_user_model().objects.all(), widget=Select2Widget)
content_type = django_filters.ModelChoiceFilter(
queryset=ContentType.objects.filter(pk__in=Export.objects.order_by('content_type').values_list('content_type', flat=True).distinct()),
widget=Select2Widget
)
class Meta:
model = Export
fields = [
'id', 'created', 'format', 'context', 'content_type', 'status',
'total', 'creator'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.form.fields['format'].empty_label = _("Doesn't matter")
self.form.fields['context'].empty_label = _("Doesn't matter")
self.helper = SingleSubmitFormHelper()
self.helper.form_tag = False
self.helper.disable_csrf = True
self.helper.layout = Layout(
Row(
Div(
Row(
Fieldset(
_('Generic'),
Row(
Div('id', css_class='col-md-4'),
Div(Field('created', css_class='date-picker form-control'), css_class='col-md-8 range-filter')
),
css_class='col-md-12'
),
),
Row(
Fieldset(
_('Related'),
Row(
Div('creator', css_class='col-md-5'),
Div(Field('total', css_class='form-control'), css_class='col-md-7 range-filter')
),
Row(
Div('content_type', css_class='col-md-5')
),
css_class='col-md-12'
),
),
css_class='col-md-9'
),
Fieldset(
_('Attributes'),
InlineRadios('format'),
InlineRadios('context'),
css_class='col-md-3'
),
)
)
class ExportFilterSet(django_filters.FilterSet):
export = django_filters.ModelChoiceFilter(queryset=Export.objects.all(), widget=HiddenInput(), label=_('Export'), method='filter_export')
def filter_export(self, queryset, name, value):
return queryset.filter(id__in=value.object_list)
class SchedulerFilter(django_filters.FilterSet):
created = django_filters.DateFromToRangeFilter()
creator = django_filters.ModelChoiceFilter(queryset=get_user_model().objects.all(), widget=Select2Widget)
content_type = django_filters.ModelChoiceFilter(
queryset=ContentType.objects.filter(pk__in=Scheduler.objects.order_by('content_type').values_list('content_type', flat=True).distinct()),
widget=Select2Widget
)
class Meta:
model = Scheduler
fields = [
'id', 'created', 'format', 'context', 'content_type',
'creator', 'routine', 'is_active'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.form.fields['format'].empty_label = _("Doesn't matter")
self.form.fields['context'].empty_label = _("Doesn't matter")
self.helper = SingleSubmitFormHelper()
self.helper.form_tag = False
self.helper.disable_csrf = True
self.helper.layout = Layout(
Row(
Div(
Row(
Fieldset(
_('Generic'),
Row(
Div('id', css_class='col-md-4'),
Div(Field('created', css_class='date-picker form-control'), css_class='col-md-8 range-filter')
),
css_class='col-md-12'
),
),
Row(
Fieldset(
_('Related'),
Row(
Div('creator', css_class='col-md-5'),
Div(Field('total', css_class='form-control'), css_class='col-md-7 range-filter')
),
Row(
Div('content_type', css_class='col-md-5')
),
css_class='col-md-12'
),
),
css_class='col-md-9'
),
Fieldset(
_('Attributes'),
InlineRadios('format'),
InlineRadios('context'),
InlineRadios('routine'),
InlineRadios('is_active'),
css_class='col-md-3'
),
)
)
|
Yes, Hitman’s Bodyguard is available on Netflix in Japan, but did you know you can unlock thousands of movies and shows not currently available in Japan? The release date for Netflix Japan was August 25th 2017, and here are the dates it was released on Netflix in other countries:
Netflix Netherlands : Released on August 20th, 2018
: Released on August 20th, 2018 Netflix USA : Released on August 6th, 2018
: Released on August 6th, 2018 Netflix Ireland : Released on April 3rd, 2018
: Released on April 3rd, 2018 Netflix UK : Released on April 3rd, 2018
: Released on April 3rd, 2018 Netflix Argentina : Released on March 16th, 2018
: Released on March 16th, 2018 Netflix Canada: Released on March 16th, 2018
Check out this sample list of movies you can unlock through American and International Netflix, including "Ben-Hur (1959)", "The Big Blue (1988)", and "I Am Not Your Negro (2016)" |
def version(self):
version_command = 'SYSTem:VERSion?'
responce = self.send_scpi_command(command=version_command)
return responce |
def build_shift_dict(self, shift):
assert(0 <= shift < 26), "shift not in [0,26]: %d" % shift
cipher = {}
for c in string.ascii_lowercase:
if ord(c) + shift > ord("z"):
cipher[c] = chr(ord(c) + shift - ord("z") + ord("a") - 1)
else:
cipher[c] = chr(ord(c) + shift)
cipher[c.upper()] = cipher[c].upper()
return cipher |
by Chio
I didn’t realize it was time for finals until I read the Facebook status updates. My newsfeed was littered with posts discussing immense sleep deprivation; pictures of meals comprised of Hot Cheetos, Red Bulls, and 5-Hour Energy drinks; and extensive lists of extracurricular activities that needed to be accomplished, alongside finals, in a ridiculously short amount of time. I’m no longer in college, so I was able to look at this with an outsider’s lens and what I saw astounded me. It was ridiculous. I was bothered by how the practices, and consequences, of busyness were glorified. Students wrote about them as if they were embarking on a fruitful challenge: maxing out the total credits they could take, being involved in every club, not sleeping. They would reap the rewards of A’s today and impressive resumes later, the health of their bodies not even considered. Several months ago, I was doing the exact same thing.
In fact, I was probably the perfect illustration of the situation I am describing. By my senior year, I was managing student government, acting in a play, teaching a class, taking 20 credits, being in a research program, trying to bring about revolution…you get the idea. My mind was proud of my accomplishments, but my body suffered the consequences. It became so difficult to sleep that I required sleeping pills. I had panic attacks, which I never had before. My back and head were constantly hurting from tension. The food I was eating did not feel good in my body.
Maybe it was my overachieving self. Maybe it was my inferiority complex as a poor womyn of color who doubted whether she was good enough. Who was trying to ensure she was a good job candidate to help her family pay rent they couldn’t afford. Who dreamed of graduate school, but was unsure of what it looked like or how to get there. Who tried to shout, “Fuck you!” to stereotypes and barriers. Who was trying to bring change NOW because she was impatient and tired of experiencing oppression.
An inferiority complex is described as a lack of self-worth, a doubt and uncertainty, and feelings of not measuring up to society’s standards. It is often subconscious and is thought to drive afflicted individuals to overcompensate, resulting either in spectacular achievement or extreme asocial behavior.
I have an inferiority complex.
I believe my inferiority complex to be an effect of white supremacist, capitalist patriarchy. I was driven to overachieve, to defy uncertainties brought on by the dominating standards of white supremacist capitalist patriarchy, at the expense of my body’s wellbeing.
BGD is a reader-funded, non-profit project. Please GIVE today and help amplify marginalized voices.
As I keep trying to remind myself that self-preservation is an act of political warfare, I continue to see the mistreatment of bodies of color in my surroundings. I am in a culture that is trying to tear me apart. I don’t want to be the product of a machine that devours bodies of color, a machine that sees us as disposable objects that can produce its desired results. I refuse to participate in my own dehumanization. This machine has attempted to transform and damage our bodies for centuries. I think of early colonial times when indigenous peoples in the Americas bought coca-leafs instead of food, which shortened their lives but allowed them to endure deadly tasks imposed on them by the colonizers. To this day, people still chew coca to kill hunger.
I realize that not everyone has the privilege to practice the sort of self-care I am discussing. I think of those who have to work constantly and produce outstandingly. I think of my mother being exploited at a flower warehouse. She comes home exhausted, describing the ways in which her supervisors scream, “Faster! Faster!” to all the employees while demanding that they chop flowers at robot speeds. She can’t quit because jobs are scarce, so she continues, her hands trembling from lack of proper occupational gloves and from her “nervios.” The supervisors laugh in her face by providing pathetic paychecks, completely dismissing her efforts and pain because to them, she is just another disposable body of color, a source of income.
It can be easy to forget that the University still functions as a capitalistic machine, extracting all of our energy to the very last drop until we are dwindled bodies, robotically producing. In this sense, it does well in preparing us for the capitalist job market. I ask that we remind ourselves of this, and question whether we are willfully participating in, and internalizing, the ways capitalism associates our human worth with the amount of production they can extract from us.
When I recognized I was subconsciously embodying capitalistic values of extraction, I began to feel very depressed and ashamed. I did not want to, consciously or unconsciously, be an agent or tool of oppression. Eventually, I realized that I had to be patient and compassionate with myself – two traits I will forever be in the process of learning. In the process, I began to discover what self-love looked like for my unique body and spirit, and I used that understanding to counteract the oppressive values I internalized. I treated my body with the kind of love I felt it needed by actively looking for signs of stress. As I became more conscious of how the food I consumed impacted my mood and energy, my diet drastically changed and my health improved. Whether through exercise, painting, writing, or lying still for a few moments, I made sure to meditate frequently.
I left the University of California, Santa Cruz a few months ago and I have been restoring my body and reclaiming it from the white supremacist patriarchy ever since. It has been a difficult process, but the support of my family has been of incredible help. I’m working on maintaining my drive, but being careful not to place too many things on my plate. My family calls me out when they see that I am stressed or too busy. I take those moments as signs to evaluate how I am managing my time and priorities. I haven’t had a panic attack in a long time, and I stopped taking sleeping pills. My body is my temple and little by little I am providing it the respect it deserves.
This is my resistance.
All work published on BGD is the intellectual property of its writers. Please do not republish anything from this site without express written permission from BGD. For more info, go here.
Chio is a free spirited queer xicana feminist. She is a fighter who laughs in the face of a world that tries to break her spirit. She believes that another world is possible and is eager to create it. |
A Nutrigenomic Inflammation-Related PBMC-Based Approach to Predict the Weight-Loss Regain in Obese Subjects
Background: Long-term maintenance of a dietary-induced weight loss continues to be a major health problem and warrants research on innovative approaches to understand weight stability. We investigated the role of the proinflammatory status on weight changes in obese subjects receiving a low-calorie diet (LCD) and during the subsequent 6-month weight maintenance period. Methods: Eighty-four subjects (age: 34.2 ± 0.53 years; body mass index, BMI: 30.4 ± 1.8 kg/m2) followed an 8-week LCD intervention and were contacted again 6 months later. Body composition, circulating proinflammatory markers and mRNA levels of inflammation-related genes in peripheral blood mononuclear cells (PBMC) were evaluated. Results: The 6-month weight regain was predicted by high concentrations of TNFα at LCD completion (OR = 4.21, p = 0.036) along with the baseline amount of fat mass (OR = 7.23, p = 0.029). In addition, baseline leptin concentrations (p = 0.028) as well as mRNA levels of TNFα and NFκB subunits were higher at the end of the dietary intervention (p < 0.05) in PBMC of subjects who regained ≥10% of the dietary-induced weight loss. Conclusions: These findings demonstrate a role for the proinflammatory state and body adiposity in the prediction of weight-loss regain. This relationship could contribute to the design of more personalized nutritional treatments in obese patients and favor the weight maintenance process. |
/**
* @desc collects groups of concurrent items in the offset range
*/
QList< QLinkedList<QxtScheduleInternalItem *> > QxtScheduleViewPrivate::findConcurrentItems(const int from, const int to) const
{
QList< QLinkedList<QxtScheduleInternalItem *> > allConcurrentItems;
QList<QxtScheduleInternalItem *> allItemsSorted = m_Items;
if(m_Items.size() == 0)
return allConcurrentItems;
qSort(allItemsSorted.begin(), allItemsSorted.end(), qxtScheduleItemLessThan);
int startItem = 0;
int endItem = allItemsSorted.size() - 1;
for (int i = 0; i < allItemsSorted.size(); i++)
{
if (i > 0)
{
if (!(allItemsSorted.at(i - 1)->visualEndTableOffset() >= allItemsSorted.at(i)->visualStartTableOffset()
&& allItemsSorted.at(i - 1)->visualStartTableOffset() <= allItemsSorted.at(i)->visualEndTableOffset()))
startItem = i;
}
if (allItemsSorted.at(i)->visualEndTableOffset() >= from && allItemsSorted.at(i)->visualStartTableOffset() <= to)
break;
}
for (int i = allItemsSorted.size() - 1; i >= 0 ; i--)
{
if (i < allItemsSorted.size() - 1)
{
if (!(allItemsSorted.at(i + 1)->visualEndTableOffset() >= allItemsSorted.at(i)->visualStartTableOffset()
&& allItemsSorted.at(i + 1)->visualStartTableOffset() <= allItemsSorted.at(i)->visualEndTableOffset()))
endItem = i;
}
if (allItemsSorted.at(i)->visualEndTableOffset() >= from && allItemsSorted.at(i)->visualStartTableOffset() <= to)
break;
}
int startOffset = allItemsSorted.at(startItem)->visualStartTableOffset();
int endOffset = allItemsSorted.at(endItem)->visualEndTableOffset();
QLinkedList<QxtScheduleInternalItem *> concurrentItems;
for (int iAllItemLoop = startItem; iAllItemLoop <= endItem; iAllItemLoop++)
{
int tempStartOffset = allItemsSorted.at(iAllItemLoop)->visualStartTableOffset();
int tempEndOffset = allItemsSorted.at(iAllItemLoop)->visualEndTableOffset();
if (tempEndOffset >= startOffset && tempStartOffset <= endOffset)
{
if (concurrentItems.size() >= 1)
{
bool bAppend = false;
for (QLinkedList<QxtScheduleInternalItem *>::iterator it = concurrentItems.begin(); it != concurrentItems.end(); ++it)
{
int lastStartOffset = (*it)->visualStartTableOffset();
int lastEndOffset = (*it)->visualEndTableOffset();
if (tempEndOffset >= lastStartOffset && tempStartOffset <= lastEndOffset)
{
bAppend = true;
break;
}
}
if (bAppend)
{
concurrentItems.append(allItemsSorted.at(iAllItemLoop));
}
else
{
allConcurrentItems.append(concurrentItems);
concurrentItems.clear();
concurrentItems.append(allItemsSorted.at(iAllItemLoop));
}
}
else
concurrentItems.append(allItemsSorted.at(iAllItemLoop));
if (tempStartOffset < startOffset)
startOffset = tempStartOffset;
if (tempEndOffset > endOffset)
endOffset = tempEndOffset;
}
}
if (concurrentItems.size() > 0)
allConcurrentItems.append(concurrentItems);
return allConcurrentItems;
} |
// cleanRemote Deleting file on the server
func (c SshClient) cleanRemote(remotePath string) (err error) {
ftp, err := c.NewSftp()
if err != nil {
return err
}
defer func(ftp *sftp.Client) {
err := ftp.Close()
if err != nil {
pterm.FgRed.Println(err)
}
}(ftp)
err = ftp.Remove(remotePath)
return err
} |
/**
* @module adaptive-expressions
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Type of quantifier for expanding trigger expressions.
*/
export declare enum QuantifierType {
/**
* Within a clause, duplicate any predicate with variable for each possible binding.
*/
all = "all",
/**
* Create a new clause for each possible binding of variable.
*/
any = "any"
}
/**
* Quantifier for allowing runtime expansion of expressions.
*/
export declare class Quantifier {
readonly variable: string;
readonly type: QuantifierType;
readonly bindings: string[];
/**
* Initializes a new instance of the `Quantifier` class.
* @param variable Name of variable to replace.
* @param type Type of quantifier.
* @param bindings Possible bindings for variable.
*/
constructor(variable: string, type: QuantifierType, bindings: string[]);
/**
* Returns a string that represents the quantifier.
*/
toString(): string;
}
//# sourceMappingURL=quantifier.d.ts.map |
British media have censored the death of hundreds of people who have lost their lives in the Grenfell Tower fire in west London, a local resident has said.
The more than 500 people unaccounted from Grenfell Tower fire are dead, Nadia, whose family name was not given, told Press TV.
London Police Commander Stuart Cundy told reporters on Saturday that 58 people are feared dead in the fire.
According to reports, however, the building was home to about 600 people.
Nadia told Press TV's correspondent in London, Camilia Shambayati, that only 76 out of some 600 people who were living in the building where she grew up, had been accounted for and more than 500 residents were still missing.
Nadia has identified herself on social media as DJ Isla where she has a large following.
"Where are the missing people? Where is the list of the 500, 600 people living in that building," she asked.
"Where is everyone," she further asked, adding, "Little kids are asking: 'Where are my friends?'"
She insisted that the missing residents had all died and the UK media, particularly BBC, had censored the news.
"Everyone has died and no one is telling them," she said, adding that, "the news can't pick it up" referring to the alleged media blackout of the fatalities.
The charred remains of the Grenfell Tower in Kensington, west London, on June 17, following the June 14 fire at the residential building. (Photo by AFP)
On Wednesday June 14, a massive fire erupted at London’s Grenfell Tower.
The building is a 24-story, 67-meter high tower block with 120 separate apartments in North Kensington, west London.
The cause of the fire, where many of the residents were Muslims, is not yet known and the deadly incident is under investigation. |
/**
* Class representing a text plugin definition.
*
* format_mask_examples is optional, but all other fields are mandatory
*
* All ArrayList fields should contain the same number of elements
*/
public final class TextPluginDefinition extends PluginDefinition {
/**
* List of format masks provided by the plugin, each in the format %m
*/
public ArrayList<String> format_masks;
/**
* Description of format masks provided by the plugin, to be presented to user iun the format mask editor dialog
*/
public ArrayList<String> format_mask_descriptions;
/**
* Optional: initial value for each format mask, to be used by Canvas if no data has been received yet for each mask
*/
public ArrayList<String> format_mask_examples;
/**
* Default format string to be populated in Canvas editor when the user creates a layer using this plugin.
* May use more than one format mask and static text, e.g. "SMS: %S Missed: %M"
*/
public String default_format_string;
} |
// Dir checks the given path, will return error if path not exists or path
// is not directory.
func Dir(path string) error {
if info, err := os.Stat(path); err != nil {
return fmt.Errorf(`directory not exists: %s`, path)
} else if !info.IsDir() {
return fmt.Errorf(`path is not directory: %s`, path)
}
return nil
} |
def create_input(density: list, velocity: list, solid: list, cmap="", qcolor="", filename=""):
if not cmap: cmap = "None"
text = f"colormap={cmap}\n"
if not cmap: cmap = "None"
text += f"quiver={qcolor}\n"
text += f"density={len(density)}\n"
for den in density:
text += f"{den}\n"
text += f"velocity={len(velocity)}\n"
for vel in velocity:
text += f"{vel}\n"
text += f"solid={len(solid)}\n"
for sol in solid:
text += f"{sol}\n"
text = text[:-1]
file = open("Config/" + filename + ".txt", "w")
file.write(text)
file.close()
print(f"The file has been saved as {filename}.txt in Config folder") |
<filename>packages/lesswrong/server/indexUtil.ts
import { expectedIndexes, isUnbackedCollection } from '../lib/collectionUtils';
import { getCollection, getAllCollections } from '../lib/vulcan-lib/getCollection';
import * as _ from 'underscore';
function indexesMatch(indexA: any, indexB: any)
{
return (_.isEqual(indexA.key, indexB.key)
&& _.isEqual(_.keys(indexA.key), _.keys(indexB.key))
&& _.isEqual(indexA.partialFilterExpression, indexB.partialFilterExpression));
}
function isUnrecognizedIndex(collection: CollectionBase<any>, index: any)
{
let expectedIndexesForCollection = expectedIndexes[collection.collectionName]
if (!expectedIndexesForCollection)
return true;
if (index.name === '_id_')
return false;
for(let i=0; i<expectedIndexesForCollection.length; i++)
{
if (indexesMatch(expectedIndexesForCollection[i], index))
return false;
}
return true;
}
// Return a list of indexes that don't correspond to an ensureIndex call
export async function getUnrecognizedIndexes()
{
let unrecognizedIndexes: Array<any> = [];
for(let collection of getAllCollections())
{
try {
if (isUnbackedCollection(collection))
continue;
let indexes = await collection.rawCollection().indexes();
indexes.forEach((index: any) => {
if (isUnrecognizedIndex(collection, index)) {
unrecognizedIndexes.push({
collectionName: collection.collectionName,
index: index,
});
}
})
} catch(e) {
//eslint-disable-next-line no-console
console.error(e)
}
}
return unrecognizedIndexes;
}
function isMissingIndex(index: any, actualIndexes: any[])
{
for (let actualIndex of actualIndexes)
{
if (indexesMatch(index, actualIndex))
return false;
}
return true;
}
// Return a list of indexes for which an ensureIndex call was made, but the
// index isn't in the database. (This can happen if the collection has more
// than the 64 maximum indexes, or its specification is malformed in some way
// that prevents it from being created.)
export async function getMissingIndexes()
{
let missingIndexes: Array<any> = [];
for (let collectionName in expectedIndexes)
{
let collection = getCollection(collectionName as CollectionNameString);
if (!collection || isUnbackedCollection(collection))
continue;
let indexes = await collection.rawCollection().indexes();
for (let expectedIndex of expectedIndexes[collectionName]) {
if (isMissingIndex(expectedIndex, indexes)) {
missingIndexes.push({
collectionName: collectionName,
index: expectedIndex
});
}
}
}
return missingIndexes;
}
|
Measurement of Mechanical Properties of Cantilever Shaped Materials
Microcantilevers were first introduced as imaging probes in Atomic Force Microscopy (AFM) due to their extremely high sensitivity in measuring surface forces. The versatility of these probes, however, allows the sensing and measurement of a host of mechanical properties of various materials. Sensor parameters such as resonance frequency, quality factor, amplitude of vibration and bending due to a differential stress can all be simultaneously determined for a cantilever. When measuring the mechanical properties of materials, identifying and discerning the most influential parameters responsible for the observed changes in the cantilever response are important. We will, therefore, discuss the effects of various force fields such as those induced by mass loading, residual stress, internal friction of the material, and other changes in the mechanical properties of the microcantilevers. Methods to measure variations in temperature, pressure, or molecular adsorption of water molecules are also discussed. Often these effects occur simultaneously, increasing the number of parameters that need to be concurrently measured to ensure the reliability of the sensors. We therefore systematically investigate the geometric and environmental effects on cantilever measurements including the chemical nature of the underlying interactions. To address the geometric effects we have considered cantilevers with a rectangular or circular cross section. The chemical nature is addressed by using cantilevers fabricated with metals and/or dielectrics. Selective chemical etching, swelling or changes in Young's modulus of the surface were investigated by means of polymeric and inorganic coatings. Finally to address the effect of the environment in which the cantilever operates, the Knudsen number was determined to characterize the molecule-cantilever collisions. Also bimaterial cantilevers with high thermal sensitivity were used to discern the effect of temperature variations. When appropriate, we use continuum mechanics, which is justified according to the ratio between the cantilever thickness and the grain size of the materials. We will also address other potential applications such as the ageing process of nuclear materials, building materials, and optical fibers, which can be investigated by monitoring their mechanical changes with time. In summary, by virtue of the dynamic response of a miniaturized cantilever shaped material, we present useful measurements of the associated elastic properties.
Introduction
Microcantilevers were first designed and fabricated for use as force sensors. Possessing an extremely high force sensitivity, in the piconewton (pN) range, the cantilevers have made Atomic Force Microscopy (AFM) universally recognized not only as a versatile microscopy technique with high spatial resolution, but also as a powerful tool for measuring the forces between surfaces. Using conventional micromachining techniques it is possible to fabricate cantilevers with desired spring constants, and therefore, force sensitivity. Availability of inexpensive, mass-produced cantilevers also triggered applications other than imaging, where cantilevers act as physical, chemical, and biological sensors. It has been observed that the bending of a cantilever is influenced by ambient conditions such as relative humidity and temperature. In 1994, researchers reported a novel exploitation of these undesirable effects in imaging applications and laid the basis for the development of highly sensitive sensors for vapor adsorption and measurement of changes in temperature . These early observations later lead to the development of a unique family of mechanical sensors with numerous new applications in physical, chemical and biological sensing. The miniature size and the simple structure of a cantilever, together with its ability to operate in different ambient conditions such as liquids, gases, and vacuum, make the cantilever a versatile sensor platform. Since the cantilevers can also be modified to detect electromagnetic fields and forces, they find applications in many aspects of physical sensing.
A cantilever sensor can be operated in two different modes: the static mode, where the cantilever deflection is monitored, and the dynamic mode, where the cantilever resonance is monitored. The deflection of a cantilever can be due to number of processes such as molecular adsorption, thermal effects, electric and magnetic fields, and fluid flow. Adsorption-induced deflections are attributed to changes in the surface free energy and are observed only when a differential adsorption occurs between the cantilever surfaces. Depending on the mode of operation, several methods for reading the movement of a cantilever have been developed. These readout techniques can be applied to a single cantilever or to arrays of cantilevers.
One of the first applications of the microcantilever was in sensitive mass balance measurements, where it served as a micro resonator. As a result, a mass resolution in the picogram range was achieved , which outperformed the thermogravimetric approaches by five orders of magnitude. Cantilevers shorter than 10 µm in length with sub-attogram sensitivity were demonstrated in 2004 , enabling the detection of single virus particles of femtogram mass . Optimization results in an increase of the Q-factor of the nanoresonators , and values as high as 10,000 can be achieved. The use of higher order modes for short cantilevers is also critical. Operation at frequencies as high as 1.5 MHz enables a theoretical mass resolution of approximately 20 ag/Hz .
Based upon the simultaneous measurements of bending and resonance frequency, a miniature magnetic force balance was developed by Finot et al. to measure the magnetic susceptibility of nanogram quantities of powders . Here the cantilever with nanogram amount of magnetic material acts as a Faraday balance.
Applications of microcantilevers as label free b iological and chemical sensors have been demonstrated by many groups. Good overviews of the early work have been written by Raiteri and Thundat . More recent works have been covered by Lavrik and others . Briefly, when the molecular adsorption is confined to a single surface of a microcantilever, the molecular interactions can be studied by: (i) noting a shift in the resonance frequency and (ii) monitoring the bending. The latter offers an advantage over other acoustic sensors (QCM, SAW) by providing an additional measurable physical quantity: the surface stress caused by the forces involved in the adsorption process. In molecular recognition experiments using an array of cantilevers, adsorption enhancement is achieved by coating each cantilever sensor with a different sensitive layer allowing the array-device to operate as an artificial chemical nose .
Microcantilevers were also found to be particularly suitable for the chemical sensing of vapours and gases . Hydrogen, for example, can be detected by its adsorption on a Platinum-coated sensor . Likewise, hydrogen fluoride can be detected using a silica microcantilever both in liquid phase at femtomolar concentrations and in gas phase . Other examples include the detection of various alcohols using polymers such as PMMA or PDMS and quantification of individual components in a gas mixture . Quantitative measurements of the concentration of metal ions in aqueous solutions down to 10-10 M using ion-selective SAM-modified microcantilevers , as well as the measurement of pH values of solutions with a sensitivity of around 50 nm deflection per pH unit 10 have also been achieved.
Another application, where the use of microcantilevers has not been fully exploited, is the study of mechanical properties of materials. Microcantilevers have proven to be powerful tools for the investigation of the mechanical properties of microsystems that is otherwise unattainable, or not easily achievable by other more macroscopic approaches . A variety of methods already exist for the measurement of the elastic properties of thin films. Well-established measurement techniques for the properties of macrostructures include ultrasound , rheology , and tribology . Ultrasonic wave techniques require centimetre-sized samples, which do not ensure the sample homogeneity. Techniques based on the nanoindentation of the sample surface can accurately measure the local surface stiffness, but not the bulk mechanical properties. A review of the existing methods indicates that the conventional techniques are not readily suitable for in-situ investigations of micrometer-sized sample volumes and therefore, the determination of these parameters in the field of microtechnology remains quite difficult.
The determination of physical parameters is of significant interest for optimizing the design of mechanical structures. The accurate measurement of mechanical properties is contingent upon a rigorous understanding of the length scale dependence. The natural length scale will depend on such structural features of the material as the average grain size, and the dislocation length. To further classify the material properties, one may distinguish the "thin" microstructure, with length scales below a grain size, from a "thick" microstructure or a macrostructure, with length scales encompassing many grains.
In order to optimize the performance of the meso and macro-scale devices, material engineers have recognized the need for a better understanding of the processes in the micro-domain. Such optimization efforts require similar investigations of the mechanical properties at the nanoscale. Five parameters are usually used to characterize the mechanical response of the material: The Young modulus (E) is the primary measure of the stiffness of the material. It is defined for small strains (e) as the rate of change of stress (s) with strain, that is, E = σ/ ε. Stress can be induced thermally in thin film multilayer structures due to the difference in the thermal expansion coefficients between the adjacent layers, or because the structures are subjected to temperature changes during their manufacturing and subsequent use.
The Poisson ratio (ν) is the ratio between the transverse strain (contraction normal to the applied load) and the axial strain (extension).
The yield strength (σ Y ) corresponds to the stress at which the material gets plastically deformed. It depends on the rate of deformation (strain rate) and, more significantly on the temperature T and the microstructure (grain size).
The fracture strength (σ F ) is the stress leading to the beginning of fracture. The residual stress (σ R ), which is often neglected , but can also lead to the bending and buckling. It is characterized by two quantities: its magnitude (σ R ) and its gradient ∇(σ R ).
For thin mechanical structures, the elastic (E, ν? ) or inelastic response (s ? ? ) play a major role. The viscoelastic properties of silicon microcantilevers can usually be avoided. However, amorphous solids such as glass, polymers can be characterized with a viscosity η (10 18-21 Pa.s for glass) in the plastic regime. The viscosity is defined mathematically as the ratio of the shearing stress to the velocity gradient in the material, i.e., the material's resistance to flow.
Continued miniaturization of mechanical structures will lead to increased influence of surface stress , and these effects have found applications in, for example, electrochemistry , and actuators , among others. In resonance frequency measurements, often changes in the surface stress, for instance induced by adsorption or/and a viscous environment , can give rise to a noticeable change in the spring constant resulting in a miscalculation of the mass loading. Quantum mechanical calculations show that, in a viscous solution, the frequency shift of the nanoscale cantilever can be determined from the change in the surface stress that is generated by the biomolecular interaction with negligible contributions from the ensuing mass loading by the bio molecules . A general scaling law connecting the stiffness and dissipative properties of a linear mechanical oscillator immersed in a viscous fluid has been derived .
While, many mechanical properties of macrostructures may exist in handbooks, as shown in Table 1, there is still no database for thin structures. For instance, Young's modulus of amorphous silicon differs largely from the single-crystal phase (400 GPa). Unlike other mechanical oscillators, an advantage of the cantilever may be that it is not limited to only one type of material. For example, fabrication of SAW devices is restricted to piezoelectric substrates. Silicon was initially the material of choice in the microfabricated devices because of its favorable electrical and mechanical properties, enabling inexpensive, batch-fabricated, high-performance sensors and transducers that could be easily interfaced with advanced microelectronics .
Recently polymers have been applied in the fabrication of microdevices because of their desirable properties (e.g. biocompatibility and cost) . Cantilevers can be fabricated using the polymer SU-8, thereby providing the sensors with very high sensitivity due to convenient mechanical material properties . The fabrication process for polymer cantilevers is based on spin coating of the photosensitive polymers and near-ultraviolet lithography , allowing well-controlled and uniform mechanical properties for the cantilevers. The elastic constants of such cantilevers have been measured, and their dynamic response has been studied .
Other materials used in cantilever and micromechanical oscillator fabrication include, glass or amorphous carbon (ta-C) , suitable for the study of mechanical dissipation mechanisms in such materials . Exotic materials such as cement , wood and rubber have also been investigated using cantilevers.
Microfabrication techniques for cantilevers can be categorized into surface or bulk micromachining, which are based on IC manufacturing technologies. Surface micromachining is an additive process, which consists of fabricating micromechanical structures from deposited thin films, such as silicon nitride, polycrystalline silicon and other materials . Bulk micromachining, such as laser lithography or focused ion beam is a subtractive process that uses the selective removal of significant amounts of silicon, or other materials, from a substrate to form microstructures.
Here we review our recent research on the measurement of the mechanical properties of cantilever shaped materials. First, we present the advantage of the small size of the cantilever real-time, in-situ measurement of their mechanical properties. Then, we will introduce the necessary theoretical background of the elastic and inelastic parameters for discerning the bulk and surface mechanical properties. We also discuss the limitations of the continuum mechanics as well as the effect of the environment such as the pressure and the temperature. Finally, we will discuss applications in various areas such as the ageing process in nuclear plant, the setting of cement or the etching or swelling of coatings.
In situ measurements
One of the underutilized capabilities of a microcantilever is its ability to carry out in-situ measurements of mechanical properties. Here we will begin with a description of the experimental setup used for carrying out such measurements. Due to its micrometric size, the cantilever can easily be inserted into or integrated with a small vessel or cell.
Static Measurements
For static gas measurements, a prior vacuum is often required. A special cell holding the cantilever can be designed easily in the laboratory to withstand pressures ranging from a secondary vacuum to almost 15 bar . The cell made of aluminium alloy ( Figure 1, A-B) has a low mass of about 1 g and a small internal volume of 0.5 cm 3 . The pumping, achieved using a primary pump in conjunction with a turbo molecular pump, permits achieving pressures down to 10 -8 bar at the input of the capillary tube. Heating of the cantilever is achieved electrically using wires wrapped around the cell with a proper temperature calibration. Such a setup permits the isolation of the cell from the pumping system. Vapors can be introduced into the system using a liquid tube connected to the vacuum cell. The vapor, emanating from a small amount of liquid kept at room temperature in a tube, expands throughout the enclosed volume of the cantilever cell.
Dynamic Measurements
For dynamic gas measurements, a control of the gas flow is required (Figure 1, C-D), C-D) . The gas molecules to be detected are first concentrated in a tank compressed at a pressure of around 100 bars and then diluted using a carrier gas. Automated mass flow controllers (MFC) coupled with solenoid valves allow monitoring and mixing the gas flow. The ratio between the gas flow rate V gas at the tank output and the total flow rate V=V gas + V carrier defines the gas concentration C at the inlet of the measurement cell. In dynamics, the time t dyn to complete the adsorption process can be regulated using the flow rate V : where, W could be viewed as the adsorption capacity of the cantilever (molecules/µm 2 ), C is the vapor inlet concentration (molecules/liters), and S the active surface area of the cantilever. On a bare silicon cantilever, a SiO 2 surface, the gas molecule binds to the Si-OH groups through two or three hydrogen bonds. Assuming about 8 Si-OH groups/nm 2 , the estimated gas adsorption capacity is around 3 molecules/nm 2 , or 3x10 6 molecules/µm 2 . For controlling the adsorption rate, t dyn should be faster than the time governed by thermodynamic adsorption. Basically, for an adsorption of 1 ppm of gas, V must be higher than 1 L/min. The flow rate can then be maintained constant at 15 mL/min during experiments. Higher flow rates could cause turbulence, or unsteady cantilever vibrations .
Measurements in Liquids
In liquids, the injection is usually performed using a cell of small volume (around 1 mL) using a syringe (Figure 1 E) associated eventually with a closed loop flow. A low flow of around 1mL/min is usually used . In liquids, cantilevers can also be directly integrated with conventional micro fluidic systems . Stereolithography has been recently used to fabricate 3D and high aspect ratio microstructures for microfluidics. The advantage is to eliminate the dead volume of the reaction chamber and to decrease the assembly time . Microsystems comprising a multiplexed array of 20 silicon microcantilevers and a polymer microfluidic system for delivery of the samples was developed for nucleic acid hybridization detection . Due to the small volume of the chamber, diffusion needs to be taken into account in the adsorption kinetics . Another advantage of microfluidics is the ability to accelerate the chemical reactions by a factor of 20 µL allowing the capability of handling concentrations of 100nM .
The cantilever response can be read out by several methods depending on the static or dynamic mode of operation but also on the spring constant of the cantilever. The cantilever deflection can be easily measured using a position sensitive detector (PSD) monitoring the reflection of a laser beam from the cantilever. The cantilever curvature can also be obtained optically with subnanometer resolution with a processing speed of about ten cantilevers per second .
For cantilevers with low spring constants, the dynamic response, i.e., the resonance frequency f and the quality factor Q of the resonance peak, can be obtained from the vibrational noise spectrum obtained with a spectrum analyzer. The effective spring constant of cantilevers may be determined using thermal noise driven resonance frequency. The amplitude and the width of the thermal noise peak are also in agreement with the integrated noise energy of the oscillator of around k B T.
For cantilevers with higher spring constants, when the deflection is not easily detectable, the cantilever can be excited mechanically (using a piezoelectric transducer ), magnetically , or electrostatically . In certain cases, due to potential reactions with aggressive gases, piezoelectric transducers used for the excitation of the cantilever must be placed outside the measuring cell. The signal from the reader is sent to a lock-in amplifier for analysis.
Elastic parameters
The elastic parameters, Young's modulus E and Poisson's ratio? ν? are difficult to dissociate experimentally from the reduced Young's modulus E* given by:
Static approach using single material cantilevers
In the static mode, E* can be deduced from a measurement of the cantilever's spring constant (k) by applying a force F at the end of the cantilever and measuring the corresponding deflection ∆z. k o must be corrected if F is not exactly located at the end of the cantilever but at a distance l from the end. We therefore have: where, L is the cantilever length. The shape of the cross-section of the cantilever ( Figure 2) is described by the moment of inertia I. Denoting the cylinder radius with R, the cantilever width with b, and the cantilever thickness with h, we have :
Cylindrical beam
Rectangular beam V-shaped cantilever The uncertainty in the evaluation of the Young modulus increases with the complexity of the system. Errors of 3-5% have been found for cylindrical cantilevers, whereas using a simplified model to describe the V-shaped cantilevers, results in 25% uncertainty . The accurate metrology of the geometric parameters of cantilevers, especially with respect to thickness measurements, is known to be hard. Actually, k cannot be determined easily with less than 10% uncertainty for complex geometries . The best approach is offered by a Finite Element Analysis . The preceding equations assume perfectly rigid support behavior and are valid in the small deformation regime. Both these assumptions can be easily violated in many microscale tests, and numerical analyses using finite-element techniques, which solves the necessary equations beyond the small deformation limit, are necessary to interpret the data.
Static approach for a bilayer cantilever
Bilayer cantilevers, e.g., those with a coating, also appear to be promising for the determination of the Young modulus of the coating . The bilayer cantilever can be considered as two springs in parallel.
where E f and hf are the effective Young modulus and the thickness of the film, respectively. Figure 3 shows the effect of the film deposition on the spring constant of a cantilever. For a soft coating, such as used in biosensors, the spring constant of the cantilever does not undergo any measurable changes during the adsorption (less than 0.1%). On the contrary for inorganic coatings having E f > 1 GPa, a subsequent change above 0.1% can be detected even for ultra thin films.
Dynamic approach for single material cantilevers
The second method used to determine the Young modulus is the mechanical tuning method. The resonance frequencies of a micromachined cantilever has been extensively employed in the determination of the elastic modulus 103 of thin films .
The equation governing the cantilever motion, that is, the time dependent deflection z at a point x along the cantilever of length L, mass m, and spring constant k, is given by: The corresponding eigenfrequencies are given by: where n=0,1,2,… As a first approach, the problem may be approximated using a simple mechanical harmonic oscillator with the frequency: From a measurement of the fundamental mode and depending on the cantilever geometry, the effective Young modulus can be determined. Both changes in the spring constant k and the effective mass m of the cantilever must be considered. A geometrical correction factor is used to account for the fact that, in the simplified model, the cantilever mass is not distributed. Equivalent mass and Young's modulus for cantilevers of most common geometries are summarized below.
Cylindrical beam
Rectangular beam V-shaped cantilever Effective mass Effective Young's modulus Determination of resonance frequencies of small cantilevers seems to be the most suitable way for estimating the Young modulus. This is particularly useful since, signals measured in frequency domain often display sharp peaks allowing for very small frequency shifts to be measured. But as the cantilever dynamics is very sensitive to the environmental conditions, the measurements are preferably performed in a vacuum chamber. The accuracy of the measurements may further be studied by the use of eigenmodes of higher frequencies.
The experimental procedure is based on the periodic excitation of the fixed end of the cantilever and the detection of its natural resonance frequency f. Measuring f and assuming known sample geometry and density permit therefore a determination of the mechanical properties. shows a typical frequency spectrum obtained for a rectangular cantilever under vacuum. The resonance frequencies are well described by the eigenmodes; the first mode is accurately calculated, whereas the following modes are systematically underestimated ( Table 2). Note that the first eigenmodes of the cylindrical cantilevers are more accurate and the discrepancy between the results decreases with increasing number of modes n. Although the vibration energy of the cantilever is less for the second mode than for the first mode, the bending angle is larger at the cantilever end and therefore more easily detectable by an optical method. hod operating in the MHz range. Table 3 shows that cantilever measurement of the sound velocities for various metals yields values that do not exceed the well established ultrasonic values by more than 5%. The method is then reliable even if all cantilever results appear to be underestimated compared to the ultrasonic method operating in the MHz range.
Dynamic approach using bilayer cantilevers
If we consider a bilayer rectangular beam, the effective Young modulus of the film E f can be obtained from the eigenfrequencies of the uncoated (f) and the coated cantilever (f f ).
The effective mass density of the bilayer cantilever is given by: Changes in the cantilever mass as a function of the coating thickness are shown for various materials in 12 As shown in Fig 5, for the bioadsorption, changes in the resonance frequency are essentially related to changes in the cantilever mass. For inorganic coatings or polymer films, the frequency is governed by both mechanical and mass changes. The mechanical properties become predominant for metals. Therefore, microcantilevers can be used to measure the Young modulus of metals. In this case, the first approximation of the cantilever as a spring (simple harmonic oscillator) can be refined when considering the residual stress.
Poisson ratio
The Poisson ratio ν of a thin material is a very important quantity for stress analysis and structural dynamics. However, thus far, the determination of this parameter remains difficult.
The Poisson ratio is a function of the Young modulus E and the shear modulus G according to: The shear modulus G can be calculated from a measurement of the natural frequency of the first torsional mode f T of a rectangular cantilever using: ( ) The Poisson ratio must be considered for the flexural frequencies of relatively large cantilevers (compared to the cantilever length).
The flexural frequency is in direct proportion to the elastic parameters following the equation where D is a correction factor which depends on the width b to length ratio κ = b/L and ν. C is expressed as: Note that in the major cases where L >> b, D remains close to 1. Continuum mechanics is applicable if the resonance frequency f normalized by L 2 varies linearly with the cantilever thickness h without a characteristic discontinuity. The 1/L 2 dependence of the resonance frequency f ( Figure 6) reveals a nonlinear behavior for shorter cantilever lengths. For L < 9 mm, a correction factor C involved in Eq. (25) must be considered to fit all of the experimental points with a Poisson ratio of ν=0. 3.
As the effect of geometrical parameters on the results is of great importance, only results obtained in the linear behavior in f, i.e., for long cantilevers, the curve slope corresponds to the acoustic speed (E/ρ) 1/2 .
Inelastic parameters
This section is devoted to the measurement of the inelastic parameters of materials using cantilevers. We will first consider the effect of residual stress in simple or bimaterial cantilevers. When the cantilever becomes relatively thin compared to the cantilever length and when the cantilever coating is a monolayer, the surface stress must be considered. Anelastic behavior and fracture strength are also discussed.
Residual stress and yield strength
Residual stress is a tension or compression, which exists in the bulk of a material without application of any external loads. The residual stress can vary from -500 MPa to 500 MPa.
The main factor that causes this stress is the grain boundary rather than the grain size. Two kinds of residual stress are therefore usually defined: the macro stress corresponds to the behavior of few grains whereas the micro stress deals with sub-microscopic areas, within a grain.
Residual stress may be created during the manufacturing process of a material, or it may accumulate in a structure over many years in operation. In either case, this stress can have a serious negative effect on a product's quality, durability and lifetime. Accurate detection of residual stress is an important element of the quality control process and helps predict the service lifetime of the product .
To illustrate, we note that the residual stress depends strongly on the film thickness: the highest compressive stress is created in the first 200 nm of a deposited film and the stress is relaxed significantly if the film gets thicker than 350 nm. A structure with many crystal defects can also generate a stress, which can be minimized by annealing. At high temperatures, the atoms can rearrange themselves, thus the number of crystal defects decreases, thereby reducing the stress. Generally, compressive residual stress is benefic for the fatigue life since it delays crack initiation and propagation. Tensile stress on the contrary reduces the mechanical performance of materials. Such phenomena can be at the origin of the observed asymmetric oscillations of coated cantilevers. The residual stress can be represented by a uniform stress s R and a gradient stress. The uniform residual stress is relieved though the free end of a single material cantilever. This component can be measured using a bilayer cantilever, in which the residual strains in the two materials are different leading to a bending moment. The bilayer cantilever is usually bent by several micrometers, corresponding to a radius of curvature R s given by: where s f is the film's normal stress, E s is the Young modulus of the substrate, h is the cantilever thickness, and h f is the film thickness. 1/R s and 1/R o are respectively, the curvature caused by intrinsic stress after and before the deposition. In two-dimensional film-substrate systems, the film stress s f is deduced by replacing E s with the biaxial modulus E s /(1-ν s ), where ν s is Poisson's ratio of the substrate.
Assuming σ f to be uniform, the radius of curvature R s should be constant. This equation was also applied locally to calculate the film stress point-by-point, when the curvature is not constant. In these cases, the constant curvature 1/ R s is replaced by the local curvature, which depends on the positions of data points and the measured directions. Although the local application of Stoney equation is widely used, its validity cannot be established.
A more realistic approach consists in considering the uniform stress for both the bare cantilever s R and the coated one s Rf . The cantilever will bend but it is still difficult to isolate s R and s Rf. The radius of curvature is given by: The gradual residual stress causes the single material cantilevers to bend. The detection of the bending of single material cantilevers provides then a convenient method to measure the internal stress gradient: The residual stress can be also obtained from the resonance frequency. For a bridge, that is, a beam supported at both ends we have: Cantilevers have been used to determine the yield strength. The limit of validity of the elastic regime for thin films is thickness dependent, especially due to the changes in the microstructures related to the fabrication process. As the thickness is reduced, the yield strength increases with usually a decrease in the grain size. The yield strength appears to be constant for a film thicker than 1 µm (Figure 7). For small-scale structures, the elastic strain gradient should be considered. The rigidity exhibits an inverse squared dependence on the beam's thickness Surface stress Surface stiffness can be viewed, in a top down perspective, as a residual stress near the surface when the thickness of the film tends to zero. This stiffness can arise, for instance, from the surface roughness of the cantilever or some localized mechanical defects . The cantilever can be treated as an effective mass in parallel with two springs, one linked to the bulk properties and the other one to the surface stress.
On the other hand, from a bottom up point of view, the surface stress finds its origin at the molecular scale. It corresponds to the variation of interfacial energy U with respect to the strain e: where U is related to the molecular potential and s l the distance between the surface molecules. The surface stress of a cantilever can be deduced without knowledge of its Young modulus . The measurement of surface stress can be controvertial, specially within dynamical regimes , where adsorption-induced changes in the spring constant may result in errors in the adsorbed mass calculated from shifts in the resonant frequency.
As previously noted, mass effects due to molecular adsorption do not contribute to a significant shift in the resonance frequency. The mass of a monolayer will result in a shift of a few Hz. However, shifts of around 100 Hz for a monolayer have been measured. Such results suggest that molecular interactions somehow affect the resonance frequency. To describe this effect, simultaneous measurements of the resonance frequency and the adsorption-induced cantilever bending have been used to determine the variation in the spring constant. Plotting the change in surface stress as a function of the chemical concentration, the surface excess of adsorbed molecules and, therefore, the mass adsorbed can be determined . Change in the cantilever stiffness were first estimated for antigen-antibody interactions .
The surface stress can be viewed as the sum of two contributions: one is an axial force per unit length and the second is a moment (N.m) per unit cross section. A variation in the moment induces a cantilever bending but not a frequency shift. If the central part of the beam is under compression, the surface must be under tension, and the forces are balanced. No shear stress exists between the bulk and the surface layer, except at the very end.
In a first order approximation, Stoney's equation may be used to estimate the differential stress ∆s from the cantilever deflection ?z given by: where L and h are the length and the thickness of the cantilever, respectively, ν the Poisson ratio, and E is the Young modulus of the substrate. Typical values of surface stress encountered are around 30 mN/m in the case of gas adsorption, 50 mN/m in the case of thiol binding, and 10 mN/m in the case of protein binding. However, inadequate modeling can lead to significant error in the estimation of the surface stress: around 10% in microscopic experiments, whereas for macroscopic cantilevers, the surface stress could be overestimated by a factor of 5 if the mass effect is neglected . The original derivation of Stoney equation was then refined, in order to account for the cantilever shape , and the size for MEMS when the residual strain is not uniform along the thickness of the cantilever.
The effect of surface morphology on the surface stress such as the surface roughness is also controversial. Unlike prior reports that suggest the surface roughness enhances adsorption-induced stress, we observe that nanometer-size roughness may slightly decrease the adsorption kinetics and the associated surface stress .
The changes in the axial force can be used to determine the surface stress by measurements of the resonant frequency . The effect of surface stress on the resonance frequency of a cantilever sensor was modeled analytically by incorporating strain-dependent surface stress terms for pure surface stress and an adsorption-induced surface stress. The effect of the pure surface stress can be considered as negligible. The equation governing the cantilever is modified to introduce the surface tension s s in . It is related to the energy absorbed per cycle of cantilever oscillation. The total losses of the system include those of the lever Q c and those of the accompanying experimental devices Q a . We note that Q a can strongly modify the apparent value of the quality factor Q, which may be obtained in 3 ways: by fitting the vibration amplitude in frequency domain using the following formula: where ω f is the resonance frequency, Z p vertical extension of the piezoelectric crystal and Z c the displacement of the free end of the lever; by the direct use of the resonance peak by measuring its width ∆f at the 1/ 2 of the maximum amplitude and by applying the relation: (40), where n is the index of the n th peak after the lever has been displaced from its equilibrium position to oscillate freely while decaying exponentially back to its equilibrium position through a series of transient oscillations. Typically, Q can vary between 10 and 10000 depending on the nature of the cantilever. The following equation may be considered when distinguishing Q A , the quality factor of the apparatus and Q c , the Q-factor of the cantilever: where K P is the stiffness of the piezoelectric crystal and K c is that of the cantilever, both expressed in N/m. Cantilevers have been used to determine the dependence of the internal friction on temperature in the range between -50 to 150°C. A slight decrease in damping Q -1 indicates the occurrence of a structural rearrangement of the film. Internal friction as low as 10 -5 in micrometer thick metal films in the temperature range 300-800 K has been measured . The dependence of the internal friction on the temperature, the frequency and the thickness of the film provide information on the origin of mechanical losses. The activation energy points to a dragging mechanism of jogs accompanied by vacancy diffusion along the dislocation core. This knowledge becomes important for the design of reliable MEMS devices, especially the cognition of the strength distribution of the structural material. Strength is determined by the distribution of the flaw size (around 100 nm for Si) and hence can be influenced by grain size, microstructure, and etching processes .
When residual stresses are sufficiently large, they can lead to fracture or delamination either after processing or during the application of sub-critical loads. For instance, fracture strength of polysilicon in uniaxial tension could vary between 2.2 and 4.3 GPa, depending upon the details of the fabrication process.
Flexural elements such as cantilevers are naturally concerned with the effects of cyclic loading on material failure . Since Si does not exhibit any dislocation activity at low homologous temperatures, there is little evidence for extrinsic toughening mechanisms observed in some brittle materials. Si should not exhibit fatigue at room temperature. However, fatigue in a polysilicon device has been observed . The resonance frequency of a reversed bending structure was used to monitor crack growth at a notch or precrack. Applied bending stress amplitude was plotted as a function of the cycles to failure to generate fatigue stress-life. While more than 10 8 cycles to failure were observed at a stress amplitude estimated to be 3 GPa, this was reduced to 10 5 cycles at a stress amplitude estimated to be 4 GPa. Environment-assisted cracking of the oxide layer is thought to cause crack growth that ultimately leads to failure. In the presence of aggressive environments, environmentally-accelerated fatigue behavior is important .
Reliability of mechanical measurements
The reliability of the mechanical measurements will depend on both the accuracy of the measurements and the validity of the continuum mechanics. Analysis of the literature shows controversial measurements; for instance, measurements of E using micro cantilevers can vary over a broad range from 150 GPa up to 290 GPa . The frequency f can be determined with an accuracy of 0.01%. The cantilever geometry is usually determined by scanning electron microscopy (SEM). Among the current experimental calibration methods for measuring k, none appears to be superior to the others. The thermal fluctuation method can be viewed as simple but the effect of interference with other noise sources is usually ignored . The mass attachment does not need the cantilever geometry to be known but can be destructive. Measurement of k from the resonance frequency is the simplest method which is only valid for rectangular beams, k is strongly dependent on the thin cantilever thickness. The use of another reference spring in contact with the microcantilever appears to be the most appealing method , although delicate and time-consuming to set up. A new method based on micro drop evaporation was proposed for the determination of the spring constant .
The model for calculating Young's modulus presupposes an isotropic material with a constant thickness, no surface roughness, and no texture effects. These effects may cause a mean variation in the measured signals. Laser acoustic methods are insensitive to microscopic methods such as nanoindentation or microcantilevers.
A large difference in the measurement of the Young modulus for sprayed coatings was found for the cases of tension and compression, which was explained in terms of microcracks . The most common error in the measurement of these properties comes from the boundary between the cantilever and the rigid support. Details of the compliance of the support should be taken into account.
It was necessary to experimentally confirm the influence of the dimensions of the cantilevers on their fundamental frequency of resonance f 0 . The thinner the cantilever, the more important the effects of surface and size. The limiting factors below which the macroscopic theory is no longer valid were determined. The theoretical frequencies were compared with the frequencies measured in experiments using rectangular cantilevers of thicknesses varying from 3 to 250 µm. The widths b and the lengths L were chosen so that L b <0.2. The variations of the theoretical frequency are deferred according to the thickness h of the cantilever used. This variation with the value of reference is 10% for h = 3 µm and decreases with increasing thickness except for a key thickness (20 µm in this case) that can be correlated with the microstructure of the material: the average size of the grain is 500 nm; the bigger grains, of a size of 1.5 µm, account for approximately 5% of the total quantity of grains. The instantaneous frequency deviations according to the thickness of the cantilevers and the material microstructure converge towards the same conclusion.
To apply the mechanics of the continuous media require that the smallest dimension of the sample, in fact the thickness of the cantilevers, is at least 20-fold larger than the larger characteristic dimension of material, that is to say the grain size for a polycrystalline solid. Variation of the reference resonance frequency remained lower than 2% as long as h>20 µm, a value corresponding to a ratio of approximately 20 between the thickness and the largest characteristic dimension, given by the grain size. Measuring the bulk mechanical properties correctly will imply, thereafter, to choose a cantilever thicker than 20 µm.
The nonlinear response of a cantilever at large deflections is sometimes also overlooked. A general study of cantilever beam nonlinearity under a variety of loading conditions was performed with analytical and finite element analyses. The cantilever nonlinearity was found to increase with increasing cantilever deflection. The linear analysis was found to underestimate the applied load by up to 15% .
Measurement of the environmental properties of cantilevers
Variations in the environmental parameters of the cantilever, namely the change in temperature and the pressure surrounding the cantilever can strongly affect the cantilever response compared to its behavior in high ultra vacuum.
Temperature
The double-layer microcantilevers are very sensitive to the variations in temperature because of the "bimetallic" effect in connection with the difference between the thermal dilation coefficients of various materials. The cantilever deflection becomes then extremely sensitive to temperature changes. Two temperature modes were distinguished: For small temperature changes ∆T (< 3°C), the deflection ∆z varies linearly with ∆T in agreement with the thermal coefficients of gold a Au or/and the constituent silicon nitride a S of the microcantilever such that: where t s and t au are the thicknesses of silicon nitride and the gold layer, respectively. For higher temperatures, the sensitivity in temperature is attenuated due to non linearity of the cantilever response. In addition to the sensitivity in deflection, the sensitivity S T in frequency of resonance has two origins: first, the sensitivity of the Young modulus of each material with the temperature, and second, the bimetallic effect stretching the layers out, and we have 0 , 22 The temperature sensitivity is thus at the origin of new types of sensors by coupling electrical and thermal measurements: cantilever-type integration of a piezoresistor device for simultaneous sensing of the bending, ramping the temperature, and controlling the temperature cycles. With a mass resolution in the picogram range, this approach can outperform current thermogravimetric methods by five orders of magnitude. Due to its small size, thermal time constants as low as 1 µs can be reached and adjusted via the cantilever geometry and material properties .
Microcantilevers with quantum wells were also fabricated for manipulating, in real-time, the energy states, thus providing photon wavelength tunability. Applications were then found in an effective and rapid change in electron energy levels for photon detection devices, such as InSb microcantilevers and small arrays of GaAs/GaAlAs microcantilever. Uncooled Infrared (IR) radiation detector were then designed at room temperature . Local thermal analysis was then achieved using heated silicon atomic force microscopy probes for a thin film of polystyrene and using tapered optical fibers .
Pressure sensitivity, Knudsen's number, Reynold's number
The pressure effect on microcantilever is clearly visible in the dynamic mode but also in the static mode for both gas and liquid environments. Figure 9. The pressure dependence of the deflection, the Q-factor, and the resonance frequency of the cantilever In gases Various gases, such as helium and nitrogen with pressures between 10 -2 and 10 5 Pa were used to investigate specific molecular properties ( Figure 9). Among the various flow characteristics, the Knudsen number K n is the most significant: Where λ is the mean free path of the gas molecules, b the cantilever width, dg the density of the gas (air=1)? ? σ c the cross section of collision of the molecules.
In the molecular mode, the properties of the gas, considered as rarefied, are difficult to reach by macroscopic parameters like the temperature. If no variation in frequency and temperature is detected, the Q-factor decreases according to: where A 1 is a geometrical constant, R g is the constant of perfect gases, M is the molar mass of the gas and η ? its viscosity, P is the pressure, and f o is the resonance frequency under ultra high vacuum.
In the viscous regime, the intermolecular collisions control mainly the gas properties. The cantilever acceleration is the paramount parameter determining the frequency dependence of the resonance; the increase in the pressure induces the uptake of effective mass of the cantilever. In this mode, the frequency of resonance and the quality factor vary in accordance with: Q decreases in an identical way in the viscous and molecular regimes. The deflection being stable in this regime, the temperature can be considered as constant in this zone.
The transitional regime, suitable for the passage from the molecular mode to the viscous mode, is explained by the equilibrium between the effects of the speed and the inertia. Q is then disturbed, but this zone is especially well described by the signal of deflection. The deflection is thus explained not by an adsorption of helium but primarily by heating effects. In the molecular mode, the cantilever temperature is not necessarily identical to that of the gas molecules at the surface; thermal balance is reached only with the transitional arrangement with a sufficiently strong density of gas molecules. The nitrogen having a thermal conductivity lower than helium causes less cantilever bending confirming the heating effects of the transitional arrangement.
In liquids In liquids, the cantilever motion is damped by a viscous term. The damping can be used to determine the viscosity? ? and the density ? of very small volumes of fluids. The Reynold number is used to account for the geometry of the vibrating cantilever as well as in the description of the viscous properties of the liquid.
The general equation of motion of the cantilever in a medium can be written as: where E is the Young modulus, I is the moment of inertia of the cantilever, x the coordinate along the cantilever, D is the intrinsic damping of the cantilever (internal loss) which can be determined separately under vacuum. D F is the fluid damping coefficient describing the energy loss in the fluid. M 1 is the mass per unit length of the cantilever, M .2 the added mass due to the fluid (mass of fluid moving along with the cantilever per unit length), and z is the cantilever displacement at distance x from the fixed end of the cantilever. The damping due to the viscosity of the fluid is given by: where R e is the Reynold number of the fluid, which depends on the angular frequency ω and is defined as: The solution of the equation of motion is a complex quantity. The angular resonance frequency is given by: where ω r and ω i can be deduced from the measurements of the resonance frequency f and the quality factor Q under liquid according to: Therefore, M 2 and C V can now be written as: 3.52 Initially the cantilever can be calibrated in vacuum or in a fluid with known properties for determining its intrinsic resonance properties. Later the cantilever can be resonated in unknown fluids.
Applications
Cantilevers provide the opportunity to develop a new method for the identification of material damage and/or for the experimental verification appropriate for the evolution of the damage laws . We review here our recent applications in metallurgy such as palladium tritide materials, in buildings materials such as cement, in composite materials such optical fibers, or organic materials. Determination of the ageing process using cantilevers is found to be particularly relevant.
Palladium tritide cantilevers
Palladium cantilevers were used to investigate the issue of the storage of tritium, a radioactive isotope of hydrogen . A good means to store tritium is to form a metal tritiure, PdT 0.6 palladium, thereby ensuring a valuable storage in terms of compactness (7 liters TPN of hydrogen in 9 cm 3 of palladium) and safety (low equilibrium pressure, approximately 50 mbar at room temperature). The performance of this type of device with time, i.e., the ageing process of metal tritiures, requires the determination of the evolution of their physicochemical properties.
Isotopic effect (Hydrogen, Deuterium, Tritium) on Young's modulus
Young's modulus E of the palladium was measured using vibrating cantilevers according to the pressure of hydrogen, deuterium and tritium. In situ measurements enable one to monitor the changes in E of the hydride phase as a function of the stoichiometry x=H/Pd (Figure 10). When the palladium is completely hydrided in ß phase (PdH 0.6 ), a 10% swelling in material volume occurs; E x for the hydride is then obtained from: Where: with f 0 and f x being the resonance frequencies of the Pd and its hydride, respectively. L 0 , r 0 and L x , r x correspond to the length and radius of the cantilevers Pd and its phase hydride, Cantilevers with rectangular and circular cross sections were hydrogenated. The circular cross section was preferred for dynamic analysis since rectangular sections induce irreversible bending by gradients of residual stress generated by the hydrogen insertion differing from one cantilever face to the other.
An isotopic effect ( Figure 11) on the properties of the material was thus established. The change in the Young modulus (E PdH > E PdD > E PdT ) was explained in terms of optical phonons, strongly related to the isotope mass.
Let us consider the radioactive decay of PdT x , helium-3 atoms are produced following the equation where? β is an electron and υ an electronic anti-neutrino. Every 12 years, half of the tritium atoms present in the octahedral sites of palladium is transformed into 3 He . This relatively short time duration is at the origin of a considerable quantity of 3 He (1.5% at the end of three months of ageing). Being very insoluble in Pd; 3 He tends to precipitate forming 3 He nanobulles with a number and a diameter growing with time. The elastic properties of PdT x were monitored with time under a tritium pressure. The ageing process of several microcantilevers enables one to demonstrate that during the first days, the Young modulus of PdT 0.6 increases approximately by 2% before stabilizing after one month . Figure 11. Resonance frequency peaks of a cylindrical palladium cantilever under vacuum, hydrogen, deuterium and tritium.
Ageing process of optical fibers
One of the limitations in the communications by optical fibers is the mechanical resistance in the long run of fibers in aggressive and varied environments such as underwater or underground spaces in the subway. The ageing of optical fibers with respect to moisture or temperature is not completely understood. Hydrogen H 2 at the origin of the growth of defects (Si-O-Si + H 2 0 → Si-O-H, Si-O-H) seems to induce the most dramatic degradations. Several mechanical models based on the finite elements, discretizing the fiber by elements of 1 mm length, were developed to analyze the problems of fracture. The resonance frequency was used to determine the unknown Young modulus of these fiber elements .
The influence of the radius of the fiber core was studied using 2 monomode fibers (r core = 3.5 and 10 µm) and a multimode fiber (r core = 50 µm). The composition laws for the elastic modules of the composites (Voigt model) were studied to obtain: as a function of the volume V of the clading and the core. The effective Young modulus E composite of various fibers were then deduced from the fundamental frequencies of vibration and compared with different volumes. The reactivity of optical fibers with hydrogen was monitored in time showing a linear drop in frequency (30 Hz per minute) during the first 20 hours, with a gradual reduction in the Q-factor ( Figure 12). An AFM study does not reveal any surface modification after the hydrogen exposure, confirming that the phenomenon takes place in the bulk of the fiber. The frequency drop is not connected to the mass uptake of the hydrogen but to the degradation in the mechanical properties: 4% frequency shift corresponds to 2% loss in Young modulus E.
Strengthening of cement cantilevers
The mechanical setting of the cement pastes is known to be very slow, the miniaturization of the samples fortunately helps accelerate the process. The mortar is interesting since this composite material is made up of a porous cement matrix and rigid inclusions such as sand. Its specificity stems from the interface between the grains and the matrix; a discontinuity responsible for the mechanical properties of the mortars .
The determination of the role played by such interfaces remain however difficult by conventional methods (rheology, techniques involving an inflection of the beam, or ultrasonic) requiring samples of centimeter size. Since hydration is highly exothermic, the miniaturization of the samples on a scale lower than the millimeter is recommended, especially for better modeling of the inclusion/matrix interface. Mortar based cantilevers have been fabricated with millimeter lengths and micrometric thicknesses.
Resonance frequencies of the mortar cantilevers cover an interesting range between 1 and 100 kHz corresponding to a region of the spectrum that has not been explored by either rheology (Hz) or ultrasonics (MHz). We therefore sought to investigate the various contributions to the elastic properties of the composite cantilevers to determine the influence of the parameters such as the hydration time, the porosity of the cement paste and the inclusion concentration within the matrix. The formalism of the continuous media could still be applied to the pure cement cantilevers thicker than 1 µm. For mortar cantilevers, namely including glass balls of 40 µm in diameter, the minimal thickness was fixed at 300 µm.
The viscoelastic limit was determined by requiring that the deflection of 5 mm long cantilevers must not exceed 75 µm to satisfy the deformation criterion of 0.02%. Results were analyzed in terms of acoustic speed, measured very precisely starting from the variations of the resonance frequency f standardized by the thickness h according to the inverse of the length square, i.e., 1/L 2 . The absolute determination of the effective Young modulus E of the material remained approximate (about 25 GPa) accounting for the approximate knowledge of the density (2 kg/m 3 ) of the miniaturized levers. The evolution of the resonance frequency with the hydration time ( Figure 13) shows that prior to 4 days, the mechanical properties strongly evolve due to the percolation in the cement paste; then during the ensuing 9 months, the increase in E weakens because of the filling of the pores by the hydrates reinforcing the structure. Material porosity was modified via the volumetric ratio between the water and the cement.
Measurement of changes in surface tension and film stress Irreversible surface tension induced by chemical etching
Variations in surface stress can be generated reversibly by water adsorption or by etching on one face of the cantilever.
Silica is known in micro-electronics to be very sensitive to hydrofluoric (HF) acid. Microcantilevers can be used then as alternative sensors for heavy post-analysis methods. Both the deflection and the resonance frequency of the microcantilevers were analyzed according to the acid flow and concentration as shown in Figure 14 . The stoichiometry and the roughness of the sensitive layers play a paramount role in the surface reactivity. For the lowest concentrations (< 10 ppm), the cantilever deflection provides the most sensitive signal. In the case of Si 3 N 4 coatings, a linear and small variation is induced in the surface tension compared to the case with SiO 2 coatings. Frequency shift was explained in terms of mass loss at high concentrations. The non-linearity of the deflection observed for the SiO 2 levers arises from the etching, which initially commences on the sides, and continues in the transverse direction.
Film stress or swelling induced by chemical absorption
Absorption of organic vapors such as benzene and hexane in thin film sensors can lead to changes in the film stress. PECVD membranes deposited on microcantilevers are advantageous on many points: they provide continuous films without porosity, are chemically inert, and possess physically stable defects. In addition to a strong capacity for gas absorption, their high selectivity makes them very competitive in the field of polymeric membranes. For example, the selectivity of butane/methane is 4 for polymers PDMS (PolyDiMethylSiloxane) and 15 for plasma polymers. A 1 µm thick polymeric membrane (a-SiOC:H) was plasma deposited on a quartz microbalance (QCM) and a microcantilever for comparison.
The QCM (Figure 15) shows that cyclic molecules (cyclohexane and benzene), having the lowest saturation pressure, are more soluble in the film than the linear molecules (pentane and hexane). Desorption is also quasi instantaneous for the linear molecules whereas cyclic molecules diffuse more slowly. A) Absorption kinetics of hexane vapor at various pressures monitored by the bending of the cantilever coated with a-SiOC :H polymer. B) Cantilever selectivity in deflection of the a-SiOC :H polymer to hydrocarbon vapors (P=220 mbar).C) Cantilever deflection as a function of the vapor pressure standardized by the saturated vapor pressure for each gas P S . D) Frequency response of the cantilever as a function of the vapor pressure standardized by the saturated vapor pressure for each gas P S .
Concerning the selectivity of the polymeric films, the hexane induces clearly the most important bending (Figure 16 B). Cyclohexane is not so easily detectable contrary to the QCM measurements; complementarities of the techniques thus become obvious. The origin of the tension of film becomes understandable when plotting the cantilever deflection as a function of the gas pressure standardized by the vapor pressure of each gas (Figure 16 C). The most influent parameter is ∆σ; the variations of film swelling and the elastic properties explain the slight variations in the linearity of ∆z/∆P. All the linear molecules seem to induce identical variations in tension, but especially more important than the cyclic molecules, certainly more compact, they may condense between the aggregates. The increase in deflection means that the film tension decreases; the condensation of gases between the grains increasing the intergranular distance can be at the origin of the softening of film.
The study reproduced in the dynamic mode confirms the selectivity with the vapors already noticed in static mode (Figure 16 D). Interpreting the major reduction in frequency (4%) just in terms of mass uptake seems delicate. The QCM measurements indicate a 20% mass uptake of polymeric film, namely changes in cantilever mass of 0.3%. The mass effect contributes only to 10% of the frequency shift. Variations in the film tension appear to be the major contribution in ∆f/f. The spring constant of the cantilever k having been measured to 36 N/m, was also initially obtained from estimating the deflection ∆σ to 2.6 N/m; the variations ∆k/2k = 3.6% agree with the observed frequency shift. The resonance frequency reflects consequently the mechanical properties of the polymer layer.
Conclusions
In summary, we have shown that cantilevers provide genuine tools for the investigation of the mechanical properties of small volumes of materials and their temporal evolution under gaseous environments.
As temperature gauges, double-layered microcantilevers operating in deflection mode, can reach extreme thermal sensitivities.
As pressure sensors, using properties such as the quality factor, microcantilevers operating under dynamical resonance mode, can detect various molecular modes defined by the Knudsen number..
As mass sensors, cantilevers exhibit sensitivities on the order of pg/Hz. Converted to the frequency shift per unit area; this sensitivity is 10 times higher than that generally obtained by other types of piezoelectric sensors (quartz microbalances, surface acoustic waves).
It can be concluded that even if the mass change must be considered, the high sensitivity of microcantilevers to molecular adsorption comes from the change in the mechanical properties. A rigorous analysis as a function of the size and the dynamic and the static behavior of the cantilever enables one to discern between: The bulk properties: such as the change in the Young modulus, which can be measured by analyzing the resonance frequency response. This was illustrated by the studies of the ageing process of three materials: metal tritides, optical fibers, and composite materials such as cement.
Film and interface properties such as the residual stress, and the surface stress were studied by the etching or the absorption process using polymeric or inorganic thin films.
Future trends will consider smaller cantilevers to investigate the mechanical properties of nanosized cantilevers in the MHz regime. Silicon and carbon cantilevers are promising for further exploration. The use of other materials having electro or photomechanical abilities will bring the subject one step further. Simultaneous analysis of the mechanical response of the cantilevers with local electrical and/or optical properties is also an interesting challenge. |
package com.ycao.mysite.controller.admin;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ycao.mysite.constant.ErrorConstant;
import com.ycao.mysite.exception.BusinessException;
import com.ycao.mysite.model.FileCategoryDomain;
import com.ycao.mysite.service.markdown.IMdCategoryService;
import com.ycao.mysite.utils.APIResponse;
import com.ycao.mysite.utils.MyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* controller for part "write your markdown"
* Created by ycao on 20211211
*/
@Controller
@RequestMapping(value = "/home")
public class MarkdownController {
private static final Logger LOGGER = LoggerFactory.getLogger(MarkdownController.class);
@Autowired
IMdCategoryService iMdCategoryService;
@ResponseBody
@GetMapping(value = "getAllCategory")
public APIResponse getALlCategory(HttpServletRequest request,HttpServletResponse response,
@RequestParam(name = "userId", required = false)
String userId){
try{
List<FileCategoryDomain> resList = iMdCategoryService.getAllCategory(userId);
if(resList==null||resList.size()==0){
return APIResponse.success(new FileCategoryDomain[0]);
}
FileCategoryDomain[] resArr = resList.toArray(new FileCategoryDomain[resList.size()]);
return APIResponse.success(resArr);
}catch (BusinessException exception){
return APIResponse.fail(exception.getErrorCode());
}
}
@ResponseBody
@PostMapping(value = "saveMarkdown")
public APIResponse saveMarkdownRT(HttpServletRequest request, HttpServletResponse response,
@RequestBody String params){
try {
Map map = MyUtils.getMapFromAPI(params,"htmlText","ifCreate","uniqueMdFileId","userId","content","fileStar","fileName","fileCategory");
String doRes = iMdCategoryService.doMarkdownService(map);
if(doRes==null||"".equals(doRes)||"fail".equals(doRes)){
return APIResponse.fail("Save Markdown file fails");
}
return APIResponse.success();
}catch (BusinessException exception){
return APIResponse.fail(exception.getErrorCode());
}
}
}
|
Read circuits for resistive memory (ReRAM) and memristor-based nonvolatile Logics
Resistive memory device (Memristor) is one of the candidates for energy-efficient nonvolatile memory and nonvolatile logics (nvLogics) in the applications of wearable devices, Internet of Things (IoT), cloud computing, and big-data processing. However, resistive RAM (ReRAM) and memristor-based nvLogics suffer limited performance and low yield due to process variations in transistors and resistance of memristor. This presentation discusses the design challenges in read circuits for high-speed, area-efficient, and low-voltage ReRAM and nvLogics. Memristor-based nvLogics, such as nonvolatile-SRAM (nvSRAM), nonvolatile flip-flops (nvFF), and nonvolatile TCAM (nvTCAM) are included in this presentation. Several silicon-verified solutions on read scheme and sense amplifiers are also discussed in this presentation. |
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { DefaultLayoutService, LayoutOptions } from '../../layout/layout.settings';
@Component({
selector: 'vr-toolbar-alpha',
templateUrl: './toolbar-alpha.component.html',
styleUrls: ['./toolbar-alpha.component.scss']
})
export class ToolbarAlphaComponent implements OnInit {
@Input() sidenavCollapsed: boolean;
@Input() quickpanelOpen: boolean;
@Output() toggledSidenav = new EventEmitter();
@Output() toggledQuickpanel = new EventEmitter();
options: LayoutOptions;
constructor(layout: DefaultLayoutService) {
this.options = layout.options;
}
ngOnInit() { }
toggleSidenav() {
this.toggledSidenav.emit();
}
toggleQuickpanel() {
this.toggledQuickpanel.emit();
}
}
|
Overview of the events of 1972 in film
The year 1972 in film involved several significant cinematic events including the release of Francis Ford Coppola's Academy Award-winning film, The Godfather.
Highest-grossing films (U.S.) [ edit ]
The top ten 1972 released films by box office gross in North America are as follows:
Awards [ edit ]
Academy Awards:
Golden Globe Awards:
Palme d'Or (Cannes Film Festival):
Golden Bear (Berlin Film Festival):
The Canterbury Tales (I Racconti di Canterbury), directed by Pier Paolo Pasolini, Italy / France
1972 film releases [ edit ]
U.S.A. unless stated
Notable films released in 1972 [ edit ]
U.S.A. unless stated
#
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
R
S
T
U
V
W
XYZ
Births [ edit ]
Notable deaths [ edit ]
Film debuts [ edit ]
Notes [ edit ] |
n = int(input())
stu = [int(x) for x in input().split()]
stu.sort()
# print(stu)
print(sum(stu[i+1]-stu[i] for i in range(0,n,2)))
|
// NewPGPopularRepository creates the new popular characters repository for postgres
// and the redis cache for appearances.
func NewPGPopularRepository(db ORM, ctr CharacterThumbRepository) *PGPopularRepository {
return &PGPopularRepository{
db: db,
ctr: ctr,
}
} |
/** Equality expressions to aid in converting between DepNodes and CAS objects */
public static boolean equalCoverage(Annotation annot1,Annotation annot2) {
if (annot1==null || annot2==null)
return false;
return annot1.getBegin()==annot2.getBegin() &&
annot1.getEnd()==annot2.getEnd() &&
annot1.getCoveredText().equals(annot2.getCoveredText());
} |
import { useEffect, useMemo, useState, useCallback } from 'react';
import * as anchor from '@project-serum/anchor';
import styled from 'styled-components';
import { Container, Snackbar } from '@material-ui/core';
import Paper from '@material-ui/core/Paper';
import Alert from '@material-ui/lab/Alert';
import { PublicKey } from '@solana/web3.js';
import { useWallet } from '@solana/wallet-adapter-react';
import { WalletDialogButton } from '@solana/wallet-adapter-material-ui';
import {
awaitTransactionSignatureConfirmation,
CandyMachineAccount,
CANDY_MACHINE_PROGRAM,
getCandyMachineState,
mintOneToken,
} from './candy-machine';
import { AlertState } from './utils';
import { Header } from './Header';
import { MintButton } from './MintButton';
import { GatewayProvider } from '@civic/solana-gateway-react';
import Display from './shinobisers.gif';
import { CrossMintButton } from "@crossmint/client-sdk-react-ui";
const ConnectButton = styled(WalletDialogButton)`
width: 100%;
height: 60px;
margin-top: 10px;
margin-bottom: 5px;
background: linear-gradient(180deg, #604ae5 0%, #813eee 100%);
color: white;
font-size: 16px;
font-weight: bold;
`;
const MintContainer = styled.div``; // add your owns styles here
export interface HomeProps {
candyMachineId?: anchor.web3.PublicKey;
connection: anchor.web3.Connection;
startDate: number;
txTimeout: number;
rpcHost: string;
}
const Home = (props: HomeProps) => {
const [isUserMinting, setIsUserMinting] = useState(false);
const [candyMachine, setCandyMachine] = useState<CandyMachineAccount>();
const [alertState, setAlertState] = useState<AlertState>({
open: false,
message: '',
severity: undefined,
});
const [isDisabled, setIsDisabled] = useState(true);
const rpcUrl = props.rpcHost;
const wallet = useWallet();
const anchorWallet = useMemo(() => {
if (
!wallet ||
!wallet.publicKey ||
!wallet.signAllTransactions ||
!wallet.signTransaction
) {
return;
}
return {
publicKey: wallet.publicKey,
signAllTransactions: wallet.signAllTransactions,
signTransaction: wallet.signTransaction,
} as anchor.Wallet;
}, [wallet]);
const refreshCandyMachineState = useCallback(async () => {
if (!anchorWallet) {
return;
}
if (props.candyMachineId) {
try {
const cndy = await getCandyMachineState(
anchorWallet,
props.candyMachineId,
props.connection,
);
console.log(JSON.stringify(cndy.state, null, 4));
setCandyMachine(cndy);
} catch (e) {
console.log('There was a problem fetching Candy Machine state');
console.log(e);
}
}
}, [anchorWallet, props.candyMachineId, props.connection]);
const onMint = async () => {
try {
setIsUserMinting(true);
document.getElementById('#identity')?.click();
if (wallet.connected && candyMachine?.program && wallet.publicKey) {
const mintTxId = (
await mintOneToken(candyMachine, wallet.publicKey)
)[0];
let status: any = { err: true };
if (mintTxId) {
status = await awaitTransactionSignatureConfirmation(
mintTxId,
props.txTimeout,
props.connection,
true,
);
}
if (status && !status.err) {
setAlertState({
open: true,
message: 'Congratulations! Mint succeeded!',
severity: 'success',
});
} else {
setAlertState({
open: true,
message: 'Mint failed! Please try again!',
severity: 'error',
});
}
}
} catch (error: any) {
let message = error.msg || 'Minting failed! Please try again!';
if (!error.msg) {
if (!error.message) {
message = 'Transaction Timeout! Please try again.';
} else if (error.message.indexOf('0x137')) {
message = `SOLD OUT!`;
} else if (error.message.indexOf('0x135')) {
message = `Insufficient funds to mint. Please fund your wallet.`;
}
} else {
if (error.code === 311) {
message = `SOLD OUT!`;
window.location.reload();
} else if (error.code === 312) {
message = `Minting period hasn't started yet.`;
}
}
setAlertState({
open: true,
message,
severity: 'error',
});
} finally {
setIsUserMinting(false);
}
};
useEffect(() => {
refreshCandyMachineState();
const WL = [
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'AhynTRYSrG84wzzgq8s8KVusMvgrZ4CVNkAtx1mYC4Np',
'<KEY>',
'<KEY>',
'<KEY>jALqVZzXUj7TYcHVj8f62dACqPFLRXVs',
'G3SsXr575UKxvebz3EeLMfQmk1rQChC6Us9e5X1jH72f',
'AeQpB28j2Ph9tXLbBzSYS5Gn5WcfHwhMWi4Kw2HM8kdZ',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>tTvmA4eLssaxCtnBX7x3armRTe',
'<KEY>',
'3SnnjCkByrsNPpQCaEsDzdsv7TDA6W4SFo6XzWmEALdu',
'<KEY>',
'z263XYbqMaKe8oJHdR8hkNUbB5zt4iLB3Yx2vYjJfSR',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'X8w8ewaiLLhRitVYyF9LDjX4dpEwprXuqYQX7MSUr4V',
'<KEY>',
'8YeNHanJziE29fsFpfMoxZR4bFCpXrDcsqL8pd7atxw8',
'<KEY>NTfaRcztx7GKSVbbkzXTLNK',
'6Ayn1cyiEzdQxJZCjZUHsjY4gJq3j9zbLBMDoBa65qvn',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'CBPKhXmcDXrrdZhygLxoExgFpoEfu5wTnc5XzpLUrh72',
'GFWAYvJvF1NvoipTW<KEY>',
'<KEY>',
'<KEY>U',
'2QxawuwnFp33BH7xTrmhDHrU9N3yW8k8vVEst1EM3JPi',
'CXfmARwhKDbpABMe9PFBEkudnAJ2en9NxYqgSisgHiVf',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'D<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'CcbVPQe3cBeLYHtRSonjJ8LxGKcFptTUmQmD1sTt2gGm',
'7GakLnvSmmdjoYUWsJfDih8aCNhorBqsTnEjq4ue3hiY',
'BMp1usoVmAANSzwcqTrVNWLKCXAdmcs25QnBxz2BcGmb',
'5Vn9M1ndij2TmmFeoXpxAGLToRWhh4SWvH7x4LBffzZ5',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'mEz9Ju5Lg6U8dxvjdRUQXQHEx9pcwL4ZCy7zADazmWY',
'<KEY>',
'DvBy6rK2ygUT91LMuDEVmFdaVfpYfSWa22y1877Qmk9i',
'EeFWxSM6FLrwQx2du5Ex6KfdZ8WaW3usjrMBsZ5pLxWX',
'ApJpgs6kFaFUZkcRDZzuduSVrUat3Z5swDxkXFy7qL6f',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'CwM3y8YTtKwDah5HzKy51hoNdS517F1AzxsCjLbhWdQ6',
'<KEY>',
'<KEY>',
'<KEY>kTUdoBYFS6YidEx7yW7rTc7TFPnHDXSYLuP',
'BfDjW475YVE7EtaFRZZynkZdv5puaaLH6fRbcFmKcL97',
'<KEY>xSzz91hnw1pif9V76796vpzB',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'2SR98d2yPPxU<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'0xf920353c25a1cf09761c069c17ed2be32dacb10b',
'<KEY>',
'0x807ac80eF6c72f8075ceD<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'CAzvPo883os7EWdEvHcEGALDAiF41KWuhYn74YEzr1Bq',
'<KEY>',
'HBdtSzcRazdZ6xE3fC5pc8kKwkp1oVbMkKxc71c6pW85',
'EC6jMjQYbPBjpcv9WJ3VUEdqFT17Esh9gbeR5YKsvkRa',
'5ZVLdGzm5yNQrqY2fYpQ7eoKjWgcg1ubfiEq5wX1v2jg',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'FU8EmmroGAcxVJbgACZPdgGbnw381qbsqR6fs7DfyxUS',
'BpYApU<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'C9U7Yoh1G2XHZnYFRWyVVE96abup7FnDrTPMXMuiHQKm',
'<KEY>',
'AQEhZXJ<KEY>',
'AUZAhY<KEY>',
'<KEY>',
'<KEY>',
'BiqWv4qaKi9p3dQUafAeunb41aNvdL<KEY>',
'72fPFsxavQUVQySVHKQftyj1i6S21X841RV2gBJqjoZZ',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'Eh4b1R5znweobQt7UnAxc5sCkoEuvZsxN2VPQtc6ZCc6',
'9Sthx1Rje11fMt6UYBbeRkdfxJyoB4XzWSGtpeWj6J31',
'9epTEtzTVLeNnUGdAvipcdiv5z9ynCwHCkt4sxJR8NLg',
'ESsfzwjN5BnXud6MPdxhqpcqM8hbUwcsaqzMEstSULEo',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'0x903ba5Ed02C275494eDF1541e6A84146F3F6eA18',
'7hVsab2PSN9Yb1igvyhRiQC8qM1a7WzKbq7fgaxeXRDE',
'<KEY>',
'F6SSEHb1N6e4hkX7Rm6duwsa2Cb2uHGXVUZGgUkTBhDz',
'<KEY>cXat28ET3PdhvmdG9R6KANm31SKrtv3zWuaw',
'CKcrDjvQzumt5XPfB7mrP8mSbxyUkq9TmCLwDuPZdfA5',
'3MecTUStRNQnzQ4n9RjP6UsoajgpAECkVGxeSuaymrWt',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>kWHn1nVtDFUWRqGgPAvCm9tsuka5r7Ggu',
'<KEY>oLaqdA7Qx1gyfyKx3p7vvs',
'6ZAvDAiFRp5vDNmHyUs4LguV6QxmtsrnamHVTrqwtoPm',
'61Wfm8h4sMugXp4VJVpBqjuUjFWFVnDKPYMgTDsE6xYu',
'J2gSx6tPhzhi35i4GopE1emExC7ssQDXHSKh7uo6p9sU'
]
const WL_DATE = Date.parse('05 Feb 2022 18:40:00 UTC');
const LAUNCH_DATE = Date.parse('05 Feb 2022 19:00:00 UTC');
const dateInPast = (firstDate: Number) => {
let today = new Date();
if (firstDate <= today.getTime()) {
return true;
}
return false;
};
const checkInWL = (addy: string | undefined) => {
if (addy !== undefined) {
console.log(addy);
return WL.includes(addy);
}
return false;
};
const whitelisted = checkInWL(anchorWallet?.publicKey?.toBase58());
console.log("whitelisted " + whitelisted);
const whiteListStarted = dateInPast(WL_DATE);
console.log("whitelisted sale started " + whiteListStarted);
const publicStarted = dateInPast(LAUNCH_DATE);
console.log("public sale started " + publicStarted)
const canMint = (whitelisted && whiteListStarted) || publicStarted;
if (canMint) {
setIsDisabled(false);
}
}, [
anchorWallet,
props.candyMachineId,
props.connection,
refreshCandyMachineState,
]);
const StyledImage = styled.img`
display: block;
width:300px;
height:300px;
text-align: center;
margin-left: auto;
margin-right: auto;
`;
return (
<Container style={{ marginTop: 100 }}>
<Container maxWidth="xs" style={{ position: 'relative' }}>
<Paper
style={{ padding: 24, backgroundColor: '#151A1F', borderRadius: 6 }}
>
<StyledImage src={Display}/>
<h3><NAME> Mint Launch</h3>
<h4>Presale: 5th Feb 1840 UTC</h4>
<h4>Public sale: 5th Feb 1900 UTC</h4>
{!wallet.connected ? (
<ConnectButton>Connect Wallet</ConnectButton>
) : (
<>
<Header candyMachine={candyMachine} />
<MintContainer>
{candyMachine?.state.isActive &&
candyMachine?.state.gatekeeper &&
wallet.publicKey &&
wallet.signTransaction ? (
<GatewayProvider
wallet={{
publicKey:
wallet.publicKey ||
new PublicKey(CANDY_MACHINE_PROGRAM),
//@ts-ignore
signTransaction: wallet.signTransaction,
}}
gatekeeperNetwork={
candyMachine?.state?.gatekeeper?.gatekeeperNetwork
}
clusterUrl={rpcUrl}
options={{ autoShowModal: false }}
>
<MintButton
candyMachine={candyMachine}
isMinting={isUserMinting}
isDisabled={isDisabled}
onMint={onMint}
/>
<CrossMintButton
collectionTitle="<NAME>"
collectionDescription="444 ninjas making alpha accessible"
theme="dark"
/>
</GatewayProvider>
) : (
<div>
<MintButton
candyMachine={candyMachine}
isMinting={isUserMinting}
isDisabled={isDisabled}
onMint={onMint}
/>
<CrossMintButton
collectionTitle="<NAME>"
collectionDescription="444 ninjas making alpha accessible"
theme="dark"
disabled={isDisabled}
/>
</div>
)}
</MintContainer>
</>
)}
</Paper>
</Container>
<Snackbar
open={alertState.open}
autoHideDuration={6000}
onClose={() => setAlertState({ ...alertState, open: false })}
>
<Alert
onClose={() => setAlertState({ ...alertState, open: false })}
severity={alertState.severity}
>
{alertState.message}
</Alert>
</Snackbar>
</Container>
);
};
export default Home;
|
/**
* Filter out index that are replaced by another index with the same base
* name but newer version.
*
* Indexes without a version number in the name are always used, except if
* there is an active index with the same base name but a newer version.
*
* Active indexes have a hidden ":oak:mount-" node, which means they are
* indexed in the read-only node store.
*
* @param indexPaths the set of index paths
* @param rootState the root node state (used to find hidden nodes)
* @return the filtered list
*/
public static Collection<String> filterReplacedIndexes(Collection<String> indexPaths, NodeState rootState) {
HashMap<String, IndexName> latestVersions = new HashMap<String, IndexName>();
for (String p : indexPaths) {
IndexName indexName = IndexName.parse(p);
if (indexName.isVersioned) {
if (!isIndexActive(p, rootState)) {
continue;
}
}
IndexName stored = latestVersions.get(indexName.baseName);
if (stored == null || stored.compareTo(indexName) < 0) {
latestVersions.put(indexName.baseName, indexName);
}
}
ArrayList<String> result = new ArrayList<>(latestVersions.size());
for (IndexName n : latestVersions.values()) {
result.add(n.nodeName);
}
return result;
} |
/**
* A collection of useful class methods.
*
* @author Casey Marshall ([email protected])
*/
public final class Util
{
// Constants.
// -------------------------------------------------------------------------
public static final String HEX = "0123456789abcdef";
// Class methods.
// -------------------------------------------------------------------------
/**
* Convert a byte array to a hexadecimal string, as though it were a
* big-endian arbitrarily-sized integer.
*
* @param buf The bytes to format.
* @param off The offset to start at.
* @param len The number of bytes to format.
* @return A hexadecimal representation of the specified bytes.
*/
public static String toHexString(byte[] buf, int off, int len)
{
CPStringBuilder str = new CPStringBuilder();
for (int i = 0; i < len; i++)
{
str.append(HEX.charAt(buf[i+off] >>> 4 & 0x0F));
str.append(HEX.charAt(buf[i+off] & 0x0F));
}
return str.toString();
}
/**
* See {@link #toHexString(byte[],int,int)}.
*/
public static String toHexString(byte[] buf)
{
return Util.toHexString(buf, 0, buf.length);
}
/**
* Convert a byte array to a hexadecimal string, separating octets
* with the given character.
*
* @param buf The bytes to format.
* @param off The offset to start at.
* @param len The number of bytes to format.
* @param sep The character to insert between octets.
* @return A hexadecimal representation of the specified bytes.
*/
public static String toHexString(byte[] buf, int off, int len, char sep)
{
CPStringBuilder str = new CPStringBuilder();
for (int i = 0; i < len; i++)
{
str.append(HEX.charAt(buf[i+off] >>> 4 & 0x0F));
str.append(HEX.charAt(buf[i+off] & 0x0F));
if (i < len - 1)
str.append(sep);
}
return str.toString();
}
/**
* See {@link #toHexString(byte[],int,int,char)}.
*/
public static String toHexString(byte[] buf, char sep)
{
return Util.toHexString(buf, 0, buf.length, sep);
}
/**
* Create a representation of the given byte array similar to the
* output of `hexdump -C', which is
*
* <p><pre>OFFSET SIXTEEN-BYTES-IN-HEX PRINTABLE-BYTES</pre>
*
* <p>The printable bytes show up as-is if they are printable and
* not a newline character, otherwise showing as '.'.
*
* @param buf The bytes to format.
* @param off The offset to start at.
* @param len The number of bytes to encode.
* @return The formatted string.
*/
public static String hexDump(byte[] buf, int off, int len, String prefix)
{
String nl = System.getProperty("line.separator");
CPStringBuilder str = new CPStringBuilder();
int i = 0;
while (i < len)
{
str.append(prefix);
str.append(Util.formatInt(i+off, 16, 8));
str.append(" ");
String s = Util.toHexString(buf, i+off, Math.min(16, len-i), ' ');
str.append(s);
for (int j = 56 - (56 - s.length()); j < 56; j++)
str.append(" ");
for (int j = 0; j < Math.min(16, len - i); j++)
{
if ((buf[i+off+j] & 0xFF) < 0x20 || (buf[i+off+j] & 0xFF) > 0x7E)
str.append('.');
else
str.append((char) (buf[i+off+j] & 0xFF));
}
str.append(nl);
i += 16;
}
return str.toString();
}
/**
* See {@link #hexDump(byte[],int,int,String)}.
*/
public static String hexDump(byte[] buf, String prefix)
{
return hexDump(buf, 0, buf.length, prefix);
}
/**
* Format an integer into the specified radix, zero-filled.
*
* @param i The integer to format.
* @param radix The radix to encode to.
* @param len The target length of the string. The string is
* zero-padded to this length, but may be longer.
* @return The formatted integer.
*/
public static String formatInt(int i, int radix, int len)
{
String s = Integer.toString(i, radix);
CPStringBuilder buf = new CPStringBuilder();
for (int j = 0; j < len - s.length(); j++)
buf.append("0");
buf.append(s);
return buf.toString();
}
/**
* Convert a hexadecimal string into its byte representation.
*
* @param hex The hexadecimal string.
* @return The converted bytes.
*/
public static byte[] toByteArray(String hex)
{
hex = hex.toLowerCase();
byte[] buf = new byte[hex.length() / 2];
int j = 0;
for (int i = 0; i < buf.length; i++)
{
buf[i] = (byte) ((Character.digit(hex.charAt(j++), 16) << 4) |
Character.digit(hex.charAt(j++), 16));
}
return buf;
}
} |
Is It Possible To Walk And Work At The Same Time?
toggle caption iStockphoto.com
When it comes to walking, the easy part is understanding the benefits: Regular, brisk walks can strengthen our bones, help control blood sugar, help lower blood pressure and cholesterol, and the list goes on. The hard part is finding the time to fit it in.
Engineering physical activity back into Americans' daily lives is the goal of an educational campaign launched by Kaiser Permanente,an Oakland, Calif.-based health plan.
There are tons of tips and resources online, with the goal of creating a culture of walking. Kaiser Permanente even seems to be walking the walk with its own employees.
"We actually do have walking meetings at Kaiser Permanente, believe it or not," says executive Ray Baxter. "My team is pretty productive, so it must be working." Baxter believes walking together — as opposed to sitting down at a table — can change the dynamics of interactions for the better (think consensus building and brainstorming).
So, how much exercise do we really need to get all the benefits that are touted?
A lot of folks here at NPR have signed up for a 10,000-steps program sponsored by our health-plan provider. I've seen colleagues strap on pedometers to keep running tallies, and what they're learning is that it can be tough to get 10,000 steps — which equates to about 5 miles of walking — into a work day.
But experts who have crunched the numbers on how much we need to walk say, instead of focusing on steps, set a goal of 30 minutes of walking a day, five days a week.
Baxter says 150 minutes a week "has some pretty extraordinary effects on your health." That's a lot less than the nearly two hours a day it can take to reach 10,000 steps.
Studies show this 30 minutes a day is the amount of exercise needed to get serious reductions in the risk of lifestyle diseases that so many Americans are living with.
"The rule of thumb is that you get roughly half the reduction [about a 50 percent reduction] in the risk of heart disease, stroke and diabetes at the 150-minute mark," Baxter says. When people sustain this regular activity, the long-term benefits for bones and weight maintenance are measurable, too.
Of course, for those who are ready to push past 150 minutes a week, more exercise can be better. When you increase the intensity, however, you have to balance the benefits with the risk of injury.
So if you're ready to pick up the pace and you're wondering how high you need to get your heart rate, here's a rule of thumb: Walk briskly enough that it's still possible to carry on a conversation but no longer comfortable to sing. |
// ListCommonPrefixes gets a list of all object key prefixes that come
// after the provided prefix and before the provided delimiter (this is
// often used to simulate a directory hierarchy in object storage).
func (c *ObjectStoreGRPCClient) ListCommonPrefixes(bucket, prefix, delimiter string) ([]string, error) {
req := &proto.ListCommonPrefixesRequest{
Plugin: c.plugin,
Bucket: bucket,
Prefix: prefix,
Delimiter: delimiter,
}
res, err := c.grpcClient.ListCommonPrefixes(context.Background(), req)
if err != nil {
return nil, fromGRPCError(err)
}
return res.Prefixes, nil
} |
<filename>examples/python/cpu/tensors/tensor_split_03.py
import pyOcean_cpu as ocean
a = ocean.tensor([5,6])
a.T.copy(range(a.nelem))
print("---------------------------------------")
print("a")
print("---------------------------------------")
print(a)
print("\n---------------------------------------")
print("a.split(1,[1,5,0])")
print("---------------------------------------")
v = a.split(1,[1,5,0])
for tensor in v :
print(tensor)
print("\n---------------------------------------")
print("a.split(0,[ocean.cpu, ocean.cpu],[1,4])")
print("---------------------------------------")
v = a.split(0,[ocean.cpu, ocean.cpu],[1,4])
for tensor in v :
print(tensor)
|
<reponame>zealoussnow/chromium
// Copyright 2016 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/webui/print_preview/local_printer_handler_chromeos.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/check.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/stl_util.h"
#include "base/values.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/ui/webui/print_preview/print_preview_utils.h"
#include "chrome/common/printing/printer_capabilities.h"
#include "chromeos/crosapi/mojom/local_printer.mojom.h"
#include "components/device_event_log/device_event_log.h"
#include "content/public/browser/browser_thread.h"
#include "printing/backend/print_backend.h"
#include "printing/backend/print_backend_consts.h"
#include "printing/backend/printing_restrictions.h"
#include "printing/print_job_constants.h"
#include "url/gurl.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/crosapi/crosapi_ash.h"
#include "chrome/browser/ash/crosapi/crosapi_manager.h"
#include "chrome/browser/ash/crosapi/local_printer_ash.h"
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
#include "chromeos/lacros/lacros_service.h"
#endif
namespace printing {
namespace {
void OnGetPrintersComplete(
LocalPrinterHandlerChromeos::AddedPrintersCallback callback,
std::vector<crosapi::mojom::LocalDestinationInfoPtr> printers) {
if (!printers.empty()) {
base::Value::ListStorage list;
for (const crosapi::mojom::LocalDestinationInfoPtr& p : printers)
list.push_back(LocalPrinterHandlerChromeos::PrinterToValue(*p));
std::move(callback).Run(base::ListValue(std::move(list)));
}
}
} // namespace
// static
std::unique_ptr<LocalPrinterHandlerChromeos>
LocalPrinterHandlerChromeos::Create(
content::WebContents* preview_web_contents) {
auto handler =
std::make_unique<LocalPrinterHandlerChromeos>(preview_web_contents);
#if BUILDFLAG(IS_CHROMEOS_ASH)
DCHECK(crosapi::CrosapiManager::IsInitialized());
handler->local_printer_ =
crosapi::CrosapiManager::Get()->crosapi_ash()->local_printer_ash();
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
chromeos::LacrosService* service = chromeos::LacrosService::Get();
if (!service->IsAvailable<crosapi::mojom::LocalPrinter>()) {
PRINTER_LOG(ERROR) << "Local printer not available (Create)";
return handler;
}
handler->local_printer_ =
service->GetRemote<crosapi::mojom::LocalPrinter>().get();
handler->local_printer_version_ =
service->GetInterfaceVersion(crosapi::mojom::LocalPrinter::Uuid_);
#endif
return handler;
}
std::unique_ptr<LocalPrinterHandlerChromeos>
LocalPrinterHandlerChromeos::CreateForTesting() {
return std::make_unique<LocalPrinterHandlerChromeos>(nullptr);
}
LocalPrinterHandlerChromeos::LocalPrinterHandlerChromeos(
content::WebContents* preview_web_contents)
: preview_web_contents_(preview_web_contents) {}
LocalPrinterHandlerChromeos::~LocalPrinterHandlerChromeos() = default;
// static
base::Value LocalPrinterHandlerChromeos::PrinterToValue(
const crosapi::mojom::LocalDestinationInfo& printer) {
base::Value value(base::Value::Type::DICTIONARY);
value.SetStringKey(kSettingDeviceName, printer.id);
value.SetStringKey(kSettingPrinterName, printer.name);
value.SetStringKey(kSettingPrinterDescription, printer.description);
value.SetBoolKey(kCUPSEnterprisePrinter, printer.configured_via_policy);
return value;
}
// static
base::Value LocalPrinterHandlerChromeos::CapabilityToValue(
crosapi::mojom::CapabilitiesResponsePtr caps) {
if (!caps)
return base::Value();
base::Value dict = AssemblePrinterSettings(
caps->basic_info->id,
PrinterBasicInfo(
caps->basic_info->id, caps->basic_info->name,
caps->basic_info->description, 0, false,
PrinterBasicInfoOptions{
{kCUPSEnterprisePrinter, caps->basic_info->configured_via_policy
? kValueTrue
: kValueFalse}}),
PrinterSemanticCapsAndDefaults::Papers(), caps->has_secure_protocol,
base::OptionalOrNullptr(caps->capabilities));
// TODO(b/195001379, jkopanski): This block of code should be removed once
// Ash Chrome M94 is on stable channel.
base::Value policies(base::Value::Type::DICTIONARY);
policies.SetIntKey(kAllowedColorModes, caps->allowed_color_modes_deprecated);
policies.SetIntKey(kAllowedDuplexModes,
caps->allowed_duplex_modes_deprecated);
policies.SetIntKey(
kAllowedPinModes,
static_cast<int>(caps->allowed_pin_modes_deprecated_version_1));
policies.SetIntKey(kDefaultColorMode,
static_cast<int>(caps->default_color_mode_deprecated));
policies.SetIntKey(kDefaultDuplexMode,
static_cast<int>(caps->default_duplex_mode_deprecated));
policies.SetIntKey(kDefaultPinMode,
static_cast<int>(caps->default_pin_mode_deprecated));
dict.FindKey(kPrinter)->SetKey(kSettingPolicies, std::move(policies));
return dict;
}
// static
base::Value LocalPrinterHandlerChromeos::StatusToValue(
const crosapi::mojom::PrinterStatus& status) {
base::Value dict(base::Value::Type::DICTIONARY);
dict.SetStringKey("printerId", status.printer_id);
dict.SetDoubleKey("timestamp", status.timestamp.ToJsTimeIgnoringNull());
base::Value status_reasons(base::Value::Type::LIST);
for (const crosapi::mojom::StatusReasonPtr& reason_ptr :
status.status_reasons) {
base::Value status_reason(base::Value::Type::DICTIONARY);
status_reason.SetIntKey("reason", static_cast<int>(reason_ptr->reason));
status_reason.SetIntKey("severity", static_cast<int>(reason_ptr->severity));
status_reasons.Append(std::move(status_reason));
}
dict.SetKey("statusReasons", std::move(status_reasons));
return dict;
}
void LocalPrinterHandlerChromeos::Reset() {}
void LocalPrinterHandlerChromeos::GetDefaultPrinter(
DefaultPrinterCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// TODO(b/172229329): Add default printers to ChromeOS.
std::move(callback).Run(std::string());
}
void LocalPrinterHandlerChromeos::StartGetPrinters(
AddedPrintersCallback callback,
GetPrintersDoneCallback done_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!local_printer_) {
PRINTER_LOG(ERROR) << "Local printer not available (StartGetPrinters)";
std::move(done_callback).Run();
return;
}
local_printer_->GetPrinters(
base::BindOnce(OnGetPrintersComplete, std::move(callback))
.Then(std::move(done_callback)));
}
void LocalPrinterHandlerChromeos::StartGetCapability(
const std::string& device_name,
GetCapabilityCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!local_printer_) {
PRINTER_LOG(ERROR) << "Local printer not available (StartGetCapability)";
std::move(callback).Run(base::Value());
return;
}
local_printer_->GetCapability(
device_name, base::BindOnce(CapabilityToValue).Then(std::move(callback)));
}
void LocalPrinterHandlerChromeos::StartPrint(
const std::u16string& job_title,
base::Value settings,
scoped_refptr<base::RefCountedMemory> print_data,
PrintCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
size_t size_in_kb = print_data->size() / 1024;
base::UmaHistogramMemoryKB("Printing.CUPS.PrintDocumentSize", size_in_kb);
crosapi::mojom::LocalPrinter::GetUsernamePerPolicyCallback cb =
base::BindOnce(&LocalPrinterHandlerChromeos::OnProfileUsernameReady,
weak_ptr_factory_.GetWeakPtr(), std::move(settings),
std::move(print_data), std::move(callback));
if (!local_printer_) {
LOG(ERROR) << "Local printer not available";
std::move(cb).Run(absl::nullopt);
return;
}
#if BUILDFLAG(IS_CHROMEOS_LACROS)
if (local_printer_version_ <
int{crosapi::mojom::LocalPrinter::MethodMinVersions::
kGetUsernamePerPolicyMinVersion}) {
LOG(WARNING) << "Ash LocalPrinter version " << local_printer_version_
<< " does not support GetUsernamePerPolicy().";
std::move(cb).Run(absl::nullopt);
return;
}
#endif
local_printer_->GetUsernamePerPolicy(std::move(cb));
}
void LocalPrinterHandlerChromeos::OnProfileUsernameReady(
base::Value settings,
scoped_refptr<base::RefCountedMemory> print_data,
PrinterHandler::PrintCallback callback,
const absl::optional<std::string>& username) {
if (username.has_value() && !username->empty()) {
settings.SetKey(kSettingUsername, base::Value(*username));
settings.SetKey(kSettingSendUserInfo, base::Value(true));
}
StartLocalPrint(std::move(settings), std::move(print_data),
preview_web_contents_, std::move(callback));
}
void LocalPrinterHandlerChromeos::StartGetEulaUrl(
const std::string& destination_id,
GetEulaUrlCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!local_printer_) {
PRINTER_LOG(ERROR) << "Local printer not available (StartGetEulaUrl)";
std::move(callback).Run("");
return;
}
local_printer_->GetEulaUrl(destination_id,
base::BindOnce([](const GURL& url) {
return url.spec();
}).Then(std::move(callback)));
}
void LocalPrinterHandlerChromeos::StartPrinterStatusRequest(
const std::string& printer_id,
PrinterStatusRequestCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!local_printer_) {
PRINTER_LOG(ERROR)
<< "Local printer not available (StartPrinterStatusRequest)";
std::move(callback).Run(base::Value());
return;
}
local_printer_->GetStatus(
printer_id, base::BindOnce([](crosapi::mojom::PrinterStatusPtr ptr) {
return StatusToValue(*ptr);
}).Then(std::move(callback)));
}
} // namespace printing
|
#include<stdio.h>
int main()
{
char s[100],a[100],temp;
gets(s);
int i,len,j=0,k=0,l;
len=strlen(s);
while(s[j]!='\0')
{
if(s[j]!='+')
{
a[k]=s[j];
k++;
}
j++;
}
for(i=1;i<k;i++)
{
for(l=0;l<(k-i);l++)
if(a[l]>a[l+1])
{
temp=a[l];
a[l]=a[l+1];
a[l+1]=temp;
}
}
for(i=0;i<k;i++)
{
if(i==(k-1))printf("%c",a[i]);
else printf("%c+",a[i]);
}
}
|
//
// Created by MichelT on 10/12/2019.
//
#ifndef STACK_STACK_H
#define STACK_STACK_H
typedef struct node {
int item;
struct node *next;
} Node;
typedef struct stack {
Node *top;
} Stack;
Stack* create_stack();
void push(Stack* stack, int item);
int pop(Stack* stack);
int peek(Stack* stack);
int is_empty(Stack* stack);
int is_full(Stack *stack);
#endif //STACK_STACK_H
|
<reponame>lee20h/ALPS_2020_Summer_Study
#pragma once
#include "GameObject.h"
namespace rpg_extreme
{
class Character : public GameObject
{
public:
virtual bool IsCharacter() const override;
virtual bool IsEquipmentBox() const override;
virtual bool IsWall() const override;
virtual bool IsSpikeTrap() const override;
virtual bool IsPlayer() const = 0;
virtual bool IsMonster() const = 0;
bool IsAlive() const;
void FillUpHp();
int16_t GetHp() const;
int16_t GetMaxHp() const;
int16_t GetAttack() const;
int16_t GetDefense() const;
uint16_t GetExp() const;
protected:
Character(const int8_t x, const int8_t y, const int16_t attack, const int16_t defense, const int16_t hp, const uint16_t exp);
int16_t mHp;
int16_t mMaxHp;
int16_t mAttack;
int16_t mDefense;
uint16_t mExp;
};
}
|
The significance of digital gene expression profiles.
Genes differentially expressed in different tissues, during development, or during specific pathologies are of foremost interest to both basic and pharmaceutical research. "Transcript profiles" or "digital Northerns" are generated routinely by partially sequencing thousands of randomly selected clones from relevant cDNA libraries. Differentially expressed genes can then be detected from variations in the counts of their cognate sequence tags. Here we present the first systematic study on the influence of random fluctuations and sampling size on the reliability of this kind of data. We establish a rigorous significance test and demonstrate its use on publicly available transcript profiles. The theory links the threshold of selection of putatively regulated genes (e.g., the number of pharmaceutical leads) to the fraction of false positive clones one is willing to risk. Our results delineate more precisely and extend the limits within which digital Northern data can be used. |
def pop(self, *args, **kwargs):
if self.focus_stack().pop():
self.master.prompt_for_exit()
else:
self.refresh()
self.view_changed()
self.focus_changed() |
from time import time
import random
def performance_sum():
"""Evaluate performance of sum"""
scores = {}
trial = 1
while trial <= 20:
numbers = [random.randint(1, 9) for i in list(range(2**trial))]
now = time()
sum = 0
for d in numbers:
sum = sum + d
done = time()
scores[trial] = (done-now)
trial += 1
for i in scores:
print(2**i, "\t\t\t\t", scores[i])
def performance_sort():
"""Evaluate performance of sum"""
scores = {}
trial = 1
while trial <= 16:
numbers = [random.randint(1, 2**(trial*4)) for i in list(range(2**trial))]
now = time()
numbers.sort()
done = time()
scores[trial] = (done-now)
trial += 1
for i in scores:
print(2**i, "\t\t\t\t", scores[i])
performance_sum()
performance_sort() |
// set the return stream name to the adapter cluster name
private void decorateRequest(Request r) {
Request.RInfo rinfo = r.getRInfo();
if (rinfo instanceof Request.ClientRInfo) {
String cname = clusterEventListener.getRawListener()
.getAppName();
((Request.ClientRInfo) rinfo).setStream("@" + cname);
}
} |
/**
* A simple data class for storing information about registered call backs.
*/
private static class CallBackData
{
/** Stores the call back. */
private ComponentBuilderCallBack callBack;
/** Stores the parameter for the call back. */
private Object param;
/**
* Creates a new instance of {@code CallBackData} and initializes
* it.
*
* @param cb the call back
* @param p the parameter for the call back
*/
public CallBackData(ComponentBuilderCallBack cb, Object p)
{
callBack = cb;
param = p;
}
/**
* Invokes the stored call back.
*
* @param data the builder data object
* @throws FormBuilderException if the call back throws an exception
*/
public void invokeCallBack(ComponentBuilderData data)
throws FormBuilderException
{
callBack.callBack(data, param);
}
} |
def product_of_experts(mu_experts, var_experts, eps=1e-7):
T = 1. / (var_experts + eps)
mu_product = torch.sum(mu_experts * T, dim=1) / torch.sum(T, dim=1)
var_product = 1. / torch.sum(T, dim=1)
return mu_product, var_product + eps |
/**
* A session is an authentication request sent to a user. Creating a session initiates a push notification to the user's mobile device.
*/
public class Session {
/**
* Various states that Sessions can take on.
*/
public static enum State {
/**
* The recipient has not yet responded to the request.
*/
PENDING,
/**
* The recipient has rejected the request.
*/
APPROVED,
/**
* The recipient has denied the request.
*/
DENIED;
}
private String id = null;
private State state = null;
/**
* @param id The session's identifier.
* @param state The state of the session.
*/
public Session(String id, State state) {
this.id = id;
this.state = state;
}
/**
* @return The sessions's identifier.
*/
public String getId() {
return this.id;
}
/**
* @return The sessions's state.
*/
public State getState() {
return this.state;
}
} |
<reponame>jfbarthe/gedcom
package gedcom_test
import (
"github.com/elliotchance/gedcom"
"github.com/stretchr/testify/assert"
"testing"
)
var stringTests = []struct {
a, b string
jaro, str float64
}{
// Simple values
{"", "", 0, 0},
{"Foo", "Foo", 1, 1},
{"foo bar", "foo bar", 1, 1},
{"Foo bar", "foo bar", 0.9333333333333333, 1},
{"foo bar", "Foo Bar", 0.8666666666666668, 1},
{"foo", "bar", 0, 0},
// Names
{"<NAME>", "<NAME>", 0.9163461538461538, 0.9271794871794872},
{"<NAME>", "<NAME>", 0.9271794871794872, 0.9271794871794872},
{"<NAME>", "<NAME>", 0.8975, 0.91},
{"<NAME>", "<NAME>", 0.8678947368421053, 0.8784210526315789},
{"<NAME>", "<NAME>", 0.7822055137844612, 0.7977610693400166},
{"<NAME>", "<NAME>", 0.7814285714285714, 0.7814285714285714},
{"<NAME>", "<NAME>", 0.9214141414141415, 0.9214141414141415},
{"<NAME>", "<NAME>", 0.8962962962962963, 1},
{"<NAME>", "<NAME>", 0.9271794871794872, 1},
{"<NAME>", "Elliot '<NAME>", 0.9218181818181819, 1},
// Places
{", Connecticut", "Connecticut", 0.7972027972027972, 1},
{
"28 <NAME>, London, England, United Kingdom",
"40 Augustus Rd, Birmingham, England, United Kingdom",
0.6681987417281535,
0.6800831443688585,
},
{
"Adams County, Adams County, Iowa, United States",
"Adams, Umatilla County, Oregon, United States",
0.8408101718740018,
0.8632912132912133,
},
}
func TestJaroWinkler(t *testing.T) {
for _, test := range stringTests {
t.Run(test.a+"_"+test.b, func(t *testing.T) {
assert.Equal(t, test.jaro, gedcom.JaroWinkler(test.a, test.b, 0.7, 4))
})
}
}
func TestStringSimilarity(t *testing.T) {
for _, test := range stringTests {
t.Run(test.a+"_"+test.b, func(t *testing.T) {
assert.Equal(t, test.str, gedcom.StringSimilarity(test.a, test.b, 0.7, 4))
})
}
}
|
Tetraspanins CD9 and CD81 function to prevent the fusion of mononuclear phagocytes
Tetraspanins CD9 and CD81 facilitate the fusion between gametes, myoblasts, or virus-infected cells. Here, we investigated the role of these tetraspanins in the fusion of mononuclear phagocytes. Expression of CD9 and CD81 and their complex formation with integrins were up-regulated when blood monocytes were cultured under normal conditions. Under fusogenic conditions in the presence of Con A, CD9 and CD81 up-regulation was inhibited, and their complex formation with integrins was down-regulated. Anti-CD9 and -CD81 antibodies, which were previously shown to inhibit the fusion of gametes, myoblasts, and virus-infected cells, unexpectedly promoted the fusion of monocytes and alveolar macrophages. However, these effects were not due to altered cell adhesion, aggregation, or cytokine production. When stimulated in vitro or in vivo, alveolar macrophages and bone marrow cells of CD9- and CD81-null mice formed larger numbers of multinucleated cells than those of wild-type mice. Finally, CD9/CD81 double-null mice spontaneously developed multinucleated giant cells in the lung and showed enhanced osteoclastogenesis in the bone. These results suggest that CD9 and CD81 coordinately prevent the fusion of mononuclear phagocytes.
Introduction
The tetraspanin proteins comprise at least 28 distinct members of transmembrane proteins that include CD9, CD37, CD53, CD63, CD81, CD82, and CD151. All these proteins share a characteristic structure that spans the membrane four times and thereby forms two extracellular loops. Tetraspanins complex with transmembrane proteins such as CD4, CD8, CD19, CD21, CD46, major histocompatibility complex class I and II proteins, and integrins. They also bind to intracellular signaling molecules including phosphatidylinositol 4-kinase, phosphatases, and small GTP-binding proteins. It is thought that, by facilitating the formation of these multimolecular complexes, tetraspanins play roles in cell activation, proliferation, differentiation, motility, fusion, and apoptosis (Boucheix and Rubinstein, 2001).
Although their multifunctional characteristics and multipartnerships with other proteins have been increasingly reported, the definitive biological functions of tetraspanins still remain elusive. In this respect, studies of tetraspanin knockout mice have revealed the cellular functions for which a given tetraspanin is essential. One of these is a role of CD9 in gamete membrane fusion; CD9 knockout mice were infertile because CD9-null eggs were incapable of fusing with sperm (Miyado et al., 2000). Tetraspanins may play a more general role in cell-cell fusion because additional reports have implicated tetraspanins in other fusion events. Antibodies against CD9 and CD81 inhibit the fusion of myoblasts, and CD9 transfection into myoblast-derived sarcoma cells enhances syncytium formation (Tachibana and Hemler, 1999). Anti-CD81 and -CD82 mAbs perturb the fusion of cells infected with human T cell leukemia virus type 1 (Fukudome et al., 1992). CD9 overexpression renders cells more susceptible to feline immunodeficiency virus and canine distemper virus, leading to elevated syncytium formation (Löffler et al., 1997;Willett et al., 1997). These results suggest that tetraspanins facilitate the fusion between gametes, myoblasts, and virus-infected cells. However, it is still unknown whether they play a similar role in cell fusion into other multinucleated cells, such as multinucleated giant cells (MGCs)* or osteoclasts.
Syncytia formed after the fusion of mononuclear phagocytes are called MGCs or osteoclasts. Multinucleation via cell fusion appears to endow monocytes/macrophages with the capacity to digest and resorb extracellular infectious agents, foreign materials, and other components that are too large to be internalized (Vignery, 2000). The presence of MGCs is a hallmark of granulomas, which are formed in inflammatory sites of tuberculosis, fungal infection, HIV infection, sarcoidosis, Crohn's disease, and tumors (Anderson, 2000;James, 2000). The physiological meanings of MGCs still remain unknown, but possible roles in the host defense against bacterial infection have been suggested; MGCs may limit the cell-to-cell spread of Mycobacterium tuberculosis (Byrd, 1998) and may have stronger candidacidal activity than macrophages (Enelow et al., 1992). Osteoclasts are formed by the fusion of mononuclear progenitors of the monocyte/macrophage lineage. These polykaryons are characterized by the presence of tartrate-resistant acid phosphatase (TRAP) activity and have a crucial role not only in physiological bone remodeling, but also in local bone disorders such as osteoporosis and bone tumors. However, the actual cut-off line that discriminates between osteoclasts and MGCs remains controversial (Vignery, 2000).
The mechanisms of the fusion of mononuclear phagocytes are not well understood, but previous papers have shown that several membrane proteins, such as CD44, CD47, CD98, macrophage fusion receptor, P2X 7 receptor, AD-AMs, and integrins, are involved (Vignery, 2000;Namba et al., 2001). In the present paper, we show that tetraspanins CD9 and CD81 play a preventive role in the fusion of mononuclear phagocytes.
Con A modulates tetraspanin levels and integrintetraspanin complex formation in monocytes
MGCs can be generated in vitro in different ways by stimulating human blood monocytes or alveolar macrophages with cytokines (Fais et al., 1994), phorbol myristate acetate (Hassan et al., 1989), lectins (Chambers, 1977), conditioned media (Abe et al., 1991), or mAbs (Tabata et al., 1994). We isolated monocytes from human peripheral blood and allowed them to attach to culture plate surfaces in the presence of serum for 3 d, but the monocytes were not able to fuse into MGCs. However, on stimulation with Con A, cell-cell fusion occurred and many syncytia were formed within 3 d of incubation (see following paragraph). We examined the expression of six tetraspanin proteins (CD9, CD63, CD81, CD82, CD151, and NAG-2) by flow cytometry, and confirmed that all of these tetraspanins except NAG-2 were present on blood monocytes (unpublished data). To analyze the expression in detail, the time courses of CD9, CD63, and CD81 expression were examined by immunoblotting ( Fig. 1 A). When blood monocytes were cul-*Abbreviations used in this paper: 1 ␣ ,25(OH) 2 D 3 , 1 ␣ ,25-dihydroxyvitamin D 3 ; BAL, bronchoalveolar lavage; MGC, multinucleated giant cell; MTT, 3-(4,5-dimethylthiazol-2-yl)-2,5-diphenyltetrazolium bromide; sRANKL, soluble RANKL; TRAP, tartrate-resistant acid phosphatase. Figure 1. Con A modulates tetraspanin levels and integrin-tetraspanin complex formation in monocytes. (A) Blood monocytes were cultured in the absence (left) or presence (right) of 10 g/ml Con A. After the indicated number of days, the cells were lysed with Brij99 lysis buffer. Whole-cell lysates containing equal amounts of protein were separated by SDS-PAGE and transferred to an Immobilon-P membrane. The membranes were blotted with anti-CD63 (AHN-16), anti-CD9 (MM2/57) plus anti-CD81 (M38), or anti-actin (C4) mAb. (B) Monocytes were lysed at d 0 or at d 3 in the absence or presence of Con A. Immunoprecipitations were performed with anti-1 integrin (A-1A5), anti-2 integrin (IB4), anti-CD9 (BU16), or anti-CD81 (M38) mAb. Immunoprecipitated proteins were electrophoresed, transferred to membranes, and probed with anti-CD9 or -CD81 mAb (left). To confirm the presence of comparable amounts of each protein, wholecell lysates were blotted with anti-CD9, anti-CD81, anti-1 (A-1A5), anti-2 (MEM48), or anti-actin mAb (right). tured under normal conditions, levels of CD9 and CD81 were up-regulated, reached a peak at ف 2 d, and were sustained until 3 d after incubation. CD63 also appeared to be gradually up-regulated ( Fig. 1 A, left). Notably, when monocytes were cultured in the presence of Con A, the upregulation of CD9 and CD81 was inhibited compared with that under normal conditions. In contrast, the up-regulation of CD63 was enhanced in the presence of Con A ( Fig. 1 A, right). Control anti-actin blots showed that comparable amounts of protein were loaded in each lane.
The up-regulation of tetraspanin-integrin complex formation during myoblast fusion has been reported (Tachibana and Hemler, 1999). Among integrins, the  1 subfamily most commonly associates with tetraspanins, but a  2 integrin, ␣ L  2, also complexes with tetraspanins in hematopoietic cells. Tetraspanins also form complexes with other tetraspanins (Boucheix and Rubinstein, 2001). In freshly isolated blood monocytes, CD9 and CD81 associated with  1 and  2 integrins and with each other as shown in coimmunoprecipitation experiments ( Fig. 1 B, left). During the culture under normal conditions, the formation of tetraspanin-integrin and CD9-CD81 complexes was up-regulated (compare d 3 with d 0, "-"). Notably, during multinucleation under fusogenic conditions containing Con A, the formation of tetraspanin-integrin complexes was instead down-regulated. On the other hand, the up-regulation of the CD9-CD81 complex formation was not affected by the presence of Con A (compare d 3 with d 0, "Con A"). In control immunoblot- Figure 2. Anti-CD9 and -CD81 mAbs promote the fusion of blood monocytes. (A) Blood monocytes were induced to fuse into MGCs in culture medium containing 10 g/ml Con A for 3 d in the absence or presence of 10 g/ml of the indicated mAbs. Nuclei were then visualized using Wright stain. Bar, 250 m. (B) Monocytes (2 ϫ 10 5 ) were plated into the wells of a 96-well tissue culture plate and induced to fuse in the absence or presence of 10 g/ml of the indicated mAbs. Fusion rates were determined by calculating the percentages of the number of nuclei within MGCs (three or more nuclei per cell) per total number of nuclei. (C) Monocytes were induced to fuse in the absence or presence of increasing concentrations of anti-CD9 (BU16), anti-CD81 (JS64) mAbs, or isotype-matched IgG, and then fusion rates were determined. (D) Monocytes were induced to fuse in the absence or presence of 10 g/ml of the indicated mAbs (in the case of BU16 ϩ JS64, 10 g/ml of each was used). Fusion rates were then determined. Each bar and data point represent the mean Ϯ SD.
ting using whole-cell lysates ( Fig. 1 B, right), the up-regulation of CD9 and CD81 under normal conditions was confirmed as already shown in Fig. 1 A. The presence of Con A inhibited this up-regulation, but even under these conditions, higher levels of CD9 and CD81 appeared at d 3 compared with the level at d 0. The expression of  1 and  2 integrins was not much affected by these culture conditions. Thus, the down-regulation of CD9 and CD81 in  1 or  2 immunoprecipitates under fusogenic conditions was not due to the reduction of total CD9, CD81,  1, or  2 proteins.
Anti-CD9 and -CD81 mAbs promote the fusion of blood monocytes/alveolar macrophages Anti-CD9 and -CD81 antibodies were previously shown to inhibit the fusion of sperm and egg (Takahashi et al., 2001), myoblasts (Tachibana and Hemler, 1999), or virus-infected cells (Fukudome et al., 1992;de Parseval et al., 1997). To examine the role of tetraspanins in monocyte fusion, we added anti-tetraspanin mAbs to the monocyte culture under fusogenic conditions containing Con A. Unexpectedly, anti-CD9 (BU16) and anti-CD81 (JS64) mAbs dramatically promoted monocyte fusion (Fig. 2). The fusion rates in the presence of BU16 and JS64 were elevated 3.5-fold and fourfold relative to those in control IgG cultures, respectively. Moreover, MGCs formed in the presence of these mAbs were larger in size than the control MGCs ( Fig. 2 A). Another anti-CD9 mAb, MM2/57, also promoted the fusion, although its effect was weaker than those of BU16 and JS64. On the other hand, anti-CD14, -CD63, and -CD151 mAbs had little, if any, fusion-promoting effects. Anti-integrin  1 and  2 mAbs significantly inhibited the fusion (Fig. 2, A and B), consistent with previous reports (Most et al., 1990;Tabata et al., 1994). To examine the dose dependency, fusion rates in the presence of various concentrations of BU16, JS64, and isotypematched IgG were determined (Fig. 2 C). The fusion-promoting effects of BU16 and JS64 were dose dependent, reached a plateau at 1-10 g/ml, and decreased slightly at 20 g/ml. Meanwhile, the isotype-matched control IgG had little effect on monocyte fusion even at 20 g/ml. To exclude the possibility that the effects of BU16 and JS64 were mediated by Fc receptors, we generated divalent F(ab Ј ) 2 fragments and examined their effects on monocyte fusion. As shown in Fig. 2 D, these F(ab Ј ) 2 fragments exerted similar degrees of fusion-promoting effects as untreated mAbs. Finally, the coaddition of anti-CD9 and -CD81 mAbs appeared to have additive effects on the monocyte fusion (Fig. 2, A and D).
Next, we isolated alveolar macrophages from human lungs and examined the effects of these mAbs on the fusion of these cells. Like blood monocytes, alveolar macrophages were capable of fusing into MGCs in response to stimulation by Con A. Anti-CD9 and -CD81 mAbs enhanced the fusion of alveolar macrophages as well as that of blood monocytes. In contrast, anti-integrin  1 and  2 mAbs inhibited their fusion (unpublished data).
Anti-CD9 and -CD81 mAbs do not affect cell adhesion, aggregation, proliferation, or cytokine production
The effects of anti-CD9 and -CD81 mAbs may have been due to altered cell adhesion or aggregation, both of which are prerequisite for cell-cell fusion. To examine these possibilities, we performed adhesion and aggregation assays. As shown in Fig. 3 A, anti- 1 and - 2 mAbs significantly in- Figure 3. Anti-CD9 and -CD81 mAbs do not affect monocyte adhesion or aggregation. (A) Blood monocytes (2 ϫ 10 5 ) were suspended in RPMI 1640 containing 10 g/ml Con A, and were allowed to adhere to the wells of a 96-well culture plate for 12 h in the absence or presence of 10 g/ml of the indicated mAbs. Nonadherent cells were removed, and the remaining adherent cells were evaluated using an MTT assay. (B) Monocytes (2 ϫ 10 5 ) were cultured in RPMI 1640 containing 5 g/ml Con A in the absence or presence of 10 g/ml mAbs for 12 h on the wells of a 96-well nontissue culture-treated plate. The numbers of cell aggregates (Ͼ4 cells/aggregate) were determined under a light microscope. Each bar represents the mean Ϯ SD.
hibited monocyte adherence to the tissue culture-treated surfaces. This is consistent with a previous report showing that  1 and  2 integrins mediate adhesion to culture surfaces during macrophage fusion (McNally and Anderson, 2002). Meanwhile, anti-CD9 and -CD81 mAbs, and control IgG had no effect on the monocyte adherence. In aggregation assays, no mAb had a significant effect on the monocyte aggregation that was induced by 10 g/ml Con A (unpublished data). However, when a lower concentration of Con A (5 g/ml) was used, anti- 2 integrin mAbs markedly inhibited the monocyte aggregation ( Fig. 3 B). On the other hand, neither anti- 1 integrin mAb, anti-CD9 and -CD81 mAbs, anti-CD14 mAb, nor control IgG affected the monocyte aggregation. We also examined whether anti-CD9 and -CD81 mAbs alter the proliferation of monocytes using a 3-(4,5-dimethylthiazol-2-yl)-2,5-diphenyltetrazolium bromide (MTT) assay, and observed that these mAbs had no effect on monocyte proliferation (unpublished data).
Previous reports suggested that activated macrophages secrete cytokines such as tumor necrosis factor-␣ (TNF-␣ ), IL-1  , and IL-6, and that these cytokines play an important role in MGC formation (Anderson, 2000). Accordingly, we investigated whether anti-CD9 and -CD81 mAbs affect the production of these cytokines by Con A-stimulated monocytes. Blood monocytes were cultured for 3 d with Con A in the absence or presence of mAbs, and then the concentrations of TNF-␣ , IL-1  , and IL-6 in culture supernatants were determined using enzyme-linked immunosorbent assays. The supernatants of monocytes cultured without Con A (normal conditions) were also examined in parallel. As compared with normal conditions, Con A remarkably enhanced the production of these cytokines by monocytes. The up-regulation of TNF-␣ , IL-1  , and IL-6, was 23-, 59-, and 48-fold, respectively (380 to 8730 pg/ml for TNF-␣ , 50 pg/ml to 2970 pg/ ml for IL-1  , and 230 pg/ml to 10980 pg/ml for IL-6). The presence of anti-tetraspanin, integrin, or control mAbs had no significant effect on this up-regulation (unpublished data).
Soluble GST-CD9 large extracellular loop protein inhibits monocyte fusion
There was a possibility that the results of the antibodyblocking experiments were caused by steric hindrance to molecules adjacent to the tetraspanins. Thus, to extend the observations made in the antibody experiments, we studied effects of a recombinant GST fusion protein that contained the large extracellular loop of human CD9 (GST-CD9; Shimizu et al., 2002). Various concentrations of GST-CD9 were added to the monocyte culture under fusogenic conditions containing Con A. As shown in Fig. 4, GST-CD9 inhibited monocyte fusion, and this inhibitory effect was dosedependent in the range of 0.2-20 g/ml. On the other hand, neither GST alone nor GST-murine CD9 fusion protein (GST-mCD9) had significant fusion-inhibitory effect even at 20 g/ml.
Anti-CD9 and -CD81 mAbs promote the fusion of murine alveolar macrophages and bone marrow cells
To further extend our observations on cell fusion of the monocyte/macrophage lineage, murine alveolar macrophages were isolated by bronchoalveolar lavage (BAL) and induced to fuse into MGCs by the addition of 1 ␣ ,25-dihydroxyvitamin D 3 (1 ␣ ,25(OH) 2 D 3 ) and culture supernatants of Con A-stimulated spleen cells as described previously (Abe et al., 1983). We performed an immunofluorescence study because CD9 protein on murine alveolar macrophages was resistant to fixation and permeabilization procedures. As compared with control IgG (Fig. 5 A), staining of CD9 was positive in freshly isolated murine alveolar macrophages ( Fig. 5 B), and it was up-regulated after 3 d of incubation under normal culture conditions, especially at the cell periphery and cell-cell contacts (Fig. 5 C). Conversely, fusogenic culture conditions appeared to inhibit this CD9 upregulation (Fig. 5 D). CD9 expression was relatively weak in unfused macrophages and MGCs, and its distribution was more obvious at the perinuclear region than at the cell periphery in MGCs (Fig. 5 D, inset). The findings of immunoblotting were consistent with those of the immunofluorescence. Up-regulation of CD9 was observed under the normal culture conditions, whereas the fusogenic conditions suppressed this up-regulation (Fig. 5 E).
To examine the effects of anti-mouse tetraspanin mAbs, anti-mouse CD9 and CD81 mAbs were added to murine alveolar macrophages under fusogenic conditions. Because murine alveolar macrophages formed smaller numbers of MGCs than human monocytes/macrophages, we evaluated their fusion by determining the numbers of MGCs instead of fusion rates. As shown in Fig. 6, anti-mouse CD9 and CD81 mAbs promoted the fusion of murine macrophages. Moreover, the combination of anti-CD9 and -CD81 mAbs exerted an additive effect. The effect of anti-CD9 mAb, KMC8, was not mediated by Fc portion-Fc receptor interaction, because the F(ab Ј) 2 fragments exerted a quite similar effect (Fig. 6 B). Next, we examined the effects of anti-mouse CD9 and CD81 mAbs in the fusion of osteoclast progenitor cells. Murine bone marrow cells were isolated from tibiae and induced to fuse by the addition of soluble RANKL (sRANKL) and M-CSF . Like alveolar macrophages, the addition of these mAbs promoted the fusion of bone marrow cells. Relative to control IgG, numbers of TRAP-positive multinucleated cells in the presence of anti-CD9 mAb (KMC8) and anti-CD81 mAb (2F7) increased fourfold and twofold, respectively (unpublished data).
Enhanced cell fusion by CD9-and CD81-null alveolar macrophages and bone marrow cells after in vitro or in vivo stimulation
To determine more definitively the roles of CD9 and CD81 in monocyte/macrophage fusion, we investigated MGC formation of CD9-and CD81-deficient murine alveolar mac-rophages. Alveolar macrophages were isolated by BAL from the lungs of wild-type, CD9-null, and CD81-null mice, but no MGCs were present in these mice (unpublished data). Equal numbers of collected macrophages were then induced to fuse into MGCs in vitro. Notably, after the stimulation, CD9 (Ϫ/Ϫ) and CD81 (Ϫ/Ϫ) alveolar macrophages formed threefold and fourfold more MGCs than wild-type macrophages, respectively (Fig. 7 A). To further examine if the deficiency of CD9 or CD81 alters MGC formation in vivo, we used a Propionibacterium acnes-induced lung inflammation model (Itakura et al., 2001). Wild-type and mutant mice were challenged by intratracheal injection of heat-killed P. acnes. After 7 d, lung paraffin sections were prepared and analyzed to detect MGCs. Although infiltration of inflammatory cells consisting of neutrophils, macrophages, and lymphocytes into the alveolar space was reported 3ف d after P. acnes injection (Itakura et al., 2001), most of cells remaining at d 7 were macrophages. Remarkably, although few MGCs were present in wild-type mice, substantial numbers of MGCs were formed in the airspace of CD9-and CD81-null mice (Fig. 7 B, left). In a separate experiment to quantify the MGC formation, alveolar macrophages were separated by BAL after P. acnes injection, and the number of MGCs was determined (Fig. 7 B, right). The total numbers of cells isolated from wild-type and mutant mice were not significantly different (unpublished data), but nonetheless, sixfold and threefold more MGCs were detected in CD9-and CD81null mice compared with wild-type mice, respectively.
We also isolated bone marrow cells from wild-type, CD9null, and CD81-null mice and induced these cells to fuse in Figure 7. Enhanced cell fusion by CD9-and CD81-null murine alveolar macrophages and bone marrow cells after in vitro or in vivo stimulation. (A) Alveolar macrophages (3 ϫ 10 5 ) from wild-type, CD9 (Ϫ/Ϫ), and CD81 (Ϫ/Ϫ) mice were plated into the wells of a 96-well culture plate and induced to fuse into MGCs by a 3-d incubation with 1␣,25(OH) 2 D 3 and splenocyte-conditioned medium. Nuclei were then visualized using Wright stain (left). The numbers of MGCs per well were determined (right). (B) 300 g heat-killed P. acnes was administered intratracheally to wild-type, CD9 (Ϫ/Ϫ), and CD81 (Ϫ/Ϫ) mice. After 7 d, lung paraffin sections were stained with hematoxylin and eosin (left). Arrowheads indicate MGCs. In a separate experiment, alveolar macrophages were isolated by BAL from the lung, and the numbers of MGCs per lung were determined (right). Assays were done in triplicate for each animal tested. Two additional experiments gave similar results. (C) Bone marrow cells (2 ϫ 10 6 ) from wild-type, CD9 (Ϫ/Ϫ), and CD81 (Ϫ/Ϫ) mice were plated into the wells of a 24-well culture plate and induced to fuse by a 7-d incubation with sRANKL and M-CSF. Cells were then stained for TRAP (left). The numbers of TRAP-positive multinucleated cells (MNCs) per well were determined (right). Bar, 100 m (A-C). Each bar represents the mean Ϯ SD.
vitro by the addition of sRANKL and M-CSF. TRAP-positive multinucleated cells generated from CD9-and CD81null marrow cells were larger in size and increased sixfold and twofold in number, respectively, compared with those from wild-type marrow cells (Fig. 7 C).
Discussion
To induce fusion between monocytes in vitro, we used cultures containing Con A, because Con A readily induces monocyte fusion in a dose-and time-dependent manner (Takashima et al., 1993). A time-course analysis based on immunoblotting revealed that the up-regulation of the CD63 level was moderate under normal culture conditions, whereas stronger elevation of CD63 was observed under fusogenic conditions containing Con A. On the other hand, although CD9 and CD81 were up-regulated under normal conditions, their up-regulation was rather inhibited under fusogenic conditions. The findings of immunofluorescence and immunoblotting analysis of murine alveolar macrophages were in line with this. CD9 distribution into the cell periphery and cell-cell contacts was less marked under fuso- genic conditions. Moreover, CD9 staining was more obvious at the perinuclear area than at the cell periphery in MGCs. Consistent with these findings, a recent paper reported CD9 down-regulation in murine peritoneal macrophages stimulated with IFN-␥, which is a cytokine capable of promoting fusion of macrophages (Wang et al., 2002). These results suggest that the functions of CD9 and CD81 may be suppressed under fusogenic conditions, and that the functional contribution of these tetraspanins to monocyte/ macrophage fusion might be different from that of CD63.
All of anti-tetraspanin mAbs used in fusion assays of the present work were previously shown to inhibit cellular functions in vitro. In particular, the anti-human CD9 mAbs MM2/57 and BU16 were reported to inhibit virus-induced fusion (Löffler et al., 1997). The anti-mouse CD9 mAbs KMC8 and JF9 were reported to prevent sperm-egg fusion (Miyado et al., 2000;Takahashi et al., 2001). KMC8 and anti-mouse CD81 mAb 2F7 inhibited/delayed the fusion of the myoblast cell line C2C12 (Tachibana and Hemler, 1999). These anti-CD9 and -CD81 mAbs unexpectedly promoted the fusion of mononuclear phagocytes. It is unlikely that the effects were mediated by Fc portion-Fc receptor interactions, because isotype-matched control IgG had no effect on the fusion, and F(abЈ) 2 fragments had similar effects to untreated mAbs. These results raise the possibility that CD9 and CD81 facilitate the fusion of virus-infected cells, sperm-egg, and myoblasts, while preventing the fusion of monocytes/macrophages via the same epitopes. A previous work used a soluble GST-CD81 extracellular loop fusion protein to demonstrate that this protein bound to neurons but not to astrocytes, and that it blocked neuroninduced astrocyte proliferative arrest, thus suggesting the presence of a ligand for CD81 on neurons (Kelic et al., 2001). In the present work, the GST-CD9 extracellular loop fusion protein inhibited monocyte fusion in a dosedependent manner. This result further supports the involvement of CD9 protein in monocyte fusion, and may reflect a functional interaction between the CD9 extracellular loop and its putative ligand on an apposed cell surface.
With regard to genuine tetraspanins (Boucheix and Rubinstein, 2001), mice lacking CD9 (Miyado et al., 2000), CD37 (Knobeloch et al., 2000), CD81 Miyazaki et al., 1997), and Tssc6 (Tarrant et al., 2002) have been produced by gene targeting. CD9-null mice are infertile due to defective fusion capacity of their eggs. CD81-null mice are deficient in T cell-dependent IgG production and in Th2 cytokine secretion . Recently, CD81-null mice were also reported to have reduced reproductive capacity after repeated backcrosses (Deng et al., 2000). Moreover, exogenously overexpressed CD81 rescued the fusibility of CD9-null eggs (Kaji et al., 2002). Thus, CD9 and CD81 may share an essential role in gamete fusion processes. Meanwhile, no abnormal findings in other cell fusion events and no morphological abnormalities have been reported in tetraspanin knockout mice. However, given that several different tetraspanins form complexes with each other, the loss of a particular tetraspanin may be compensated by other tetraspanins. We presumed that single tetraspanin knockout mice under particular conditions or multiple tetraspanin knockout mice may reveal novel tetraspanin functions. In fact, in the present work, in response to in vitro and in vivo stimulation, CD9-and CD81-null macrophages and bone marrow cells displayed enhanced fusion capacity. Furthermore, CD9/CD81 double-null mice spontaneously developed MGCs in the lung and showed increased osteoclastogenesis in the bone. It is tempting to presume that osteopenic phenotype of CD9/ CD81 double-null mice is due to enhanced osteoclastogenesis. However, bone mass is maintained under a balance between bone resorption and formation. In fact, CD9 is present on osteoblast progenitors, and this CD9 molecule is also likely to be involved (Hayashi et al., 2000). Thus, detailed morphometric analysis and studies to evaluate the activities of osteoclasts and osteoblasts are obviously required to elucidate mechanisms in the osteopenic phenotype; such studies are currently in progress. Collectively, our data obtained using mAb and knockout mouse experiments suggest that CD9 and CD81 function to inhibit the fusion of mononuclear phagocytes, and that these tetraspanins may be able to compensate for each other.
Because the roles of CD9 and CD81 in monocyte/macrophage fusion proposed based on the present paper are contradictory to the previous hypothesis that these tetraspanins facilitate cell-cell fusion, the mechanisms of the tetraspanin contribution to cell-cell fusion now appear to be complex. One possible reason for this may be that the functions of tetraspanins are dependent on the cell lineage. Notably, although lectins such as Con A and phytohemagglutinin induce the fusion of macrophages, these lectins paradoxically inhibit the fusion of virus-infected cells, myoblasts, and gametes (Chambers, 1977). This evidence may indicate a fundamental distinction between macrophage and nonmacrophage cell fusion.
Integrins are well known to form complexes with tetraspanins, and tetraspanins may modulate the adhesive functions of integrins during cell-cell fusion (Boucheix and Rubinstein, 2001). In fact, it was shown in previous papers that the fusion of blood monocytes involves 1 and 2 integrins (Most et al., 1990;Tabata et al., 1994). In the present work, both anti-1 and -2 integrin mAbs inhibited the fusion of monocytes, probably due to blocking of monocyte adherence and aggregation, respectively. However, these adhesive and aggregative functions are not likely to be modified by tetraspanins because neither anti-CD9 nor anti-CD81 mAb altered monocyte adhesion or aggregation. We also observed that 1 and 2 integrins were complexed with CD9 and CD81 in freshly isolated blood monocytes, and this complex formation was up-regulated under normal culture conditions. Complexes between CD9 and CD81 were also increased; these up-regulations may at least partly reflect the elevated levels of total CD9 and CD81 proteins, but are consistent with the previous report that CD9 and 1 integrins assemble into a molecular complex during maturation of monocytes (Kurita-Taniguchi et al., 2001). However, under fusogenic conditions, the complex formation of tetraspanin (CD9 or CD81)-integrin (1 or 2) was downregulated, whereas tetraspanin-tetraspanin (CD9-CD81) complex formation occurred normally. A mild detergent (Brij99) was used in coimmunoprecipitation experiments, indicating that the molecular complexes in cell lysates could be part of raft-like membrane microdomains (Claas et al., 2001). Possibly, the different regulation of tetraspanin-integrin and tetraspanin-tetraspanin complexes might reflect differential localization of these complexes into distinct microdomains. Further studies will be needed to clarify the contribution of tetraspanin-integrin complexes to monocyte/macrophage fusion.
Other proteins involved in the fusion of mononuclear phagocytes, such as ADAMs (Namba et al., 2001), CD44, CD47 (Vignery, 2000), and CD98 (Tabata et al., 1994), may be affected by CD9 and CD81. An interaction between CD9 and ADAMs was suggested in the fusion between sperm and eggs (Zhu and Evans, 2002). Both CD44 and CD47 were reported to associate with CD9 (Jones et al., 1996;Longhurst et al., 1999). CD98 associates with 1 integrins and is important in integrin activation (Fenczik et al., 2001). Tetraspanins may indirectly influence CD98 function through their participation in integrin complexes. Roles of these proteins in tetraspanin-regulated monocyte/ macrophage fusion remains unknown, but the fact that CD9 associates with multiple monocyte/macrophage fusionrelated proteins further supports the involvement of tetraspanins in this particular type of fusion.
In conclusion, the present paper has demonstrated a novel fusion-regulatory function of tetraspanins. While facilitating the fusion of gametes, myoblasts, and virus-infected cells, CD9 and CD81 are essential to prevent the fusion of mononuclear phagocytes. Given that multinucleation endows cells with more resorptive capacity for extracellular components such as bone or infectious agents (Vignery, 2000), functional alterations of tetraspanins may contribute to the progression of osteoporosis, infection, and granulomatous diseases.
Isolation of blood monocytes, alveolar macrophages, and bone marrow cells
Peripheral blood mononuclear cells were isolated from heparinized whole blood by Ficoll-Hypaque density gradient centrifugation. Mononuclear cells were collected and cultured on MSP plates (Japan Immunoresearch). The adherent monocytes were detached and suspended in RPMI 1640 medium containing 10% heat-inactivated FCS, 100 U/ml penicillin, and 100 g/ml streptomycin (culture medium). Human alveolar macrophages were collected by BAL from patients in Osaka University Hospital (Osaka, Japan) with informed consent. Murine alveolar macrophages were obtained by BAL from 6-8-wk-old ddY male mice. Lungs of mice were subjected to lavage six times with 1.0 ml saline. Collected cells consisting mostly of macrophages were suspended in DME containing 5% human serum. Murine bone marrow cells were obtained from tibiae of 8-12-wk-old C57BL/6 male mice and suspended in ␣MEM containing 10% FCS.
Immunoprecipitation
Lysates containing equal amounts of protein were incubated with anti-integrin and -tetraspanin mAbs. Immune complexes were collected with protein A-Sepharose (Sigma-Aldrich), separated by SDS-PAGE under nonreducing conditions, and transferred to an Immobilon-P membrane. Immunoblotting was performed with biotinylated mAbs followed by peroxidase-conjugated streptavidin (Zymed Laboratories).
In vitro fusion assay of monocytes, macrophages, and bone marrow cells
For human blood monocyte/alveolar macrophage fusion experiments, 2 ϫ 10 5 cells were suspended in 100 l culture medium, plated in a 96-well tissue culture plate (Falcon), and induced to fuse into MGCs by the addition of 10 g/ml Con A for 3 d. To estimate the degree of cell fusion in the absence or presence of 10 g/ml mAb or recombinant GST-CD9 protein, nuclei were visualized using Wright stain. Fusion rates were determined by calculating the percentages of the number of nuclei within MGCs (three or more nuclei per cell) per total number of nuclei in six independent fields. Between 400 and 600 nuclei were counted in each field. For murine alveolar macrophage fusion, 3 ϫ 10 5 macrophages were suspended in 50 l DME containing 5% human serum, plated onto a 96-well plate, and then induced to fuse into MGCs by the addition for 3 d of 10 nM 1␣,25(OH) 2 D 3 and 50 l culture supernatant that was obtained from cultures of Con A-stimulated murine spleen cells. The number of MGCs per well in triplicate cultures was determined. For murine bone marrow cells, 2 ϫ 10 6 cells were suspended in 500 l ␣MEM containing 10% FCS, plated onto a 24-well plate, and then induced to fuse by the addition for 7 d of 50 ng/ml sRANKL and 20 ng/ml M-CSF. Cells were then fixed and stained for TRAP . The number of TRAP-positive multinucleated cells (three or more nuclei per cell) per well in triplicate cultures was determined.
In vivo fusion assay of murine alveolar macrophages 300 g heat-killed and sonicated P. acnes (ATCC 11828; American Type Culture Collection) was suspended in 100 l PBS and administered intratracheally to CD9 (Ϫ/Ϫ), CD81 (Ϫ/Ϫ), and wild-type mice under anesthesia as described previously (Itakura et al., 2001). After 7 d, the mice were killed and lung paraffin sections were prepared to observe MGC formation in the lung. In separate experiments, alveolar macrophages were isolated by BAL as described above, and the number of MGCs per lung was determined.
Cell adhesion assay
200,000 monocytes were suspended in 100 l RPMI 1640 containing 10 g/ml Con A and plated onto the wells of a 96-well tissue culture plate (Falcon). Cells were then allowed to adhere to the plate for 12 h in the absence or presence of 10 g/ml mAbs. After nonadherent cells were removed by rinsing, the remaining adherent cells were evaluated in triplicate cultures using an MTT assay.
Cell aggregation assay
200,000 monocytes were cultured in 100 l RPMI 1640 with 5 g/ml Con A in the absence or presence of 10 g/ml mAbs for 12 h in wells of a 96well nontissue culture-treated plate (Linbro). The number of cell aggregates (Ͼ4 cells/aggregate) was determined in six independent fields. |
/**
* This file is part of Eclipse Steady.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* SPDX-FileCopyrightText: Copyright (c) 2018-2020 SAP SE or an SAP affiliate company and Eclipse Steady contributors
*/
package org.eclipse.steady.python.virtualenv;
import static org.junit.Assert.assertTrue;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Set;
import org.eclipse.steady.FileAnalysisException;
import org.eclipse.steady.python.ProcessWrapperException;
import org.eclipse.steady.python.pip.PipInstalledPackage;
import org.eclipse.steady.shared.categories.Slow;
import org.eclipse.steady.shared.json.model.ConstructId;
import org.eclipse.steady.shared.util.FileUtil;
import org.eclipse.steady.shared.util.StringList;
import org.junit.Test;
import org.junit.experimental.categories.Category;
public class VirtualenvWrapperTest {
/**
* Attention: Runs long...
*
* @throws IllegalArgumentException
* @throws ProcessWrapperException
* @throws FileAnalysisException
*/
@Test
@Category(Slow.class)
public void testCreateVirtualenv()
throws IllegalArgumentException, ProcessWrapperException, FileAnalysisException {
// Create virtualenv
final Path project = Paths.get("src", "test", "resources", "cf-helloworld");
final VirtualenvWrapper vew = new VirtualenvWrapper(project);
final Path ve_path = vew.getPathToVirtualenv();
assertTrue(FileUtil.isAccessibleDirectory(ve_path));
// Get packages
final Set<PipInstalledPackage> packs = vew.getInstalledPackages();
assertTrue(packs.size() >= 8);
// Get rid of the project itself
final Set<PipInstalledPackage> filtered_packs =
PipInstalledPackage.filterUsingArtifact(
packs, new StringList().add("cf-helloworld"), false);
assertTrue(filtered_packs.size() >= 7);
// Get SHA1 for every package
for (PipInstalledPackage p : filtered_packs) {
final String sha1 = p.getDigest();
assertTrue(sha1 != null && !sha1.equals(""));
}
// Get constructs for every package
for (PipInstalledPackage p : filtered_packs) {
final Collection<ConstructId> constructs = p.getLibrary().getConstructs();
assertTrue(constructs != null && constructs.size() > 0);
}
}
}
|
Using Appraisal Taxonomies for Sentiment Analysis
Recent years have seen a growing interest in non-topical text analysis, in which characterizations are sought of the opinions, feelings, and attitudes expressed in a text, rather than just the facts. A key problem in this area is sentiment classification, in which a document is labelled as a positive (‘thumbs up’) or negative (’thumbs down’) evaluation of a target object (film, book, product, etc.). Immediate applications include data and web mining, market research, and customer relationship management. |
/// Process an event to destroy a component
fn destroy(self, parent_to_detach: bool) {
scheduler::push_component_destroy(Box::new(DestroyRunner {
state: self.state,
parent_to_detach,
}));
// Not guaranteed to already have the scheduler started
scheduler::start();
} |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// test move
#include <utility>
#include <type_traits>
#include <cassert>
#include "test_macros.h"
class move_only
{
move_only(const move_only&);
move_only& operator=(const move_only&);
public:
move_only(move_only&&) {}
move_only& operator=(move_only&&) {return *this;}
move_only() {}
};
move_only source() {return move_only();}
const move_only csource() {return move_only();}
void test(move_only) {}
int x = 42;
const int& cx = x;
template <class QualInt>
QualInt get() TEST_NOEXCEPT { return static_cast<QualInt>(x); }
int copy_ctor = 0;
int move_ctor = 0;
struct A {
A() {}
A(const A&) {++copy_ctor;}
A(A&&) {++move_ctor;}
A& operator=(const A&) = delete;
};
#if TEST_STD_VER > 11
constexpr bool test_constexpr_move() {
int y = 42;
const int cy = y;
return std::move(y) == 42
&& std::move(cy) == 42
&& std::move(static_cast<int&&>(y)) == 42
&& std::move(static_cast<int const&&>(y)) == 42;
}
#endif
int main(int, char**)
{
{ // Test return type and noexcept.
static_assert(std::is_same<decltype(std::move(x)), int&&>::value, "");
ASSERT_NOEXCEPT(std::move(x));
static_assert(std::is_same<decltype(std::move(cx)), const int&&>::value, "");
ASSERT_NOEXCEPT(std::move(cx));
static_assert(std::is_same<decltype(std::move(42)), int&&>::value, "");
ASSERT_NOEXCEPT(std::move(42));
static_assert(std::is_same<decltype(std::move(get<const int&&>())), const int&&>::value, "");
ASSERT_NOEXCEPT(std::move(get<int const&&>()));
}
{ // test copy and move semantics
A a;
const A ca = A();
assert(copy_ctor == 0);
assert(move_ctor == 0);
A a2 = a; (void)a2;
assert(copy_ctor == 1);
assert(move_ctor == 0);
A a3 = std::move(a); (void)a3;
assert(copy_ctor == 1);
assert(move_ctor == 1);
A a4 = ca; (void)a4;
assert(copy_ctor == 2);
assert(move_ctor == 1);
A a5 = std::move(ca); (void)a5;
assert(copy_ctor == 3);
assert(move_ctor == 1);
}
{ // test on a move only type
move_only mo;
test(std::move(mo));
test(source());
}
#if TEST_STD_VER > 11
{
constexpr int y = 42;
static_assert(std::move(y) == 42, "");
static_assert(test_constexpr_move(), "");
}
#endif
#if TEST_STD_VER == 11 && defined(_LIBCPP_VERSION)
// Test that std::forward is constexpr in C++11. This is an extension
// provided by both libc++ and libstdc++.
{
constexpr int y = 42;
static_assert(std::move(y) == 42, "");
}
#endif
return 0;
}
|
Operative hysteroscopy with the Bigatti shaver (IBS ®) for the removal of placental remnants
Background About 15-20% of pregnant women will miscarry spontaneously during the first trimester. Traditionally, the surgical treatment of placental remnants has been dilation and curettage (D&C). However, because of its ‘blind’ nature there is a risk of serious complications, such as infection, adhesion, uterine perforation, or bowel injury. Hysteroscopy, with direct visualization of the uterine cavity, decreases these complications. In this retrospective case series we evaluated the efficacy and the feasibility of operative hysteroscopy using the Intrauterine Bigatti Shaver (IBS ® ) for the treatment of placental remnants, both, in a University hospital in Italy and in a private hospital in Iran. Materials and Methods From December 2013 to April 2018 a retrospective medical records review, of patients undergoing placental remnant removal with the IBS ® , was performed. Sixty-five patients suspected of retained products of conception (RPOC) underwent operative hysteroscopy during this period using the IBS ® . Placental remnants were confirmed histologically in 52 cases (80%). The median age of the patients was 36 years. Placental remnants were observed after 42 early miscarriages, 5 terminations of pregnancy, 4 vaginal deliveries and 1 cesarean delivery. Thirty-two patients had abnormal uterine bleeding, 15 were asymptomatic and 5 had subfertility after miscarriage. Most cases (90%) were diagnosed by transvaginal ultrasound. Results The median interval between surgery and the end of pregnancy was 56 days (a range of 15-90 days). The size of placental remnants was between 15 and 30mm. Three women showed a cavity filled with placental tissue residual (more than 4cm). The median resection time was 4.5 minutes and the median total surgery time was 6.6 minutes. Median fluid deficit was 240 ml. In two cases there was excessive intraoperative bleeding, and one patient required a conversion to bipolar resectoscope for hemostatic reasons. No perforation or postoperative complications occurred. There was no need for second-look operative hysteroscopy and postoperative ultrasound confirmed complete evacuation of the RPOC. Only one patient had a minor adhesion. Conclusion The IBS ® seems to be an effective and safe instrument for the removal of placental remnants. It allows for short operation time with a high success and low complication rate.
Introduction
About 15-20% of pregnant women will miscarry spontaneously during the first trimester (Luise et al., 2002). Although first trimester miscarriages can be successfully managed conservatively, 20% of patients do not respond to expectant and conservative management after 4 weeks. In these cases, surgical treatment is recommended (Luise et al., 2002;Zhang et al., 2005). Patients with miscarriage could experience placental remnants with symptoms including vaginal bleeding (80%), fever (5%) and abdominal or pelvic pain (5%) (Maslovitz et al., 2004). However, as some cases of placental remnants may be asymptomatic, ultrasound is recommended for more accurate diagnosis. Ultrasound is a reliable Operative hysteroscopy with the Bigatti shaver (IBS ® ) for the removal of placental remnants The aim of this study is to evaluate whether the IBS ® technique should be considered as an alternative approach for the removal of placental remnants on the basis of safety and success rate.
Patients
From December 2013 to April 2018, 65 medical records of patients treated for removal of placental remnants with the Shaver technique were evaluated. All patients were suspected of having RPOCs. Histology confirmed placental remnants in 52 patients (80%) after surgery. These patients underwent IBS ® removal of placental remnants in two different centers: Milan (Italy) and Tehran (Iran). Clinical records of each patient were collected and reviewed. The median age was 36 years, 22 patients were nulliparous, 23 patients were primiparous, and 7 patients were secondiparous. Patients' Surgical details are shown in Table I.
Diagnosis and distribution of patients
Most cases were diagnosed with transvaginal ultrasound. If a previous uterine surgery has been held, it was reported as risk factor for abnormal placentation in 31 patients (66%): 14 patients had D&C at less than 10 weeks of gestation miscarriage, and 10 had previous cesarean sections. Six patients had termination of pregnancy (TOP) for chromosomal abnormality at >12 weeks, and 1 had a manual removal of placenta after vaginal delivery. Placental remnants occurred mainly after early miscarriage (<10 weeks) in 42 patients (80%), in 5 others (10 %) after termination of pregnancy (TOP, in 4 cases after vaginal deliveries (8%), and in 1 case after cesarean section in a twin pregnancy (2%).
Patients were referred to our clinics with different symptoms: 32 patients had abnormal uterine bleeding (61%), 15 were asymptomatic (29%), and 5 had been affected by subfertility and amenorrhea (10%) lasting more than 2 months after miscarriage. method to predict whether placental remnants will evacuate spontaneously or require intervention (Abbasi et al., 2008).
Traditionally, the surgical treatment of placental remnants is dilation and curettage (D&C) which has been the most widely used treatment for the removal of products of conception (RPOC) (Pather et al., 2005). However, there is a high risk of serious complications, such as infection, adhesion, uterine perforation, or bowel injury. Furthermore, it is well known that 'blind' procedures, such as too aggressive curettage, may damage the basal layer of the endometrium, leading to intrauterine adhesion formation (Asherman Syndrome) (Westendorp et al., 1998;Hooker et al., 2011). Some studies have reported intra uterine adhesions (IUAs) in 20% of women following surgical treatment for RPOC.
D&C is associated with more IUAs and incomplete removal, compared to operative hysteroscopy (Hooker et al., 2016). Therefore, products of conception removal under direct vision should be the treatment of choice. In such cases hysteroscopy was found to be complementary to 'blind' curettage in identifying and removing intrauterine lesions (Goldenberg et al., 1997). Hysteroscopy has been described in cases of postabortal or postpartum bleeding treatment, 3 decades ago (Tjanina et al., 2013). Hysteroscopy confirmed its value as a safe and precise procedure for the removal of placental remnants (Golan et al., 2011).
The Intrauterine Bigatti Shaver, (IBS ® ), has been able to selectively remove products of conception under direct visual control. The advantages of this technique include a small 8.5mm sheath diameter and its speed, with minimal injury and damage to the healthy endometrium. In addition, the Shaver technique did not cause any thermal injury of the uterine cavity. This may lead to reduced postoperative adhesion formation. IBS® has already proved to be a safe and efficient technique for endometrial polyps' removal (Bigatti, 2011;Bigatti et al., 2012). If there was a suspicion of a RPOC, different diagnostic approaches were performed.
Patients underwent surgery at a median of 56 days (range: 15-90 days) after the obstetrical event (Table III).
Surgical procedure
Surgeons with different levels of experience performed all the operations under general anesthesia. Cervical dilatation was done with a Hegar dilator up to No. 8. Normal saline (NaCl 0.9%) was used as distention media.
In all patients the IBS ® , Intrauterine Bigatti Shaver (Karl Storz GmbH & Co. of Tuttlingen) was used.
This device used a mechanical rotational cutting power with no electrical current. Tissue chips were removed at the same time as resection. A full and detailed description of the Shaver technique, including equipment and indications, has been well described in a recent publication (Bigatt, 2018).
Results
The mean size of placental remnants was reported to be 2cm (range 15 to 30 mm) in 49 patients (94%) by ultrasound imaging (Figure 1). Placental remnants filled the whole uterine cavity in 3 cases. Hysteroscopic resection of placental remnants required a median time of 4.5 minutes (range; 3 -8 minutes) with a total procedure median time of 6.6 minutes (range: 5 -10 minutes). In our cases, the median inflow fluid balance was 1380 ml (range: 700-4000), the median outflow 1200 ml (range: 500-3500), and the median deficit 240 ml (range: 100-400). Surgery outcomes are shown in Table III.
Intra-operative bleeding occurred in 3 cases. In 2 of them the placental remnants filled the whole cavity. For the first case we opted for a "shark jaw" blade offering a deeper grasp in order to successfully remove all the placental remnants. Whereas in the second case, the surgeon decided to alternate to bipolar resectoscopy. Finally, in the third case, where placental remnant obscured the whole cavity, RPOCs were first reduced by means of a grasping forceps and then removed with the IBS ® . No secondlook surgery was considered necessary, as the uterine cavity was completely free of placental remnants at the end of the procedure (Figure 1). Patients were kept under observation in the hospital for 6 hours after the procedure and then discharged on the same day, with follow up instructions at 5-6 weeks.
After the first post-operative menstrual period, all patients underwent a transvaginal ultrasound scan to assess the endometrial cavity and to confirm the absence of any placental remnants. In all cases, ultrasound confirmed a smooth endometrium. In only one patient minor adhesions were found after 3D vaginal ultrasound. A. 42-year-old nulliparous woman with a placental remnant of 15 mm after a miscarriage at <10 weeks; patient was asymptomatic, and an ultrasound scan revealed a retained product of conception. B. 42-year-old pluriparous woman with a placental remnant of 20 mm after an abortion in a twin pregnancy; patient was in amenorrhea after the procedure, and both an ultrasound scan and a diagnostic hysteroscopy revealed a retained product of conception. C. 40-year-old primiparous woman with a placental remnant of 30 mm after a miscarriage at 12 weeks. She had AUB (Abnormal uterine bleeding).
Discussion
Delayed bleeding with, or without, fever could be caused by RPOC after miscarriage. In most cases there is no clinical suspicion of retained placental tissue prior to the onset of symptoms and only in few cases amenorrhea may occur. Similarly, to what has been reported in the literature, in the present study, patients experienced the following clinical symptoms: 61% abnormal uterine bleeding, 29% asymptomatic, 10% subfertility and amenorrhea.
In regard to diagnosis, ultrasound is the best tool to diagnose RPOC (Hooker et al., 2014). Its most accurate feature (positive predictive value 80%) is the presence of an echogenic focus allowing to observe a thickened endometrium, if more than 10mm (Abbasi et al., 2008).
In 90% of our patients (47/52), RPOC was determined by transvaginal ultrasound. In most of these (80%), RPOC occurred after miscarriage or TOP (10%), whereas in the remaining 10% placental remnants occurred after delivery (by both vaginal and caesarean section). If retained placental tissue is suspected, whether to proceed directly to surgical intervention, or try medical treatment remains controversial (Acharya et al., 2004).
In a majority of cases, spontaneous expulsion of the placental tissue occurs within 2-4 weeks (Hooker et al., 2011). However, when conventional methods have been exhausted surgery is the only option. Another question that must be addressed is the choice between curettage and hysteroscopy, as primary surgical intervention. Traditionally D&C has been the first choice surgery, however this trend has changed with operative hysteroscopy.
One in five women encounter IUAs after miscarriage. In more than half of these cases, the extent of these adhesions is mild and without clinical relevance. Recurrent miscarriages and D&C procedures were identified as key risk factors for adhesion formation. The risk of adhesion increased up to 40% if repeated D&C is performed (Hooker et al., 2016). Therefore it is reasonable to assume that direct visualization offered by hysteroscopy reduces the risk of uterine perforation. Plus, the risk of incomplete removal of retained placenta will also be decreased, certainly leading to fewer IUA's. Hysteroscopic removal of placental remnants, has been registered by several authors as an alternative method to 'blind' aspiration and/or curettage (Goldenberg et al., 1997;Westendorp et al., 1998;Golan et al., 2011;Hooker et al., 2013;Tjalina et al., 2013). The advantages of this approach are well established. Direct visualization of the RPOC, complete removal without damaging the surrounding healthy endometrium, and availability of a specimen for pathologic analysis make this approach preferable to 'blind' D&C. Goldenberg et al. (1997) reported their experiences with 18 patients (16 post-abortion and 2 postpartum) who underwent a hysteroscopy for removal of residual trophoblastic tissue causing continuous bleeding. Complete removal of the residual tissue was achieved in all these patients with no short-term complications reported. The authors concluded that selective curettage of residual trophoblastic tissue performed under hysteroscopy was a safe and fast procedure, and could be the firstchoice procedure, compared to conventional nonselective, 'blind' curettage. However, the current low level of surgeons' preference for hysteroscopy, versus the traditional D&C for RPOC, reflects some disadvantages with the current approach. Some of these are listed below: 1. Resectoscopy requires skill and has a long learning curve.
2. Abundant bleeding may impair the sight, making the procedure very difficult. In such cases a good irrigation system is crucial to maintain a clear sight of the uterine cavity.
3. In some cases, the resectoscope loop may bend.
4. Before the introduction of the bipolar resectoscope, the concern of fluid overload and water intoxication with Hypernatremia must be considered.
In order to increase surgeon adoption of hysteroscopy for RPOC, the new Shaver technique address these challenges. Specifically, with the IBS ® method the following advantages are observed: • A good visualization of the uterine cavity and the relative intrauterine pathology, through the removal of tissue chips at the same time as the resection. When the resectoscope is used, tissue chips may impair vision. This requires the surgeon to perform repeated in-and-out movements, with a higher risk of perforation and cervical laceration. Once inserted into the uterine cavity, the IBS ® is left in place for the entire duration of the procedure.
• A reduced risk of intravasation due to the use of saline solution, the brevity of the procedure, and a very low fluid deficit. In our study, a fluid loss limit of 2500 mL was reached in 1 patient only. In addition, no fluid-related adverse events were observed.
• A much more precise and clean surgery, due to the good visualization and direct action of the IBS ® over the pathological tissue. Moreover, the gentle mechanical technique and the blunt tip of the IBS ® , limits the damage to the healthy surrounding endometrium, leading to a reduced risk of uterine perforation, formation of intrauterine adhesions and
Conclusion
This is the first study using the hysteroscopic IBS ® for the removal of placental remnants.
This technique has shown to be an effective treatment method in the management of RPOC. We did not experience any complications, such as uterine perforation. In our study, we found that the longer the surgical procedure was performed after miscarriage, the less bleeding was observed. This is certainly due to the devascularization of the placental remnants which is time related. Thus, a reduced bleeding, allowed the surgeon to finalize the procedure in a single step. Adverse events, such as intrauterine bleeding may occur when using this technique, especially when treating large placental remnants. In the study, IBS ® demonstrated a good outcome in terms of operative time, fluid deficit, ease of procedure and postoperative adhesion. It is a safe, reliable, cost-effective and reusable tool for removing placental remnants. These results, as well as other outcomes, should however be confirmed by further studies with larger patient samples. More data is required for the preoperative decision over which modality is the safest and most complete to remove placental remnants for each patient. A randomized clinical trial with a larger number of patients should be therefore planned to determine which is the best modality for removal of placental remnants.
• A narrower outer instrument sheath of 8.5 mm (24 Fr.) allows for cervical dilatation only up to 8 of Hegar, instead of 9.5 of Hegar (of the 26 Fr. resectoscope). This leads to a reduced cervical trauma, with a lower risk of uterine perforation. In our cases, no uterine perforation occurred. Interestingly, a 19 Fr. IBS ® has been developed and is available, which should further improve these results.
• The possibility to collect all tissues for pathologic examination.
• The convenience of the re-usability of the shaver • A very short learning curve for the IBS ® procedure may encourage gynaecologists to choose operative hysteroscopy instead of D&C for removing RPOC.
(To note: the longer the interval between the end of pregnancy and the operative hysteroscopy with IBS ® , the easier the procedure. As reported in the literature (Golan et al., 2011), devascularization (time related) of retained placenta may lead to less bleeding) However, one limitation of the IBS ® is the impossibility of coagulation during the operation. This must taken into account in cases of heavy bleeding. Nevertheless, if necessary, a bipolar probe to selectively coagulate vessels can be introduced through the straight operative channel of the optics. In the presented cases, despite the lack of coagulation, no postoperative bleeding was observed.
Our data confirm precedent studies (Golan et al;2011;Hamerlynck et al., 2013) which suggest that to prevent intraoperative bleeding and further reduce the risk of incomplete removal of placental remnants, an await of at least 2 to 3 months after pregnancy before hysteroscopic removal of placental remnants should be respected. To our knowledge, this is the first study on the removal of placental remnants with the IBS ® (Bigatti, 2011). It should also be noted that a number of studies have shown good results for the use of a morcellator to remove placental remnants (Pather et al., 2005). Furthermore, our results are similar to those reported in the literature on hysteroscopic surgery, including both resectoscope and morcellator to treat RPOC (Hamerlynck et al., 2013).
We had no postoperative complications, no need for second-look surgery, and had complete removal of RPOC after one hysteroscopic surgery, with satisfactory outcomes at the 6-week follow-up. This study confirms the already well-known advantages of the IBS and specifically it's use for the removal of placental remnants (Bigatti, 2011). |
Neutronics studies on the feasibility of developing fast breeder reactor with flexible breeding ratio
This paper investigates the feasibility of designing a flexible fast breeder reactor from the view of neutronics. It requires that the variable breeding ratio can be achieved in operating a fast reactor without significant changes of the core, including the minimum change of fuel assembly design, the minimum change of the core configuration and the same control system arrangement in the core. The sodium cooled fast reactor is investigated. Two difficulties are overcome: (1) the different excess reactivity is well controlled for different cores, especially for the one with small breeding ratio; (2) the maximum linear power density is well controlled while the breeding ratio changes. The optimizations are done to meet the requirements. The U–Pu–Zr alloy is applied to enhance the breeding. The enrichment-zoning technique with unfixed blanket assembly loading position is searched to get acceptable power distributions when the breeding ratio changes. And the control system is designed redundantly to fulfill the control needs. Then, the achieved breeding ratio can be adjusted from 1.1 to 1.4. The reactivity coefficients, temperature distributions and preliminary safety performances are evaluated to investigate the feasibility of the new concept. All the results show that it is feasible to develop the fast reactor with flexible breeding ratios, although it still highly relies on the advancement of the coolant flow control technology. |
/*
* Notifies just get posted to the monitor. The actual notification is done
* when the monitor is fully exited so that MP systems don't contend for a
* monitor that they can't enter.
*/
static void _PR_PostNotifyToMonitor(PRMonitor *mon, PRBool broadcast)
{
PR_ASSERT(mon != NULL);
PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mon);
if (broadcast)
mon->notifyTimes = -1;
else if (mon->notifyTimes != -1)
mon->notifyTimes += 1;
} |
<filename>stats/stats_smallworld.c<gh_stars>0
/**
* Function for calculating the small world index of a graph.
*
* Author: <NAME> <<EMAIL>>
*/
#include <math.h>
#include <stdint.h>
#include "graph/graph.h"
#include "stats/stats.h"
#include "stats/stats_cache.h"
double stats_local_smallworld_index(graph_t *g, uint32_t n) {
double clustering;
double pathlength;
double randClustering;
double randPathlength;
double gamma;
double lambda;
stats_cache_node_pathlength(g, n, &pathlength);
stats_cache_node_clustering(g, n, &clustering);
randClustering = stats_er_clustering(g);
randPathlength = stats_er_pathlength(g);
gamma = clustering / randClustering;
lambda = pathlength / randPathlength;
return gamma / lambda;
}
double stats_smallworld_index(graph_t *g) {
double clustering;
double pathlength;
double randClustering;
double randPathlength;
double gamma;
double lambda;
pathlength = stats_cache_graph_pathlength(g);
clustering = stats_cache_graph_clustering(g);
randClustering = stats_er_clustering(g);
randPathlength = stats_er_pathlength(g);
gamma = clustering / randClustering;
lambda = pathlength / randPathlength;
return gamma / lambda;
}
double stats_er_pathlength(graph_t *g) {
double randPathlength;
double numnodes;
double degree;
numnodes = graph_num_nodes( g);
degree = stats_avg_degree(g);
/*
* Approximation of characteristic path length in an
* Erdos-Renyi random graph :
*
* <NAME>, <NAME>, <NAME>. Average path
* length in random networks. Physical Review E(70)
* 056110-1-7, 2004
*/
randPathlength = 0.5 + (log(numnodes) - 0.5772) / log(degree);
return randPathlength;
}
double stats_er_clustering(graph_t *g) {
/*
* In an Erdos Renyi random graph, the clustering
* coefficient of any node is, on average, equal to
* the density of the graph.
*/
return stats_density(g);
}
|
Illustration by Alex Eben Meyer.
Last week a man bumped into me on Fifth Avenue.
“Out of the way, tutti-frutti!” he boomed, eliciting shocked glances from passersby. As I scanned for a cop, I thought, “What kind of crazy, Little Richard–inspired hate speech was that?” But the moment quickly passed. The quaintness of this old-school 1950s insult gradually sank in. I elected to turn the other cheek and move on. This is unusual for me. I am typically more about grudge-bearing than forgiveness.
Almost 15 years ago a good friend of mine was murdered. The attacker offed himself shortly after committing the crime, so there was no opportunity for justice. At my pal’s funeral, a New Age preacher suggested to the congregation of grieving family and friends that it was “not too early to start thinking about forgiveness.” I was stunned, as was the victim’s sister, standing next to me. We had barely begun to navigate the horror and unfairness of our loss. Now we had to contend with a lay shaman exhorting us to move forward and to “let the healing begin.” I was ready to cut her.
This bizarre moment is etched in my memory. It was my first encounter with the now-ubiquitous forgiveness movement. The basic idea seems to be that the only way to come to terms with the murder or rape of a loved one is to forgive the perp. This notion has gained serious traction. In days gone by it was only the Man Upstairs who could pardon and absolve. Now everybody is taking a crack at it.
On a website called Give Forgiveness, viewers are treated to a quote from Joan Lunden:
“Holding on to anger, resentment and hurt only gives you tense muscles, a headache and a sore jaw from clenching your teeth. Forgiveness gives you back the laughter and the lightness in your life.”
This lovely thought seems to express the prevailing opinion. Regardless of how horrid your experience, you owe it to yourself to forgive so that you can bypass all that pain and anger and resume your life of nonstop chuckles, shoe shopping, and umbrella drinks.
In recent years there has been no shortage of high-profile forgiveness fests. Mary Jo Buttafuoco forgave Amy Fisher, the Long Island Lolita, for shooting her in the head at point-blank range. At one of his many parole hearings, Mark David Chapman, John Lennon’s killer, perturbed his interlocutors by suggesting that his victim would have forgiven him by now. (Impressively, Yoko Ono, a promoter of forgiveness in general, has repeatedly said she’s not ready to forgive Chapman.)
In 2010 a lad in Tallahassee, Fla., named Conor McBride shot his girlfriend in the head. As she was clinging to life-support, her father says he somehow sensed her pleading with him to forgive Conor. He forgave the young man.*
On March 7, just over a month after Oscar Pistorius was arrested on suspicion of murdering girlfriend Reeva Steenkamp, the uncle of the deceased beauty told CNN, “I would like to be face to face with him [Pistorius] and forgive him, forgive him [for] what he’s done and that way I can find most probably more peace with the situation but tell him face to face.”
Most recently, we have the Steubenville, Ohio, rape case. Last month, the mother of the victim shocked the courtroom when she told one of the rapists that she forgave him. Though I disagree wildly with her position, I can understand how she ended up there. Immersed in our culture of healing and kumbaya, and confronted with the sobbing, apologetic 16-year-old perp, she probably felt obliged to say something. But instead of offering to forgive him, how about a little helpful advice, for example: “Young man, terrible acts have terrible consequences. You must take your punishment like a man, and then, when you have paid your debt to society, you will be given a chance to rebuild your life. Don’t fuck it up.”
It’s easy to blame Oprah for the hug-it-out quick fix, but I think the responsibility lies with ourselves. We have all gotten a little squishy and confused. I suggest that we take a breath and try to sort the forgivable from the unforgivable. Here’s a start: If some drunken jerk wants to pick a fight or insults your choice of shoe, then by all means turn the other cheek. But rape and murder? Not so much.
At one time, knowing that some actions are beneath the valley of the forgivable—the Holocaust, murder, rape, animal cruelty—gave our existence a little structure. All we have are our teensy, fragile, tutti-frutti lives. If taking them away is forgivable, then we are left vulnerable, blowing in the wind, clutching our handbags and manbags, and hoping for the best.
On a less serious note, let’s talk about grudges. I am a firm believer that grudges and the bearing thereof can be less burdensome than Joan Lunden might think. In some instances they can actually be quite invigorating.
I have loads of chips on my shoulder, and I particularly enjoy munching through them while I am working out. I got the idea from an interview with Michael Phelps. He enlivens his grueling training schedule by mulling over previous slights and grievances. Get mad, and the time just flies by.
Here, for inspirational purposes, are a couple of the sizzling gripes that I am currently nurturing in my bosom:
The plight of pachyderms: I am beyond enraged at the people who unforgivably decimate the elephant population in order to feed the unforgivable Chinese appetite for ivory. Ditto rhino horns.
Naff news-anchors: I have grudges against all the network “journalists” and “current affairs news analysts.” Vivacious personalities, spray tans, blown-out hair … and that’s just the men. For a gruesome example, check out CNN’s new panel-fest, (Get to) the Point. This nightly over-rehearsed opinion match is screaming for a Saturday Night Live parody.
Sadistic schoolmarms: When I recall the violence visited upon myself and my scabby-kneed cohorts at my British primary school back in the 1950s, I can still get all riled up. Was it really necessary to clobber us on the head with that solid mahogany blackboard peg? Mrs. Pocock, I’m talking to you!
When I run out of grudges I often go back to remembering my old pal. At first I think about how insanely fun and life-enhancing he was. Inevitably, after musing for a while, I start to get irate at the injustice of his death, and I can feel my body fill with anger. But I wear that clenched jaw and tension headache—sorry, Joan Lunden—as a badge of honor. Out of respect for the memory of my pal, I will carry that rage and indignation to my grave. No forgiveness necessary.
Correction, April 4, 2013: This article originally stated that Conor McBride’s girlfriend forgave him on her deathbed. The NYT article reported that the woman’s father, while alone in her hospital room, “felt her say, ‘Forgive him.’ ” But she never verbally articulated the forgiveness herself. (Return.) |
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<math.h>
#include<assert.h>
using namespace std;
#define mod 1000000007
typedef long long int ll;
void combine(ll p[],ll mid,ll l,ll h){
ll i=l;
ll j=mid+1,k=l,c[100002];
while(i<=mid && j<=h){
if(p[i]>p[j]){
c[k]=p[i]; i++;k++;
}else{
c[k]=p[j]; j++;k++;
}
}
while(i<=mid){
c[k]=p[i]; i++;k++;
}
while(j<=h){
c[k]=p[j]; j++;k++;
}
for(ll i=l;i<k;i++){
p[i]=c[i];
}
}
void merge_sort(ll p[],ll l,ll h){
if(h-l<=1){
if(p[l]<p[h]){
ll t=p[l];
p[l]=p[h];
p[h]=t;
}
return;
}
ll mid=(l+h)/2;
merge_sort(p,l,mid);
merge_sort(p,mid+1,h);
combine(p,mid,l,h);
}
ll primes[1000000];
ll count_prime=0;
ll gl_i=0;
int chck_prime(ll n){
ll t= sqrt(n);
ll i;
int flg2=0;
if(n==2)
return 1;
for(i=0;i<count_prime;i++){
if(n%primes[i] ==0){
return 0;
}
if(t<primes[i]){
return 1;
}
}
return 1; // prime
}
void gen_primes(ll n){
primes[0]=2;count_prime++;
primes[1]=3;count_prime++;
for(ll i=3;i<n;i++){
{
if(i%2==0 ){
continue;
}
if(i%3==0 ){
continue;
}
if(chck_prime(i)==1){
primes[count_prime]=i; count_prime++;
}
}
}
}
int main(){
gen_primes(100000);
ll n;
//printf("%d %d\n",chck_prime(2),chck_prime(3));
scanf("%lld",&n);
for(ll i=4;i<n;i++){
if(chck_prime(i)==0){
if(chck_prime(n-i)==0){
printf("%lld %lld\n",i,n-i);
break;
}
}
}
return 0;
} |
<reponame>h-arlt/morphia<gh_stars>100-1000
package dev.morphia.test.mapping;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.Property;
import dev.morphia.mapping.codec.pojo.EntityModel;
import dev.morphia.mapping.codec.pojo.PropertyModel;
import dev.morphia.mapping.codec.pojo.TypeData;
import dev.morphia.test.TestBase;
import org.bson.types.ObjectId;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static dev.morphia.query.experimental.filters.Filters.eq;
public class TestPropertyModel extends TestBase {
private EntityModel entityModel;
@Test
public void arrayFieldMapping() {
final PropertyModel property = getMappedField("arrayOfInt");
Assert.assertFalse(property.isScalarValue());
Assert.assertTrue(property.isMultipleValues());
Assert.assertTrue(property.isArray());
Assert.assertTrue(property.getType().isArray());
Assert.assertEquals(property.getName(), "arrayOfInt");
Assert.assertEquals(property.getMappedName(), "arrayOfInt");
}
@Test
public void basicFieldMapping() {
final PropertyModel property = getMappedField("name");
Assert.assertTrue(property.isScalarValue());
Assert.assertSame(property.getType(), String.class);
Assert.assertEquals(property.getName(), "name");
Assert.assertEquals(property.getMappedName(), "n");
}
@Test
public void collectionFieldMapping() {
final PropertyModel property = getMappedField("listOfString");
Assert.assertFalse(property.isScalarValue());
Assert.assertTrue(property.isMultipleValues());
Assert.assertFalse(property.isArray());
Assert.assertSame(property.getType(), List.class);
Assert.assertSame(property.getNormalizedType(), String.class);
Assert.assertEquals(property.getName(), "listOfString");
Assert.assertEquals(property.getMappedName(), "listOfString");
}
@Test
public void idFieldMapping() {
final PropertyModel property = getMappedField("id");
Assert.assertTrue(property.isScalarValue());
Assert.assertSame(property.getType(), ObjectId.class);
Assert.assertEquals(property.getName(), "id");
Assert.assertEquals(property.getMappedName(), "_id");
}
@BeforeMethod
public void mapping() {
getMapper().map(List.of(TestEntity.class));
entityModel = getMapper().getEntityModel(TestEntity.class);
}
@Test
public void nestedCollectionsMapping() {
final PropertyModel property = getMappedField("listOfListOfString");
Assert.assertFalse(property.isScalarValue());
Assert.assertTrue(property.isMultipleValues());
Assert.assertFalse(property.isArray());
Assert.assertSame(property.getType(), List.class);
final TypeData<?> typeData = property.getTypeData();
Assert.assertSame(typeData.getType(), List.class);
Assert.assertEquals(typeData.getTypeParameters().get(0).getTypeParameters().get(0).getType(), String.class);
Assert.assertEquals(property.getName(), "listOfListOfString");
Assert.assertEquals(property.getMappedName(), "listOfListOfString");
final List<List<String>> list = new ArrayList<>();
list.add(dbList("a", "b", "c"));
list.add(dbList("d", "e", "f"));
TestEntity testEntity = new TestEntity();
testEntity.listOfListOfString = list;
getDs().save(testEntity);
Assert.assertEquals(list, getDs().find(TestEntity.class)
.filter(eq("_id", testEntity.id))
.first()
.listOfListOfString);
}
private PropertyModel getMappedField(String name) {
return entityModel.getProperty(name);
}
private List<String> dbList(String... values) {
return new ArrayList<>(Arrays.asList(values));
}
@Entity
private static class TestEntity {
@Id
private ObjectId id;
@Property("n")
private String name;
private List<String> listOfString;
private List<List<String>> listOfListOfString;
private int[] arrayOfInt;
private Map<String, Integer> mapOfInts;
private List<Embed> listOfEmbeds;
}
@Entity
private static class Embed {
private String embedName;
private List<Embed> embeddeds;
}
}
|
<filename>src/lambda-calls-phone-api.py
# Version: Python 3.9 (verified)
# Import libraries
import json, os
import boto3
import urllib3 # The requests library is desperated in Lambda, so we need to use urllib3
# For logging and trace
import logging, traceback
import time
from base64 import b64decode # For data decryption
from botocore.exceptions import ClientError # For Exception handling
# Environment variables
notify_url = os.environ['notify_url']
token_secret_name = os.environ['token_secret_name']
max_tries = int(os.environ['max_tries'])
wait_secs = int(os.environ['wait_secs'])
template = os.environ['template']
input_receivers = os.environ['receivers']
# System variables
aws_region = os.environ['AWS_DEFAULT_REGION']
# Retrieve token from Amazon Secrets Manager
def get_secret(secret_name, region_name):
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
if e.response['Error']['Code'] == 'DecryptionFailureException':
# Secrets Manager can't decrypt the protected secret text using the provided KMS key.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InternalServiceErrorException':
# An error occurred on the server side.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidParameterException':
# You provided an invalid value for a parameter.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'InvalidRequestException':
# You provided a parameter value that is not valid for the current state of the resource.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
# We can't find the resource that you asked for.
# Deal with the exception here, and/or rethrow at your discretion.
raise e
else:
# Decrypts secret using the associated KMS key.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
decoded_binary_secret = ''
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
secret = decoded_binary_secret
return secret
secrets = get_secret(token_secret_name, aws_region)
if secrets != '':
secrets = json.loads(secrets)
if 'api_token' in secrets:
token = secrets['api_token']
receivers = secrets['default_receiver']
# Request headers
authorization = 'Token ' + token
headers = {'Accept': 'application/json', 'Content-type':'application/json', 'Authorization': authorization}
# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Message class
class Message:
def __init__(self, receivers, subject, body, template):
self.receivers = receivers
self.subject = subject
self.body = body
self.template = template
def send(self):
# @TODO Construct the message based on configurations of the 3rd-party API.
messages = {"template": self.template, "content": self.body, "receivers": self.receivers}
# Logging
logger.info(self.receivers + " " + self.body)
# Send a POST request via urllib3
http = urllib3.PoolManager(timeout=1.0, retries=False)
response = http.request('POST', notify_url, headers=headers, body=json.dumps(messages))
# return HTTP response
return response
### Lambda Handler begins ###
def lambda_handler(event, context):
# Debug information
print("Received event: " + json.dumps(event, indent=2))
# Example: sns_message = json.loads(event['Records'][0]['Sns']['Message'])
# Default error repsonse
output_message = 'Calling the API Failed!'
try:
# @TODO get parameters from the event object
# receivers = os.environ['receivers']
subject = os.environ['subject']
body = os.environ['body']
print("Receivers: ", receivers)
print("Subject: ", subject)
print("Body: ", body)
except:
e = traceback.format_exc()
# Logging
logging.error(e)
attempts = 0
success = False
# Create a message object
message = Message(receivers, subject, body, template)
while attempts < max_tries:
attempts += 1
try:
r = message.send() # Send the message
if r.status < 500:
if r.status == 200:
success = True
output_message = 'Calling the API Succeeded!'
else: # Other types of errors, but end the loop
# Log the error
output_message = 'Error: ' + str(r.data)
break
# except:
except urllib3.exceptions.NewConnectionError as e:
# Log the error
logger.debug(e)
logger.debug("Resend message " + str(attempts) + " times!")
time.sleep(wait_secs)
if attempts == max_tries:
break
if success:
return {
'statusCode': 200,
'body': json.dumps(output_message)
}
else:
return {
'statusCode': 400,
'body': json.dumps(output_message)
}
### Lambda Handler ends here
|
It seems like it was just yesterday that we were awaiting an update to version 13 of Google Hangouts with its host of new emoticons and stability improvements. And while Google is trying to really market Allo to its growing consumer base, Hangouts looks to be in continued development as it makes the shift to a more enterprise-level service.
Around here, Hangouts is still king, so we are very happy to see ongoing development. Let’s see what’s new!
App Shortcuts
First up, we have the addition of app shortcuts. Some of you may be unfamiliar with this as it is a feature unique to Android 7.1. In its most basic form, app shortcuts are like 3D Touch on an iPhone. No real pressure is needed (and never was necessary, IMHO), just a simple long-press on the app icon and you get a nice sub-menu of quick actions. (see the main pic above)
For Hangouts, we get:
Voice Call
Video Call
Chat
Clicking any of these starts a new call or chat, and is super-handy if you are ready to jump into a new conversation. You don’t have to open the app and click around. Simply select the action and you are ready to go.
These will get more and more useful as time goes on and developers take advantage of app shortcuts as time goes on.
Simplified Group Setup
I’ve always thought creating a group to be just a bit clunky in Hangouts. Version 14 separates out the single and group contact spaces, making both much simpler and more clear.
You can see from the screen grab that the default new conversation is with a single contact. Start typing or select from a contact in the list and you are in the chat window. Easy.
For a group, simply select ‘New Group’. You get the chance to name the group and quickly add in contact there. Again, simpler and way more straightforward. Little user flow fixes like this make apps feel much more polished and user friendly.
Clearer Menu Options
I nside chats, we used to have the menu item ‘People and Options’ and it never made sense to stick them together. Usually I’m just hunting for who’s in a group, not really wanting to mess with settings. As of version 11, Hangouts finally gave users the ability to remove users from groups as well, so having a simple place to see who’s in a group is much simpler and streamlined.
So far, that’s all the new we’ve seen, but we’re encouraged and excited that development continues on our much-beloved Hangouts app. It give me hope that I won’t have to part ways with it for a long time to come. |
Association between protein intake and lean body mass in a group of Masters Athletes
Recommendations for protein intake are based on total body weight; however, these recommendations do not consider lean body mass (LBM). The purpose of the present study was to identify the average protein intake in g/kg LBM in a group of healthy Masters Athletes (≥26 years of age, exercising ≥2 d/week). Data were obtained from a cross-sectional study. Body weight (kg), height (cm) and LBM via dual-energy X-ray absorptiometry were measured. Dietary intake was measured using a 2005 Block Food Frequency Questionnaire. The average energy intake, the percent energy from protein and the average protein intake in g/kg LBM were calculated. Differences between protein intake and the US Recommended Dietary Allowance (US RDA) (0⋅8 g/kg body weight) were determined. Alpha levels were set a priori to P < 0⋅05. A total of 176 participants (94 women, 82 men; 39 ± 11 years of age; body mass index: 24⋅6 ± 3⋅4 kg/m2) were analysed. The average energy intake, the percent protein energy and the average protein intake were 7996⋅9 ± 110⋅9 kilojoules (kJ)/d (1,910⋅4 ± 26⋅5 kcal), 15⋅5 ± 2⋅6 % and 1⋅43 ± 0⋅53 g/kg LBM, respectively. No differences existed between women and men for protein intake/kg LBM. Both sexes had significantly higher protein intakes than the US RDA (P < 0⋅001). We identified the average protein intake (g/kg LBM) in healthy Masters Athletes that may contribute to evolving perspectives on the determination of protein needs. The present study helps establish the relationship between protein intake and LBM so that we may further increase our accuracy when developing future protein recommendations.
Introduction
Dietary protein is a crucial nutrient in the human diet that is essential for maintaining cellular function and body composition. Intake recommendations for dietary protein in healthy adults have been established using the estimated average requirement (EAR) to determine the United States Recommended Dietary Allowance (US RDA). Rather than providing absolute values, the dietary recommendation for protein intake is 0⋅80 gram per kilogram (g/kg) of total body weight; however, these recommendations do not provide disaggregated reference recommendations for adults by age or sex. Instead, the adult recommendations for dietary protein were based on meta-analyses of studies evaluating the daily protein intake needed to achieve zero-nitrogen balance as its endpoint (1) . Maintaining zero-nitrogen balance is an indirect marker for the maintenance of protein needs as a measurement of protein breakdown to protein synthesis. A zeronitrogen balance, therefore, equates to an equilibrium of protein breakdown to synthesis, which may be integral to the establishment of protein needs; however, nitrogen balance fails to identify mechanisms for such processes and their implications in lean body mass (LBM). During times of energy balance, zero-nitrogen balance does not directly account for the maintenance of LBM, and therefore clinically, it has its limitations.
Limitations of the nitrogen balance studies conducted to date are well recognised, and incorporation of outcome measures for protein intake, such as maintaining or improving LBM, are needed to better reflect physiologic needs (2)(3)(4) . Although protein recommendations are proportionate to total body weight, recent evidence suggests that LBM may provide a more accurate and precise metric for dietary protein needs given the known relationship between dietary protein and body composition in the literature (3)(4)(5) .
Data exploring the relationship between LBM and protein intake are also limited and are often found in correlational studies with older adults living with or who are at-risk for sarcopenia (6,7) . Finally, research that has examined outcomes for effective protein intake have revealed a possible range between 0⋅83 g and 1⋅77 g/kg LBM, well above the US RDA using total body weight (4,8) . Given the large inter-individual variability in body composition, coupled with nitrogen balance as an intermediate marker that reflects body cell mass or its clinical proxy, LBM, it may, therefore, be more appropriate to consider LBM when analysing adult protein needs.
Based on the limited research available for LBM in relation to protein need, more data are needed to better understand the relationship between these two variables. Data capturing the relationship between protein intake and LBM are needed to elucidate protein needs that can be based on LBM as opposed to total body mass. The most representative sections of the population who are likely meeting their daily protein needs and nitrogen balance are healthy, weight stable adults. Previous researchers have elucidated that Masters Athletes have similar muscle characteristics, physiological responses to exercise and protein metabolism as young athletes, and are unlikely to have protein requirements that are different from their young contemporaries (9) . We, therefore, selected a cohort of Masters Athletes to better articulate the relationship between LBM and protein intake. In addition, there is a paucity of data on protein needs for Masters Athletes. The primary aims of the present study were to compare protein intake to the current guidelines as well as describe the average protein intake in g/kg of LBM in a group of healthy adult Masters Athletes as a first step to exploring the relationship between dietary protein intake and LBM. We hypothesised that dietary protein intake would be significantly different from current intake guidelines.
Participants
Data were obtained from a cross-sectional study in a cohort of healthy Masters Athletes. Masters Athletes were defined as athletes, 26 years of age and older, who exercised at least 2 d/week. Our population represented a diverse group of sports, in which the age of Masters Athletes varied from as young as 21 years of age. Therefore, we used 26 years of age as the starting age for those who would be grouped as Masters Athletes. Participants were excluded if they were active smokers, pregnant women or diagnosed with an uncontrolled chronic disease. Recruitment was conducted using posted flyers around the Philadelphia area. The present study was conducted according to the guidelines laid down in the Declaration of Helsinki and all procedures involving human subjects/patients were approved by the Institutional Review Board at Drexel University (Approval No. 1304002037). Written and verbal informed consent was obtained from all subjects/patients.
Anthropometric and body composition assessment
Body weight, height and body mass index. Participants were measured for body weight (kg) and height (cm), using a mechanical column scale and an attached stadiometer (Seca Hamburg, Germany), respectively. Body weight and height were measured twice, and the average of the measurements was computed and recorded as a quality control measure. Body mass index (BMI) was calculated for each participant using their weight in kg divided by height in metre squared (kg/m 2 ).
Dual-energy X-ray absorptiometry. Body composition and LBM were measured using dual-energy X-ray absorptiometry (DXA; LunariDXA, General Electric Company, 2018). DXA is considered one of the most accurate methods for body composition assessment due to its demonstrated validity, reliability and precision (10)(11)(12)(13) . Participants subjected to the DXA scan received a total body scan to assess LBM, which was interpreted in pounds. LBM was then converted from pounds to kg for analysis.
Energy and protein intakes
To assess total energy and protein intakes, each participant completed a self-administered 2005 Block's Food Frequency Questionnaire (FFQ) (14,15) . The FFQ is a previously validated tool that produces data representative of yearly dietary consumption by asking questions about dietary habits and specific food consumption. The FFQ has been shown to accurately predict protein intake when compared to 4-d diet records (14) . Completed questionnaires were sent to NutritionQuest© (Berkeley, CA) for analysis and returned to the research team for interpretation and statistical analyses.
Statistical analyses
Descriptive statistics (mean ± standard deviation) were used to determine the average energy intake, the percent energy intake from dietary protein and the average protein intake in g/kg of LBM. An independent samples t-test was used to determine whether differences existed in protein intake (g/kg LBM) between women and men. A one-sample t-test was also used to compare the average protein intake of participants (total sample, and by women and men) to the US RDA (0⋅8 g/kg body weight). A post hoc power analysis was applied with an effect size of 0⋅5 and with a sample size of 176, which resulted in a power of 0⋅99 for the total sample. All statistical procedures were performed with the Statistical Package for the Social Sciences (SPSS) version 24.0 with alpha levels set a priori to P < 0⋅05.
Participant characteristics
A total of 176 Masters Athletes (94 women, 82 men) were included in our analyses (Table 1).
Specific athletic activities reported by participants are included in Fig. 1.
Discussion
The objective of the present study was to describe the average dietary protein intake in g/kg LBM and to explore the relationship between these two variables in a healthy sample. Our sample consumed 15⋅6 % of their energy as protein, well within the AMDR (10-35 %). Protein intake of 1⋅4 g/kg LBM was similar between women and men, with a proteinto-energy ratio of about 0⋅038 compared to the normative values for light and moderately active women (0⋅059 to 0⋅074) and men (0⋅081 to 0⋅098) (17) . Based on previous research, it is clear that there are limitations when determining protein needs. As a reference standard, the US RDA for protein is established as a reference for consumers with respect to how much protein they should consume. These recommendations are designed to guide the general population in estimating protein needs, but have been critiqued for the accuracy across diverse populations. Notably, for active populations, it has been suggested that protein needs are closer to a range of 1⋅2-2⋅0 g/kg (18) . The US RDA for protein is a highly valuable tool for estimation; however, it may better translate as a minimum threshold for maintenance rather than a precise obtainable amount, which can have high individual variability. In support of this, it has been previously speculated that current protein recommendations based on the US RDA may be lower than physiological needs, especially in those who exercise regularly (3,4,19) . There are data suggesting that this technique tends to overestimate intake. Mitchell et al. (20) conducted a 10-week randomised controlled trial where participants consumed protein at twice the US RDA. This increased protein intake resulted in a better retention of LBM in older adults (74⋅2 ± 3⋅6 years of age), suggesting that protein needs may be higher in older individuals, which is in agreement with others. (21) In addition, protein intake within the AMDR of 10-35 % of energy intake routinely allows intake to exceed the US RDA (22) . Campbell et al. (3) reported that meeting the US RDA for protein during a controlled 14-week eucaloric diet resulted in a significant loss of mid-thigh muscle area during a period with no weight loss in a group of healthy, women and men, 55-77 years of age. In an animal model, nitrogen balance data have displayed a significant underestimation of protein needs when compared against the requirements to maintain LBM measured by DXA (23) , which is consistent with our data. Furthermore, a biphasic linear regression analysis of the nitrogen balance data resulted in a higher value for protein recommendations (1 g/kg), which is consistent with our findings (24) . The critique of the current recommendations may be due to the failure of nitrogen balance data to account for other physiologic outcomes that are important to protein status. Therefore, the goal of our analyses was to describe protein intake using LBM, a primary physiological driver of protein needs, and compare these findings to the current recommendations.
The indicator amino acid oxidation (IAAO) technique is an alternative tool and has estimated adult protein needs to be around 1⋅2 g/kg (24) , which is in close agreement to the average intake we found. Like nitrogen balance, the IAAO technique uses the biological response under controlled conditions as an indirect estimation of a theoretical protein equilibrium. Nitrogen balance and the IAAO technique appear to be accurate measures of protein balance; however, they are not without their limitations, specifically, their inability to accurately account for body composition (4,8,25) .
In addition, the use of total body weight for the aforementioned methods leads to one of the biggest critiques of current protein recommendations. Total body weight is indicative of weight status, but does reflect body composition differences, which can lead to underestimation of protein needs. Notably, sarcopenia is a protein intake-related condition characterised by a reduced quantity of skeletal muscle mass, of which progression is directly measurable through body composition analysis (26) . Additionally, sarcopenic obesity is a new class of obesity in older adults in which low skeletal muscle mass is coupled with high levels of adiposity (27) . The lack of body composition data makes it extremely difficult to track the progression of conditions like sarcopenia and sarcopenic obesity.
In addition to body composition, methods like nitrogen balance and the IAAO do not account for physiological outcomes that are indicative of protein needs. Physiological outcomes are often measured as a sign of progression, related to protein-supported muscle hypertrophy, or regression related to protein-deficient muscle breakdown. LBM is a wellaccepted outcome measure for protein status and can account for tissue distribution differences. Protein intakes have been positively associated with the development of LBM. In fact, increased protein intakes have been reported to improve LBM and functional capacity (20,(28)(29)(30)(31) . Higher intakes of protein also help to maintain LBM in hypocaloric weight loss diets (32)(33)(34) . In the elderly, loss of LBM was the lowest in those consuming the most protein (about 18 % of total energy intake) (35) .
As suggested, the US RDA for protein needs has been established using primarily nitrogen balance data. If nitrogen balance serves as a surrogate for LBM, then the influence of varying protein intakes following adaptation over time on LBM would be valuable. If the protein intakes required to maintain LBM were an outcome, it would be of great interest to appreciate the current protein intakes relative to LBM. Using maintenance of LBM as an outcome, instead of zeronitrogen balance, may necessitate higher accuracy when estimating protein intake, especially in the elderly, those on bed rest, or during energy restriction. Limited data have been gathered to support LBM as a more accurate metric. The present study is in agreement with previous data exploring this relationship and suggests that there may be promise in using LBM to estimate protein needs (4,8) . Recently, Rafii et al. (8) reported average protein needs of 1⋅62 ± 0⋅14 g/kg LBM based on the amino acid oxidation technique in a cohort of older women. These protein needs are slightly higher than the average protein intake consumed by our cohort (8) . In addition, we reported no significant differences in protein intake (g/kg LBM) between women and men. Women appeared to have slightly, but not significantly, higher protein intakes than men. This might be expected because women and men's protein intakes per gram of total mass are very similar (1⋅0 ± 0⋅38 v. 1⋅0 ± 0⋅45, respectively), and women typically have a lower proportion of lean mass compared to men (36) . We speculate that the lack of differences observed between women and men in protein intake (in g/kg LBM) may be due to indexing to LBM instead of total body weight, which is more relative to an individual's body composition. It is important to note that our analysis relies on the assumption that our healthy population was meeting their physiological protein needs. Based on the data presented here, it is still unclear whether the dosing of protein should be based on LBM, but our analysis is a start to how much protein it takes for healthy weight stable adults to maintain their LBM. Our overall findings may, therefore, contribute to the evolving perspective on how best to determine protein recommendations for healthy adults.
The present study was not without limitations, which included the use of self-reported dietary intake information. Self-reported data introduces the potential of self-reporting bias and/or the misrepresentation of information (37) . However, participants were not aware that protein was our nutrient of interest, therefore, reducing the potential to influence the results. Another limitation of the present study includes the lack of nitrogen balance data with which to corroborate the present results. Given the historic use of nitrogen balance in deriving the current US RDA, it would be beneficial to have had access to this information to better ascertain the present results. In addition, we maintained underlying assumptions: participants were weight and metabolically stable, and their intake was constant without yearly variation. To help account for limitations in weight stability, body weights were measured at two different sessions to compare weight discrepancies. The assumed weight stable status occurs without a change in body composition including LBM, or a change in protein turnover, without the need for habitual adaptation or accommodation. Stability, therefore, suggests a predictable interrelationship between LBM and protein intake. The limitations of relying on the assumptions of weight stability were uncontrolled in the present study and have the potential to negatively influence the data. With respect to potential variations in yearly protein intake, it is important to note that the FFQ attempts to account for this by collecting intake based on a yearly average. Finally, dietary measures of protein are absolute and do not take into account the quality of protein or the distribution of protein intake across the day. Protein quality can influence muscle protein synthesis, which can, in turn, alter LBM. In an effort to account for potential limitations in sample size, post hoc power analysis was applied with an effect size of 0⋅5 and with a sample size of 176, which resulted in a power of 0⋅99 for the total sample. This revealed an adequate sample size to detect differences from the US RDA. Despite the limitations, the data provide a valuable examination of the relationship between protein intakes in a cohort of healthy Masters Athletes.
In conclusion, in our cross-sectional analysis, we found that the average protein intake was significantly higher than the current US RDA in a cohort of healthy individuals. We also found a significantly higher protein need per kg LBM when compared to the US RDA for both women and men. Our intention is to establish the foreground for the relationship between LBM and protein need. In addition, we hope to establish the foundation for LBM to be used to calculate protein needs. Furthermore, there was no significant difference between women and men with respect to protein intake per kg of LBM. Therefore, LBM may be involved in the physiological driver of protein needs in physically active, healthy adults. Further exploration of the relationship between protein intake and LBM is warranted to support the notion of calculating protein needs based on LBM. These studies should consider longitudinal designs that monitor weight changes, energy and protein intakes in healthy as well as at-risk populations to better elucidate meeting physiological protein needs. In addition, nitrogen balance studies that monitor body composition should also be considered to better understand how lean mass reflects protein needs. By establishing the relationship, between protein need and LBM, we may increase our accuracy when developing protein recommendations for individuals, which, in turn, can increase the quality of care for all. |
a, b, c = map(int, raw_input().split())
res = (a+b)/c
deb = (a+b)/c - a/c - b/c
a %= c
b %= c
dt = 0
if deb:
dt = c-max(a,b)
print res,dt |
<reponame>sgholamian/log-aware-clone-detection<filename>LACCPlus/Camel/271_1.java
//,temp,LuceneIndexAndQueryProducerIT.java,159,179,temp,LuceneIndexAndQueryProducerIT.java,123,144
//,2
public class xxx {
public void configure() {
from("direct:start").setHeader("QUERY", constant("Grouc?? Marx"))
.to("lucene:searchIndex:query?analyzer=#stdAnalyzer&indexDir=#std&maxHits=20").to("direct:next");
from("direct:next").process(new Processor() {
public void process(Exchange exchange) throws Exception {
Hits hits = exchange.getIn().getBody(Hits.class);
printResults(hits);
}
private void printResults(Hits hits) {
LOG.debug("Number of hits: " + hits.getNumberOfHits());
for (int i = 0; i < hits.getNumberOfHits(); i++) {
LOG.debug("Hit " + i + " Index Location:" + hits.getHit().get(i).getHitLocation());
LOG.debug("Hit " + i + " Score:" + hits.getHit().get(i).getScore());
LOG.debug("Hit " + i + " Data:" + hits.getHit().get(i).getData());
}
}
}).to("mock:searchResult");
}
}; |
Target Detection and Identification with a Heterogeneous Sensor Network by Strategic Resource Allocation and Coordination
In this paper, an approach for target acquisition and identification with a heterogeneous sensor network through strategic resource allocation and coordination is presented. Based on sensor management technologies, low performance sensors are deployed to guide and cue scarce high performance sensors in the network to best improve the data quality. We focus on the problem of designing such a network system in which issues of resource selection and allocation, system behavior and performance, and multiple constraints must be addressed simultaneously. Simulation results offer significant insight into sensor selection and network operation, and demonstrate the benefits introduced by guided search in an application of target localization and identification on the battlefield |
The Flyers enter the month of March, where they have 14 games in 28 days including three sets of back-to-backs in which five of those six games are played on the road… They are three points behind Pittsburgh for the final playoff spot with three games remaining against the Penguins… The Flyers are in the midst of a six-game homestand, having won all three games and scoring an average of four goals per-game thus far… They have also scored a goal on the power play in all three games, operating at 50 percent (4-for-8)… The Flyers have won five of their last seven (5-1-1) and have earned points in 18 of 26 games since the start of the new year, going 14-8-4.
The Oilers come into tonight having won two straight games… They have not won three games in-a-row since they had a six-game winning streak from Dec. 2-14… This is also the first game in back-to-back nights for the Oilers, who own a 4-2-2 record in the opening contest of back-to-back sets… The Oilers have not scored on the power-play in seven straight games, going 0-for-16 in that stretch… Taylor Hall leads the team in scoring with 20 goals and 54 points in 65 games… Goaltender Cam Talbot has made eight straight starts and has appeared in 20 of the Oilers last 21 games… He’s won two straight and faced over 30 shots in each of his last four games, stopping 133 of 139 shots and recording a .957 save percentage in that span… The Oilers have been outshot by their opponent in 43 of their 65 games (66.1%), but have 16 of their 24 wins when they are out-shot (16-22-5). |
<filename>src/contexts/app.tsx
import React, { useContext } from 'react';
import { ChildrenProps } from 'global-types';
import { ApiClient } from 'lib/http';
import BackendApiService from 'services/backend';
import SectionsApiService from 'services/section';
import { AppServices } from 'services';
import StorageService from 'services/storage';
import configureAppStore from 'lib/create-store';
import { Provider } from 'react-redux';
import rootReducer from 'slices';
const AppServiceContext = React.createContext<AppServices | undefined>(undefined);
const store = configureAppStore();
export type FullStoreShape = ReturnType<typeof rootReducer>;
export function AppStoreProvider({ children }: ChildrenProps) {
return (
<Provider store={store}>
<AppServicesProvider>{children}</AppServicesProvider>
</Provider>
);
}
export const AppServicesProvider = ({ children }: ChildrenProps): JSX.Element => {
const appServices: AppServices = {
sectionsService: new SectionsApiService(new ApiClient()),
backendService: new BackendApiService(new ApiClient()),
storageService: new StorageService(localStorage)
};
return <AppServiceContext.Provider value={appServices}>{children}</AppServiceContext.Provider>;
};
export function useAppService() {
const context = useContext(AppServiceContext);
if (context === undefined) {
throw new Error('useAppService must be used within AppServiceContextProvider');
}
return context;
}
|
/// data is available only if there're tables related to input sequences and parameters of the input sequences.
bool DB_adapter::is_data_available ()
{
if ( is_seqs_available () && is_params_available () )
return DB_YES;
else
return DB_NO;
} |
// A placeholder fragment containing a simple view.
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private Button startButton = null;
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
// event handlers
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
int section = getArguments().getInt(ARG_SECTION_NUMBER);
if (section == 0) {
rootView = inflater.inflate(R.layout.fragment_videotitle, container, false);
VideoView videoView = rootView.findViewById(R.id.videoViewTitle);
Uri videoUri = Uri.parse("android.resource://" + getActivity().getPackageName()
+ "/" + R.raw.whitesmoke);
videoView.setVideoURI(videoUri);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
videoView.start();
videoView.requestFocus();
}
else {
rootView = inflater.inflate(R.layout.fragment_mode, container, false);
startButton = rootView.findViewById(R.id.button_mode);
}
// adjust TextViews
TextView title = rootView.findViewById(R.id.textView_mode_title);
TextView description = rootView.findViewById(R.id.textView_mode_description);
switch (section) {
case 0:
// no text for video title
break;
case 1:
title.setText(R.string.mode_blebride_title);
description.setText(R.string.mode_blebride_description);
break;
case 2:
title.setText(R.string.mode_localdisplay_title);
description.setText(R.string.mode_localdisplay_description);
break;
default:
title.setText(R.string.mode_emptytitle);
description.setText(R.string.mode_emptydescription);
Log.w(TAG, "Trying to access more fragments than possible.");
}
return rootView;
}
@Override
public void onResume() {
if (startButton != null) {
startButton.setText(R.string.button_mode_start);
}
super.onResume();
}
} |
<reponame>m-philipps/pyPESTO<gh_stars>10-100
# setup.py is still needed for editable installs
import setuptools
setuptools.setup()
|
package net.anotheria.moskito.core.util;
import net.anotheria.moskito.core.predefined.RuntimeStats;
import net.anotheria.moskito.core.producers.IStats;
import net.anotheria.moskito.core.producers.IStatsProducer;
import net.anotheria.moskito.core.registry.ProducerRegistryFactory;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
/**
* Builtin producer for values supplied by jmx for the runtime.
* @author lrosenberg
*/
public class BuiltInRuntimeProducer extends AbstractBuiltInProducer implements IStatsProducer, BuiltInProducer{
/**
* Associated stats.
*/
private RuntimeStats stats;
/**
* Stats container
*/
private List<IStats> statsList;
/**
* The monitored pool.
*/
private RuntimeMXBean mxBean;
public BuiltInRuntimeProducer(){
mxBean = ManagementFactory.getRuntimeMXBean();
statsList = new ArrayList<IStats>(1);
stats = new RuntimeStats();
statsList.add(stats);
BuiltinUpdater.addTask(new TimerTask() {
@Override
public void run() {
readMbean();
}});
ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(this);
}
@Override
public String getCategory() {
return "runtime";
}
@Override
public String getProducerId() {
return "Runtime";
}
@Override
public List<IStats> getStats() {
return statsList;
}
private void readMbean() {
long starttime = mxBean.getStartTime();
long uptime = mxBean.getUptime();
String name = mxBean.getName();
stats.update(name, starttime, uptime);
}
}
|
/**
* Created by Andreas Dyck on 26.07.17.
*/
public class AuditApiTest {
@Test
public void testAuditApi() {
final CloudOfThingsRestClient cotRestClientMock = Mockito.mock(CloudOfThingsRestClient.class);
AuditApi auditApi = new AuditApi(cotRestClientMock);
Assert.assertNotNull(auditApi);
}
@Test
public void testGetAuditRecord() {
final CloudOfThingsRestClient cotRestClientMock = Mockito.mock(CloudOfThingsRestClient.class);
final AuditApi auditApi = new AuditApi(cotRestClientMock);
final String auditRecordId = "234";
final String text = "new audit record created";
final AuditRecord testAuditRecord = new AuditRecord();
testAuditRecord.setId(auditRecordId);
testAuditRecord.setText(text);
final Gson gson = GsonUtils.createGson();
final String json = gson.toJson(testAuditRecord);
Mockito.when(cotRestClientMock.getResponse(eq(auditRecordId), any(String.class), any(String.class))).thenReturn(json);
AuditRecord retrievedAuditRecord = auditApi.getAuditRecord(auditRecordId);
Assert.assertNotNull(retrievedAuditRecord);
Assert.assertEquals(retrievedAuditRecord.getId(), auditRecordId);
Assert.assertEquals(retrievedAuditRecord.getText(), text);
}
@Test
public void testCreateAuditRecord() {
final CloudOfThingsRestClient cotRestClientMock = Mockito.mock(CloudOfThingsRestClient.class);
final AuditApi auditApi = new AuditApi(cotRestClientMock);
final String auditRecordId = "234";
final String text = "new audit record created";
final AuditRecord testAuditRecord = new AuditRecord();
testAuditRecord.setText(text);
Mockito.when(cotRestClientMock.doRequestWithIdResponse(any(String.class), any(String.class), any(String.class), any(String.class))).thenReturn(auditRecordId);
AuditRecord createdAuditRecord = auditApi.createAuditRecord(testAuditRecord);
Assert.assertNotNull(createdAuditRecord);
Assert.assertEquals(createdAuditRecord.getId(), auditRecordId);
Assert.assertEquals(createdAuditRecord.getText(), text);
}
@Test
public void testGetAuditRecordCollection() {
final CloudOfThingsRestClient cotRestClientMock = Mockito.mock(CloudOfThingsRestClient.class);
final AuditApi auditApi = new AuditApi(cotRestClientMock);
AuditRecordCollection auditRecordCollection = auditApi.getAuditRecordCollection();
Assert.assertNotNull(auditRecordCollection);
}
@Test
public void testGetAuditRecordCollectionWithFilter() {
final CloudOfThingsRestClient cotRestClientMock = Mockito.mock(CloudOfThingsRestClient.class);
final AuditApi auditApi = new AuditApi(cotRestClientMock);
final String type = "com_telekom_audit_TestType";
final Filter.FilterBuilder filterBuilder = Filter.build().byType(type);
AuditRecordCollection auditRecordCollection = auditApi.getAuditRecordCollection(filterBuilder);
Assert.assertNotNull(auditRecordCollection);
}
@Test
public void testDeleteAuditRecords() {
final CloudOfThingsRestClient cotRestClientMock = Mockito.mock(CloudOfThingsRestClient.class);
final AuditApi auditApi = new AuditApi(cotRestClientMock);
final String type = "com_telekom_audit_TestType";
final Filter.FilterBuilder filterBuilder = Filter.build().byType(type);
auditApi.deleteAuditRecords(filterBuilder);
Mockito.verify(cotRestClientMock, Mockito.times(1)).deleteBy("type="+type, "audit/auditRecords/");
}
} |
Next to sushi, low carb soup is my favorite food. Pretty much year round, you can open my fridge or freezer and see at least one or two low carb soups lining the shelves. While I convert a lot of my slow cooker recipes to stovetop recipes because I am impatient and just want to eat my soup NOW, I still really love all the deliciously complex flavors that slow cooking can create. I am a big fan of low carb slow cooker recipes.
At the first hint of fall, I break out both of my slow cookers and get to work on all the delicious low carb slow cooker recipes. In fact, I use my crockpot year round. It is great in the winter when you just want to curl up on the couch and don’t feel like cooking and it is equally as great in the summer for transporting food to cookouts, low carb barbecues or any type of fun get together. BUT, it can be a lifesaver during the really hot months when you don’t want to heat up the stove and make you house even hotter. One of my favorite type of low carb recipes to make in the slow cooker is definitely low carb soups and stews. This low carb chowder being among the top favorite.
This low carb Slow Cooker Chicken Bacon Chowder is deliciously rich and flavorful. If you are looking to impress your friends with your cooking skills, this would be the dish to make them. Although it keeps well in the fridge, good luck having any leftovers. Be sure to also check out my Keto Chili Recipe and my Keto Clam Chowder Recipe. In fact, I love low carb soup recipes so much, that I wrote an entire ebook about them. |
/*************************************************************************
* Description: Initialization for timer
* Returns: none
* Notes: none
*************************************************************************/
void timer_init(
void)
{
TIMECAPS tc;
if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
fprintf(stderr, "Failed to get timer resolution parameters\n");
}
Timer_Period = min(max(tc.wPeriodMin, 1L), tc.wPeriodMax);
if (Timer_Period != 1L) {
fprintf(stderr,
"Failed to set timer to 1ms. " "Time period set to %ums\n",
(unsigned) Timer_Period);
}
timeBeginPeriod(Timer_Period);
atexit(timer_cleanup);
} |
<filename>app/jobs/DnsInquireJob.java<gh_stars>0
package jobs;
import helpers.DnsInquireHelper;
import models.Domain;
public class DnsInquireJob implements Runnable {
private Domain domain;
public DnsInquireJob(Domain domain) {
this.domain = domain;
}
@Override
public void run() {
DnsInquireHelper helper = new DnsInquireHelper(domain);
helper.inquire();
}
}
|
async def put_node_title(response: Response, node_id: str = "", title: str = ""):
query = Query()
nodes = DB.table("nodes")
node_doc = nodes.get(query.node_id == node_id)
if node_doc is None:
msg = "Node does not exist"
logging.info(msg)
response.status_code = status.HTTP_400_BAD_REQUEST
return {
"error": "confrm-022",
"message": msg,
"detail": "While attempting to set the title of a node, the node id given was not"
" found"
}
title = escape(title)
if len(title) > 80:
msg = "Node title is too long"
logging.info(msg)
response.status_code = status.HTTP_400_BAD_REQUEST
return {
"error": "confrm-023",
"message": msg,
"detail": "While attempting to set the title of a node, the title was too long"
}
nodes.update({"title": title}, query.node_id == node_id)
return {} |
// No route for the HTTP2 request, send 404 on the corresponding HTTP2 stream
void send404(
int streamId)
{
ArrayFW<HttpHeaderFW> headers =
factory.headersRW.wrap(factory.errorBuf, 0, factory.errorBuf.capacity())
.item(b -> b.name(":status").value("404"))
.build();
writeScheduler.headers(0, streamId, Http2Flags.END_STREAM, headers);
if ((streamId & 0x01L) == 0x00L)
{
factory.counters.pushHeadersFramesWritten.getAsLong();
}
else
{
factory.counters.headersFramesWritten.getAsLong();
}
} |
<gh_stars>10-100
"""Command design pattern - run shell command."""
from fastapi_mvc.commands import Command
from fastapi_mvc.utils import ShellUtils
class RunShell(Command):
"""Define the common interface for ShellUtils.run_shell method.
Args:
cmd (list): Shell command to run.
cwd (str): Path under which process should execute command. Defaults
to current working directory.
check (bool): If True raise a subprocess.CalledProcessError error when
a process returns non-zero exit status.
stdout (Union[None, int, IO[Any]]): Specify the executed program’s
standard output file handles.
stderr (Union[None, int, IO[Any]]): Specify the executed program’s
standard error file handles.
Attributes:
_cmd (list): Shell command to run.
_cwd (str): Path under which process should execute command. Defaults
to current working directory.
_check (bool): If True raise a subprocess.CalledProcessError error when
a process returns non-zero exit status.
_stdout (Union[None, int, IO[Any]]): Specify the executed program’s
standard output file handles.
_stderr (Union[None, int, IO[Any]]): Specify the executed program’s
standard error file handles.
"""
__slots__ = (
"_cmd",
"_cwd",
"_check",
"_stdout",
"_stderr",
)
def __init__(self, cmd, cwd=None, check=False, stdout=None, stderr=None):
"""Initialize RunShell class object instance."""
Command.__init__(self)
self._log.debug("Initialize RunShell class object instance.")
self._cmd = cmd
self._cwd = cwd
self._check = check
self._stdout = stdout
self._stderr = stderr
def execute(self):
"""Execute RunShell command."""
self._log.info("Executing shell command: {cmd}".format(cmd=self._cmd))
ShellUtils.run_shell(
cmd=self._cmd,
cwd=self._cwd,
check=self._check,
stdout=self._stdout,
stderr=self._stderr,
)
|
/**
*
* @author fkaraman
*
* Implementation of DDR extension !walkj9pool
*
*/
public class WalkJ9PoolCommand extends Command
{
private static final String nl = System.getProperty("line.separator");
/**
* Constructor
*/
public WalkJ9PoolCommand()
{
addCommand("walkj9pool", "<address>", "Walks the elements of J9Pool");
}
/**
* Prints the usage for the walkj9pool command.
*
* @param out the PrintStream the usage statement prints to
*/
private void printUsage (PrintStream out) {
out.println("walkj9pool <address> - Walks the elements of J9Pool");
}
/**
* Run method for !walkj9pool extension.
*
* @param command !walkj9pool
* @param args args passed by !walkj9pool extension.
* @param context Context
* @param out PrintStream
* @throws DDRInteractiveCommandException
*/
public void run(String command, String[] args, Context context, PrintStream out) throws DDRInteractiveCommandException
{
if ((0 == args.length) ||
(1 < args.length)) {
printUsage(out);
}
long address = CommandUtils.parsePointer(args[0], J9BuildFlags.env_data64);
out.append("J9Pool at 0x"
+ CommandUtils.longToBigInteger(address).toString(CommandUtils.RADIX_HEXADECIMAL)
+ "\n{\n");
walkJ9Pool(address, out);
out.append("}\n");
}
/**
* This method walks through each element in the pool and prints each elements' address.
* Elements can be in the same puddle or different, and this method do not print puddle information.
*
* @param address address of the pool
* @param out print stream
* @throws DDRInteractiveCommandException
*/
private void walkJ9Pool(long address, PrintStream out) throws DDRInteractiveCommandException {
try {
J9PoolPointer j9pool = J9PoolPointer.cast(address);
Pool pool = Pool.fromJ9Pool(j9pool, VoidPointer.class);
SlotIterator<VoidPointer> poolIterator = pool.iterator();
VoidPointer currentElement;
int i = 0;
while (poolIterator.hasNext()) {
currentElement = poolIterator.next();
out.println(String.format("\t[%d]\t=\t%s", i++, currentElement.getHexAddress()));
}
} catch (CorruptDataException e) {
throw new DDRInteractiveCommandException("Either address is not a valid pool address or pool itself is corrupted.");
}
}
} |
<reponame>daisy/books-to-videos
import dayjs from 'dayjs';
import fs from 'fs-extra';
import path from 'path';
import winston from 'winston';
import * as types from '../types/index.js';
import * as utils from '../utils/index.js';
// create an HTML page with the video embedded in it
function createHtmlPage(book: types.Book, videoFilename: string, captionsFilename: string, videoDuration: any, outDirname: string): string {
winston.info("Creating HTML page with embedded video and captions");
let htmlPage =
`<!DOCTYPE html>
<html lang="${book.metadata.lang}">
<head>
<title>${book.metadata.title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>${book.metadata.title}</h1>
<p>Author(s): ${book.metadata.authors}</p>
<p>Date: ${dayjs(book.metadata.date).format("YYYY-MM-DD")}</p>
<p>Duration: ${utils.toHHMMSS(videoDuration)}</p>
<video id="video" controls preload="metadata" style="width: 30%">
<source src="${path.basename(videoFilename)}">
<track default kind="captions" src="${path.basename(captionsFilename)}">
</video>
</body>
<script>
// turn captions off by default, they're a bit chaotic when presented with an all-text video
document.addEventListener("DOMContentLoaded", e=> {
document.querySelector("track").track.mode = "hidden";
});
</script>
</html>`;
let outFilename = path.resolve(outDirname, "video.html");
fs.writeFileSync(outFilename, htmlPage);
winston.info("Done creating HTML page with embedded video and captions");
return outFilename;
}
export { createHtmlPage };
|
<gh_stars>0
package com.supyuan.school.umutil;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.supyuan.component.base.BaseProjectController;
import com.supyuan.jfinal.component.annotation.ControllerBind;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
/**
* Created by CSJ11 on 2017/6/15.
*/
@ControllerBind(controllerKey = "/um")
public class UmController extends BaseProjectController {
public void index() {
render("/pages/school/um/index.html");
}
/**
* ueditor上传
*/
public void upload(){
if ("config".equals(getPara("action"))) {
render("/static/component/ueditor/jsp/config.json");
return;
}
String path = PathKit.getWebRootPath().replace("\\","/") + "/upload/";
UploadFile file = getFile("upfile"); //获取文件
String fileName = file.getFileName();
String[] typeArr = fileName.split("\\.");
String orig = file.getOriginalFileName();
long size = file.getFile().length();
String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss");
int temp = (int) (Math.random() * 9000 + 1000);
fileName = getRequest().getRemoteAddr().replaceAll(":", "")
+ dateFormat.format(new Date())
+ new Integer(temp).toString() + "." + extName;//对文件进行重命名,防治文件重名。命名的规则是使用上传客户端的ip+上传时间+四位随机数的方法。
file.getFile().renameTo(new File(path + fileName));
Ret ret = Ret.create("state", "SUCCESS") //下面这几个都是必须返回给ueditor的数据
.set("url", "/upload/"+fileName) //文件上传后的路径
.set("title", fileName) //文件名称
.set("original", orig)
.set("type", "."+typeArr[1])
.set("size", size);
renderJson(ret);
}
}
|
<reponame>njenga5/django-mediastore-site
from django.db import models
from PIL import Image
from taggit.managers import TaggableManager
from django.utils.translation import gettext_lazy as _
from commonops.models import CustomUser as User
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("Owner"))
tags = TaggableManager()
# collections = models.ManyToManyField(Collection)
upload_date = models.DateTimeField(auto_now_add=True)
description = models.TextField(null=True, blank=True, max_length=1000)
picture = models.ImageField(upload_to="pictures/")
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.picture.path)
if img.height > 300 or img.width > 300:
img.thumbnail((300, 300))
img.save(self.picture.path)
class Video(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("Owner"))
tags = TaggableManager()
# collections = models.ManyToManyField(Collection)
artist = models.CharField(max_length=255, null=True, blank=True)
title = models.CharField(max_length=500)
upload_date = models.DateTimeField(auto_now_add=True)
description = models.TextField(null=True, blank=True, max_length=1000)
video = models.FileField(upload_to="videos/")
thumbnail = models.ImageField(upload_to='thumbnails/', default='default/Video.jpg', blank=True, null=True)
def __str__(self):
return self.title
class Music(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("Owner"))
tags = TaggableManager()
# collections = models.ManyToManyField(Collection)
artist = models.CharField(max_length=255, null=True, blank=True)
title = models.CharField(max_length=100)
upload_date = models.DateTimeField(auto_now_add=True)
description = models.TextField(null=True, blank=True, max_length=1000)
track = models.FileField(upload_to="music/")
art = models.ImageField(upload_to='arts/', default='default/screen-0.jpg', blank=True, null=True)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.art.path)
if img.height > 300 or img.width > 300:
img.thumbnail((300, 300))
img.save(self.art.path)
def __str__(self):
return self.title
class AlbumDescription(models.Model):
"""
Gives the title and description for the introductory text in the album.
"""
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("Owner"))
title = models.CharField(max_length=100, null=True, blank=True)
description = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
|
async def _async_register(self) -> None:
metadata = aioxmpp.make_security_layer(None, no_verify=not self.verify_security)
query = ibr.Query(self.jid.localpart, self.password)
_, stream, features = await aioxmpp.node.connect_xmlstream(
self.jid, metadata, loop=self.loop
)
await ibr.register(stream, query) |
All Publishers 6th Ave Press A House Called Alice Ltd A Stravaiger Abbeymead Books Academy UK LTD Agile Student Ltd aintlifewonderful books Alogo Publications Amazing If AMD Publishing (UK) Ancient Family Roots Ltd Ancient History Seminars Andrew Everett MA Angela Kilmartin Angela Kilmartin Angela Krause Aniseed Press Ankh Mind Body Spirit Centre Ltd Ann Merivale Antony Rowe Publishing Services Arabest Publishing Dundee Areti Publications Arkyprint Artisan Creative Ltd Ascot Publishing Ashmount Press Ashmount Press Aster Publishing Avanti Books B Wheldon Backworth Publishing Baffin Books UK Bainbridge Press Bakersboy Books Balaclava Publishing Batchmere Books Bathwood Manor Publishing Batrachia Publishing Batul Bearsted House Publications Beawood Publishing Benefits Management Publishing Beret Books BH Books Bill Martin Bill Tatham Publications Blockley Bank Books Boatman Cryptics Bob Holmes Boermans Books Bookaholics Publishing Bookaholics Publishing Boroughgate Books Bottom End Publishing Bourchier Bourchier Ltd Bradan Publishing Bumblebee Conservation Trust Byrom Projects C J Bentley Cairns Publishing Canday 33 Publishing Carr Design Studio Cartref Publications Celeiros Press Centre for Women and Democracy Chagos Conservation Trust Christine Ruskin Christopher Marton Church Cottage Publications Circus Design Limited Clive Wormald Clontarf Press Colin Walter Columbus Publishing Ltd Companion Way Press Copper Beech Press Courtney Publishers CPD Publishing Cressar Publications Crowning Glory Publishing Ltd Damian Ranjan Mellawa Danior Publishing Dartas Books David Dhekelia David Dhekelia David Shepheard Debernardi Publishing Denise Bowes Denise Hayton Diane Trevena Don Halliday Dr Steph Adam Dragoon Publications Dronne River Publishing Drop Kick Books Dujio Publishing Edge Publishing Effective Networker Ltd Elysee Associates Ferncliffe Publishing Filippo del Re Publishing Final Chapter Publishing FirstFilm Production Fitzpatrick Press Fitzpatrick Publishing Flaxton Publishing Fluke and Tash Publishing Focal Point Forbidden Books Forecast Publishing Forest Glade Publishing Forgotten Times Publishing Forlaget press Forqueray Press Forty Steps Forward With Phonics Frances Woodward Francis Alan Jackson Fraser Blake Gary James Dean Grant Gassho Publishing Gibbons Williams Publishing Gladys Connaughton Gleneagle Books Ltd Golden Oak Press Goodramgate Press Goodyear Publications Grace's Place Graeme Harvey Grapevine Publishing Graystone LA Great Photos Ltd Greatest Guides Ltd Greenmoor Books Grey Dolphin Press Greymalkin Books HAGI Publishing Hame House Hardraw Force Publishing Harmony-9 Headsail Books High Wolds Heritage Group Highcroft Publishing Highfield Publishing Hilbert Publishing HyTIS Publishing Ian Bunton Ian Shaw Ianto Hugh Stevens Inclusive Innovations Ltd Ings Press Inkslingers Publishing Inventive Publishing J B Phillips J Boles Jachimo Press Janella Press Janusz Jarzecki Jason Nickels Jellyfish Solutions JEM Photography JGSCR Publishing Joan Khurody Johansen & Johansen Publications John Aubin Books John Gears Publications John O Roberts Publishing Jolliwood Books Jonnysoundbyte Ltd Jubilee Sailing Trust Ltd Judith Bowker Books Justin Tomlinson Kathryn Adams Publishing Kathryn Adams Publishing Kearton Books Kenneth Henley Kent Gardens Trust Klickerförlaget Kroosch Publishing L T Saunders Lagon Bleu Books Latitude14.com Leggatt Lemniscate Press Lemon Kid Publishing Lemondrop Publishing Leonard G Saunders Leslie Carvall Publishing Level Press Ltd Life Up s.r.o. Lifejoy Publishing Little Ginnel Press Little Vision Grows Lollipop Publishing Ltd MA Khin Cafe Major Afzaal Shafi Major Oakes Malcolm Edmunds Mark O'Donnell Mayburn Publishing MCKASTLE Meserani Publishing Michael Greisman Michelle Diana Lowe Press (UK) Molly Brearley Moondance Publishers Motiv Press s.r.o. Mr Ronald George Moore MuMac MVH Publishing Mylesiris Publishing National Coursing Club Natures Coaching Ltd Nauticools Neil Humphrey Lock Neville Williams New Forest Electronics Noor Alam Publications Northumbrian Writer's League Oakdale Books Old Trafford Publishing Olop and Flossie Publishing Open Angle Books Ormston Publishing P C Delaney PAD Press PakaMdogo Press PAL Books Palmer Publishing Parfoys Press Particular Press Paul Antcliffe Peakpublish Pete Allen Peter Flanagan Peto Publishers Phil Hart Phoenix Again Pickard Brothers Pickard Brothers PME Publishing Podkin Press Prideaux Press Prime Median Ltd Print2Demand Ltd Priskus Books Propagator Press Pubcat Publishing Pugh Stones Quarry House Press QuizzicalWorks R Amoore R&R Publishing (Dorset) Ralphyburl Publishing Raw Creative Ray Lau Consultancy Revelation Books Richard Humphries Photography Robert Keats Robin Wade Press Rock 'n' Roll Ltd Ron Cooke Rosemarie Bartel and David Lupton, IG Stolpersteine Gelnhausen RPS Publications RV Publications Santicum Medien Sapna Patel SAvery Books SAW Books Sawman Publications Scrimgeour Yorkshire Selmain Books Serapion Books Shaffron Publishing Shared Press Sian Townsend Skid Publishing SKN Publishing Sorbus Press Speight of the Art Communications Squirrel Publishing Stairmand Publishing Starburst Books Steve Anderson Stonecrop Strauss House Productions Szafarnia Taberno publications Tema Publishing Tennison Publishing The Blue Shed Press The Box Book Company The Elmyrste Press The Goodchild Press The Lost Shadow The Old Print Workshop The Whippet Press Theophilus Publishing Town Bridge Press Travelleur Treaty for Government Trigraph Ltd Trust Consent Publishing Upcott Press Urso Major Publishing Vicky Norman Victor John Tarry Visitor Safety in the Countryside Group W I Thompson W K Publishing Wade Allison Publishing West End Publications Weyba Books Whale Tale Book Publishers Whis & Co White Rabbit Proclamations William Sessions Ltd Willow Tree Farm Press Wily Publications Windwhistle Publishing Wine Travel Media Wishful Thinking Literary Services Woodlands Publishing Worktown Publishing Wydel Press Xadrum Yelena Gibson York Authors Coffee Shop Zura Shiolashvili Publishing |
def _residue_key_func(node):
attrs = 'mol_idx', 'chain', 'resid', 'resname'
return tuple(node.get(attr) for attr in attrs) |
// common extensions unit tests
package testing
|
<reponame>ianeli1/simple-chat-web
import '../assets/main.css';
import TopBar from '../components/TopBar';
import Sidebar, { SidebarProps } from '../components/Sidebar';
import React, { useContext } from 'react';
import { Chat } from '@material-ui/icons';
import AvatarScroller from '../components/AvatarScroller';
import RectangleScroller from '../components/RectangleScroller';
import Button from '../components/Button';
import { DialogContext } from '../components/Providers/DialogProvider';
import { userContext } from '../components/Providers/UserProvider';
import { serverContext } from '../components/Providers/ServerProvider';
import { channelContext } from '../components/Providers/ChannelProvider';
import { ChatScreen } from './ChatScreen';
export default function Main() {
const { login } = useContext(DialogContext);
const { user } = useContext(userContext);
const { currentServer, setCurrentServer } = useContext(serverContext);
const { currentChannel, setCurrentChannel } = useContext(channelContext);
const ChannelMenu: SidebarProps['screens'][0] = {
element: (
<div>
<AvatarScroller
orientation="v"
elements={
user?.servers.map(({ name, id, icon }) => ({
alt: name,
icon: icon ?? undefined,
key: id,
})) ?? []
}
selected={currentServer ?? undefined}
onAvatarClick={(id) => setCurrentServer(id)}
/>
<RectangleScroller
elements={
user?.servers
.find(({ id }) => currentServer === id)
?.channels.map(({ id, name }) => ({
title: name,
key: id,
})) ?? []
}
onClick={(key) => setCurrentChannel(key)}
selected={currentChannel ?? undefined}
/>
</div>
),
menu: {
alt: 'Chat',
icon: <Chat />,
},
};
async function handleLogin() {
const result = await login();
if (result) {
console.log('logged in ak7');
} else {
console.log('oops');
}
}
return (
<main className="h-screen w-screen">
<TopBar
title="Simple Chat Web"
right={<Button onClick={handleLogin}>Login</Button>}
/>
<div className="flex pt-12 h-full w-full box-border grid-cols-2">
<Sidebar screens={[ChannelMenu]} />
<section className="flex-grow bg-black h-full">
<ChatScreen />
</section>
</div>
</main>
);
}
|
// ResolveCredentialsEUser resolves the effective user id of the process to a username
func (ev *Event) ResolveCredentialsEUser(e *model.Credentials) string {
if len(e.EUser) == 0 && ev != nil {
e.EUser, _ = ev.resolvers.UserGroupResolver.ResolveUser(ev.ResolveCredentialsEUID(e))
}
return e.EUser
} |
<reponame>samwestmoreland/please<gh_stars>1000+
package cgo
import (
"fmt"
"strconv"
)
// CheckAnswer checks that the given answer matches the canonical one.
func CheckAnswer(answer string) error {
ans, _ := strconv.ParseInt(answer, 13, 32)
if int(ans) != 6*9 {
return fmt.Errorf("universe parameters incorrect")
}
return nil
}
|
Study on the evaluation of waterlogging tolerance about different Dactylis glomerata L. germplasm resources and the difference on microstructure of root under waterlogging stress
In order to characterize the physiological mechanisms of waterlogging tolerance of Dactylis glomerata L. and to help rationally select waterlogging-tolerant species to alleviate the waterlogging damage to agricultural production, effects of waterlogging on the growth, morphological indexes, physiological changes and root microstructure of Dactylis glomerata L. were studied. A total of 20 varieties (lines) of Dactylis glomerata L. from different areas were flooded treatment for 0 day and 28 days, respectively. Morphological indexes and physiological indexes of 20 Dactylis glomerata L. resources were evaluated under waterlogging stress comprehensively. In addition, paraffin section technology was used for observing the microstructure changes on root of 6 types of Dactylis glomerata L. under waterlogging stress for 0 day, 14 days and 28 days respectively. Our results demonstrated that the orders of 20 Dactylis glomerata L. resources by ability of waterlogging tolerance were ‘Dianbei’ > ‘Cambria’ > ‘Aldebaran’ > ‘Athos’ > ‘Donata’ > ‘Sparta’> ‘PI 231482’ >‘Endurance’ > ‘PI 598418’ > ‘02-114’ > ‘PI 311388’ > ‘01472’ > ‘PG28’ > ‘Glorus Sweden’ = ‘PI593995’> ‘Smithii PI 441032’ = ‘PI594994’ > ‘Geneal Belgnaio’ > ‘PG49’ > ‘Amba’. What’s more, with the extension of waterlogging stress time, the number/size of vessel and the diameter of vascular cylinder were significantly (P<0.05) reduced. Cells ruptured and structure collapsed were found in the root microstructure of ‘PI 594994’, ‘Geneal Belgnaio’, ‘PG 49’ while structurallycomplete of root in ‘Dianbei’, ‘Cambria’, ‘Aldebaran’ for under waterlogging stress 28 days. Therefore, they could be used as the key selection accessions and studied on their genes of waterlogging tolerance for further research. |
#include "internal.h"
#include "script_int.h"
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include "pullpush.h"
unsigned char *push_bytes(unsigned char **cursor, size_t *max,
const void *src, size_t len)
{
if (cursor == NULL || *cursor == NULL) {
*max += len;
return NULL;
}
if (len > *max) {
if (src)
memcpy(*cursor, src, *max);
/* From now on, max records the room we *needed* */
*max = len - *max;
*cursor = NULL;
return NULL;
}
if (src)
memcpy(*cursor, src, len);
*cursor += len;
*max -= len;
return *cursor - len;
}
void pull_bytes(void *dst, size_t len,
const unsigned char **cursor, size_t *max)
{
if (len > *max) {
memcpy(dst, *cursor, *max);
memset((char *)dst + *max, 0, len - *max);
pull_failed(cursor, max);
return;
}
memcpy(dst, *cursor, len);
*cursor += len;
*max -= len;
}
const unsigned char *pull_skip(const unsigned char **cursor, size_t *max,
size_t len)
{
const unsigned char *p;
if (*cursor == NULL) {
return NULL;
}
if (len > *max) {
pull_failed(cursor, max);
return NULL;
}
p = *cursor;
*cursor += len;
*max -= len;
return p;
}
void pull_failed(const unsigned char **cursor, size_t *max)
{
*cursor = NULL;
*max = 0;
}
void push_le64(unsigned char **cursor, size_t *max, uint64_t v)
{
leint64_t lev = cpu_to_le64(v);
push_bytes(cursor, max, &lev, sizeof(lev));
}
uint64_t pull_le64(const unsigned char **cursor, size_t *max)
{
leint64_t lev;
pull_bytes(&lev, sizeof(lev), cursor, max);
return le64_to_cpu(lev);
}
void push_le32(unsigned char **cursor, size_t *max, uint32_t v)
{
leint32_t lev = cpu_to_le32(v);
push_bytes(cursor, max, &lev, sizeof(lev));
}
uint32_t pull_le32(const unsigned char **cursor, size_t *max)
{
leint32_t lev;
pull_bytes(&lev, sizeof(lev), cursor, max);
return le32_to_cpu(lev);
}
void push_u8(unsigned char **cursor, size_t *max, uint8_t v)
{
push_bytes(cursor, max, &v, sizeof(uint8_t));
}
uint8_t pull_u8(const unsigned char **cursor, size_t *max)
{
uint8_t v;
pull_bytes(&v, sizeof(v), cursor, max);
return v;
}
uint8_t peek_u8(const unsigned char **cursor, size_t *max)
{
uint8_t v = pull_u8(cursor, max);
if (*cursor) {
*cursor -= sizeof(v);
*max += sizeof(v);
}
return v;
}
void push_varint(unsigned char **cursor, size_t *max, uint64_t v)
{
unsigned char buf[sizeof(uint8_t) + sizeof(uint64_t)];
size_t len = varint_to_bytes(v, buf);
push_bytes(cursor, max, buf, len);
}
uint64_t pull_varint(const unsigned char **cursor, size_t *max)
{
unsigned char buf[sizeof(uint8_t) + sizeof(uint64_t)];
uint64_t v;
/* FIXME: Would be more efficient to opencode varint here! */
pull_bytes(buf, 1, cursor, max);
pull_bytes(buf + 1, varint_length_from_bytes(buf) - 1, cursor, max);
varint_from_bytes(buf, &v);
return v;
}
void push_varbuff(unsigned char **cursor, size_t *max,
const unsigned char *bytes, size_t bytes_len)
{
push_varint(cursor, max, bytes_len);
push_bytes(cursor, max, bytes, bytes_len);
}
size_t pull_varlength(const unsigned char **cursor, size_t *max)
{
uint64_t len = pull_varint(cursor, max);
if (len > *max) {
/* Impossible length. */
pull_failed(cursor, max);
return 0;
}
return len;
}
void pull_subfield_start(const unsigned char *const *cursor, const size_t *max,
size_t subfield_len,
const unsigned char **subcursor, size_t *submax)
{
if (subfield_len > *max) {
pull_failed(subcursor, submax);
} else {
*subcursor = *cursor;
*submax = subfield_len;
}
}
void pull_subfield_end(const unsigned char **cursor, size_t *max,
const unsigned char *subcursor, size_t submax)
{
if (subcursor == NULL) {
pull_failed(cursor, max);
} else if (*cursor != NULL) {
const unsigned char *subend = subcursor + submax;
assert(subcursor >= *cursor);
assert(subend <= *cursor + *max);
*max -= (subend - *cursor);
*cursor = subend;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.