content
stringlengths 10
4.9M
|
---|
Henrin A: A New Anti-HIV Ent-Kaurane Diterpene from Pteris henryi
Henrin A (1), a new ent-kaurane diterpene, was isolated from the leaves of Pteris henryi. The chemical structure was elucidated by analysis of the spectroscopic data including one-dimensional (1D) and two-dimensional (2D) NMR spectra, and was further confirmed by X-ray crystallographic analysis. The compound was evaluated for its biological activities against a panel of cancer cell lines, dental bacterial biofilm formation, and HIV. It displayed anti-HIV potential with an IC50 value of 9.1 µM (SI = 12.2). |
/*********************************************************************
* @file event_dispatcher.h
* @author <NAME>
* @date 2021/12/12 15:10
* @brief イベントディスパッチャーパターン
********************************************************************/
#pragma once
#include <algorithm>
#include <functional>
#include <unordered_map>
#include <unordered_set>
// 前方宣言
template <typename EventType, typename... Args>
class EventDispatcher;
/**
* @brief イベントリスナー
* @tparam EventType イベントの種類を判別するためのキーの型
* @tparam CallbackArgsType コールバックに渡される引数の型
*/
template <typename EventType, typename... CallbackArgsType>
class EventListener final
{
//! 対応したイベント発行クラスの型
using EventDispatcherType = EventDispatcher<EventType, CallbackArgsType...>;
//! コールバック関数型
using CallbackFunc = std::function<void(CallbackArgsType ...)>;
//! イベント発行クラスのアクセスを許可
friend class EventDispatcherType;
public:
EventListener() = default;
/**
* @brief コールバック関数をセットする
* @param callback コールバック関数
*/
explicit EventListener(CallbackFunc callback) noexcept
: callback_(std::move(callback)) {}
~EventListener() = default;
// ムーブとコピーを許可
EventListener(const EventListener& other) = default;
EventListener& operator=(const EventListener& other) = default;
EventListener(EventListener&& other) = default;
EventListener& operator=(EventListener&& other) = default;
/**
* @brief コールバック関数をセットする
* @param callback コールバック関数
*/
void SetCallback(const CallbackFunc& callback) noexcept
{
callback_ = callback;
}
/**
* @brief 初期化する
*/
void Clear() noexcept
{
callback_ = {};
}
/**
* @brief コールバック関数を呼び出し可能か調べる
* @return 呼び出し可能か
*/
[[nodiscard]] bool HasCallback() const noexcept
{
return static_cast<bool>(callback_);
}
private:
/**
* @brief コールバックを呼び出す
* @param args コールバックの引数
*/
void OnDispatch(const CallbackArgsType&... args) const
{
if (HasCallback())
{
callback_(args...);
}
}
//! コールバック関数
CallbackFunc callback_{};
};
/**
* @brief イベント発行機
* @tparam EventType イベントの種類を判定するためのキーの型
* @tparam CallbackArgsType コールバックに渡される引数の型
*/
template <typename EventType, typename... CallbackArgsType>
class EventDispatcher
{
//! イベントリスナーの型
using EventListenerType = EventListener<EventType, CallbackArgsType...>;
public:
EventDispatcher() = default;
virtual ~EventDispatcher() = default;
// ムーブとコピーを許可
EventDispatcher(const EventDispatcher& other) = default;
EventDispatcher& operator=(const EventDispatcher& other) = default;
EventDispatcher(EventDispatcher&& other) = default;
EventDispatcher& operator=(EventDispatcher&& other) = default;
/**
* @brief イベントを発行する
* @param event イベントの種類
* @param args コールバックに渡す引数
*/
void Dispatch(EventType event, const CallbackArgsType&... args)
{
if (listeners_.empty())
return;
auto [itr, end] = listeners_.equal_range(event);
for (; itr != end; ++itr)
{
if (itr->second)
itr->second->OnDispatch(args...);
else
itr = listeners_.erase(itr);
}
}
/**
* @brief イベントリスナーを登録する
* @param event イベントの種類
* @param eventListener 登録するイベントリスナー
*/
void AppendListener(EventType event, EventListenerType& eventListener)
{
listeners_.emplace(event, &eventListener);
}
/**
* @brief 指定したイベントのイベントリスナーを登録解除する
* @param event 登録解除するイベントの種類
* @param eventListener 登録解除するイベントリスナー
*/
void RemoveListener(EventType event, EventListenerType& eventListener)
{
if (listeners_.empty())
return;
std::erase_if(
listeners_,
[&](const auto& x)
{
return x.first == event && x.second == &eventListener;
});
}
/**
* @brief イベントリスナーを全て登録解除
*/
void Clear()
{
listeners_.clear();
}
private:
//! イベントリスナーの連想配列
std::unordered_multimap<EventType, EventListenerType*> listeners_{};
};
|
<reponame>omnis-org/omnis-ui
import { NbMenuItem } from '@nebular/theme';
export const MENU_ITEMS: NbMenuItem[] = [
{
title: 'Dashboard',
icon: 'browser-outline',
link: '/pages/dashboard',
home: true,
},
{
title: 'Map',
icon: 'map-outline',
link: '/pages/map',
},
{
title: 'Notifications',
icon: 'bell-outline',
link: '/pages/notifications',
},
{
title: 'Pending Machines',
icon: 'checkmark-square-outline',
link: '/pages/pending-machines',
},
{
title: 'Administration',
icon: 'options-2-outline',
children: [
{
title: 'Users',
link: '/pages/administration/users',
},
{
title: 'Roles',
link: '/pages/administration/roles',
}
],
},
];
|
def cloudwatch(event, context, service=None):
return contexts.CloudwatchContext(event, context, logging.root, service) |
/**
* This method is used to detail read method to read register from ODS file
*
* @param RegDataMap reference to key of register
* @param sheet reference to the single sheet name in the ODS file name
* @param activeSites activated sites information
*
*/
private Map<String,String> rdSheet(Map<String,String> RegDataMap, Sheet sheet,int[] activeSites){
String shtName = sheet.getName();
Map<Integer, String> PerRegData = new LinkedHashMap<>();
int colCount = sheet.getColumnCount();
int rowCount = sheet.getRowCount();
int maxRowCount = 1000;
int maxColCount = 50;
if(rowCount>maxRowCount)
{
sheet.setRowCount(maxRowCount);
rowCount = maxRowCount;
}
if(colCount > maxColCount)
{
sheet.setColumnCount(maxRowCount);
colCount = maxColCount;
}
for(int row=1;row<rowCount;row++){
ArrayList<String> valuePerRow = new ArrayList<>();
for(int col=0;col<colCount;col++)
{
MutableCell<SpreadSheet> cell = sheet.getCellAt(col,row);
String cellValue = cell.getValue().toString();
valuePerRow.add(col,cellValue);
}
if(valuePerRow.get(0).equals(""))
{
continue;
}
if(shtName.contains("POR")&&row>1)
{
PerRegData = readPorData(valuePerRow,PerRegData,shtName,row,activeSites);
}
else if(shtName.contains("Common"))
{
RegDataMap = readComData(valuePerRow,RegDataMap,shtName,row,activeSites);
}
}
int size = PerRegData.size();
String Sum = "";
for(int i=2;i<size+2;i++)
{
if(PerRegData.containsKey(i)&&!PerRegData.get(i).isEmpty())
{
Sum = Sum+PerRegData.get(i);
}
else
{
continue;
}
}
if(shtName.contains("POR"))
{
RegDataMap.put(shtName, Sum);
}
return RegDataMap;
} |
Inhibition of death receptor signaling by FLICE-inhibitory protein as a mechanism for immune escape of tumors.
Cell death by apoptosis is a tightly regulated physiological process that enables the elimination of unwanted cells. It is crucial for embryonic development and the maintenance of tissue homeostasis, but also for defense against certain infectious diseases and cancer.
Apoptosis can be triggered
C ell death by apoptosis is a tightly regulated physiological process that enables the elimination of unwanted cells. It is crucial for embryonic development and the maintenance of tissue homeostasis, but also for defense against certain infectious diseases and cancer.
Apoptosis can be triggered from outside the cell, generally after cell-cell contact, by a family of transmembrane proteins called death receptors, which belong to the TNF family of receptors. Six human death receptors (Fas , TNFR-1, TRAMP , TNF-related apoptosis-inducing ligand R-1 , TRAILR-2 , and DR-6) have been identified to date (1,2), and all contain a cytoplasmic sequence named "death domain" (DD) that couples each receptor to caspase cascades essential for the induction of apoptosis. The best studied signaling pathway is the one triggered by binding of Fas ligand (L) to Fas. Schematically, multimerization or clustering of Fas upon binding of the membrane-bound form of FasL recruits the bipartite molecule FADD (Fas-associated death domain, composed of an NH 2 -terminal death effector domain and a COOH-terminal DD). FADD binds to Fas (via homophilic DD-DD interactions) and recruits the upstream DED-containing caspase-8 (and probably caspase-10) to the receptor via homophilic DED-DED interactions. Caspase-8 (or -10) within this newly formed death-inducing signaling complex then proteolytically autoactivates itself and initiates apoptosis by subsequent cleavage of downstream effector caspases (caspase-3, -6, and -7) (Fig. 1).
Fas signaling is known to be implicated in peripheral deletion of autoimmune cells, activation-induced T cell death, and CTL-mediated target cell death (for review see references 1 and 3). To avoid inappropriate cell death and disease, however, death receptor signals must be tightly controlled. It is known that death receptor apoptosis can be inhibited at different points: at the receptor level (by receptor endocytosis, soluble ligands, and/or decoy receptors), during signal transduction, and at the effector stage (e.g., caspase inhibitors CrmA, p35, and inhibitor of apoptosis proteins ). Recently, we identified a new family of viral inhibitors of death receptor-mediated cell death named vFLIPs (FADD-like IL1  -converting enzyme /caspase-8-inhibitory proteins) that are found in several herpesviruses (including oncogenic human herpesvirus 8/Kaposi's sarcoma-associated herpesvirus and molluscipox virus) and inhibit DED-DED interactions between FADD and caspase-8 and -10 (4). Cellular homologues of vFLIPs were subsequently identified by us and others (cFLIPs; aliases Casper, iFLICE, FLAME-1, CASH, CLARP, MRIT, and usurpin) and shown to structurally resemble caspase-8, except that they lack proteolytic activity (5,6). Their inhibition of caspase-8 activation renders cells resistant to apoptotic signals transmitted by Fas and all other death receptors known to date (Fig. 1).
Although the exact physiological function of cFLIP has yet to be completely elucidated, a role in disease was rapidly suspected. Indeed, several viruses, some of which are oncogenic, and human malignant melanomas express high levels of FLIP (4,5). It was therefore postulated that virally infected cells and tumor cells may thereby acquire a certain degree of immune privilege by becoming resistant to FasL and perhaps other death ligands. The in vivo relevance of this hypothesis has since remained open and uncertain, however, as CTLs can lyse their targets through both Fasand perforin-dependent pathways, and FLIP has only been shown to inhibit the former, at least in vitro (7).
In this issue, papers by Medema et al. (8) and Djerbi et al. (9) have clarified this issue. Both clearly demonstrate in different tumor models that in vivo expression of FLIP confers an advantage to tumors within an immunocompetent setting. In addition, they show that induction of tumor cell death by death receptor triggering is a more important mechanism of defense against tumors than had been suspected to date.
Djerbi et al. (9) generated mouse A20 lymphoma transfectants that stably overexpress viral FLIP from HHV8. These vFLIP-A20 cells, when compared with mock-transfected A20 cells, were shown to be resistant to Fas-mediated apoptosis by inhibition of caspase-8 activation but also showed decreased caspase-9 and -3 activation after triggering by FasL. Additionally, when grown in the continuous presence of death stimuli (agonistic anti-Fas antibody), vFLIP selectively allowed A20 cells to grow clonally. When tested in vivo using syngeneic (BALB/c) or semiallogeneic (BALB/c ϫ C57BL/6) F1 recipients injected subcutaneously, both the frequency of tumor appearance and the time to tumor appearance were drastically higher for 892 Commentary vFLIP-A20 cells as compared with mock-A20 cells. Depending on the vFLIP-A20 clone tested, in syngeneic mice vFLIP-A20 cells induced tumors in roughly 90% of mice versus 32% for mock-A20 cells. Similarly, in semiallogeneic mice, vFLIP-A20 cells induced tumors in roughly 65-80% of mice, depending on the clone used, versus 17% for mock-A20 cells. Further experiments revealed that this difference is most likely due to T cell immune escape conferred by vFLIP, as tumor establishment and growth of transfected and mock A20 cells was virtually identical in SCID mice. genes. The latter express low but detectable levels of Fas, whereas the former express high levels of Fas. Independent cFLIP transfectant clones from both the MBL2-Fas and AR6 cell lines were shown to be resistant to Fas-mediated cell death in vitro as compared with mock-transfected counterparts. In agreement with previous results (7), these FLIP transfectants are, however, sensitive to CTL-induced apoptosis in vitro, the perforin pathway being able to induce target cell apoptosis despite caspase-8 (and -10) inhibition by FLIP.
When these cell lines are injected in vivo, similar to the results of Djerbi et al. (9), Medema et al. (8) show that transfectants expressing little or no FLIPs are rejected in the majority of mice, whereas injection of the same number of cells expressing high amounts of FLIP consistently resulted in tumor development. When injected into nude mice, both cell types result in tumors that grow equally fast no matter how much FLIP they express. Thus, FLIP offers significant protection from the in vivo immune response to these tumors, and protection is not limited to tumors with high Fas expression (MBL2-Fas). Additionally and interestingly, when the same experiments were performed in perforin-deficient mice with the AR6 cell line, AR6-FLIP tumors grew nearly as efficiently as in wild-type mice, suggesting that elimination of this tumor by the immune system depends almost exclusively on the Fas pathway. Last but not least, when the rare tumors that had developed in mice injected with MBL2-Fas cells expressing low amounts of FLIP were analyzed in vitro, they were shown to have become Fas resistant and high expressors of FLIP. Thus, tumor cells appear to be selected in vivo for elevated FLIP expression, most likely due to selective pressure by the immune system.
The novel and complementary experimental data pre- The first is that Fas-mediated apoptosis is a more important mechanism of defense against tumors than had been suspected to date. The second is that FLIP expression by tumors is a significant and novel mechanism of immune escape from T cell immunity in vivo (Fig. 2). This may appear to be a surprise, as FLIP does not affect perforinmediated lysis by CTLs in vitro. However, as suggested by Medema et al. (8), this discrepancy may be due to limitations of classical in vitro cytolysis assays that may not reflect the situation occurring in the tumor microenvironment as accurately as currently conceived. In line with this observation, recent evidence suggests that to trigger the release of perforin/granzyme B from cytoplasmic granules, stronger and more persistent TCR signals may be required than for the release of FasL (Fig. 2). Furthermore, whereas partial agonistic MHC peptides are capable of eliciting FasL but not perforin cytotoxicity, strong signals from fully agonistic MHC peptides trigger both pathways (10). Consequently, in vivo CTL recognition of tumor cells as "nonself" may be inefficient, leading to preferential activation of FasL and leaving the perforin pathway virtually unimplicated.
In humans, FLIP has been shown to be overexpressed in melanomas, tumors that elicit T cell responses including the generation of melanoma-directed CTLs. Despite evidence for the in vivo generation of such CTLs, spontaneous regression of malignant melanoma only rarely occurs. The mechanisms thought to be responsible for this tumor immune escape to date include the expression of local inhibitory factors by tumor cells, such as transforming growth factor  , IL-10, and FasL, deficient antigen processing by tumor cells or loss of MHC expression, the lack of immunogenicity and costimulation for CTL activation, and defective lymphocyte homing to tumors. In certain tumor cell types, downregulation of Fas by oncogenic Ras is also observed, thereby rendering tumor cells resistant to FasL (11). Functionally, this has the same effect as overexpression of FLIP, which can now be added to the above list with reasonable confidence. Although not reported to date, FLIP upregulation may well be implicated in the pathogenesis of tumors other than melanomas.
Current attempts to improve cancer survival depend essentially on early diagnosis and the development of new treatment modalities, one of the most promising being immunotherapy. Given the new findings described herein, strategies to inhibit FLIP expression and/or FLIP-mediated inhibition of death receptor signaling may prove to be a useful complementary approach to the treatment of cancer. |
from mdp_playground.spaces.discrete_extended import DiscreteExtended
from mdp_playground.spaces.box_extended import BoxExtended
from mdp_playground.spaces.grid_action_space import GridActionSpace
from mdp_playground.spaces.multi_discrete_extended import MultiDiscreteExtended
from mdp_playground.spaces.image_multi_discrete import ImageMultiDiscrete
from mdp_playground.spaces.image_continuous import ImageContinuous
from mdp_playground.spaces.tuple_extended import TupleExtended
__all__ = [
"BoxExtended",
"DiscreteExtended",
"GridActionSpace",
"MultiDiscreteExtended",
"ImageMultiDiscrete",
"ImageContinuous",
"TupleExtended",
]
|
/** Add a {@link DataAccessPoint} as a builder. */
private Builder addDataAccessPoint(DataAccessPoint dap) {
if ( isRegistered(dap.getName()) )
throw new FusekiConfigException("Data service name already registered: "+dap.getName());
addNamedDataService$(dap.getName(), DataService.newBuilder(dap.getDataService()));
return this;
} |
def generate_database_indices_dict(dc: Union[dict, None]) -> dict:
if dc == {} or dc is None:
return {}
else:
requests = []
requests_keys = []
for k, vdc in dc.items():
if vdc == [] or vdc is None:
continue
else:
v = pd.DataFrame(vdc)
requests_keys.append(k)
requests.append(v)
res = dict(zip(requests_keys, [indexDict[k] for k in requests_keys]))
return res |
/*
* Handle any core-RCU processing required by a call_rcu() invocation.
*/
static void __call_rcu_core(struct rcu_data *rdp, struct rcu_head *head,
unsigned long flags)
{
if (!rcu_is_watching())
invoke_rcu_core();
if (irqs_disabled_flags(flags) || cpu_is_offline(smp_processor_id()))
return;
if (unlikely(rcu_segcblist_n_cbs(&rdp->cblist) >
rdp->qlen_last_fqs_check + qhimark)) {
note_gp_changes(rdp);
if (!rcu_gp_in_progress()) {
rcu_accelerate_cbs_unlocked(rdp->mynode, rdp);
} else {
rdp->blimit = DEFAULT_MAX_RCU_BLIMIT;
if (READ_ONCE(rcu_state.n_force_qs) == rdp->n_force_qs_snap &&
rcu_segcblist_first_pend_cb(&rdp->cblist) != head)
rcu_force_quiescent_state();
rdp->n_force_qs_snap = READ_ONCE(rcu_state.n_force_qs);
rdp->qlen_last_fqs_check = rcu_segcblist_n_cbs(&rdp->cblist);
}
}
} |
import io
mod = 1000000007
def power(x, e):
if e == 1:
return x % mod
tmp = power(x, e // 2)
tmp = ((tmp % mod) * (tmp % mod)) % mod
if e % 2 != 0:
tmp = ((tmp % mod) * (x % mod)) % mod
return tmp
class Solution:
def __init__(self, n):
fact = list(range(n + 1))
fact[0], fact[1] = 1, 1
for i in range(2, n + 1):
fact[i] = fact[i - 1] * i
fact[i] %= mod
self.fact = fact
def rCn(self, p, n):
tmp = power(self.fact[n - p] * self.fact[p], mod - 2)
return ((tmp % mod) * (self.fact[n] % mod)) % mod
def is_good(self, x, a, b):
s = str(x)
return s.count(str(a)) + s.count(str(b)) == len(s)
def solve(self, a, b, n):
ans = 0
for p in range(n+1):
if self.is_good(p * a + (n - p) * b, a, b):
ans += self.rCn(p, n)
ans %= mod
return ans
out = io.StringIO()
a, b, n = map(int, input().split())
sol = Solution(n)
print(sol.solve(a, b, n))
|
There are plenty of LUTs out there that aim at giving your films a distinct, beautiful look, but if you're looking for some that accurately emulate the look of 35mm film, you will definitely want to check out Koji Color's brand new suite.
Led by film color timer Dale Grahn (Saving Private Ryan, Gladiator), Koji Color's goal was to produce highly accurate 35mm film emulation for digital filmmakers. Koji isn't necessarily meant to be a finished grade for your footage, but a starting point that allows you to adjust the look (quickly) as you wish. Here's a bit of backstory from KC's website:
Seeing that film as a medium was facing possible extinction, the Koji team began in 2011 to attempt the accurate preservation of film color. Working with experts around the world and the top film labs in Hollywood, the team was able to preserve six 35mm print stocks, sometimes rescuing film cans from stock rooms at the last possible moment. These recovered film stocks were painstakingly preserved digitally, and are now available for use by digital filmmakers.
Koji includes 6 different film stocks and works with most major NLEs and post programs. It supports footage shot on DSLRs as well larger cameras, like the Alexa, Canon C-series, and more. But, before we get into the technical aspects, take a look at a piece made by filmmaker Paul Schefz using Koji.
Here are a few stills:
You can also try out Koji on your own still images using their web app.
Technical Specifications
Works with: Davinci Resolve, Premiere Pro, Final Cut Pro X, After Effects, and Autodesk Smoke
Supports footage shot on DSLR camera formats
Supports log footage, including REDlogFilm, Arri Log C, BMDFilm, BMDFilmV2, Canon C-Log, and Sony SLog3
Koji Log takes care of Rec.709 conversion for you -- no need to convert from log to Rec.709 (unless you want to)
Koji Packages/Pricing
Koji DSLR: Brings beautiful, highly accurate film color to footage shot on DSLRs. Works with a wide variety of camera formats including Canon DSLRs, Panasonic DSLRs, and Blackmagic cameras (video mode). ($199)
Koji Log: Fast, powerful film color for log footage. Designed to work natively with REDlogFilm, Arri Log C, BMDFilm, BMDFilmV2, Canon C-Log, and Sony SLog3. ($299)
Koji Studio: Advanced film color for experienced colorists. Includes technical versions of the Koji film stocks with full color separation, as well as DCI-P3 output for Cineon. Includes Koji DSLR and Log. ($799)
Take a look at each Koji suite to see if they're right for your projects, and make sure you check the system requirements. Koji is also giving NFS readers a 10% intro discount on their products. This coupon code is good for just one week (until 10/15): NOFILMSCHOOL1WEEK. |
// Parts returns the repo id, ref and path according to whether the request is path-style or virtual-host-style.
func Parts(host string, urlPath string, bareDomains []string) (repo string, ref string, pth string) {
urlPath = strings.TrimPrefix(urlPath, path.Separator)
var p []string
ourHosts := httputil.HostsOnly(bareDomains)
if memberFold(httputil.HostOnly(host), ourHosts) {
p = strings.SplitN(urlPath, path.Separator, 3)
repo = p[0]
if len(p) >= 1 {
p = p[1:]
}
} else {
host := httputil.HostOnly(host)
repo = ""
for _, ourHost := range ourHosts {
if strings.HasSuffix(host, ourHost) {
repo = strings.TrimSuffix(host, "."+ourHost)
break
}
}
p = strings.SplitN(urlPath, path.Separator, 2)
}
if len(p) == 0 {
return repo, "", ""
}
if len(p) == 1 {
return repo, p[0], ""
}
return repo, p[0], p[1]
} |
import matlab.engine
import sys
eng = matlab.engine.start_matlab()
def execute_service(in_path, out_path, thr=0.5):
# TODO: get args from JSON
eng.mod_changePoints(in_path, out_path, thr, nargout=0)
execute_service(sys.argv[1], sys.argv[2], float(sys.argv[3]))
|
The Annals of Research on Engineering Education—AREE
What is the Annals of Research on Engineering Education (AREE)? AREE is a project supported by the US Center for the Advancement of Scholarship on Engineering Education (CASEE) at the US National Academy of Engineering (NAE). AREE aims at promoting scholarship and innovation in engineering education with a strong emphasis on dissemination of findings into the classroom environment. AREE is based on a large partnership with a group of international scientific journals devoted to scientific and engineering education, among them EJEE. AREE consists in |
/**
* Sequence of items of type {@link Int xs:double}, containing at least two of them.
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
*/
public final class DblSeq extends NativeSeq {
/** Values. */
private final double[] values;
/**
* Constructor.
* @param values bytes
*/
private DblSeq(final double[] values) {
super(values.length, AtomType.DOUBLE);
this.values = values;
}
@Override
public Dbl itemAt(final long pos) {
return Dbl.get(values[(int) pos]);
}
@Override
public Value reverse(final QueryContext qc) {
final int sz = (int) size;
final double[] tmp = new double[sz];
for(int i = 0; i < sz; i++) tmp[sz - i - 1] = values[i];
return get(tmp);
}
@Override
public boolean equals(final Object obj) {
return this == obj || (obj instanceof DblSeq ? Arrays.equals(values, ((DblSeq) obj).values) :
super.equals(obj));
}
@Override
public double[] toJava() {
return values;
}
// STATIC METHODS ===============================================================================
/**
* Creates a sequence with the specified items.
* @param values values
* @return value
*/
public static Value get(final double[] values) {
final int vl = values.length;
return vl == 0 ? Empty.VALUE : vl == 1 ? Dbl.get(values[0]) : new DblSeq(values);
}
/**
* Creates a typed sequence with the items of the specified values.
* @param size size of resulting sequence
* @param values values
* @return value
* @throws QueryException query exception
*/
static Value get(final int size, final Value... values) throws QueryException {
final DoubleList tmp = new DoubleList(size);
for(final Value value : values) {
// speed up construction, depending on input
if(value instanceof DblSeq) {
tmp.add(((DblSeq) value).values);
} else {
for(final Item item : value) tmp.add(item.dbl(null));
}
}
return get(tmp.finish());
}
} |
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture *
* (c) 2006 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <gtest/gtest.h>
#include <sofa/core/objectmodel/BaseNode.h>
class Dummy: public sofa::core::objectmodel::BaseObject
{
bool *m_destroyed;
public:
SOFA_CLASS(Dummy, sofa::core::objectmodel::BaseObject);
Dummy(const std::string& name): m_destroyed(nullptr) {this->setName(name);}
Dummy(bool *destroyed): m_destroyed(destroyed) {}
~Dummy() override { if(m_destroyed) *m_destroyed = true; }
};
template<class Node>
void Node_test_objectDestruction_singleObject()
{
const sofa::core::objectmodel::BaseNode::SPtr node = sofa::core::objectmodel::New<Node>();
bool objectDestroyed = false;
{
const Dummy::SPtr dummy = sofa::core::objectmodel::New<Dummy>(&objectDestroyed);
node->addObject(dummy);
node->removeObject(dummy);
}
EXPECT_TRUE(objectDestroyed);
}
template<class Node>
void Node_test_objectDestruction_multipleObjects()
{
const sofa::core::objectmodel::BaseNode::SPtr node = sofa::core::objectmodel::New<Node>();
bool objectDestroyed[4] = {false};
{
Dummy::SPtr dummy[4];
for (int i=0 ; i<4 ; i++)
{
dummy[i] = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[i]);
node->addObject(dummy[i]);
}
node->removeObject(dummy[3]);
node->removeObject(dummy[0]);
node->removeObject(dummy[2]);
node->removeObject(dummy[1]);
}
EXPECT_TRUE(objectDestroyed[0]);
EXPECT_TRUE(objectDestroyed[1]);
EXPECT_TRUE(objectDestroyed[2]);
EXPECT_TRUE(objectDestroyed[3]);
}
template<class Node>
void Node_test_objectDestruction_childNode_singleObject()
{
const sofa::core::objectmodel::BaseNode::SPtr node = sofa::core::objectmodel::New<Node>();
bool objectDestroyed = false;
{
const sofa::core::objectmodel::BaseNode::SPtr childNode = sofa::core::objectmodel::New<Node>();
node->addChild(childNode);
const Dummy::SPtr dummy = sofa::core::objectmodel::New<Dummy>(&objectDestroyed);
childNode->addObject(dummy);
node->removeChild(childNode);
}
EXPECT_TRUE(objectDestroyed);
}
template<class Node>
void Node_test_objectDestruction_childNode_complexChild()
{
bool objectDestroyed[10] = {false};
const sofa::core::objectmodel::BaseNode::SPtr node = sofa::core::objectmodel::New<Node>();
{
const sofa::core::objectmodel::BaseNode::SPtr childNode1 = sofa::core::objectmodel::New<Node>();
node->addChild(childNode1);
const sofa::core::objectmodel::BaseNode::SPtr childNode2 = sofa::core::objectmodel::New<Node>();
childNode1->addChild(childNode2);
const sofa::core::objectmodel::BaseNode::SPtr childNode3 = sofa::core::objectmodel::New<Node>();
childNode2->addChild(childNode3);
const sofa::core::objectmodel::BaseNode::SPtr childNode4 = sofa::core::objectmodel::New<Node>();
childNode1->addChild(childNode4);
const Dummy::SPtr dummy1 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[0]);
childNode1->addObject(dummy1);
const Dummy::SPtr dummy2 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[1]);
childNode1->addObject(dummy2);
const Dummy::SPtr dummy3 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[2]);
childNode2->addObject(dummy3);
const Dummy::SPtr dummy4 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[3]);
childNode2->addObject(dummy4);
const Dummy::SPtr dummy5 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[4]);
childNode3->addObject(dummy5);
const Dummy::SPtr dummy6 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[5]);
childNode3->addObject(dummy6);
const Dummy::SPtr dummy7 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[6]);
childNode4->addObject(dummy7);
const Dummy::SPtr dummy8 = sofa::core::objectmodel::New<Dummy>(&objectDestroyed[7]);
childNode4->addObject(dummy8);
node->removeChild(childNode1);
}
EXPECT_TRUE(objectDestroyed[0]);
EXPECT_TRUE(objectDestroyed[1]);
EXPECT_TRUE(objectDestroyed[2]);
EXPECT_TRUE(objectDestroyed[3]);
EXPECT_TRUE(objectDestroyed[4]);
EXPECT_TRUE(objectDestroyed[5]);
EXPECT_TRUE(objectDestroyed[6]);
EXPECT_TRUE(objectDestroyed[7]);
}
|
/*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Common Public License (CPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/cpl1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.jikesrvm.compilers.opt.ir.operand;
import java.util.Arrays;
/*
* An OsrTypeInfoOperand object keeps type information of locals
* and stacks at a byte code index.
*/
public final class OsrTypeInfoOperand extends Operand {
/**
* The data type.
*/
public byte[] localTypeCodes;
public byte[] stackTypeCodes;
/**
* Create a new type operand with the specified data type.
*/
public OsrTypeInfoOperand(byte[] ltcodes, byte[] stcodes) {
this.localTypeCodes = ltcodes;
this.stackTypeCodes = stcodes;
}
/**
* Return a new operand that is semantically equivalent to <code>this</code>.
*
* @return a copy of <code>this</code>
*/
public Operand copy() {
return new OsrTypeInfoOperand(localTypeCodes, stackTypeCodes);
}
/**
* Are two operands semantically equivalent?
*
* @param op other operand
* @return <code>true</code> if <code>this</code> and <code>op</code>
* are semantically equivalent or <code>false</code>
* if they are not.
*/
public boolean similar(Operand op) {
boolean result = true;
if (!(op instanceof OsrTypeInfoOperand)) {
return false;
}
OsrTypeInfoOperand other = (OsrTypeInfoOperand) op;
result =
Arrays.equals(this.localTypeCodes, other.localTypeCodes) &&
Arrays.equals(this.stackTypeCodes, other.stackTypeCodes);
return result;
}
/**
* Returns the string representation of this operand.
*
* @return a string representation of this operand.
*/
public String toString() {
StringBuilder buf = new StringBuilder("OsrTypeInfo(");
for (int i = 0, n = localTypeCodes.length; i < n; i++) {
buf.append((char) localTypeCodes[i]);
}
buf.append(",");
for (int i = 0, n = stackTypeCodes.length; i < n; i++) {
buf.append((char) stackTypeCodes[i]);
}
buf.append(")");
return buf.toString();
}
}
|
async def emoji_rename(
self, ctx: commands.Context, emoji: discord.Emoji, name: str, *roles: discord.Role
):
if emoji.guild != ctx.guild:
await ctx.send_help()
return
try:
await emoji.edit(
name=name,
roles=roles,
reason=get_audit_reason(
ctx.author,
_("Restricted to roles: ").format(", ".join(role.name for role in roles))
if roles
else None,
),
)
except discord.Forbidden:
await ctx.send(chat.error(_("I can't edit this emoji")))
await ctx.tick() |
Considering the start that Catrina Allen has had to 2016, I can no longer ignore her dominance. Allen just keeps winning. Every weekend she adds another trophy to her mantle. The fact that she is winning so much isn’t surprising, it is by how much and how often she wins. Her normal counterparts include Paige Pierce, Val Jenkins, Sarah Hokom and a handful of others, but none of the previously mentioned players are on Catrina’s level this year. For comparison sake lets take a look at Catrina’s 2016 season compared to perhaps the best season ever from Paul McBeth in 2015.
Player Events NT/Major Wins A-Tier Wins B-Tier Wins Worst Finish McBeth 2015 10 2 5 1 3rd Allen 2016 11 3 3 3 1st
*Allen also played in the Open Division for two events finishing 13th and 45th respectively. Stats above are from the Open Women Division only.
In the Pro Women Division for her first 11 events of the year, Catrina Allen hasn’t lost. Her average margin of victory is 12.5 strokes. These include an 8 stroke margin over Valarie Jenkins at the Kansas City Wide Open and 17 stroke margin over Paige Pierce at the Glass Blown Open. Admittedly, the competition level at most of her stops isn’t as high as the NT stops, Catrina is still winning and winning big.
On her great play recently, Allen attributed part of it to her listening sessions of “Golf is Not a Game of Perfect” by Bob Rotella with her husband Paul Ulibarri. Catrina also stated that the work over the past 5 years on her physical fitness has her feeling “Like it’s all clicking”.
Heading into this weekend’s Masters Cup event, Catrina is the favorite in Santa Cruz. Looking to improve on her 3rd place finish a year ago, Allen is fresh off wins at the Kansas City Wide Open and the Utah Open the last 2 weeks. In regards to her approach this weekend Catrina told SmashboxxTV “I think DeLa (DeLaveaga) is the most, of all the courses you play, the most mentally tough”. This weekend may be her toughest test so far as her 3rd place finish in 2015 was to Paige Pierce and Valarie Jenkins. Both very capable of pushing Catrina from the top of the podium for the first time this year. That remains to be seen but for now, my money is on Catrina Allen. |
An explanation for the reduction in bilirubin levels in congenitally jaundiced Gunn rats after transplantation of isolated hepatocytes.
Isolated hepatocytes prepared from Wistar rats by mechanical means were infused into the liver of congenitally jaundiced Gunn rats. Red cell survival was determined in the recipients and their total plasma bilirubin was measured just before and 20 days after transplantation. Similar measurements were made in transplanted Gunn rats receiving the immunosuppressant drug cyclophosphamide at 5 mg/kg/day and in a group of splenectomized Gun rats. Red cell survival was significantly prolonged in all transplanted rats and in the splenectomised group. Total plasma bilirubin also fell significantly in all three groups by up to 25%, a change we attribute to reduced red cell turnover, haemoglobin synthesis and hence reduced bilirubin synthesis. Blockade of the splenic reticuloendothelial system by hepatocyte debris is suggested as a possible cause. |
/**
* Make CDATA out of possibly encoded PCDATA. <br>
* E.g. make '&' out of '&amp;'
*/
public static String xmlDecodeTextToCDATA( String pcdata )
{
if ( pcdata == null )
{
return null;
}
char c, c1, c2, c3, c4, c5;
StringBuilder n = new StringBuilder( pcdata.length() );
for ( int i = 0; i < pcdata.length(); i++ )
{
c = pcdata.charAt( i );
if ( c == '&' )
{
c1 = lookAhead( 1, i, pcdata );
c2 = lookAhead( 2, i, pcdata );
c3 = lookAhead( 3, i, pcdata );
c4 = lookAhead( 4, i, pcdata );
c5 = lookAhead( 5, i, pcdata );
if ( c1 == 'a' && c2 == 'm' && c3 == 'p' && c4 == ';' )
{
n.append( "&" );
i += 4;
}
else if ( c1 == 'l' && c2 == 't' && c3 == ';' )
{
n.append( "<" );
i += 3;
}
else if ( c1 == 'g' && c2 == 't' && c3 == ';' )
{
n.append( ">" );
i += 3;
}
else if ( c1 == 'q' && c2 == 'u' && c3 == 'o' && c4 == 't' && c5 == ';' )
{
n.append( "\"" );
i += 5;
}
else if ( c1 == 'a' && c2 == 'p' && c3 == 'o' && c4 == 's' && c5 == ';' )
{
n.append( "'" );
i += 5;
}
else
{
n.append( "&" );
}
}
else
{
n.append( c );
}
}
return n.toString();
} |
// Reads the number of active jiffies for the system
long LinuxParser::ActiveJiffies(const vector<string>& stats) {
long user{};
long nice{};
long system{};
long irq{};
long softirq{};
long steal;
if (!stats.empty()) {
user = stol(stats[kUser_]);
nice = stol(stats[kNice_]);
system = stol(stats[kSystem_]);
irq = stol(stats[kIRQ_]);
softirq = stol(stats[kSoftIRQ_]);
steal = stol(stats[kSteal_]);
}
return user + nice + system + irq + softirq + steal;
} |
<gh_stars>0
// g++ -O2 -S kernel_marco.cpp
int x, y, r;
#define ACCESS_ONCE(x) (*(volatile typeof(x) *)&(x))
void f(){
ACCESS_ONCE(x) = r;
ACCESS_ONCE(y) = 1;
} |
/**
* Represents a delete command which deletes an entity from MyGM.
*
* @author snoidetx
*/
public class DeleteCommand extends Command {
public static final String COMMAND_WORD = "delete";
public static final String MESSAGE_USAGE_PLAYER = COMMAND_WORD
+ ": Deletes a player from MyGM or lineup if lineup name is specified."
+ "\nParameters: "
+ PREFIX_PLAYER + "NAME "
+ "[" + PREFIX_LINEUP + "LINEUP NAME]\n"
+ "Example: "
+ COMMAND_WORD + " "
+ PREFIX_PLAYER + "John Doe ";
public static final String MESSAGE_USAGE_LINEUP = COMMAND_WORD
+ ": Deletes a lineup from MyGM."
+ "\nParameters: "
+ PREFIX_LINEUP + "LINEUP NAME \n"
+ "Example: "
+ COMMAND_WORD + " "
+ PREFIX_LINEUP + "Starting 5";
public static final String MESSAGE_USAGE_SCHEDULE = COMMAND_WORD
+ ": Deletes a schedule from MyGM."
+ "\nParameters: "
+ PREFIX_SCHEDULE + "INDEX \n"
+ "Example: "
+ COMMAND_WORD + " "
+ PREFIX_SCHEDULE + "1";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Deletes a player, lineup or schedule from MyGM\n"
+ MESSAGE_USAGE_PLAYER + "\n"
+ MESSAGE_USAGE_LINEUP + "\n"
+ MESSAGE_USAGE_SCHEDULE;
public static final String MESSAGE_NO_SUCH_LINEUP = "Lineup does not exist.";
public static final String MESSAGE_NO_SUCH_PERSON = "Player does not exist.";
public static final String MESSAGE_DELETE_PERSON_SUCCESS = "Deleted Person: %s";
public static final String MESSAGE_PERSON_NOT_IN_LINEUP = "Player is not inside the lineup";
public static final String MESSAGE_DELETE_PERSON_FROM_LINEUP_SUCCESS = "Person deleted from lineup %s: %s";
public static final String MESSAGE_DELETE_LINEUP_SUCCESS = "Deleted Lineup: %s";
public static final String MESSAGE_DELETE_SCHEDULE_SUCCESS = "Deleted Schedule: %s";
public static final String MESSAGE_DELETE_FAILURE = "Delete cannot be executed.";
private enum DeleteCommandType {
PLAYER, LINEUP, PLAYER_LINEUP, SCHEDULE
}
private final DeleteCommandType type;
private final Name player;
private final seedu.address.model.lineup.LineupName lineup;
private final Index targetIndex;
/**
* Constructs a new delete command.
*/
public DeleteCommand(Name player) {
this.type = DeleteCommandType.PLAYER;
this.player = player;
this.lineup = null;
this.targetIndex = null;
}
/**
* Overloaded constructor for delete command.
*/
public DeleteCommand(Name player, seedu.address.model.lineup.LineupName lineup) {
this.type = DeleteCommandType.PLAYER_LINEUP;
this.player = player;
this.lineup = lineup;
this.targetIndex = null;
}
/**
* Overloaded constructor for delete command.
*/
public DeleteCommand(seedu.address.model.lineup.LineupName lineup) {
this.type = DeleteCommandType.LINEUP;
this.player = null;
this.lineup = lineup;
this.targetIndex = null;
}
/**
* Overloaded constructor for delete command.
*/
public DeleteCommand(Index targetIndex) {
this.type = DeleteCommandType.SCHEDULE;
this.player = null;
this.lineup = null;
this.targetIndex = targetIndex;
}
/**
* Executes the DeleteCommand and returns the result message.
*
* @param model {@code Model} which the command should operate on.
* @return feedback message of the operation result for display
* @throws CommandException If an error occurs during command execution.
*/
@Override
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
switch (this.type) {
case PLAYER:
if (!model.hasPersonName(this.player)) {
throw new CommandException(MESSAGE_NO_SUCH_PERSON);
} else {
Person toDelete = model.getPerson(this.player);
model.deletePerson(toDelete);
return new CommandResult(String.format(MESSAGE_DELETE_PERSON_SUCCESS, this.player));
}
case PLAYER_LINEUP:
if (!model.hasPersonName(this.player)) {
throw new CommandException(MESSAGE_NO_SUCH_PERSON);
}
if (!model.hasLineupName(this.lineup)) {
throw new CommandException(MESSAGE_NO_SUCH_LINEUP);
}
Person person = model.getPerson(this.player);
Lineup lineup = model.getLineup(this.lineup);
if (!model.isPersonInLineup(person, lineup)) {
throw new CommandException(MESSAGE_PERSON_NOT_IN_LINEUP);
}
model.deletePersonFromLineup(person, lineup);
return new CommandResult(String
.format(MESSAGE_DELETE_PERSON_FROM_LINEUP_SUCCESS, this.lineup, this.player));
// to be added
case LINEUP:
if (!model.hasLineupName(this.lineup)) {
throw new CommandException(MESSAGE_NO_SUCH_LINEUP);
}
Lineup toDelete = model.getLineup(this.lineup);
model.deleteLineup(toDelete);
return new CommandResult(String.format(MESSAGE_DELETE_LINEUP_SUCCESS, this.lineup));
// to be added
case SCHEDULE:
List<Schedule> lastShownList = model.getFilteredScheduleList();
if (targetIndex.getZeroBased() >= lastShownList.size()) {
throw new CommandException(MESSAGE_INVALID_SCHEDULE_DISPLAYED_INDEX);
}
Schedule personToDelete = lastShownList.get(targetIndex.getZeroBased());
model.deleteSchedule(personToDelete);
model.updateFilteredScheduleList(Model.PREDICATE_SHOW_ACTIVE_SCHEDULES);
return new CommandResult(String.format(MESSAGE_DELETE_SCHEDULE_SUCCESS, personToDelete));
default:
throw new CommandException(MESSAGE_DELETE_FAILURE);
}
}
@Override
public boolean equals(Object other) {
if (player != null) {
return other == this // short circuit if same object
|| (other instanceof DeleteCommand // instanceof handles nulls
&& player.equals(((DeleteCommand) other).player));
}
if (lineup != null) {
return other == this // short circuit if same object
|| (other instanceof DeleteCommand // instanceof handles nulls
&& lineup.equals(((DeleteCommand) other).lineup));
}
if (targetIndex != null) {
return other == this // short circuit if same object
|| (other instanceof DeleteCommand // instanceof handles nulls
&& targetIndex.equals(((DeleteCommand) other).targetIndex));
}
return false;
}
} |
async def fame_board(self, ctx: commands.Context):
if not ctx.invoked_subcommand:
if not ic(self, ctx.channel):
pre = prefix(self, ctx)
embed = discord.Embed(
title="`Message` and Star board Commands",
colour=0xf1c40f
)
embed.add_field(inline=False, name=f"{pre}fb info",
value="Obtain information about the fame board if it exist")
embed.add_field(inline=False, name=f"{pre}fb c <channel ID / mention> (emote amount req)",
value="Create a fame board with the requirement if it don't exist, emote amount "
"default to 3 if not specified")
embed.add_field(inline=False, name=f"{pre}fb delete", value="Removes fame board if it exist")
embed.add_field(inline=False, name=f"{pre}modify <channel mention or ID>",
value="Changes the star board target channel")
await ctx.send(embed=embed) |
/*
* Copyright (c) 2011 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_SEL_LDR_THREAD_INTERFACE_H_
#define NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_SEL_LDR_THREAD_INTERFACE_H_
/*
* This is the NaClThreadInterface subclass that should be used by all
* thread creators in the service runtime. This interface will grab
* the NaClApp's VM lock prior to actually creating the thread (and as
* a side effect allocating the thread stack), so that no VM hole
* exists in the untrusted address space.
*
* This is not needed except for in Windows, since on Linux and OSX we
* use mmap and that maps over existing memory pages without creating
* a temporary address space hole. As an optimization, this code
* might not actually grab the VM lock anywhere *except* on windows.
*/
#include "native_client/src/include/nacl_base.h"
#include "native_client/src/trusted/threading/nacl_thread_interface.h"
EXTERN_C_BEGIN
struct NaClApp;
struct NaClAddrSpSquattingThreadInterface {
struct NaClThreadInterface base NACL_IS_REFCOUNT_SUBCLASS;
struct NaClApp *nap;
};
/* fwd */ extern
struct NaClThreadInterfaceVtbl const kNaClAddrSpSquattingThreadInterfaceVtbl;
int NaClAddrSpSquattingThreadIfFactoryFunction(
void *factory_data,
NaClThreadIfStartFunction thread_fn_ptr,
void *thread_fn_data,
size_t thread_stack_size,
struct NaClThreadInterface **out_new_thread);
int NaClAddrSpSquattingThreadIfStartThread(
struct NaClThreadInterface *vself);
void NaClAddrSpSquattingThreadIfLaunchCallback(
struct NaClThreadInterface *vself);
EXTERN_C_END
#endif
|
//
// Created by lijie on 9/6/18.
//
#include <iostream>
#include <applications/arcsim_application.h>
#include <simulators/arc_simulator.h>
#include <integrators/bogus_integrator.h>
#include <magic.hpp>
int main(int argc, char const* argv[]) {
applications::ArcsimApplication(argc, argv);
// System<ARCSimulator, BogusIntegrator>(argc, argv).start();
return 0;
} |
def resource_info(self,
resource_type,
start,
end=None,
resource_id=None,
project_id=None,
q_filter=None):
translated_resource = self.retrieve_mappings.get(resource_type,
resource_type)
qty, unit = self.volumes_mappings.get(
resource_type,
(1, 'unknown'))
query_parameters = self._generate_time_filter(
start,
end,
True if resource_id else False)
need_subquery = True
if resource_id:
need_subquery = False
query_parameters.append(
self.gen_filter(id=resource_id))
resources = self._conn.resource.search(
resource_type=translated_resource,
query=self.extend_filter(*query_parameters),
history=True,
limit=1,
sorts=['revision_start:desc'])
else:
if end:
query_parameters.append(
self.gen_filter(cop="=", type=translated_resource))
else:
need_subquery = False
if project_id:
query_parameters.append(
self.gen_filter(project_id=project_id))
if q_filter:
query_parameters.append(q_filter)
final_query = self.extend_filter(*query_parameters)
resources = self._conn.resource.search(
resource_type='generic' if end else translated_resource,
query=final_query)
resource_list = list()
if not need_subquery:
for resource in resources:
resource_data = self.t_gnocchi.strip_resource_data(
resource_type,
resource)
self._expand_metrics(
[resource_data],
self.metrics_mappings[resource_type],
start,
end)
resource_data.pop('metrics', None)
data = self.t_cloudkitty.format_item(
resource_data,
unit,
qty if isinstance(qty, int) else resource_data[qty])
resource_list.append(data)
return resource_list[0] if resource_id else resource_list
for resource in resources:
res = self.resource_info(
resource_type,
start,
end,
resource_id=resource.get('id', ''))
resource_list.append(res)
return resource_list |
Evaluation of New 99mTc(CO)3+ Radiolabeled Glycylglycine in Vivo.
BACKGROUND
Peptide-based agents are used in molecular imaging due to their unique properties, such as rapid clearance from the circulation, high affinity and target selectivity. Many of radiolabeled peptides have been clinically experienced with diagnostic accuracy. The aim of this study was investigation of in vivo biological behavior of + radiolabeled glycylglycine (GlyGly) .
METHODS
Glycylglycine was radiolabeled with high radiolabeling yield of 94.69±2 % and quality control of the radiolabeling process was performed by thin layer radiochromatography (TLRC) and high performance liquid radiochromatography (HPLRC). Lipophilicity study for radiolabeled complex (99mTc(CO)3-Gly-Gly) was carried out using solvent extraction. The in vivo evaluation was performed by both biodistribution and SPECT imaging.
RESULTS
The high radiolabelling yield of 99mTc(CO)3-GlyGly was obtained and verified by TLRC and HPLRC as well. According to the in vivo results, SPECT images and biodistribution data are in good accordance. The excretion route from body was both hepatobiliary and renal.
CONCLUSION
This study shows us that 99mTc(CO)3-GlyGly has a potential to be used as a peptide-based imaging agent. Further studies, 99mTc(CO)3-GlyGly can be performed on tumor bearing animals. |
/** Definition of constants that refer to names of properties used
* by the Tool. Use these values as the parameter of
* {@link ToolProperties#getProperty(String)} and related methods.
*/
public final class PropertyConstants {
/** Private constructor for a utility class. */
private PropertyConstants() {
}
/** PoolParty remote URL. */
public static final String POOLPARTY_REMOTEURL =
"PoolParty.remoteUrl";
/** SPARQL results XSL file. */
public static final String SPARQLRESULTS_XSL =
"SPARQLResults.xsl";
} |
package org.orienteer.core.component;
import java.util.Optional;
import org.apache.wicket.ajax.AjaxRequestTarget;
/**
* Interface to mark components (Widgets) which can be refreshed by themself
*/
public interface IRefreshable {
public void refresh(Optional<AjaxRequestTarget> targetOptional);
}
|
Review: Palehound, 'A Place I'll Always Go'
Note: NPR's First Listen audio comes down after the album is released. However, you can still listen with the Spotify or Apple Music playlist at the bottom of the page.
toggle caption Courtesy of artist
An inexorable truth of life is that we all will lose someone close. Death is cruelly indifferent, and no matter how expected or seemingly random it is, no one is ever truly prepared when a loved one is all of sudden gone. Palehound's Ellen Kempner understands this as much as anyone. In relatively close succession last year, the Boston-based songwriter faced the unforeseen death of a friend, and the passing of her grandmother, and was left reeling as a result. Palehound's second full-length album, A Place I'll Always Go, cannot help but be informed by these experiences. Channeling her grief into honest songs about mortality and the search for closure, the album reveals details from her personal life like never before.
On "If You Met Her," a song about the lingering heartache felt by her friend's absence, Kempner recalls happy moments preserved as memories, and marking the time since she passed. "Starting to count up to two / Another year of missing you / When the dust clears, where's my body?," she asks. She then flips the script with these final, devastating lines, "I'm with someone new / And I know that you would love her / If you met her," she pines with a plaintive, breathy whisper. Elsewhere, Kempner confronts her past ("Turning 21"), and admits feigning happiness while unraveling within ("Silver Toaster"). In "Flowing Over," she describes listening to sad music as a way to quell the anxiety attacks. "Flowing over 'til I'm empty!," she shouts in a mantra that others might turn to during their own low moments.
Still, for all its rumination, the album gradually projects a flicker of light amid the darkness: During this same tumultuous time, Kempner found herself entering into her first healthy relationship. A Place I'll Always Go grapples not only with the contradictory flood of emotions and guilt that arise when attempting to move on, but with the burgeoning excitement of new love. In "Room," Kempner both evokes the cloistered sanctuary of her newfound companionship and romance, and reflects a contentment and ease with her queer identity. "Call us sinners but we eat all our dinners in my room... Rests her head near, I'm feeling OK here in my room," she sings atop a bed of jangling guitars and glistening keyboard hooks.
Recorded in late 2016 at Brooklyn's Thump Studios with assistance from Gabe Wax (who also worked on Palehound's superb 2015 album, Dry Food), A Place I'll Always Go galvanizes its bedroom confessionals with Kempner's dexterous finger-plucked arpeggios and buzzy guitar melodies, and the propulsive rocking energy of drummer Jesse Weiss and bassist Larz Brogan. Palehound adds richer instrumental shadings on the album's bookends: On the transportive opener, "Hunter's Gun," loping electronic beats and ethereal guitars glide underneath the hushed vocals; in the closer, "At Night I'm Alright With You," eschews guitar for a stark synth hum and scratchy pulse that blossoms into bliss as she sings "But at night I'm alright with you," with a sense of calming reprieve.
Kempner ultimately finds that without pain, there's no joy. You can deny your grief or push it down deep, but the only relief comes when you let it be felt, and derive strength from your vulnerabilities. While the arc of A Place I'll Always Go may have initially begun in the wake of tremendous loss, Palehound's unflinching songs are also a celebration of life and embrace of love, and an empathetic reflection on how endings usually lead to beginnings. |
def find_closest_network_node(x_coord, y_coord, floor):
logger.debug("now running function find_closest_network_node")
cur = connection.cursor()
query = """ SELECT
verts.id as id
FROM geodata.networklines_3857_vertices_pgr AS verts
INNER JOIN
(select ST_PointFromText('POINT(%s %s %s)', 3857)as geom) AS pt
ON ST_DWithin(verts.the_geom, pt.geom, 200.0)
ORDER BY ST_3DDistance(verts.the_geom, pt.geom)
LIMIT 1;"""
cur.execute(query, (x_coord, y_coord, floor,))
query_result = cur.fetchone()
if query_result is not None:
point_on_networkline = int(query_result[0])
return point_on_networkline
else:
logger.debug("query is none check tolerance value of 200")
return False |
<gh_stars>1-10
from unittest.mock import NonCallableMock, sentinel
from pytest import mark
from preacher.core.scenario.scenario_result import ScenarioResult
from preacher.core.scenario.scenario_task import ScenarioTask
from preacher.core.scenario.scenario_task import StaticScenarioTask, RunningScenarioTask
from preacher.core.scenario.util.concurrency import CasesTask
from preacher.core.status import Status, StatusedList
def test_static_scenario_task():
task = StaticScenarioTask(sentinel.result)
assert task.result() is sentinel.result
def test_running_scenario_task_empty():
cases_result = NonCallableMock(StatusedList, status=Status.SKIPPED)
cases = NonCallableMock(CasesTask)
cases.result.return_value = cases_result
task = RunningScenarioTask(
label=sentinel.label,
conditions=sentinel.conditions,
cases=cases,
subscenarios=[],
)
result = task.result()
assert result.label is sentinel.label
assert result.status is Status.SKIPPED
assert result.message is None
assert result.conditions is sentinel.conditions
assert result.cases is cases_result
assert not result.subscenarios.items
cases.result.assert_called_once_with()
@mark.parametrize(
("cases_status", "subscenario_status", "expected_status"),
(
(Status.SUCCESS, Status.UNSTABLE, Status.UNSTABLE),
(Status.UNSTABLE, Status.FAILURE, Status.FAILURE),
),
)
def test_running_scenario_task_filled(cases_status, subscenario_status, expected_status):
cases_result = NonCallableMock(StatusedList, status=cases_status)
cases = NonCallableMock(CasesTask)
cases.result.return_value = cases_result
subscenario = NonCallableMock(ScenarioTask)
subscenario_result = ScenarioResult(status=subscenario_status)
subscenario.result.return_value = subscenario_result
task = RunningScenarioTask(
label=sentinel.label,
conditions=sentinel.conditions,
cases=cases,
subscenarios=[subscenario],
)
result = task.result()
assert result.label is sentinel.label
assert result.status is expected_status
assert result.message is None
assert result.conditions is sentinel.conditions
assert result.cases is cases_result
assert len(result.subscenarios.items) == 1
assert result.subscenarios.items[0] is subscenario_result
|
<gh_stars>1000+
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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.
r"""Simple tool for computing $L$-scores from Wikipron data.
Wikipron contains multilingual pronunciation data mined from Wiktionary.
The project can be found here: https://github.com/kylebgorman/wikipron.
Produces tab-separated file with the following format:
- Language code
- Language name.
- Type of the lexicon: phonemic or phonetic
- Number of unique pronunciations.
- Number of unique spellings.
- $L$-score.
Sample output:
--------------
bul Bulgarian phonetic 239 233 1.000000
Example:
--------
Given the Wikipron installation in ${WIKIPRON_DIR}:
> python3 wikipron_lscores_main.py \
--input_dir ${WIKIPRON_DIR}/data/wikipron/tsv \
--output_tsv lscores.tsv \
--sort_by score
Dependencies:
-------------
absl-py
pycountry
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import os
from absl import app
from absl import flags
from absl import logging
import pycountry as pyc
# Separator used in the filename.
_NAME_SEPARATOR = "_"
flags.DEFINE_string(
"input_dir", "",
"Directory containing Wikipron lexicons in tsv format.")
flags.DEFINE_string(
"output_tsv", "",
"Tab-separated output file with the results.")
flags.DEFINE_string(
"sort_by", "language",
"Sorting criterion. One of: \"language\", \"score\".")
FLAGS = flags.FLAGS
def _compute_stats(filename):
"""Accumulates the statistics and computes the (type) L-score."""
pron_spellings = {}
unique_spellings = set()
with open(os.path.join(FLAGS.input_dir, filename),
mode="r", encoding="utf8") as f:
reader = csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
for row in reader:
pron = row[1]
spelling = row[0]
unique_spellings.add(spelling)
if pron not in pron_spellings:
pron_spellings[pron] = set()
pron_spellings[pron].add(spelling)
spell_sum = 0.0
for spellings in pron_spellings.values():
spell_sum += len(spellings)
num_unique_prons = len(pron_spellings)
lscore = spell_sum / num_unique_prons
return num_unique_prons, len(unique_spellings), lscore
def _process_lexicon_file(filename):
"""Processes single lexicon file in Wikipron format."""
basename = os.path.basename(filename)
toks = os.path.splitext(basename)[0].split(_NAME_SEPARATOR)
if len(toks) < 2:
logging.error("%s: Expected at least two components in name", basename)
return
if len(toks) > 3:
logging.error("%s: Too many components in name!", basename)
return
language = toks[0]
if len(toks) == 3:
language += "_" + toks[1]
lexicon_type = toks[2]
else:
lexicon_type = toks[1]
logging.info("Processing %s (%s)...", language, lexicon_type)
stats = _compute_stats(filename)
return language, lexicon_type, stats
def _sort(results):
if FLAGS.sort_by == "language":
return sorted(results, key=lambda tup: tup[0]) # Language name.
elif FLAGS.sort_by == "score":
return sorted(results, key=lambda tup: tup[2][2]) # L-score.
else:
return None
def main(unused_argv):
if not FLAGS.input_dir:
raise ValueError("Supply --input_dir")
if not FLAGS.output_tsv:
raise ValueError("Supply --output_tsv!")
if FLAGS.sort_by != "language" and FLAGS.sort_by != "score":
raise ValueError("Invalid sorting critertion: %s" % FLAGS.sort_by)
results = []
for filename in os.listdir(FLAGS.input_dir):
if not filename.endswith(".tsv"):
continue
results.append(_process_lexicon_file(filename))
if not results:
raise ValueError("No files with .tsv extension found!")
results = _sort(results)
logging.info("Processed %d lexicons.", len(results))
with open(FLAGS.output_tsv, mode="w", encoding="utf8") as f:
for result in results:
language_code = result[0]
language_alpha_3 = language_code.split(_NAME_SEPARATOR)[0]
language_info = pyc.languages.get(alpha_3=language_alpha_3)
language_full = "-"
if language_info:
language_full = language_info.name
else:
bib_info = pyc.languages.get(bibliographic=language_alpha_3)
if bib_info:
language_full = bib_info.name
lexicon_type = result[1]
stats = result[2]
f.write("%s\t%s\t%s\t%d\t%d\t%f\n" % (
language_code, language_full, lexicon_type,
stats[0], stats[1], stats[2]))
if __name__ == "__main__":
app.run(main)
|
/**
* this send forces remote connect - for registering services
*
* @param url
* @param method
* @param param1
*/
public void send(URI url, String method, Object param1) {
Object[] params = new Object[1];
params[0] = param1;
Message msg = createMessage(name, method, params);
outbox.getCommunicationManager().send(url, msg);
} |
def vap_auto():
build = get_current_build()
if build is not None:
set_makeprg(build)
set_ycm_conf(build)
set_env(build) |
//! Returns name of md2 animation.
const c8* CAnimatedMeshMD2::getAnimationName(s32 nr) const
{
if (nr < 0 || nr >= (s32)FrameData.size())
return 0;
return FrameData[nr].name.c_str();
} |
/*
* File: 226-c.cpp
* Author: hbaid
*
* Created on January 24, 2014, 10:27 PM
*/
#include<stdio.h>
#include<iostream>
using namespace std;
/*
*
*/
int a[10000001] = {0};
int m[10000001]={0};
int c[10000001]={0};
int main() {
int lim = -1;
int i, j, k;
int total = 0;
int n,x,t,p,q;
scanf("%d",&n);
int maxval =-1;
for(i=0;i<n;i++)
{
scanf("%d",&x);
m[x]++;
lim = max(lim,x);
}
a[0] = 1;
a[1] = 1;
a[2] = 0;
int prev=0;
for (i = 0; i <= lim; i++) {
if (a[i] == 0) {
//b[total] = i;
//printf("%d ",b[total]);
//total++;
c[i]+=prev+m[i];
for (j = 2 * i; j <= lim; j += i)
{
c[i]+=m[j];
a[j] = 1;
}
prev = c[i];
}
c[i]=prev;
//printf("%d-->%d\n",i,c[i]);
}
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d%d",&p,&q);
if(p>lim)
{
printf("0\n");
continue;
}
p = min(p,lim);
q = min(q,lim);
printf("%d\n",c[q]-c[p-1]);
}
return (0);
}
|
/**
* This class executes one run of transaction pruning every time it is invoked.
* Typically, this class will be scheduled to run periodically.
*/
@SuppressWarnings("WeakerAccess")
public class TransactionPruningRunnable implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(TransactionPruningRunnable.class);
private final TransactionManager txManager;
private final Map<String, TransactionPruningPlugin> plugins;
private final long txMaxLifetimeMillis;
private final long txPruneBufferMillis;
public TransactionPruningRunnable(TransactionManager txManager, Map<String, TransactionPruningPlugin> plugins,
long txMaxLifetimeMillis, long txPruneBufferMillis) {
this.txManager = txManager;
this.plugins = plugins;
this.txMaxLifetimeMillis = txMaxLifetimeMillis;
this.txPruneBufferMillis = txPruneBufferMillis;
}
@Override
public void run() {
try {
// TODO: TEPHRA-159 Start a read only transaction here
Transaction tx = txManager.startShort();
txManager.abort(tx);
if (tx.getInvalids().length == 0) {
LOG.info("Invalid list is empty, not running transaction pruning");
return;
}
long now = getTime();
long inactiveTransactionBound = TxUtils.getInactiveTxBound(now, txMaxLifetimeMillis + txPruneBufferMillis);
LOG.info("Starting invalid prune run for time {} and inactive transaction bound {}",
now, inactiveTransactionBound);
List<Long> pruneUpperBounds = new ArrayList<>();
for (Map.Entry<String, TransactionPruningPlugin> entry : plugins.entrySet()) {
String name = entry.getKey();
TransactionPruningPlugin plugin = entry.getValue();
try {
LOG.debug("Fetching prune upper bound using plugin {}", name);
long pruneUpperBound = plugin.fetchPruneUpperBound(now, inactiveTransactionBound);
LOG.debug("Got prune upper bound {} from plugin {}", pruneUpperBound, name);
pruneUpperBounds.add(pruneUpperBound);
} catch (Exception e) {
LOG.error("Aborting invalid prune run for time {} due to exception from plugin {}", now, name, e);
return;
}
}
long minPruneUpperBound = Collections.min(pruneUpperBounds);
LOG.info("Got minimum prune upper bound {} across all plugins", minPruneUpperBound);
if (minPruneUpperBound <= 0) {
LOG.info("Not pruning invalid list since minimum prune upper bound ({}) is less than 1", minPruneUpperBound);
return;
}
long[] invalids = tx.getInvalids();
TreeSet<Long> toTruncate = new TreeSet<>();
LOG.debug("Invalid list: {}", invalids);
for (long invalid : invalids) {
if (invalid <= minPruneUpperBound) {
toTruncate.add(invalid);
}
}
if (toTruncate.isEmpty()) {
LOG.info("Not pruning invalid list since the min prune upper bound {} is greater than the min invalid id {}",
minPruneUpperBound, invalids[0]);
return;
}
LOG.debug("Removing the following invalid ids from the invalid list", toTruncate);
txManager.truncateInvalidTx(toTruncate);
LOG.info("Removed {} invalid ids from the invalid list", toTruncate.size());
// Call prune complete on all plugins
Long maxPrunedInvalid = toTruncate.last();
for (Map.Entry<String, TransactionPruningPlugin> entry : plugins.entrySet()) {
String name = entry.getKey();
TransactionPruningPlugin plugin = entry.getValue();
try {
LOG.debug("Calling prune complete on plugin {}", name);
plugin.pruneComplete(now, maxPrunedInvalid);
} catch (Exception e) {
// Ignore any exceptions and continue with other plugins
LOG.error("Got error while calling prune complete on plugin {}", name, e);
}
}
LOG.info("Invalid prune run for time {} is complete", now);
} catch (Exception e) {
LOG.error("Got exception during invalid list prune run", e);
}
}
@VisibleForTesting
long getTime() {
return System.currentTimeMillis();
}
} |
<reponame>moissinac/csvfix<gh_stars>1-10
//---------------------------------------------------------------------------
// csved_edit.h
//
// edit fields for csved
//
// Copyright (C) 2009 <NAME>
//---------------------------------------------------------------------------
#ifndef INC_CSVED_EDIT_H
#define INC_CSVED_EDIT_H
#include "a_base.h"
#include "csved_command.h"
namespace CSVED {
//---------------------------------------------------------------------------
class EditCommand : public Command {
public:
EditCommand( const std::string & name,
const std::string & desc );
int Execute( ALib::CommandLine & cmd );
private:
void EditRow( CSVRow & row );
void EditField( std::string & f);
void AddSubCmd( const std::string & s );
struct EditSubCmd {
char mCmd;
std::string mFrom, mTo;
std::string mOpts;
EditSubCmd( char cmd,
const std::string & from,
const std::string & to,
const std::string & opts )
: mCmd( cmd ), mFrom( from ), mTo( to ), mOpts( opts ) {
}
};
std::vector <EditSubCmd> mSubCmds;
std::vector <unsigned int> mCols;
};
//------------------------------------------------------------------------
} // end namespace
#endif
|
import { $reactive, $reactiveproxy } from "@reactivedata/reactive";
import * as Y from "yjs";
import { crdtValue, getInternalAny, INTERNAL_SYMBOL, ObjectSchemaType } from ".";
import { parseYjsReturnValue, yToWrappedCache } from "./internal";
import { CRDTObject } from "./object";
import { Box } from "./boxed";
import { isYType } from "./types";
export type CRDTArray<T> = {
[INTERNAL_SYMBOL]?: Y.Array<T>;
[n: number]: T extends Box<infer A>
? A
: T extends Array<infer A>
? CRDTArray<A>
: T extends ObjectSchemaType
? CRDTObject<T>
: T;
} & T[]; // TODO: should return ArrayImplementation<T> on getter
function arrayImplementation<T>(arr: Y.Array<T>) {
const slice = function slice() {
let ic = this[$reactiveproxy]?.implicitObserver;
(arr as any)._implicitObserver = ic;
const items = arr.slice.bind(arr).apply(arr, arguments);
return items.map(item => {
const ret = parseYjsReturnValue(item, ic);
return ret;
});
} as T[]["slice"];
return {
get length() {
return arr.length;
},
slice,
unshift: arr.unshift.bind(arr) as Y.Array<T>["unshift"],
push: (...items: T[]) => {
const wrappedItems = items.map(item => {
const wrapped = crdtValue(item as any); // TODO
const internal = getInternalAny(wrapped) || wrapped;
if (internal instanceof Box) {
return internal.value;
} else {
return internal;
}
});
arr.push(wrappedItems);
return arr.length;
},
insert: arr.insert.bind(arr) as Y.Array<T>["insert"],
toJSON: arr.toJSON.bind(arr) as Y.Array<T>["toJSON"],
forEach: function() {
return [].forEach.apply(slice.apply(this), arguments);
} as T[]["forEach"],
filter: function() {
return [].filter.apply(slice.apply(this), arguments);
} as T[]["filter"],
find: function() {
return [].find.apply(slice.apply(this), arguments);
} as T[]["find"],
map: function() {
return [].map.apply(slice.apply(this), arguments);
} as T[]["map"]
// toJSON = () => {
// return this.arr.toJSON() slice();
// };
// delete = this.arr.delete.bind(this.arr) as (Y.Array<T>)["delete"];
};
}
function propertyToNumber(p: string | number | symbol) {
if (typeof p === "string" && p.trim().length) {
const asNum = Number(p);
// https://stackoverflow.com/questions/10834796/validate-that-a-string-is-a-positive-integer
if (Number.isInteger(asNum)) {
return asNum;
}
}
return p;
}
export function crdtArray<T>(initializer: T[], arr = new Y.Array<T>()) {
if (arr[$reactive]) {
throw new Error("unexpected");
// arr = arr[$reactive].raw;
}
const implementation = arrayImplementation(arr);
const proxy = new Proxy((implementation as any) as CRDTArray<T>, {
set: (target, pArg, value) => {
const p = propertyToNumber(pArg);
if (typeof p !== "number") {
throw new Error();
}
// TODO map.set(p, smartValue(value));
return true;
},
get: (target, pArg, receiver) => {
const p = propertyToNumber(pArg);
if (p === INTERNAL_SYMBOL) {
return arr;
}
if (typeof p === "number") {
let ic: any;
if (receiver && receiver[$reactiveproxy]) {
ic = receiver[$reactiveproxy]?.implicitObserver;
(arr as any)._implicitObserver = ic;
} else {
// console.warn("no receiver getting property", p);
}
let ret = arr.get(p) as any;
ret = parseYjsReturnValue(ret, ic);
return ret;
}
if (p === Symbol.toStringTag) {
return "Array";
}
if (p === Symbol.iterator) {
const values = arr.slice();
return Reflect.get(values, p);
}
// forward to arrayimplementation
const ret = Reflect.get(target, p, receiver);
return ret;
},
// getOwnPropertyDescriptor: (target, pArg) => {
// const p = propertyToNumber(pArg);
// if (typeof p === "number" && p < arr.length && p >= 0) {
// return { configurable: true, enumerable: true, value: arr.get(p) };
// } else {
// return undefined;
// }
// },
deleteProperty: (target, pArg) => {
const p = propertyToNumber(pArg);
if (typeof p !== "number") {
throw new Error();
}
if (p < arr.length && p >= 0) {
arr.delete(p);
return true;
} else {
return false;
}
},
has: (target, pArg) => {
const p = propertyToNumber(pArg);
if (typeof p !== "number") {
// forward to arrayimplementation
return Reflect.has(target, p);
}
if (p < arr.length && p >= 0) {
return true;
} else {
return false;
}
},
ownKeys: target => {
const keys: string[] = [];
for (let i = 0; i < arr.length; i++) {
keys.push(i + "");
}
return keys;
}
});
implementation.push.apply(proxy, initializer);
return proxy;
}
|
// NOTE: Only Hibernate supports this mapping
@Category({NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class})
public class EmbeddableTestEntityViewTest extends AbstractEntityViewTest {
protected EntityViewManager evm;
@Override
protected Class<?>[] getEntityClasses() {
return new Class<?>[]{
EmbeddableTestEntity2.class,
EmbeddableTestEntitySub.class,
IntIdEntity.class
};
}
@Before
public void initEvm() {
EntityViewConfiguration cfg = EntityViews.createDefaultConfiguration();
cfg.addEntityView(IntIdEntityView.class);
cfg.addEntityView(EmbeddableTestEntityView.class);
cfg.addEntityView(EmbeddableTestEntityIdView.class);
cfg.addEntityView(EmbeddableTestEntityIdView.Id.class);
cfg.addEntityView(EmbeddableTestEntityViewWithSubview.class);
cfg.addEntityView(EmbeddableTestEntityEmbeddableSubView.class);
cfg.addEntityView(EmbeddableTestEntitySimpleEmbeddableSubView.class);
cfg.addEntityView(EmbeddableTestEntitySubView.class);
evm = cfg.createEntityViewManager(cbf);
}
private EmbeddableTestEntity2 entity1;
private EmbeddableTestEntity2 entity2;
@Before
public void setUp() {
cleanDatabase();
transactional(new TxVoidWork() {
@Override
public void work(EntityManager em) {
IntIdEntity intIdEntity1 = new IntIdEntity("1");
entity1 = new EmbeddableTestEntity2();
entity1.setId(new EmbeddableTestEntityId2(intIdEntity1, "1"));
entity1.getEmbeddableSet().add(new EmbeddableTestEntitySimpleEmbeddable2("1"));
entity1.getEmbeddableMap().put("key1", new EmbeddableTestEntitySimpleEmbeddable2("1"));
entity1.getEmbeddable().setName("1");
entity1.getEmbeddable().setManyToOne(null);
entity1.getEmbeddable().getElementCollection().put("1", intIdEntity1);
IntIdEntity intIdEntity2 = new IntIdEntity("2");
entity2 = new EmbeddableTestEntity2();
entity2.setId(new EmbeddableTestEntityId2(intIdEntity2, "2"));
entity2.getEmbeddableSet().add(new EmbeddableTestEntitySimpleEmbeddable2("2"));
entity2.getEmbeddableMap().put("key2", new EmbeddableTestEntitySimpleEmbeddable2("2"));
entity2.getEmbeddable().setName("2");
entity2.getEmbeddable().setManyToOne(entity1);
entity2.getEmbeddable().getElementCollection().put("2", intIdEntity2);
em.persist(intIdEntity1);
em.persist(intIdEntity2);
em.persist(entity1);
em.persist(entity2);
}
});
entity1 = cbf.create(em, EmbeddableTestEntity2.class)
.fetch("id.intIdEntity", "embeddableSet", "embeddableMap", "embeddable.manyToOne", "embeddable.oneToMany", "embeddable.elementCollection")
.where("id").eq(entity1.getId())
.getSingleResult();
entity2 = cbf.create(em, EmbeddableTestEntity2.class)
.fetch("id.intIdEntity", "embeddableSet", "embeddableMap", "embeddable.manyToOne", "embeddable.oneToMany", "embeddable.elementCollection")
.where("id").eq(entity2.getId())
.getSingleResult();
}
@Test
public void testEmbeddableViewWithEntityRelations() {
CriteriaBuilder<EmbeddableTestEntity2> criteria = cbf.create(em, EmbeddableTestEntity2.class, "e")
.orderByAsc("id");
EntityViewSetting<EmbeddableTestEntityView, CriteriaBuilder<EmbeddableTestEntityView>> setting = EntityViewSetting.create(EmbeddableTestEntityView.class);
setting.addOptionalParameter("optionalInteger", 1);
CriteriaBuilder<EmbeddableTestEntityView> cb = evm.applySetting(setting, criteria);
List<EmbeddableTestEntityView> results = cb.getResultList();
assertEquals(2, results.size());
assertEqualViewEquals(entity1, results.get(0));
assertEqualViewEquals(entity2, results.get(1));
}
@Test
public void testEmbeddableViewWithSubViewRelations() {
CriteriaBuilder<EmbeddableTestEntity2> criteria = cbf.create(em, EmbeddableTestEntity2.class, "e")
.orderByAsc("id");
EntityViewSetting<EmbeddableTestEntityViewWithSubview, CriteriaBuilder<EmbeddableTestEntityViewWithSubview>> setting = EntityViewSetting.create(EmbeddableTestEntityViewWithSubview.class);
setting.addOptionalParameter("optionalInteger", 1);
CriteriaBuilder<EmbeddableTestEntityViewWithSubview> cb = evm.applySetting(setting, criteria);
List<EmbeddableTestEntityViewWithSubview> results = cb.getResultList();
assertEquals(2, results.size());
assertEqualViewEquals(entity1, results.get(0));
assertEqualViewEquals(entity2, results.get(1));
}
@Test
public void testEmbeddableViewWithSubViewRelationsFetches() {
CriteriaBuilder<EmbeddableTestEntity2> criteria = cbf.create(em, EmbeddableTestEntity2.class, "e")
.orderByAsc("id");
EntityViewSetting<EmbeddableTestEntityViewWithSubview, CriteriaBuilder<EmbeddableTestEntityViewWithSubview>> setting = EntityViewSetting.create(EmbeddableTestEntityViewWithSubview.class);
setting.addOptionalParameter("optionalInteger", 1);
setting.fetch("idKey");
setting.fetch("embeddable");
CriteriaBuilder<EmbeddableTestEntityViewWithSubview> cb = evm.applySetting(setting, criteria);
List<EmbeddableTestEntityViewWithSubview> results = cb.getResultList();
assertEquals(2, results.size());
assertEquals(entity1.getId(), results.get(0).getId());
assertEquals(entity1.getId().getKey(), results.get(0).getIdKey());
assertEquals(entity1.getEmbeddable().getName(), results.get(0).getEmbeddable().getName());
assertNull(results.get(0).getIdIntIdEntity());
assertEquals(entity2.getId(), results.get(1).getId());
assertEquals(entity2.getId().getKey(), results.get(1).getIdKey());
assertEquals(entity2.getEmbeddable().getName(), results.get(1).getEmbeddable().getName());
assertNull(results.get(1).getIdIntIdEntity());
}
@Test
public void testEmbeddableViewWithSubViewRelationsFetchesIdView() {
CriteriaBuilder<EmbeddableTestEntity2> criteria = cbf.create(em, EmbeddableTestEntity2.class, "e")
.orderByAsc("id");
EntityViewSetting<EmbeddableTestEntityIdView, CriteriaBuilder<EmbeddableTestEntityIdView>> setting = EntityViewSetting.create(EmbeddableTestEntityIdView.class);
setting.fetch("name");
CriteriaBuilder<EmbeddableTestEntityIdView> cb = evm.applySetting(setting, criteria);
List<EmbeddableTestEntityIdView> results = cb.getResultList();
assertEquals(2, results.size());
assertEquals(entity1.getId().getIntIdEntity().getId(), results.get(0).getId().getIntIdEntityId());
assertEquals(entity1.getId().getKey(), results.get(0).getId().getKey());
assertNull(results.get(0).getIdKey());
assertEquals(entity1.getEmbeddable().getName(), results.get(0).getName());
assertEquals(entity2.getId().getIntIdEntity().getId(), results.get(1).getId().getIntIdEntityId());
assertEquals(entity2.getId().getKey(), results.get(1).getId().getKey());
assertNull(results.get(1).getIdKey());
assertEquals(entity2.getEmbeddable().getName(), results.get(1).getName());
}
@Test
public void testEntityViewSettingEmbeddableEntityViewRoot() {
// Base setting
EntityViewSetting<EmbeddableTestEntityIdView.Id, CriteriaBuilder<EmbeddableTestEntityIdView.Id>> setting =
EntityViewSetting.create(EmbeddableTestEntityIdView.Id.class);
// Query
CriteriaBuilder<EmbeddableTestEntity2> cb = cbf.create(em, EmbeddableTestEntity2.class);
evm.applySetting(setting, cb, "id")
.getResultList();
}
private void assertEqualViewEquals(EmbeddableTestEntity2 entity, EmbeddableTestEntityView view) {
assertEquals(entity.getId(), view.getId());
assertEquals(entity.getId().getIntIdEntity(), view.getIdIntIdEntity());
assertEquals(entity.getId().getIntIdEntity().getId(), view.getIdIntIdEntityId());
assertEquals(entity.getId().getIntIdEntity().getName(), view.getIdIntIdEntityName());
assertEquals(entity.getId().getKey(), view.getIdKey());
assertEquals(entity.getEmbeddable().getName(), view.getEmbeddable().getName());
assertEquals(entity.getEmbeddable().getManyToOne(), view.getEmbeddableManyToOne());
assertEquals(entity.getEmbeddable().getOneToMany(), view.getEmbeddableOneToMany());
assertEquals(entity.getEmbeddable().getElementCollection(), view.getEmbeddableElementCollection());
Set<String> set1 = new HashSet<String>();
for (EmbeddableTestEntitySimpleEmbeddable2 elem : entity.getEmbeddableSet()) {
set1.add(elem.getName());
}
Set<String> set2 = new HashSet<String>();
for (EmbeddableTestEntitySimpleEmbeddableSubView elem : view.getEmbeddableSet()) {
set2.add(elem.getName());
}
assertEquals(set1, set2);
Map<String, String> map1 = new HashMap<String, String>();
for (Map.Entry<String, EmbeddableTestEntitySimpleEmbeddable2> entry : entity.getEmbeddableMap().entrySet()) {
map1.put(entry.getKey(), entry.getValue().getName());
}
Map<String, String> map2 = new HashMap<String, String>();
for (Map.Entry<String, EmbeddableTestEntitySimpleEmbeddableSubView> entry : view.getEmbeddableMap().entrySet()) {
map2.put(entry.getKey(), entry.getValue().getName());
}
assertEquals(map1, map2);
}
private void assertEqualViewEquals(EmbeddableTestEntity2 entity, EmbeddableTestEntityViewWithSubview view) {
assertEquals(entity.getId(), view.getId());
if (entity.getId().getIntIdEntity() == null) {
assertNull(view.getIdIntIdEntity());
} else {
assertEquals(entity.getId().getIntIdEntity().getId(), view.getIdIntIdEntity().getId());
}
assertEquals(entity.getId().getIntIdEntity().getId(), view.getIdIntIdEntityId());
assertEquals(entity.getId().getIntIdEntity().getName(), view.getIdIntIdEntityName());
assertEquals(entity.getId().getKey(), view.getIdKey());
assertEquals(entity.getEmbeddable().getName(), view.getEmbeddable().getName());
if (entity.getEmbeddable().getManyToOne() == null) {
assertNull(view.getEmbeddableManyToOneView());
} else {
assertEquals(entity.getEmbeddable().getManyToOne().getId(), view.getEmbeddableManyToOneView().getId());
}
assertEquals(entity.getEmbeddable().getOneToMany().size(), view.getEmbeddableOneToManyView().size());
OUTER: for (EmbeddableTestEntity2 child : entity.getEmbeddable().getOneToMany()) {
for (EmbeddableTestEntitySubView childView : view.getEmbeddableOneToManyView()) {
if (child.getId().equals(childView.getId())) {
continue OUTER;
}
}
fail("Couldn't find child view with id: " + child.getId());
}
assertEquals(entity.getEmbeddable().getElementCollection().size(), view.getEmbeddableElementCollectionView().size());
for (Map.Entry<String, IntIdEntity> childEntry : entity.getEmbeddable().getElementCollection().entrySet()) {
IntIdEntityView childView = view.getEmbeddableElementCollectionView().get(childEntry.getKey());
assertEquals(childEntry.getValue().getId(), childView.getId());
}
Set<String> set1 = new HashSet<String>();
for (EmbeddableTestEntitySimpleEmbeddable2 elem : entity.getEmbeddableSet()) {
set1.add(elem.getName());
}
Set<String> set2 = new HashSet<String>();
for (EmbeddableTestEntitySimpleEmbeddableSubView elem : view.getEmbeddableSet()) {
set2.add(elem.getName());
}
assertEquals(set1, set2);
Map<String, String> map1 = new HashMap<String, String>();
for (Map.Entry<String, EmbeddableTestEntitySimpleEmbeddable2> entry : entity.getEmbeddableMap().entrySet()) {
map1.put(entry.getKey(), entry.getValue().getName());
}
Map<String, String> map2 = new HashMap<String, String>();
for (Map.Entry<String, EmbeddableTestEntitySimpleEmbeddableSubView> entry : view.getEmbeddableMap().entrySet()) {
map2.put(entry.getKey(), entry.getValue().getName());
}
assertEquals(map1, map2);
}
} |
/* Iterating over channels in a given state. Note that we try
* not to blow up if the channels we are processing change state or
* vanish out from under us
*/
ev_channel *
first_channel (ev_chan_state state, ev_channel_iter *iter)
{
ev_channel *head = state_channel[state];
if (head->next == head) return NULL;
iter->list_head = head;
iter->next = head->next->next;
return head->next;
} |
David Schwimmer and his wife, Zoe Buckman, are taking some time apart after nearly seven years of marriage, the couple exclusively confirm to Us Weekly.
“It is with great love, respect and friendship that we have decided to take some time apart while we determine the future of our relationship,” the pair tell Us in a statement. “Our priority is, of course, our daughter’s happiness and well being during this challenging time, and so we ask for your support and respect for our privacy as we continue to raise her together and navigate this new chapter for our family.”
The Friends alum, 50, and British photographer Buckman, 31, have been together for more than 10 years. They met when Schwimmer was directing the 2007 romantic comedy Run in London. She relocated to Los Angeles to be with the actor and the pair tied the knot in June 2010. It is the first marriage for both.
Friends Stars: Then & Now!
Schwimmer and Buckman welcomed daughter, Cleo, now 5, in May 2011.
The People v. O.J. Simpson: American Crime Story actor and Buckman often kept private about their relationship. Their last public event together was at the opening night of The Front Page at the Broadhurst Theatre in NYC in October 2016.
Sign up now for the Us Weekly newsletter to get breaking celebrity news, hot pics and more delivered straight to your inbox!
Want stories like these delivered straight to your phone? Download the Us Weekly iPhone app now! |
/**
* xmlXPathContextSetCache:
*
* @ctxt: the XPath context
* @active: enables/disables (creates/frees) the cache
* @value: a value with semantics dependent on @options
* @options: options (currently only the value 0 is used)
*
* Creates/frees an object cache on the XPath context.
* If activates XPath objects (xmlXPathObject) will be cached internally
* to be reused.
* @options:
* 0: This will set the XPath object caching:
* @value:
* This will set the maximum number of XPath objects
* to be cached per slot
* There are 5 slots for: node-set, string, number, boolean, and
* misc objects. Use <0 for the default number (100).
* Other values for @options have currently no effect.
*
* Returns 0 if the setting succeeded, and -1 on API or internal errors.
*/
int
xmlXPathContextSetCache(xmlXPathContextPtr ctxt,
int active,
int value,
int options)
{
if (ctxt == NULL)
return(-1);
if (active) {
xmlXPathContextCachePtr cache;
if (ctxt->cache == NULL) {
ctxt->cache = xmlXPathNewCache();
if (ctxt->cache == NULL)
return(-1);
}
cache = (xmlXPathContextCachePtr) ctxt->cache;
if (options == 0) {
if (value < 0)
value = 100;
cache->maxNodeset = value;
cache->maxString = value;
cache->maxNumber = value;
cache->maxBoolean = value;
cache->maxMisc = value;
}
} else if (ctxt->cache != NULL) {
xmlXPathFreeCache((xmlXPathContextCachePtr) ctxt->cache);
ctxt->cache = NULL;
}
return(0);
} |
Image caption The explosives were seized during a wave of insurgent attacks last week
Afghan security officials say they have foiled a huge attack in the capital Kabul, as they gave details of the seizure of 10 tonnes of explosives.
The explosives were found in a truck seized along with five militants in an operation last Sunday, a National Directorate of Security spokesman said.
The group was planning to attack crowded areas in the capital, he said.
He also gave reporters a video detailing plans for a separate attack on Vice-President Mohammed Khalili.
Describing the planned bomb attack on Kabul, the spokesman, Shafiqullah Tahiri, said the 10 tonnes of explosives were stuffed in 400 bags and hidden under piles of potatoes.
"If this amount of explosives had been used, it could have caused large-scale bloodshed," Mr Tahiri said.
He said three of the captured militants are Pakistani citizens, and two are Afghans.
'Confessions'
The five suspects had confessed that the planned attack was co-ordinated by two Taliban commanders with links to Pakistan's main intelligence organisation the Inter-Services Intelligence agency (ISI), according to the spokesman.
The arrests, which came during a wave of insurgent attacks around the country, was kept quiet at the time because of the ongoing security operation, he said.
Afghanistan has often accused the ISI of involvement in supporting anti-government insurgents in Afghanistan - an allegation strongly denied by Pakistan.
Last week, 51 people died in a wave of co-ordinated attacks by insurgents in Kabul and three other provinces.
The BBC's Bilal Sarwary says the security forces are under criticism for failing to anticipate the attacks, and are keen to show that they are making progress in their investigations.
In a separate operation, security forces detained a group of fighters - including suicide bombers belonging to the Pakistan-based Haqqani network - planning to assassinate Afghanistan's second Vice-President, Mohammed Khalili, Mr Tahiri said.
The Haqqani network is a mainly Afghan ethnic Pashto group operating out of the north-western Pakistani tribal areas, and is seen as linked to, but separate from, the Afghan Taliban. |
//Returns a list of all isbns of Books that have multiple authors
public static List<String> allHavingMultipleAuthors() {
return
new DataAccessFacade()
.readBooksMap().values()
.stream()
.filter(book -> book.getAuthors().size()>1)
.map(book -> book.getIsbn())
.collect(Collectors.toList());
} |
The terrorist attacks of September 11, 2001 forever impacted the lives of every American -- but for Muslim Americans, their lives changed more than they could have expected.
The experience of Muslim Americans in a post-9/11 nation -- one often marked by scapegoating, prejudice and fear -- inspired Khurram Mozaffar, a Naperville, Ill. actor, writer and lawyer, to write "nine/twelve," a screenplay telling, as the film's website describes, "a story that hadn't been told before. But perhaps should have been."
The screenplay is currently in the process of being brought to life as a full-length feature film by director Sean Fahey and producers Fawzia Mirza and Kevin Schroeder. Telling the story of two Chicago men -- one Muslim, one Christian; one a soldier, one a blue-collar worker -- whose lives are brought together following the 9/11 attacks, the film recently launched a Kickstarter campaign to help offset its production costs.
The Huffington Post spoke with Mozaffar about his new project.
What originally inspired you to write the script for "nine/twelve"?
I come from an acting background and I do some theater in Chicago and I started writing, in general, because there weren't a lot of parts for people of my ethnicity. I fell in love with the craft of writing itself. A number of stories originate out of the South Asian Muslim American experience and they're usually told from an outsiders' perspective. I wanted to tackle that kind of story line from the inside out because I feel like that kind of voice usually isn't heard in film.
In the time after 9/11, the world changed for everybody and it changed twofold for patriotic Muslim Americans who were, on one hand, horrified as to what was happening and what they were witnessing, but at the same time, we were also suffering a backlash as we were associated with the people who committed these horrific, horrific crimes. With "nine/twelve," I wanted to tell that story of what it was like in the days right after 9/11 for people, like me, who were considered patriotic Americans one day and, in a matter of minutes, because of what happened, the perception that people had of them changed.
(Scroll down to watch a teaser clip of the film.)
This story clearly has a strong personal resonance for you. Tell me more about what you sensed changed for you and how you were perceived by others immediately following the 9/11 attacks.
I remember a few years ago, I was visiting a close friend of mine, a white American frat brother of mine from the University of Chicago, in New York. We were talking about 9/11 and he said something to the effect that, in addition to me, he knew other Muslims, including one man he worked with. He said he seemed like a really nice guy though my friend added, "But I don't know what he talks about when he gets home."
Wow, was that surprising for you to hear from your friend?
It struck me that his coworker was automatically considered suspicious, even by my friend, someone who knew other Muslims and who doesn't have a negative bone in his body. But because of what he witnessed, he had to question everything he knew about Muslims. I always thought that as a Muslim American, if people just get to know me, they'll use me as a standard for what to decide about us, but there are competing messages about what people of my faith have done in the world. It's not enough to sit back and wait for people to come to their senses -- we have to battle the presumption that is out there. That was the impetus of the film.
That said, the film is not an overtly political or overtly pro-Muslim movie. This is not that movie. I wanted to be careful not to create propaganda, because that sort of filmmaking makes me sick. I am telling a story about human people, a story that would resonate with anyone, so that people can understand we are just like anyone else, and felt pain like anyone else. We are a part of the fabric of this country.
Fictional stories can definitely be powerful in battling prejudice.
I feel like we, especially in the West, are a culture of storytellers. I feel an obligation to take on the role of storyteller. I'm a parent and I want my children to grow up in a world where they can be proud of who they are and don't have to hide aspects of themselves. A good friend of mine in Chicago told me that, in the days after 9/11, his son was 4 or 5 years old saw him shredding some financial documents and his son asked him whether he was shredding the bills because he didn't want their neighbors to know they are Muslim. Even at that age, this child was cognizant of how the world perceives him right now.
How long has this screenplay specifically been in development?
This script has been in incubation for the last few years now. It was an idea I had a while back and has gone through a couple of different transformations in terms of plot lines and characters. About a year and a half ago, I was in a play with the Silk Road Theatre Project and met a number of amazing artists there. One is Fawzia Mirza, an actress and producer of the film. We started working on the movie together and started developing a fresher take on the ideas I already had. From that point on, it's been kind of steamrolling on its own as people have really responded to the need for voices like these to be heard.
Your story feels particularly timely right now, as last fall marked the 10th anniversary of the tragedy and there has been a lot of Islamophobic language coming up in the presidential race.
I think it [the anniversary] gave me a sense of urgency. We launched our Kickstarter right after the incident where Lowe's pulled their ads from the "All-American Muslim" reality show and that situation effected all of us as filmmakers and people. It was very saddening to us that it was happening and made it even more important for us to make this movie. It is profoundly sad that there are people in our culture who have no interest in seeing people like me or my wife or my kids as anything other than some kind of aberration of humanity or something we should all be suspicious of.
I've never seen the particular show, but the argument that boycott made was that there is something wrong with a show that doesn't depict Muslims being violent. Those people don't want us to be a part of our national conversation. I don't think this film will change those peoples' minds, but I would like other voices to be out there on these issues and I hope to be one of those voices. I hope to be a part of the conversation.
What is your timeline going forward with the project?
Job one for us now is to get the money in the bank. To do this film right and to do it justice, we're looking at a $400,000 budget, which is not a lot of money for a movie, but is a lot of money to fundraise. We are bringing together a wonderful crew, we have the cast, which includes some fun names that we are looking forward to working with. One is another Chicago actor, Parvesh Cheena, who used to be on "Outsourced." Another is Faran Tahir who played the villain in the first "Iron Man" movie. And we also have Azhar Usman, a Chicago standup comic who tours the world as part of his comedy troupe which is called "Allah Made Me Funny."
We also have some rewrites going on and one of the people who has been really instrumental in helping us work on the script is "Chinglish" playwright David Henry Hwang, who I had worked with as an actor. I showed him my script and he was very generous with his time and gave me some very serious and thoughtful notes on where the story can go.
Tell me more about the decision to film in and recruit talent primarily from Chicago. What was behind that decision?
It seemed like an obvious decision for us, given that most of our talent lives here, so it made sense because it was cheaper to shoot here. But also, this is an amazing theater town and amazing writers constantly come out of Chicago. As far as we're concerned, this is a movie that Chicago is making. The crew and actors are primarily from Chicago and the majority of the filming will be done here.
The movie takes place in Chicago after 9/11 and part of it is a love letter to the experience in Chicago. This is a community-based movie. When I've been out working on other projects in LA and talking about scripts, it was almost a purposeful decision not to talk about this script with production companies. This has been a passion project for me and really everyone involved with it -- to be making the movie for the amount we're trying to make it for means that nobody is going home with a giant pay check at the end of the day. They all believe in the story we are trying to tell. We're committed to making this movie no matter what, even if we have to shoot it on iPhones.
As of Feb. 23, with 23 days to go, Mozaffar's campaign has raised just over $5,200 of its $100,000 fundraising goal. Click here to learn more about the film and help the important project become a reality.
Get in touch with us at [email protected] if you have a Chicago area-based Kickstarter or IndieGoGo project that you'd like to see featured in "Can They Kick It?" |
/*************************************************************************
> File Name: Vector.cpp
> Author: ziqiang
> Mail: <EMAIL>
> Created Time: 2018年05月13日 星期日 23时02分28秒
************************************************************************/
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <initializer_list>
#ifndef _SCZZQ_VECTOR_H_
#define _SCZZQ_VECTOR_H_
/*
* Note
* 使用new/delete进行对象的存储空间分配,例子 见 行27, 32
* 构造函数请求资源,析构函数释放资源.
*
* 类内成员函数中的类的对象可以访问类的私有变量.
*
* 在作用域Vector{ } 中,引用Vector 名字时不需要进行模板实例化
* 此作用域内的 Vector 名字默认使用类头的限定词.
*
*/
namespace sczzq{
template<typename T = double>
class Vector{
private:
T * elem;
size_t sz;
public:
Vector(size_t s) : elem { new T[s]}, sz{s} // 构造函数.
{
for(int i = 0; i != s; ++i) elem[i] = 0;
}
Vector(std::initializer_list<T> lst) // 构造函数.
:elem { new T[lst.size()]},
sz { lst.size() }
{
std::copy(lst.begin(), lst.end(), elem);
}
~Vector() { // 析构函数.
if(elem)
delete[] elem;
}
Vector(const Vector& a) // 拷贝构造函数.
:elem{new T[a.sz]},
sz{a.sz}
{
for(int i = 0; i < sz; ++i){
elem[i] = a.elem[i];
}
}
Vector& operator=(const Vector& a){ // 拷贝赋值运算符.
T* p = new T[a.sz];
for(int i = 0; i < a.sz; i++){
p[i] = a.elem[i];
}
delete[] elem;
elem = p;
sz = a.sz;
return *this;
}
Vector(Vector&& a) // 移动构造函数
:elem{a.elem}, // get the element from a
sz{a.sz}
{
a.elem = nullptr; // set null to a.
a.sz = 0;
}
Vector& operator=(Vector&& a) // 移动赋值运算符
{
delete[] elem;
elem = a.elem;
sz = a.sz;
a.elem = nullptr;
a.sz = 0;
}
T & operator[](int i)
{
if(i < 0 || i >= sz)
throw std::out_of_range("out of max size.");
return elem[i];
}
int size() const
{
return sz;
}
void push_back(T b)
{
b = b;
}
T* begin(){
return elem;
}
T* end(){
return elem+sz;
}
};
};
#endif
|
package dao
import (
coredb "fgame/fgame/core/db"
coreredis "fgame/fgame/core/redis"
wushuangweaponentity "fgame/fgame/game/wushuangweapon/entity"
"sync"
"github.com/jinzhu/gorm"
)
const (
dbSlotName = "wushuangweapon_slot"
dbSettingsName = "wushuang_settings"
dbBuchangName = "wushuang_buchang"
)
type WushuangWeaponDao interface {
GetAllWushuangWeaponSlotEntity(playerId int64) (wushuangEntityList []*wushuangweaponentity.PlayerWushuangWeaponSlotEntity, err error)
GetAllWushuangSettings(playerId int64) (wushuangSettingsEntityList []*wushuangweaponentity.PlayerWushuangSettingsEntity, err error)
GetAllWushuangBuchang(playerId int64) (wushuangSettingsEntityList *wushuangweaponentity.PlayerWushuangBuchangEntity, err error)
}
type wushuangWeaponDao struct {
ds coredb.DBService
rs coreredis.RedisService
}
func (dao *wushuangWeaponDao) GetAllWushuangWeaponSlotEntity(playerId int64) (wushuangEntityList []*wushuangweaponentity.PlayerWushuangWeaponSlotEntity, err error) {
err = dao.ds.DB().Order("`slotId` ASC").Find(&wushuangEntityList, "playerId=? and deleteTime=0", playerId).Error
if err != nil {
if err != gorm.ErrRecordNotFound {
return nil, coredb.NewDBError(dbSlotName, err)
}
return nil, nil
}
return
}
func (dao *wushuangWeaponDao) GetAllWushuangBuchang(playerId int64) (wushuangBuchangEntity *wushuangweaponentity.PlayerWushuangBuchangEntity, err error) {
wushuangBuchangEntity = &wushuangweaponentity.PlayerWushuangBuchangEntity{}
err = dao.ds.DB().First(wushuangBuchangEntity, "playerId=? and deleteTime=0 ", playerId).Error
if err != nil {
if err != gorm.ErrRecordNotFound {
return nil, coredb.NewDBError(dbBuchangName, err)
}
return nil, nil
}
return
}
func (dao *wushuangWeaponDao) GetAllWushuangSettings(playerId int64) (wushuangSettingsEntityList []*wushuangweaponentity.PlayerWushuangSettingsEntity, err error) {
err = dao.ds.DB().Order("`itemId` ASC").Find(&wushuangSettingsEntityList, "playerId=? and deleteTime=0", playerId).Error
if err != nil {
if err != gorm.ErrRecordNotFound {
return nil, coredb.NewDBError(dbSettingsName, err)
}
return nil, nil
}
return
}
var (
once sync.Once
dao *wushuangWeaponDao
)
func Init(ds coredb.DBService, rs coreredis.RedisService) (err error) {
once.Do(func() {
dao = &wushuangWeaponDao{
ds: ds,
rs: rs,
}
})
return nil
}
func GetWushuangWeaponDao() WushuangWeaponDao {
return dao
}
|
Growth and Photocatalytic Properties of Gallium Oxide Films Using Chemical Bath Deposition
: Gallium oxide (Ga 2 O 3 ) thin films were fabricated on glass substrates using a combination of chemical bath deposition and post-annealing process. From the field-emission scanning electron microscopy and x-ray di ff raction results, the GaOOH nanorods precursors with better crystallinity can be achieved under higher concentrations ( ≥ 0.05 M) of gallium nitrate (Ga(NO 3 ) 3 ). It was found that the GaOOH synthesized from lower Ga(NO 3 ) 3 concentration did not transform into α -Ga 2 O 3 among the annealing temperatures used (400–600 ◦ C). Under higher Ga(NO 3 ) 3 concentrations ( ≥ 0.05 M) with higher annealing temperatures ( ≥ 500 ◦ C), the GaOOH can be transformed into the Ga 2 O 3 film successfully. An α -Ga 2 O 3 sample synthesized in a mixed solution of 0.075 M Ga(NO 3 ) 3 and 0.5 M hexamethylenetetramine exhibited optimum crystallinity after annealing at 500 ◦ C, where the α -Ga 2 O 3 nanostructure film showed the highest aspect ratio of 5.23. As a result, the photodegeneration e ffi ciencies of the α -Ga 2 O 3 film for the methylene blue aqueous solution can reach 90%.
Introduction
Environmental protection, especially against water pollution, has generated public interest in recent years, and the application of nanotechnology in this field has become a hot topic. Photocatalysis using natural sunlight as a clean energy source, has been extensively studied for environmental remediation since its discovery . Methylene blue (MB), a common dye, has been widely used for the commercial products such as the dyeing paper, linen, silk fabric, bamboo, wood, etc. The discharge of untreated MB into the wastewater can lead to serious pollution problems, making degradation and decolorization of MB is one of the important targets of dyeing wastewater treatment .
Recently, various methods have been used to synthesize Ga 2 O 3 , including hydrothermal techniques , microwave-assisted hydrothermal methods , sol-gel methods , spray pyrolysis processes , and chemical vapor deposition . The advantages of CBD for the synthesis of metal oxide thin films are based on the relatively low cost and convenience for deposition over a large area . However, there are very few reports on the synthesis of Ga 2 O 3 thin films via CBD. In this study, the Ga 2 O 3 thin films were synthesized on the glass substrates using CBD with various post annealing treatments. The chemistry of the synthesis process can be summarized as follows :
Experimental
Ga 2 O 3 thin films were prepared on glass substrates using CBD. Analytical grade gallium (III) nitrate hydrate (Ga(NO 3 ) 3 ·nH 2 O, 99.9%) and hexamethylenetetramine (HMT, 99.9%) were used as starting materials. The glass substrates were cleaned with acetone, methanol, and 10% hydrofluoric acid for 10 min respectively, then rinsed with deionized (DI) water. Three growth solutions were prepared by dissolving 0.025 mol, 0.05 moL, or 0.075 mol Ga(NO 3 ) 3 and 0.5 mol HMT in 1 L of DI water. To obtain the GaOOH precursor, each aqueous solution was placed in a beaker with a glass substrate and vigorously stirred at 500 rpm with a magnetic stirrer for 5 h at 95 • C. The precursor was then dried at 70 • C for 5 min and allowed to cool naturally to room temperature. The as-prepared GaOOH thin films were annealed in a furnace tube at either 400 • C, 500 • C, or 600 • C for 3 h to form Ga 2 O 3 thin films.
The crystal structures of the as-prepared samples were characterized using a high resolution X-ray diffraction system (HR-XRD, X'Pert Pro MRD, PANanalytical, Almelo, Nederland). A JSM-6700F field-emission scanning electron microscope (FE-SEM, JEOL, Tokyo, Japan) equipped with an energy dispersive spectrometer (EDS) was used to analyze the morphologies of the samples and their elemental distributions. FT-IR spectra were collected in the range from 4000 to 500 cm −1 with a Vertex 80v Fourier transform infrared spectrometer (Bruker, Billerica, Massachusetts, MA, USA). The photocatalytic properties of the Ga 2 O 3 thin films in aqueous MB solutions were evaluated during and after irradiation under an 8 W UV lamp at wavelengths from 100 to 280 nm. Thin films with dimensions of 1 cm × 1 cm were first placed in aqueous solutions containing 5 ppm MB. The solutions were then irradiated for 5 h at room temperature in an otherwise dark environment. Photodegradation efficiency was determined through UV-visible spectrophotometric analysis (U3010, Hitachi, Tokyo, Japan)
Results and Discussion
The FE-SEM images of the GaOOH nanostructures obtained via CBD at various Ga(NO 3 ) 3 concentrations are shown in Figure 1, where the length, width, and the aspect ratio of at least eight GaOOH nanorods were measured. It was found that the Ga(NO 3 ) 3 concentration significantly The FE-SEM images of the GaOOH nanostructures obtained via CBD at various Ga(NO3)3 concentrations are shown in Figure 1, where the length, width, and the aspect ratio of at least eight GaOOH nanorods were measured. It was found that the Ga(NO3)3 concentration significantly influenced the synthesis of GaOOH nanorods and the formation of Ga2O3 thin films during the annealing process. The GaOOH crystalline quality increased as the Ga(NO3)3 concentration increased from 0.025 M (Figure 1a,d) to 0.075 M (Figure 1c,f). The average length, width and the aspect ratio of the GaOOH nanorods prepared from 0.025 M Ga(NO3)3 were 0.88 μm, 0.27 μm and 3.23, respectively ( Figure 1d). The average length, width and the aspect ratio of the GaOOH nanorods prepared from 0.05 M Ga(NO3)3 were 0.92 μm, 0.25 μm and 3.76, respectively (Figure 1e). When the Ga(NO3)3 concentration increased to 0.075 M, the average length, width and the aspect ratio of the GaOOH nanorods increased to 1.24 μm, 0.25 μm and 5.06, respectively (Figure 1f). These indicated that the higher concentration of Ga(NO3)3 yielded the GaOOH nanorods with better crystallinity. Figure 2b). The FWHM of this peak was related to the crystallinity of the GaOOH nanorods and indicated that the crystallinity of the nanorods prepared with 0.075 M Ga(NO3)3 was higher than that of the other GaOOH samples. The XRD results agreed well with the crystallinity trend of the GaOOH nanorods deposited from various Ga(NO3)3 concentrations as presented in Figure 1. Figure 2b). The FWHM of this peak was related to the crystallinity of the GaOOH nanorods and indicated that the crystallinity of the nanorods prepared with 0.075 M Ga(NO 3 ) 3 was higher than that of the other GaOOH samples. The XRD results agreed well with the crystallinity trend of the GaOOH nanorods deposited from various Ga(NO 3 ) 3 concentrations as presented in Figure 1.
An FTIR spectra of the as-prepared GaOOH nanorods synthesized at each Ga(NO 3 ) 3 concentration is shown in Figure 3. It is known that the peak at~3222 cm −1 in the FTIR spectra of GaOOH nanorods was assigned to the H-OH stretching vibration, and the stretching vibration of O-H bonds was observed around 1323 cm −1 due to the adsorption of water molecules . The peak at~750 cm −1 was assigned to the Ga-O-H stretching vibration . It is worthy to mention that the Ga-O-H bond will be enhanced and shifted from~750 to~820 cm −1 as the GaOOH content increased, . This confirmed that the GaOOH nanostructure thin films were successfully grown on the glass substrates via CBD. An FTIR spectra of the as-prepared GaOOH nanorods synthesized at each Ga(NO3)3 concentration is shown in Figure 3. It is known that the peak at ~3222 cm −1 in the FTIR spectra of GaOOH nanorods was assigned to the H-OH stretching vibration, and the stretching vibration of O-H bonds was observed around 1323 cm −1 due to the adsorption of water molecules . The peak at ~750 cm −1 was assigned to the Ga-O-H stretching vibration . It is worthy to mention that the Ga-O-H bond will be enhanced and shifted from ~750 to ~820 cm −1 as the GaOOH content increased, . This confirmed that the GaOOH nanostructure thin films were successfully grown on the glass substrates via CBD. An FTIR spectra of the as-prepared GaOOH nanorods synthesized at each Ga(NO3)3 concentration is shown in Figure 3. It is known that the peak at ~3222 cm −1 in the FTIR spectra of GaOOH nanorods was assigned to the H-OH stretching vibration, and the stretching vibration of O-H bonds was observed around 1323 cm −1 due to the adsorption of water molecules . The peak at ~750 cm −1 was assigned to the Ga-O-H stretching vibration . It is worthy to mention that the Ga-O-H bond will be enhanced and shifted from ~750 to ~820 cm −1 as the GaOOH content increased, . This confirmed that the GaOOH nanostructure thin films were successfully grown on the glass substrates via CBD. Figure 4 shows the XRD patterns of Ga 2 O 3 in the films after annealing for 3 h at various temperatures from 400 to 600 • C. As shown in Figure 4a, the α-Ga 2 O 3 polymorph (JCPDS no. 06-0503) was not indicated in any of the samples annealed at 400 • C. Possibly, the GaOOH could not change to α-Ga 2 O 3 at such as a low temperature . It was also found that the GaOOH synthesized from 0.025 M Ga(NO 3 ) 3 did not transform into α-Ga 2 O 3 among these annealing temperatures. However, the transformation of as-prepared GaOOH into orthorhombic α-Ga 2 O 3 occurred during annealing at 500 and 600 • C. The sharp diffraction peaks of the (104) and (110) α-Ga 2 O 3 crystal planes were observed at (2θ) 33.78 • and 36.03 • , respectively. Table 1 Figure 4 shows the XRD patterns of Ga2O3 in the films after annealing for 3 h at various temperatures from 400 to 600 °C. As shown in Figure 4a, the α-Ga2O3 polymorph (JCPDS no. 06-0503) was not indicated in any of the samples annealed at 400 °C. Possibly, the GaOOH could not change to α-Ga2O3 at such as a low temperature . It was also found that the GaOOH synthesized from 0.025 M Ga(NO3)3 did not transform into α-Ga2O3 among these annealing temperatures. However, the transformation of as-prepared GaOOH into orthorhombic α-Ga2O3 occurred during annealing at 500 and 600 °C. The sharp diffraction peaks of the (104) and (110) α-Ga2O3 crystal planes were observed at (2θ) 33.78° and 36.03°, respectively. Table 1 Figure 5 shows the corresponding FE-SEM micrograph of the α-Ga2O3 sample as tabulated in Table 1. After annealing at 500 °C, the average length, width and the aspect ratio of the Ga2O3 nanorods obtained from CBD-GaOOH with 0.05 M Ga(NO3)3 were 0.94 μm, 0.26 μm and 3.63, respectively (Figure 5a). When the annealing temperature increased to 600 °C, the average length, width and the aspect ratio of the Ga2O3 nanorods were 0.89 μm, 0.26 μm, and 3.45, respectively ( Figure 5b). Besides, the average length, width and the aspect ratio of the Ga2O3 nanorods obtained from 500 °C-annealed GaOOH with 0.075 M Ga(NO3)3 were 1.16 μm, 0.23 μm and 5.23, respectively (Figure 5c). When the annealing temperature increased to 600 °C, the average length, width and the aspect ratio of the Ga2O3 nanorods were 1.22 μm, 0.26 μm, and 4.68, respectively (Figure 5d). Here, all the data of length, width, and the aspect ratio shown in the micrographs were measured at least eight times. It becomes clear that the higher annealing temperature (i.e., 600 °C) will lead to the slight decrease in the aspect ratio of Ga2O3 nanorods. As a result, these nanorods were tightly packed together. Figure 5 shows the corresponding FE-SEM micrograph of the α-Ga 2 O 3 sample as tabulated in Table 1. After annealing at 500 • C, the average length, width and the aspect ratio of the Ga 2 O 3 nanorods obtained from CBD-GaOOH with 0.05 M Ga(NO 3 ) 3 were 0.94 µm, 0.26 µm and 3.63, respectively (Figure 5a). When the annealing temperature increased to 600 • C, the average length, width and the aspect ratio of the Ga 2 O 3 nanorods were 0.89 µm, 0.26 µm, and 3.45, respectively (Figure 5b). Besides, the average length, width and the aspect ratio of the Ga 2 O 3 nanorods obtained from 500 • C-annealed GaOOH with 0.075 M Ga(NO 3 ) 3 were 1.16 µm, 0.23 µm and 5.23, respectively (Figure 5c). When the annealing temperature increased to 600 • C, the average length, width and the aspect ratio of the Ga 2 O 3 nanorods were 1.22 µm, 0.26 µm, and 4.68, respectively (Figure 5d). Here, all the data of length, width, and the aspect ratio shown in the micrographs were measured at least eight times. It becomes clear that the higher annealing temperature (i.e., 600 • C) will lead to the slight decrease in the aspect ratio of Ga 2 O 3 nanorods. As a result, these nanorods were tightly packed together. The elemental compositions of the annealed samples were analyzed via EDS. The EDS spectra of samples prepared using Ga(NO3)3 at various concentrations after annealing at 500 °C are shown in Figure 6. The Si peaks in the EDS spectra were attributed to silicon in the glass substrates. The at.% of Ga in the sample prepared from 0.025 M Ga(NO3)3 was only 1.92% (Figure 6a). When the Ga(NO3)3 concentration increased to 0.05 M, the content of Ga atoms in the sample increased to 16.56% (Figure 6b). Moreover, the at.% of Ga in the sample prepared from 0.075 M Ga(NO3)3 was 30.35% (Figure 6c). From the XRD results as described in Figure 4, the CBD-GaOOH prepared under the lower concentration (0.025 M) cannot be transformed into the α-Ga2O3 regardless of the annealing temperature. It may be due to the fact that the 0.025 M Ga(NO3)3 cannot provide enough Ga content to transform into α-Ga2O3. The photocatalytic properties of the α-Ga2O3 thin films in the MB solutions were examined under irradiation with UV light. The Ga2O3 shows the photocatalytic activity under deep-UV absorption owing to its high bandgap. In general, when the photon was absorbed into photocatalyst, the electron-hole pairs generated on the surface of Ga2O3 were used to the degradation of the MB solution. After interacting with aqueous media, these electrons and holes generate hydroxyl ions, which play the significant role in the degradation process. These hydroxyl ions have strong oxidation capabilities as they can mineralize most of organic compounds. Moreover, the photocatalytic activities intimately depend on the crystallinity and surface area. From the XRD The elemental compositions of the annealed samples were analyzed via EDS. The EDS spectra of samples prepared using Ga(NO 3 ) 3 at various concentrations after annealing at 500 • C are shown in Figure 6. The Si peaks in the EDS spectra were attributed to silicon in the glass substrates. The at.% of Ga in the sample prepared from 0.025 M Ga(NO 3 ) 3 was only 1.92% (Figure 6a). When the Ga(NO 3 ) 3 concentration increased to 0.05 M, the content of Ga atoms in the sample increased to 16.56% (Figure 6b). Moreover, the at.% of Ga in the sample prepared from 0.075 M Ga(NO 3 ) 3 was 30.35% (Figure 6c). From the XRD results as described in Figure 4, the CBD-GaOOH prepared under the lower concentration (0.025 M) cannot be transformed into the α-Ga 2 O 3 regardless of the annealing temperature. It may be due to the fact that the 0.025 M Ga(NO 3 ) 3 cannot provide enough Ga content to transform into α-Ga 2 O 3 . The elemental compositions of the annealed samples were analyzed via EDS. The EDS spectra of samples prepared using Ga(NO3)3 at various concentrations after annealing at 500 °C are shown in Figure 6. The Si peaks in the EDS spectra were attributed to silicon in the glass substrates. The at.% of Ga in the sample prepared from 0.025 M Ga(NO3)3 was only 1.92% (Figure 6a). When the Ga(NO3)3 concentration increased to 0.05 M, the content of Ga atoms in the sample increased to 16.56% (Figure 6b). Moreover, the at.% of Ga in the sample prepared from 0.075 M Ga(NO3)3 was 30.35% (Figure 6c). From the XRD results as described in Figure 4, the CBD-GaOOH prepared under the lower concentration (0.025 M) cannot be transformed into the α-Ga2O3 regardless of the annealing temperature. It may be due to the fact that the 0.025 M Ga(NO3)3 cannot provide enough Ga content to transform into α-Ga2O3. The photocatalytic properties of the α-Ga2O3 thin films in the MB solutions were examined under irradiation with UV light. The Ga2O3 shows the photocatalytic activity under deep-UV absorption owing to its high bandgap. In general, when the photon was absorbed into photocatalyst, the electron-hole pairs generated on the surface of Ga2O3 were used to the degradation of the MB solution. After interacting with aqueous media, these electrons and holes generate hydroxyl ions, which play the significant role in the degradation process. These hydroxyl ions have strong oxidation capabilities as they can mineralize most of organic compounds. Moreover, the photocatalytic activities intimately depend on the crystallinity and surface area. From the XRD The photocatalytic properties of the α-Ga 2 O 3 thin films in the MB solutions were examined under irradiation with UV light. The Ga 2 O 3 shows the photocatalytic activity under deep-UV absorption owing to its high bandgap. In general, when the photon was absorbed into photocatalyst, the electron-hole pairs generated on the surface of Ga 2 O 3 were used to the degradation of the MB solution. After interacting with aqueous media, these electrons and holes generate hydroxyl ions, which play the significant role in the degradation process. These hydroxyl ions have strong oxidation capabilities as they can mineralize most of organic compounds. Moreover, the photocatalytic activities intimately depend on the crystallinity and surface area. From the XRD (Figure 4) and FWHMs analyses (Table 1), the good crystallinity of α-Ga 2 O 3 sample prepared using 0.075 M Ga(NO 3 ) 3 can bring the stable photocatalytic properties as compared with those of the other α-Ga 2 O 3 samples. The calculated constant reaction rates of MB photodegradation by Ga 2 O 3 in the solutions (C/C 0 ) are plotted as a function of UV irradiation time in Figure 7. C 0 is the initial MB concentration in solution, and C is the MB concentration in the UV-irradiated solution. The rates of MB self-degradation in solutions without the catalyst are shown for comparison. Absorbance by MB was monitored at 664 nm . After 5 h of UV irradiation, 82% of the MB was photodegraded by α-Ga 2 O 3 obtained from GaOOH prepared from 0.05 M Ga(NO 3 ) 3 after annealing at 500 • C (Figure 7b). Photodegradation by α-Ga 2 O 3 obtained from the GaOOH sample prepared using 0.075 M Ga(NO 3 ) 3 after annealing at 500 • C was particularly efficient. After UV irradiation for 5 h, 90% of the MB had been photodegraded by the catalyst (Figure 7c). As shown in Figure 7a, only 29% of the MB was photodegraded by the sample obtained from GaOOH prepared using 0.025 M Ga(NO 3 ) 3 . Based on the XRD results (Figure 4), its low photodegradation efficiency may have been due to the lack of GaOOH transformation into α-Ga 2 O 3 . The photodegradation efficiencies of α-Ga 2 O 3 samples obtained after annealing at 500 • C were higher than those of α-Ga 2 O 3 obtained after annealing at 600 • C. This may have been due to the higher the aspect ratio of the α-Ga 2 O 3 annealed at 500 • C, which can lead to more surface area under the process of the degradation of the MB solution. The photocatalytic properties of α-Ga 2 O 3 observed during the degradation of MB suggested it held promise for environmental remediation applications. (Table 1), the good crystallinity of α-Ga2O3 sample prepared using 0.075 M Ga(NO3)3 can bring the stable photocatalytic properties as compared with those of the other α-Ga2O3 samples. The calculated constant reaction rates of MB photodegradation by Ga2O3 in the solutions (C/C0) are plotted as a function of UV irradiation time in Figure 7. C0 is the initial MB concentration in solution, and C is the MB concentration in the UV-irradiated solution. The rates of MB self-degradation in solutions without the catalyst are shown for comparison. Absorbance by MB was monitored at 664 nm . After 5 h of UV irradiation, 82% of the MB was photodegraded by α-Ga2O3 obtained from GaOOH prepared from 0.05 M Ga(NO3)3 after annealing at 500 °C (Figure 7b). Photodegradation by α-Ga2O3 obtained from the GaOOH sample prepared using 0.075 M Ga(NO3)3 after annealing at 500 °C was particularly efficient. After UV irradiation for 5 h, 90% of the MB had been photodegraded by the catalyst (Figure 7c). As shown in Figure 7a, only 29% of the MB was photodegraded by the sample obtained from GaOOH prepared using 0.025 M Ga(NO3)3. Based on the XRD results (Figure 4), its low photodegradation efficiency may have been due to the lack of GaOOH transformation into α-Ga2O3. The photodegradation efficiencies of α-Ga2O3 samples obtained after annealing at 500 °C were higher than those of α-Ga2O3 obtained after annealing at 600 °C. This may have been due to the higher the aspect ratio of the α-Ga2O3 annealed at 500 °C, which can lead to more surface area under the process of the degradation of the MB solution. The photocatalytic properties of α-Ga2O3 observed during the degradation of MB suggested it held promise for environmental remediation applications.
Conclusions
GaOOH thin films were successfully grown on glass substrates via CBD at 95 °C. The as-prepared GaOOH thin films were annealed for 3 h at either 400 °C, 500 °C, or 600 °C to convert GaOOH into thin films of α-Ga2O3, and the crystal structures and elemental compositions were confirmed through the XRD and EDS analysis, respectively. Nanocrystalline α-Ga2O3 films were obtained from GaOOH prepared at Ga(NO3)3 concentrations at or above 0.05 M after annealing at 500 °C or 600 °C. The α-Ga2O3 sample obtained after annealing GaOOH prepared at a Ga(NO3)3 concentration of 0.075 M photodegraded 90% of the MB in a solution irradiated under a UV lamp for 5 h. These results suggest that α-Ga2O3 thin films can be very useful alternatives for the photocatalytic degradation of dyes during wastewater treatment.
Conclusions
GaOOH thin films were successfully grown on glass substrates via CBD at 95 • C. The as-prepared GaOOH thin films were annealed for 3 h at either 400 • C, 500 • C, or 600 • C to convert GaOOH into thin films of α-Ga 2 O 3 , and the crystal structures and elemental compositions were confirmed through the XRD and EDS analysis, respectively. Nanocrystalline α-Ga 2 O 3 films were obtained from GaOOH prepared at Ga(NO 3 ) 3 concentrations at or above 0.05 M after annealing at 500 • C or 600 • C. The α-Ga 2 O 3 sample obtained after annealing GaOOH prepared at a Ga(NO 3 ) 3 concentration of 0.075 M photodegraded 90% of the MB in a solution irradiated under a UV lamp for 5 h. These results suggest that α-Ga 2 O 3 thin films can be very useful alternatives for the photocatalytic degradation of dyes during wastewater treatment. |
The German starlet also appeared in Hitchcock's 'Topaz' and in films with Christopher Lee and Lex Barker.
Karin Dor, who played the red-haired villainess Helga Brandt in the 1967 James Bond film You Only Live Twice, died Monday in a nursing home in Munich, her son told the Bild newspaper. She was 79.
The German beauty also had a key role as a revolutionary in the Alfred Hitchcock Cuban missile crisis thriller Topaz (1969) and appeared opposite Christopher Lee in The Invisible Dr. Mabuse (1962), one of more than a dozen films she made with her then-husband, Austrian director Harald Reinl.
In her most famous role, Dor worked for the evil Blofeld (Donald Pleasence) as SPECTRE agent No. 11. Her character can't resist the advances of 007 (Sean Connery), then gets dropped into a pool of piranhas, paying the ultimate price for failing to dispose of the British spy.
Dor regularly appeared with Tarzan actor Lex Barker in several German films adapted from the Karl May novels about the American Wild West, including The Treasure of the Silver Lake (1962), Winnetou: The Red Gentleman (1964), Winnetou: The Last Shot (1965) and The Valley of Death (1968).
She played a murderess in Room 13 (1964), and her film résumé also included Lee's The Face of Fu Manchu (1965), The Torture Chamber of Dr. Sadism (1967) — another picture with Barker and Reinl — Warhead (1977), starring David Janssen, and I Am the Other Woman (2006).
American TV audiences also could spot her in episodes of It Takes a Thief, Ironside and The F.B.I. She more recently worked in the German theater. |
<filename>main.py
from mandelbrot import *
# Iniciando coisas do pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
pygame.display.set_caption(window_name)
mandel = Mandelbrot()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
mandel.control()
mandel.render()
surface = pygame.surfarray.make_surface(mandel.getImg())
screen.blit(surface, (1, 0))
pygame.display.flip()
clock.tick(FPS)
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PolyKinds, DataKinds #-}
module T5716 where
data family DF a
data instance DF Int = DFInt
data U = U1 (DF Int)
data I :: U -> * where I1 :: I (U1 DFInt)
|
import * as tencentcloud from "../../../tencentcloud"
// 导入对应产品模块的client models。
const CvmClient = tencentcloud.cvm.v20170312.Client
// 实例化要请求产品的client对象。profile可选。
const client = new CvmClient({
credential: {
secretId: process.env.secretId,
secretKey: process.env.secretKey,
},
region: "ap-shanghai",
profile: {
signMethod: "TC3-HMAC-SHA256",
httpProfile: {
reqMethod: "POST",
reqTimeout: 30,
},
},
})
// 通过client对象调用想要访问的接口,需要传入请求对象以及响应回调函数
client
.InquiryPriceRunInstances({
InternetAccessible: {
InternetMaxBandwidthOut: 1,
InternetChargeType: "TRAFFIC_POSTPAID_BY_HOUR",
PublicIpAssigned: true,
},
InstanceCount: 1,
Placement: {
Zone: "ap-shanghai-2",
// ProjectId: "1138633" as any,
},
SystemDisk: {
DiskType: "CLOUD_PREMIUM",
DiskSize: 50,
},
LoginSettings: {
Password: "<PASSWORD>",
},
ImageId: "img-25szkc8t",
InstanceChargeType: "POSTPAID_BY_HOUR",
EnhancedService: {
MonitorService: {
Enabled: true,
},
SecurityService: {
Enabled: true,
},
},
InstanceChargePrepaid: {
Period: 1,
RenewFlag: "NOTIFY_AND_MANUAL_RENEW",
},
InstanceName: "API-SDK-NODEJS",
InstanceType: "S2.SMALL1",
// VirtualPrivateCloud: {
// AsVpcGateway: true,
// Ipv6AddressCount: 0,
// SubnetId: "subnet-mom67r5j",
// VpcId: "vpc-pz4uwz7s",
// },
})
.then(
(response) => {
// 请求正常返回,打印response对象
console.log(response)
},
(err) => {
console.log(err)
}
)
|
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, m, x, y, cnt, par[N], mx[N], mn[N], sz[N];
set<int> p;
int find(int a) { return a == par[a] ? a : par[a] = find(par[a]); }
void unite(int a, int b){
//if(find(a) == find(b)) return;
a = find(a), b = find(b);
if(sz[a] < sz[b]) swap(a, b);
sz[a] += sz[b], par[b] = a;
mx[a] = max(mx[b], mx[a]);
mn[a] = min(mn[b], mn[a]);
}
int main(){
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) par[i] = i, sz[i] = 1, mn[i] = i, mx[i] = i;
for(int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
unite(x, y);
}
//for(int i = 1; i <= n; i++) p.insert(find(i));
//for(auto x : p) cout << "par, l, r: " << x << " " << mn[x] << " " << mx[x] << endl;
/*
for(auto x : p){
int l = mn[x], r = mx[x];
//cout << "par, l, r: " << x << " " << l << " " << r << endl;
for(int i = l; i <= r; i++){
if(find(l) != find(i)) cnt++, unite(l, i);
}
}
*/
int pos = 1;
while(pos <= n){
int pr = find(pos), l = mn[pr], r = mx[pr];
for(int i = l; i <= r; i++) if(find(l) != find(i)) cnt++, unite(l, i);
pos = r+1;
}
printf("%d\n", cnt);
}
|
// SRS_ProvisioningAmqpOperations_07_009: [sendRegisterMessage shall throw ProvisioningDeviceClientException if either responseCallback is null.]
@Test (expected = ProvisioningDeviceClientException.class)
public void sendRegisterMessageThrowsOnResponseCallbackNull() throws ProvisioningDeviceClientException, IOException, InterruptedException
{
ProvisioningAmqpOperations provisioningAmqpOperations = new ProvisioningAmqpOperations(TEST_SCOPE_ID, TEST_HOST_NAME);
provisioningAmqpOperations.sendRegisterMessage(null, null, null);
} |
/* Remove this at some point in the future */
gint32
Mono_Posix_Syscall_utimes_bad (const char *filename,
struct Mono_Posix_Timeval *tv)
{
struct timeval _tv;
struct timeval *ptv = NULL;
if (tv) {
_tv.tv_sec = tv->tv_sec;
_tv.tv_usec = tv->tv_usec;
ptv = &_tv;
}
return utimes (filename, ptv);
} |
/**
* Basic enum of all the default {@link FactoryProvider} types
* availables in the system.<br>
* <br>
* To create one use the create method for the desired type. Example:<br>
*
* This isn't really an enum, but acts like one in all ways except
* initialization; it is not one to allow us to use loops and generification
* during initialization.
*
* <pre>
* <code>
* DefaultPyramidIOFactoryProvider.FILE.create();
* </code>
* </pre>
*/
public final class DefaultTileSerializerFactoryProvider
extends AbstractFactoryProvider<TileSerializer<?>>
implements Comparable<DefaultTileSerializerFactoryProvider>
{
private static int __currentOrdinal = 0;
private static List<DefaultTileSerializerFactoryProvider> __values = new ArrayList<>();
private static Map<String, DefaultTileSerializerFactoryProvider> __reverse = new HashMap<>();
// Specific, un-generified serializer types
// Our old pre-avro serializer
@Deprecated
public static final DefaultTileSerializerFactoryProvider LEGACY =
new DefaultTileSerializerFactoryProvider("legacy", new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new com.oculusinfo.binning.io.serialization.impl.BackwardsCompatibilitySerializerFactory(parent, path);
}
});
// JSON serializers
public static final DefaultTileSerializerFactoryProvider DOUBLE_JSON =
new DefaultTileSerializerFactoryProvider("double_json", new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new DoubleJsonSerializerFactory(parent, path);
}
});
public static final DefaultTileSerializerFactoryProvider STRING_INT_PAIR_ARRAY_JSON =
new DefaultTileSerializerFactoryProvider("string_int_pair_array_json", new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new StringIntPairArrayJsonSerializerFactory(parent, path);
}
});
public static final DefaultTileSerializerFactoryProvider STRING_LONG_PAIR_ARRAY_MAP_JSON =
new DefaultTileSerializerFactoryProvider("string_long_pair_array_map_json", new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new StringLongPairArrayMapJsonSerializerFactory(parent, path);
}
});
// Generified serializer types
// Single-value serialziers
public static final List<DefaultTileSerializerFactoryProvider> PRIMITIVES =
Collections.unmodifiableList(new ArrayList<DefaultTileSerializerFactoryProvider>() {
private static final long serialVersionUID = 1L;
{
for (final Class<?> type: PrimitiveAvroSerializer.PRIMITIVE_TYPES) {
String name = PrimitiveAvroSerializer.getAvroType(type)+"_avro";
// Note that the double-valued primitive serializer should be the default.
add(new DefaultTileSerializerFactoryProvider(name, new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new PrimitiveAvroSerializerFactory<>(parent, path, type);
}
}, Double.class.equals(type)));
}
}
});
// Array serializers
public static final List<DefaultTileSerializerFactoryProvider> PRIMITIVE_ARRAYS =
Collections.unmodifiableList(new ArrayList<DefaultTileSerializerFactoryProvider>() {
private static final long serialVersionUID = 1L;
{
for (final Class<?> type: PrimitiveAvroSerializer.PRIMITIVE_TYPES) {
String name = PrimitiveAvroSerializer.getAvroType(type)+"_array_avro";
add(new DefaultTileSerializerFactoryProvider(name, new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new PrimitiveArrayAvroSerializerFactory<>(parent, path, type);
}
}));
}
}
});
// Simple Pair serializers
public static final List<DefaultTileSerializerFactoryProvider> PAIRS =
Collections.unmodifiableList(new ArrayList<DefaultTileSerializerFactoryProvider>() {
private static final long serialVersionUID = 1L;
{
for (final Class<?> keyType: PrimitiveAvroSerializer.PRIMITIVE_TYPES) {
String keyName = PrimitiveAvroSerializer.getAvroType(keyType);
for (final Class<?> valueType: PrimitiveAvroSerializer.PRIMITIVE_TYPES) {
String valueName = PrimitiveAvroSerializer.getAvroType(valueType);
String name = keyName + "_" + valueName + "_pair_avro";
add(new DefaultTileSerializerFactoryProvider(name, new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new PairAvroSerializerFactory<>(parent, path, keyType, valueType);
}
}));
}
}
}
});
// Array of Pair (can be used for maps) serializers
public static final List<DefaultTileSerializerFactoryProvider> PAIR_ARRAYS =
Collections.unmodifiableList(new ArrayList<DefaultTileSerializerFactoryProvider>() {
private static final long serialVersionUID = 1L;
{
for (final Class<?> keyType: PrimitiveAvroSerializer.PRIMITIVE_TYPES) {
String keyName = PrimitiveAvroSerializer.getAvroType(keyType);
for (final Class<?> valueType: PrimitiveAvroSerializer.PRIMITIVE_TYPES) {
String name = keyName+"_"+PrimitiveAvroSerializer.getAvroType(valueType)+"_pair_array_avro";
add(new DefaultTileSerializerFactoryProvider(name, new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new PairArrayAvroSerializerFactory<>(parent, path, keyType, valueType);
}
}));
}
}
}
});
// Kryo serializers
public static final List<DefaultTileSerializerFactoryProvider> KRYO =
Collections.unmodifiableList(new ArrayList<DefaultTileSerializerFactoryProvider>() {
private static final long serialVersionUID = 1L;
{
List<Pair<String, TypeDescriptor>> primitives = new ArrayList<>();
for (Class<?> primitive: KryoSerializer.PRIMITIVE_TYPES) {
primitives.add(new Pair<String, TypeDescriptor>(primitive.getSimpleName().toLowerCase(), new TypeDescriptor(primitive)));
}
// Simple types
for (final Pair<String, TypeDescriptor> primitive: primitives) {
String name = primitive.getFirst()+"_kryo";
add(new DefaultTileSerializerFactoryProvider(name, new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new KryoSerializerFactory<>(parent, path, primitive.getSecond());
}
}));
}
// Array types
for (final Pair<String, TypeDescriptor> primitive: primitives) {
String name = primitive.getFirst()+"_array_kryo";
add(new DefaultTileSerializerFactoryProvider(name, new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new KryoSerializerFactory<>(parent, path, new TypeDescriptor(List.class, primitive.getSecond()));
}
}));
}
// Map types
for (final Pair<String, TypeDescriptor> kPrimitive: primitives) {
for (final Pair<String, TypeDescriptor> vPrimitive: primitives) {
String name = kPrimitive.getFirst()+"_"+vPrimitive.getFirst()+"_pair_array_kryo";
add(new DefaultTileSerializerFactoryProvider(name, new Constructor() {
@Override
public ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path) {
return new KryoSerializerFactory<>(parent, path, new TypeDescriptor(List.class, new TypeDescriptor(Pair.class, kPrimitive.getSecond(), vPrimitive.getSecond())));
}
}));
}
}
}
});
// -------------------------------------
private final String _name;
private final Constructor _constructor;
private final int _ordinal;
private DefaultTileSerializerFactoryProvider (String name, Constructor constructor) {
this(name, constructor, false);
}
private DefaultTileSerializerFactoryProvider (String name, Constructor constructor, boolean isDefault) {
_name = name;
_constructor = constructor;
_ordinal = __currentOrdinal;
__currentOrdinal = __currentOrdinal+1;
if (isDefault) {
__values.add(0, this);
} else {
__values.add(this);
}
__reverse.put(name, this);
}
public int oridinal () {
return _ordinal;
}
@Override
public ConfigurableFactory<? extends TileSerializer<?>> createFactory (List<String> path) {
return createFactory(null, path);
}
@Override
public ConfigurableFactory<? extends TileSerializer<?>> createFactory (String name,
ConfigurableFactory<?> parent,
List<String> path) {
return _constructor.create(parent, path);
}
// Enum mimics
@Override
public String toString () {
return _name;
}
@Override
protected Object clone () throws CloneNotSupportedException {
throw new CloneNotSupportedException("Default Tile Serializer Factory Providers should be treated like enums.");
}
@Override
public int compareTo (DefaultTileSerializerFactoryProvider that) {
return this._ordinal - that._ordinal;
}
public final Class<DefaultTileSerializerFactoryProvider> getDeclaringClass () {
return DefaultTileSerializerFactoryProvider.class;
}
@Override
public final boolean equals (Object that) {
return this == that;
}
@Override
public final int hashCode () {
return super.hashCode();
}
// Enum static mimics
public static DefaultTileSerializerFactoryProvider valueOf (String name) {
return __reverse.get(name.toLowerCase());
}
public static DefaultTileSerializerFactoryProvider[] values () {
return __values.toArray(new DefaultTileSerializerFactoryProvider[__values.size()]);
}
private static interface Constructor {
ConfigurableFactory<? extends TileSerializer<?>> create (ConfigurableFactory<?> parent,
List<String> path);
}
} |
// Select implements storage.Querier and uses the given matchers to read series sets from the client.
// Select also adds equality matchers for all external labels to the list of matchers before calling remote endpoint.
// The added external labels are removed from the returned series sets.
//
// If requiredMatchers are given, select returns a NoopSeriesSet if the given matchers don't match the label set of the
// requiredMatchers. Otherwise it'll just call remote endpoint.
func (q *querier) Select(sortSeries bool, hints *storage.SelectHints, matchers ...*labels.Matcher) storage.SeriesSet {
if len(q.requiredMatchers) > 0 {
requiredMatchers := append([]*labels.Matcher{}, q.requiredMatchers...)
for _, m := range matchers {
for i, r := range requiredMatchers {
if m.Type == labels.MatchEqual && m.Name == r.Name && m.Value == r.Value {
requiredMatchers = append(requiredMatchers[:i], requiredMatchers[i+1:]...)
break
}
}
if len(requiredMatchers) == 0 {
break
}
}
if len(requiredMatchers) > 0 {
return storage.NoopSeriesSet()
}
}
m, added := q.addExternalLabels(matchers)
start, end := q.mint, q.maxt
if hints != nil {
start, end = hints.Start, hints.End
}
query, err := ToQuery(start, end, m, hints)
if err != nil {
return storage.ErrSeriesSet(errors.Wrap(err, "toQuery"))
}
res, err := q.client.Read(q.ctx, query)
if err != nil {
return storage.ErrSeriesSet(errors.Wrap(err, "remote_read"))
}
return newSeriesSetFilter(FromQueryResult(sortSeries, res), added)
} |
<filename>plugins/application_context/src/process/ProcessInfo_Win32.cpp
#include "process/ProcessInfo.hpp"
#include "SystemInfo.hpp"
#include "easylogging++.h"
#define WIN32_MEAN_AND_LEAN
#include <Psapi.h>
#include <windows.h>
#pragma comment(lib, "Windowsapp.lib")
struct PsAPI_INIT {
bool supported;
typedef BOOL(WINAPI* pQueryWorkingSetEx)(HANDLE hProcess, PVOID pv, DWORD cb);
pQueryWorkingSetEx QueryWorkingSetExFn = nullptr;
static PsAPI_INIT& GetPsApi() {
static PsAPI_INIT ps_api;
return ps_api;
}
private:
PsAPI_INIT() {
HINSTANCE psapi_lib = LoadLibrary(TEXT("psapi.dll"));
if (psapi_lib) {
QueryWorkingSetExFn = reinterpret_cast<pQueryWorkingSetEx>(GetProcAddress(psapi_lib, "QueryWorkingSetEx"));
if (QueryWorkingSetExFn) {
supported = true;
}
}
else {
supported = false;
}
}
};
MEMORYSTATUSEX GetMemoryStatus() {
MEMORYSTATUSEX mse;
mse.dwLength = sizeof(mse);
BOOL status = GlobalMemoryStatusEx(&mse);
if (!status) {
static bool failure_logged = false;
LOG_IF(!failure_logged, ERROR) << "Failed to get MEMORYSTATUSEX!";
failure_logged = true;
}
return mse;
}
PROCESS_MEMORY_COUNTERS GetProcessMemoryCounters() {
PROCESS_MEMORY_COUNTERS pmc;
BOOL status = GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
if (!status) {
static bool failure_logged = false;
LOG_IF(!failure_logged, ERROR) << "Failed to get process memory counters!";
failure_logged = true;
}
return pmc;
}
int _wconvertmtos(SIZE_T sz) {
return static_cast<int>(sz / (1024 * 1024));
}
ProcessInfo::ProcessInfo(const ProcessID& id) : pid(id), sysInfo(new SystemInfo()) {
auto& pse_api = PsAPI_INIT::GetPsApi();
}
ProcessInfo::~ProcessInfo() {
if (sysInfo) {
delete sysInfo;
}
}
size_t ProcessInfo::VirtualMemorySize() const {
auto mse = GetMemoryStatus();
DWORDLONG x = mse.ullTotalVirtual - mse.ullAvailVirtual;
return static_cast<size_t>(x);
}
size_t ProcessInfo::ResidentSize() const {
auto pmc = GetProcessMemoryCounters();
return static_cast<size_t>(_wconvertmtos(pmc.WorkingSetSize));
}
double ProcessInfo::GetMemoryPressure() const {
auto mse = GetMemoryStatus();
DWORDLONG total_page_file = mse.ullTotalPageFile;
if (total_page_file == 0) {
return 0.0;
}
DWORDLONG high_watermark = total_page_file / DWORDLONG(2);
DWORDLONG very_high_watermark = DWORDLONG(3) * (total_page_file / DWORDLONG(4));
DWORDLONG used_page_file = mse.ullTotalPageFile - mse.ullAvailPageFile;
if (used_page_file < high_watermark || very_high_watermark <= high_watermark) {
return 0.0;
}
return static_cast<double>(used_page_file - high_watermark) / static_cast<double>(very_high_watermark - high_watermark);
}
size_t ProcessInfo::GetTotalPhysicalMemory() const {
auto mse = GetMemoryStatus();
return static_cast<size_t>(mse.ullTotalPhys);
}
size_t ProcessInfo::GetAvailPhysicalMemory() const {
auto mse = GetMemoryStatus();
return static_cast<size_t>(mse.ullAvailPhys);
}
size_t ProcessInfo::GetCommittedPhysicalMemory() const {
auto mse = GetMemoryStatus();
return static_cast<size_t>(mse.ullTotalPhys - mse.ullAvailPhys);
}
size_t ProcessInfo::GetTotalCommittedMemoryLimit() const {
auto mse = GetMemoryStatus();
return static_cast<size_t>(mse.ullTotalPageFile);
}
size_t ProcessInfo::GetCurrentCommitLimit() const {
auto mse = GetMemoryStatus();
return static_cast<size_t>(mse.ullAvailPageFile);
}
size_t ProcessInfo::GetPageSize() {
SYSTEM_INFO sys_info;
GetNativeSystemInfo(&sys_info);
return static_cast<size_t>(sys_info.dwPageSize);
}
|
.
Some studies found no connection at all between biological parameters and mental illness. There are many reasons for the discrepancies: populations and parameters investigated as well as the method used, widely differed. The discrepancies observed, could also be partly due to several non-specific factors such as age, sex, hormonal status, circadian or circannual variations, and washout period. The authors report here some data gathered in the course of a psychobiological research program on healthy volunteers. Their results indicate that human plateler MAO activity shows an apparent menstrual cycle related variation IMI binding in human platelets shows circadian variations in summer and some antidepressant drugs have a residual effect on serotoninergic parameters during one month. These studies oblige investigators to be cautious when interpreting biological data in psychiatry. Ideally longitudinal studies should be implemented at the various stages of mental illness. |
<filename>scratchpad/voids_paper/bin/tests/test_smartvis.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
import matplotlib.pyplot as plt
import os
import h5py
import sys
import time
import seaborn as sns
import pandas as pd
sys.path.append('/home/atekawade/TomoEncoders/scratchpad/voids_paper/configs')
from params import model_path, get_model_params
sys.path.append('/home/atekawade/TomoEncoders/scratchpad/voids_paper')
from tomo_encoders.tasks.void_mapping import process_patches
from tomo_encoders.structures.voids import Voids
from tomo_encoders import DataFile
import cupy as cp
from tomo_encoders.neural_nets.surface_segmenter import SurfaceSegmenter
from tomo_encoders.tasks.void_mapping import coarse_segmentation
######## START GPU SETTINGS ############
########## SET MEMORY GROWTH to True ############
import tensorflow as tf
physical_devices = tf.config.list_physical_devices('GPU')
try:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
except:
# Invalid device or cannot modify virtual devices once initialized.
pass
######### END GPU SETTINGS ############
model_tag = "M_a07"
model_names = {"segmenter" : "segmenter_Unet_%s"%model_tag}
model_params = get_model_params(model_tag)
# patch size
wd = 32
# guess surface parameters
b = 4
b_K = 4
sparse_flag = True
pixel_res = 1.17
size_um = -1 # um
void_rank = 1
radius_around_void_um = 800.0 # um
blur_size = 0.5
# handy code for timing stuff
# st_chkpt = cp.cuda.Event(); end_chkpt = cp.cuda.Event(); st_chkpt.record()
# end_chkpt.record(); end_chkpt.synchronize(); t_chkpt = cp.cuda.get_elapsed_time(st_chkpt,end_chkpt)
# print(f"time checkpoint {t_chkpt/1000.0:.2f} secs")
## Output for vis
ply_lowres = '/home/atekawade/Dropbox/Arg/transfers/runtime_plots/lowres_full.ply'
ply_highres = '/home/atekawade/Dropbox/Arg/transfers/runtime_plots/highres_around_void_%i.ply'%void_rank
voids_highres = '/data02/MyArchive/aisteer_3Dencoders/tmp_data/voids_highres'
voids_lowres = '/data02/MyArchive/aisteer_3Dencoders/tmp_data/voids_lowres'
if __name__ == "__main__":
# initialize segmenter fCNN
fe = SurfaceSegmenter(model_initialization = 'load-model', \
model_names = model_names, \
model_path = model_path)
fe.test_speeds(128,n_reps = 5, input_size = (wd,wd,wd))
# read data and initialize output arrays
## to-do: ensure reconstructed object has dimensions that are a multiple of the (wd,wd,wd) !!
hf = h5py.File('/data02/MyArchive/aisteer_3Dencoders/tmp_data/projs_2k.hdf5', 'r')
projs = np.asarray(hf["data"][:])
theta = np.asarray(hf['theta'][:])
center = float(np.asarray(hf["center"]))
hf.close()
# make sure projection shapes are divisible by the patch width (both binning and full steps)
print("BEGIN: Read projection data from disk")
print(f'\tSTAT: shape of raw projection data: {projs.shape}')
##### BEGIN ALGORITHM ########
# guess surface
print(f"\nSTEP: visualize all voids with size greater than {size_um:.2f} um")
V_bin, rec_min_max = coarse_segmentation(projs, theta, center, b_K, b, blur_size)
voids_b = Voids().guess_voids(V_bin, b)
voids_b.select_by_size(size_um, pixel_size_um = pixel_res)
voids_b.sort_by_size(reverse = True)
surf = voids_b.export_void_mesh_with_texture("sizes")
surf.write_ply(ply_lowres)
# guess roi around a void
void_id = np.argsort(voids_b["sizes"])[-void_rank]
voids_b.select_around_void(void_id, radius_around_void_um, pixel_size_um = pixel_res)
print(f"\nSTEP: visualize voids in the neighborhood of void id {void_id} at full detail")
cp.fft.config.clear_plan_cache()
p_sel, r_fac = voids_b.export_grid(wd)
x_voids, p_voids = process_patches(projs, theta, center, fe, p_sel, rec_min_max)
# export voids
voids = Voids().import_from_grid(voids_b, x_voids, p_voids)
voids_b.write_to_disk(voids_lowres)
voids.write_to_disk(voids_highres)
surf = voids.export_void_mesh_with_texture("sizes")
surf.write_ply(ply_highres)
# # complete: save stuff
# Vp = np.zeros(p_voids.vol_shape, dtype = np.uint8)
# p_voids.fill_patches_in_volume(x_voids, Vp)
# ds_save = DataFile('/data02/MyArchive/aisteer_3Dencoders/tmp_data/test_y_pred', tiff = True, d_shape = Vp.shape, d_type = np.uint8, VERBOSITY=0)
# ds_save.create_new(overwrite=True)
# ds_save.write_full(Vp)
# Vp_mask = np.zeros(p_voids.vol_shape, dtype = np.uint8) # Save for illustration purposes the guessed neighborhood of the surface
# p_voids.fill_patches_in_volume(np.ones((len(p_voids),wd,wd,wd)), Vp_mask)
# ds_save = DataFile('/data02/MyArchive/aisteer_3Dencoders/tmp_data/test_y_surf', tiff = True, d_shape = Vp_mask.shape, d_type = np.uint8, VERBOSITY=0)
# ds_save.create_new(overwrite=True)
# ds_save.write_full(Vp_mask)
|
Influence of agrotechnical factors on diffuse pollution of aquatic ecosystems
At present, the environmental state of aquatic ecosystems is an issue of serious concern. In this context diffuse pollution, i.e. spatially distributed pollution from non-point sources with uneven and unstable characteristics is the most difficult to assess and manage. In most cases such pollution originates from agricultural fields, with the key pollutant being fertilizer nitrogen leakage with water. The aim of the study was to reveal the influence of separate agrotechnical factors on diffuse pollution of aquatic ecosystems by nitrogen and to obtain the corresponding functional dependence in the analytical form. To tackle the problem, the method of logical-linguistic modeling was applied, which allows to formalize the expert estimates. The following factors were considered: the degree of fertilizer mineralization, fertilizing technologies, the observance of agrotechnical terms, the size of field-edge storage facilities, management efficiency of manure handling and soil fertilization, fertilizer moisture, and fertilizer rates (by nitrogen). The resulting polynomial expression made it possible to reveal the significance of each factor and their relationship. This result has considerable practical value, as it allows predicting the environmental effect and to create a strategy of diffuse pollution reduction by choosing the most effective measures without excessive costs. |
/*
* Creates a new RenderPoint using the given RenderPkgNamespaces object.
*/
RenderPoint::RenderPoint(RenderPkgNamespaces *renderns)
: SBase(renderns)
,mXOffset(RelAbsVector(0.0,0.0))
,mYOffset(RelAbsVector(0.0,0.0))
,mZOffset(RelAbsVector(0.0,0.0))
,mElementName("element")
{
setElementNamespace(renderns->getURI());
connectToChild();
loadPlugins(renderns);
} |
def _process_filter(self, options):
filter_string = ""
if 'filter' in options and isinstance(options['filter'], dict):
filter_string = "&".join(list({f"{parameter}={value}" for (parameter,value) in options['filter'].items()}))
else:
filter_string = options.get('filter', "")
return filter_string |
Stubborn man not listening (Shutterstock)
A North Carolina county official said only Christian prayers are welcome before government meetings, even as a federal judge ended invocations in a neighboring county.
Carrol Mitchem, chairman of the Lincoln County board of commissioners, said he does not want people from other faiths “changing rules on the way the United States was founded,” reported the Lincoln Times-News.
“A Muslim? He comes in here to say a prayer, I’m going to tell him to leave,” Mitchem said. “I have no use for (those) people. They don’t need to be here praying to Allah or whoever the hell they pray to. I’m not going to listen to (a) Muslim pray.”
A federal court judge ruled last week that nearby Rowan County had violated the Establishment Clause of the First Amendment by leading county commission meetings with prayers to “Jesus, the Savior.”
Another county commissioner said Lincoln County said officials had not purposefully excluded other faiths, but pointed out that all 102 houses of worship in the county were Christian.
“We have never said that we would limit it to one denomination or one religion,” said Alex Patton, county commissioner. “I just don’t know that there’s any Jewish pastors or anything like that in Lincoln County.”
Patton said he disagrees with the Rowan County ruling, saying the courts had “gone overboard in catering to the small vocal minority.”
“Atheists are 1 or 2 percent or whatever, but because they cry the loudest, people cater to them,” Patton said. “Judges cater to the freedom of religion. That freedom is for me as a Christian as well.”
The Republican Mitchem agreed, saying that Christians should enjoy privileged status as the dominant religious group.
“Other religions, or whatever, are in the minority,” he told WBTV-TV. “The U.S. was founded on Christianity. I don’t believe we need to be bowing to the minorities. The U.S. and the Constitution were founded on Christianity. This is what the majority of people believe in, and it’s what I’m standing up for.”
A 2012 poll found that 73 percent of Americans identify themselves as Christian, while 6 percent identify with other religions and 19.6 percent are unaffiliated with a religious group. Just 2.4 percent considered themselves atheist.
Mitchem said he would walk out if someone from another religious group delivered a prayer before a county commission meeting, and he suggested at a county commission meeting last year that he expected religious dissenters to do the same during Christian invocations.
“If somebody don’t like it, they get up, walk out and leave so we can pray the way we want to pray,” Mitchem said last year. “If they don’t like it, they can leave and then come back in afterwards.”
Patton, although he disagrees with recent court rulings on religious plurality and agreed with Mitchem’s comments last year, said the board chairman had probably exposed the county to potential litigation.
“I am a Christian, but I do not agree with commissioner Mitchem,” Patton said. “Our country was founded on freedom of religion. All Muslims are not bad, just as all Christians are not good.” |
Nanoscale Structuring in Confined Geometries using Atomic Layer Deposition: Conformal Coating and Nanocavity Formation
Abstract Nanoscale structuring in confined geometries using atomic layer deposition (ALD) is demonstrated for surfaces of nanochannels in track-etched polymer membranes and in mesoporous silica (SBA-15). Suitable process conditions for conformal ALD coating of polymer membranes and SBA-15 with inorganic oxides (SiO2, TiO2, Al2O3) were developed. On the basis of the oxide-coated layers, nanochannels were further structured by a molecular-templated ALD approach, where calixarene macromolecules are covalently attached to the surface and then embedded into an Al2O3 layer. The removal of calixarene by ozone treatment results in 1–2 nm wide surface nanocavities. Surfaces exposed to different process steps are analyzed by small angle X-ray scattering (SAXS) as well as by X-ray photoelectron and infrared spectroscopy. The proposed nanostructuring process increases the overall surface area, allows controlling the hydrophilicity of the channel surface, and is of interest for studying water and ion transport in confinement. |
/**
* Test affinity values != 1
*/
@Test
public void testAffinity() {
TownNameProvider townNameProv = new TownNameProvider(123455);
int hits = 0;
for (int i = 0; i < 1000; i++) {
TownAffinityVector aff = TownAffinityVector.create().postfix(0.5);
String name = townNameProv.generateName(aff);
if (name.contains(" ")) {
hits++;
}
}
logger.info("Towns with postfix out of 1000: " + hits);
assertTrue(hits > 400 && hits < 600);
} |
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int minOperations(String s) {
char[] chars = s.toCharArray();
// 改成第一位为1的操作次数
int one = helper('1', chars);
// 改成第一位为0的操作次数
int zero = helper('0', chars);
return Math.min(one, zero);
}
private int helper(char c, char[] chars) {
int ans = 0;
for (int i = 0; i < chars.length; i++) {
if (i % 2 == 0) {
if (c != chars[i]) {
ans++;
}
} else {
if (c == chars[i]) {
ans++;
}
}
}
return ans;
}
} |
<reponame>Tsubasa-Works/petbook
use crate::{Array, Effect, Skill};
use std::ffi::CString;
use std::os::raw::c_char;
pub unsafe fn drop_skill(i: &Skill) {
std::mem::drop(CString::from_raw(i.info as *mut c_char));
std::mem::drop(CString::from_raw(i.name as *mut c_char));
let a: Box<Array> = std::mem::transmute(i.effect);
let b = Vec::from_raw_parts(a.ptr as *mut Effect, a.len as usize, a.cap as usize);
for j in b {
std::mem::drop(CString::from_raw(j.description as *mut c_char));
std::mem::drop(CString::from_raw(j.args as *mut c_char));
}
}
|
def create_message_set(app_name, routing_key, *messages):
write_buffer = bytearray()
write_messages_into(write_buffer, routing_key, *messages)
read_only_buffer = buffer(write_buffer)
return TMessageSet(app=app_name, compression=0, numMessages=len(messages),
crc=generate_crc(read_only_buffer), messages=read_only_buffer) |
Update: The FEMA DRC mobile unit will not be at Piermont Library but will be at Piermont Village Hall.
---
Two weeks ago, Senator Chuck Schumer joined other elected officials on a tour led by Piermont Mayor Chris Sanders. They visited businesses and residents in downtown Piermont that were one of the hardest hit areas from Hurricane Sandy.
After the tour, Schumer petitioned FEMA for a second Mobile Disaster Recovery Center (DRC) in Rockland County. The first one was opened at Provident Bank Park in Pomona.
On Sunday, U.S. Senator Chuck Schumer announced that FEMA (Federal Emergency Management Agency) will send a DRC to Piermont and the surrounding towns in order to provide better federal support to local residents and business owners in this storm-ravaged community.
The Mobile DRC is expected to begin in Piermont in the parking lot of Dennis P. McHugh Library, on Monday. The location of the Mobile DRC will change throughout Rockland County based on the local need of federal assistance, although the center could stay in a single location for an extended period if needed.
DRCs are facilities or mobile units that provide resources and guidance for residents who wish to apply for FEMA and other disaster assistance programs. It'll be staffed with FEMA and Small Business Administration (SBA) employees who answer questions and provide resources for residents affected by Sandy.
Federal specialists will staff the Mobile DRC from noon to 6 p.m. on Monday and tentatively from 8 a.m. to 6 p.m. on subsequent days, and help ensure that qualified residents and businesses get the assistance to which they're entitled. These centers provide information on housing assistance, rental resource assistance, clarification and guidance to questions and referrals to agencies that may provide further assistance.
"For residents and business owners in storm-ravaged parts of southern Rockland County, I'm pleased to announce that additional federal support is on the way," said Schumer. "FEMA has heeded my call and will send a Mobile Disaster Recovery Center to Piermont and the surrounding communities, starting on Monday, which will bring recovery experts directly into the community, and open up a great deal of additional resources to help get things back on track. This second DRC closer to Piermont, one of the hardest hit communities in the County, will serve as one stop shops for residents, business owners and local officials to work with FEMA and access the resources that the emergency disaster declaration provides."
In the days following the storm, Senator Schumer called on FEMA Administrator Fugate and urged him to establish an initial disaster recovery center in Rockland County.
This mobile DRC will help residents avoid driving a half hour or more to access resources in Pomona, without wasting fuel and time that is critical to time sensitive repairs. Schumer added that the close proximity allows FEMA specialists to visit damaged areas and offer expertise on location.
According to FEMA, over 69,000 people in New York have already registered for disaster assistance and more than $75 million in assistance has been approved.
Piermont's waterfront of restaurants, marinas and homes was severely damaged as a result of the high tides caused by Superstorm Sandy. Rising waters caused by a historic high tide resulted in the major downtown area to be completely flooded. The storm caused residents to flee their flooded homes and locked business owners out of their submerged waterfront establishments. In Piermont, the Hudson River's high tide surged upward of 9 ½ feet, submerging sea walls, damaging docks and flooding Route 9W in and out of the city.
Estimates for the damage are already projected to be several million dollars in the Town of Piermont alone. Several sailboats and cabin boats washed up throughout the town, along with concrete park benches and pieces of boardwalk from over a mile away. Superstorm Sandy also caused severe flooding in Nyack's riverfront area — including the municipal marina, the Nyack Boat Club and Clermont condos at South Main Street.
A copy of Senator Schumer's letter urging for a second DRC in Rockland County, appears below:
Dear Administrator Fugate: I write today to bring to your attention an important issue facing the residents of Rockland County, New York. As you know, Rockland County was severely impacted by Superstorm Sandy. Specifically, Rockland County, particularly in Piermont and Nyack, experienced severe flooding and wind damage following Sandy. Tens of thousands of lower Hudson Valley residents remain without power, over a week after the storm. The storm's impact was such that New York requested approval of a major disaster declaration for Individual Assistance and Public Assistance (Categories A through G). My fellow New Yorkers and I were very relieved and very grateful when this request was expeditiously approved and when FEMA opened up a Disaster Recovery Center (DRC) in Pomona (Rockland County). Unfortunately, the declaration is only the first stage in a long recovery process. Rockland County residents are still struggling to assess the impact of Sandy and what federal resources are available to them. Given this countywide uncertainty, I respectfully urge you to open a second DRC in Rockland County. Doing so will ensure that Rockland residents all across the county can feel the presence of the federal government in their local communities, know what federal resources are available, and how they can access them. I am grateful for the prompt attention that you and the entire federal government have given to quickly responding to this disaster and for your commitment to cutting bureaucratic red-tape so that assistance can be provided as quickly and efficiently as possible. In that spirit, I strongly urge you to approve this request. |
/**
* Represents a SortedMapValueFactory
* Created by nicojs on 8/16/2015.
*/
public class WeakHashMapValueFactory extends MapValueFactory<WeakHashMap> {
public WeakHashMapValueFactory() {
super(WeakHashMap.class, new Producer<WeakHashMap>() {
@Override
public WeakHashMap produce() {
return new WeakHashMap();
}
});
}
} |
Begonia balangcodiae sp. nov. from northern Luzon, the Philippines and its natural hybrid with B. crispipila, B. × kapangan nothosp. nov.
The pantropically distributed Begonia (Begoniaceae) is one of the most species-rich genera. Philippines is one of the diversity centers of Southeast Asian Begonia. In our 2012 field survey, three species of Begonia section Petermannia were collected in Barangay Sagubo, Municipality of Kapangan, Province of Benguet in the northern Luzon Island, Philippines. Our study on literatures and herbarium specimens suggests that these collections consist of B. crispipila, an unknown new species hereby we named B. balangcodiae, and the natural hybrid between them. Molecular analyses confirm that the former contributed the maternal genome while the latter provided the paternal genome. We name the natural hybrid B. × kapangan, which is the first natural hybrid reported in sect. Petermannia. |
package com.jaquadro.minecraft.bigdoors.item;
import com.jaquadro.minecraft.bigdoors.BigDoors;
import com.jaquadro.minecraft.bigdoors.block.tile.Door3x3Tile;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockWood;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemMultiTexture;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
public class ItemDoor3x3 extends ItemMultiTexture
{
@SideOnly(Side.CLIENT)
protected IIcon[] icons;
public ItemDoor3x3 (Block block) {
this(block, BlockWood.field_150096_a);
}
protected ItemDoor3x3 (Block block, String[] names) {
super(block, block, names);
}
@SideOnly(Side.CLIENT)
@Override
public IIcon getIconFromDamage (int damage) {
return icons[damage % icons.length];
}
@Override
public boolean placeBlockAt (ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) {
if (!super.placeBlockAt(stack, player, world, x, y, z, side, hitX, hitY, hitZ, metadata))
return false;
Door3x3Tile tile = (Door3x3Tile)world.getTileEntity(x, y, z);
if (tile != null)
tile.setDoorType(metadata);
return true;
}
@SideOnly(Side.CLIENT)
@Override
public void registerIcons (IIconRegister register) {
icons = new IIcon[BlockWood.field_150096_a.length];
for (int i = 0; i < icons.length; i++)
icons[i] = register.registerIcon(BigDoors.MOD_ID + ":doors_" + BlockWood.field_150096_a[i]);
}
}
|
/**
* This class provides operations to work with {@link Order}s.
*/
public class OrderService {
ApiRoot apiRoot;
String projectKey;
public OrderService(final ApiRoot client, String projectKey) {
this.apiRoot = client;
this.projectKey = projectKey;
}
public CompletableFuture<ApiHttpResponse<Order>> createOrder(final ApiHttpResponse<Cart> cartApiHttpResponse) {
final Cart cart = cartApiHttpResponse.getBody();
return apiRoot.withProjectKey(projectKey
).orders().post(
OrderFromCartDraftBuilder.of()
.version(cart.getVersion())
.id(cart.getId())
.build()
).execute();
}
public CompletableFuture<ApiHttpResponse<Order>> changeState(
final ApiHttpResponse<Order> orderApiHttpResponse,
final OrderState state) {
return null;
}
public CompletableFuture<ApiHttpResponse<Order>> changeWorkflowState(
final ApiHttpResponse<Order> orderApiHttpResponse,
final State workflowState) {
final Order order = orderApiHttpResponse.getBody();
return apiRoot.withProjectKey(projectKey)
.orders()
.withId(order.getId())
.post(
OrderUpdateBuilder.of()
.version(order.getVersion())
.actions(
Arrays.asList(
OrderTransitionStateActionBuilder.of()
.state(StateResourceIdentifierBuilder.of()
.key(workflowState.getKey())
.build()
)
.build()
)
)
.build()
)
.execute();
}
} |
import React, {useEffect} from 'react';
import List from '@material-ui/core/List';
import Restaurant from '@material-ui/icons/Restaurant';
import ListItem from '@material-ui/core/ListItem';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import ListItemText from '@material-ui/core/ListItemText';
import Avatar from '@material-ui/core/Avatar';
import axios from '../../axios';
//import interfaces
import {ServerResponse} from "../../interfaces/table"
export default function AvailableTables(props){
const {free_tables, setFreeTables} = props
useEffect(() => {
const interval = setInterval(() => {
axios.get(`Tables/free`).then(
(res: ServerResponse) => {
const data = res.data;
setFreeTables(data);
})
},1000)
return() => clearInterval(interval)
})
function mapReactTableList(){
return free_tables.map((table) =>(
<ListItem key = {table.table_number}>
<ListItemAvatar>
<Avatar>
<Restaurant />
</Avatar>
</ListItemAvatar>
<ListItemText
primary={"Table " + table.table_number.toString()}
/>
<ListItemSecondaryAction>
<ListItemText
primary={table.table_size.toString() + ' Seats'}
/>
</ListItemSecondaryAction>
</ListItem>
))
}
const reactTableList = mapReactTableList()
return(
<React.Fragment>
<List>
{
reactTableList
}
</List>
</React.Fragment>
)
}
|
Application of fuzzy and binary algorithm to regulation of load in locomotive load test
The purpose of locomotive load test is to examine and adjust the capability of locomotive often in its non-driving state, and it is a kind of important standard and means to estimate the quality of repairing locomotive in railway locomotive depot. There are two ways of load test at present. One is the water-resistor load test, the other is the dry resistor load test. Because the dry resistor-load test means does not pollute the environment and needs area less, its developing foreground is immense. To solve the difficulty that the current cannot be freely regulated continuously, for the first time, the model of weightier resistor network in digital circuit is applied to the locomotive dry resistor-load test system, which solves the problem of dry resistor-load test theoretically. It is proved by theory and test that the precision of dry resistor means can meet the request of locomotives constant power load test and reach the standard of water-resistor, so it can serve the application of the dry resistor-load test system. During the locomotive load test, the load of locomotive may be regulated so that the locomotive can be adapted run on all kinds of actual work state. According to the characteristic of weightier resistor, the control arithmetic, which is made up of fuzzy algorithm and binary algorithm, realizes the fast and exact regulation on locomotive load. This paperintroduces how to apply fuzzy and binary algorithm to regulate the dry resistor-load and explains the realization of the fuzzy and binary algorithm. |
<reponame>zipated/src
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_SERVICE_MANAGER_STANDALONE_CONTEXT_H_
#define SERVICES_SERVICE_MANAGER_STANDALONE_CONTEXT_H_
#include <memory>
#include "base/macros.h"
#include "base/time/time.h"
#include "base/values.h"
#include "services/service_manager/runner/host/service_process_launcher_delegate.h"
namespace base {
class Value;
}
namespace service_manager {
class ServiceManager;
// The "global" context for the service manager's main process.
class Context {
public:
Context(ServiceProcessLauncherDelegate* launcher_delegate,
std::unique_ptr<base::Value> catalog_content);
~Context();
// Run the application specified on the command line.
void RunCommandLineApplication();
ServiceManager* service_manager() { return service_manager_.get(); }
private:
// Runs the app specified by |name|.
void Run(const std::string& name);
std::unique_ptr<ServiceManager> service_manager_;
base::Time main_entry_time_;
DISALLOW_COPY_AND_ASSIGN(Context);
};
} // namespace service_manager
#endif // SERVICES_SERVICE_MANAGER_STANDALONE_CONTEXT_H_
|
/**
* Application
*
* @author gavincook
* @version $ID: Application.java, v0.1 2018-06-17 14:38 gavincook Exp $$
*/
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(EurekaApplication.class).web(true).run(args);
}
} |
Effects of drill speed on heat production and the rate and quality of bone formation in dental implant osteotomies. Part II: Relationship between drill speed and healing.
In Part I of this two-part study, the authors investigated heat production during osteotomy drilling at three different speeds, and determined that high-speed drilling produced the least heat when using 700 XL carbide burs. Part II of the study histologically examines the rate and quality of healing after drilling osteotomies at the three speeds in the mandible. Osteotomies were histologically examined 2, 4, and 6 weeks postoperatively. Histologic findings suggested that in the initial 6 weeks, the rate of healing and quality of new bone formation were higher after high-speed drilling than after low- or intermediate-speed drilling. These results, when considered with the results reported in Part I in which a 4.3 degrees C difference in heat production was observed between the speeds, seem to imply a relationship between heat production and healing for osteotomy drilling. |
def disk(self):
if self._disk is not None:
return self._disk
elif self._config is not None:
return self._config.defaultDisk
else:
raise AttributeError("Default value for 'disk' cannot be determined") |
def _accuracy_policy(self, error_name):
error = qp.error.from_name(error_name)
tests = [m[3] for m in self.ensemble]
scores = []
for i, model in enumerate(self.ensemble):
scores.append(evaluate(model[0], tests[:i] + tests[i + 1:], error, self.n_jobs))
order = np.argsort(scores)
self.ensemble = _select_k(self.ensemble, order, k=self.red_size) |
On Sunday, self-described Democratic Socialist Bernie Sanders (I-Vt.) sat down with ABC’s George Stephanopoulos to discuss his newly formed presidential campaign and the This Week moderator fretted that his guest’s campaign could cause trouble for Hillary Clinton.
Speaking to Sanders, Stephanopoulos claimed that “[m]ost people don’t believe you can actually become President of the United States. Are you worried at all that your race might weaken Hillary Clinton without helping yourself?”
For his part, the ABC host did correctly call Sanders a socialist but Stephanopoulos did his best to press his guest from the left over the differences between him and the Democratic Party:
You know, you’ve said this campaign will be a clash of ideas? Which ideas? What are the biggest differences between you and Hillary Clinton?...Let's talk about a Sanders administration. What would it look like? You voted against both Obama Treasury Secretary nominees both Jack Lew and Tim Geithner. Name a couple people you would consider for Treasury Secretary.
Later in the broadcast, the “Powerhouse Roundtable” discussed Sanders’ presidential prospects and Katrina vanden Heuvel, editor of the far-left Nation magazine eagerly touted his socialist agenda. Vanden Heuvel hilariously claimed that if only "the mainstream media gives Bernie Sanders a chance” the American people will embrace his agenda.
Stephanopoulos seemed taken aback and asked his liberal guest “you don’t think he can win?” and Bill Kristol, editor of the conservative Weekly Standard, could barely contain himself from laughing.
Vanden Heuvel continued to promote a Sanders presidency but complained that the “mainstream media” wasn’t giving the Socialist candidate a chance:
His message is in sync with the populist moment we are in. And I think his message that he wants to fulfill the promise of America. That this is not a country that is going to be defined by billionaires but lift up ordinary Americans, deal with staggering income inequality, the climate crisis. Give people good jobs, not be held to corporate defined trade deals. Bernie Sanders announced, who announced to the nation a year ago that he would consider running for president, let's give him a chance and the mainstream media might well trivialize and distort others. But let's give Bernie a chance.
See Stephanopoulos’ questions below. |
<reponame>leettran/VirtualOffice<gh_stars>100-1000
describe("Virtual Office", () => {
before(() => {
cy.clearAllParticipants();
});
it("shows an avatar when a user joins a room", () => {
cy.replaceOffice({ rooms: [{ roomId: "1", name: "A room", meetingId: "123", joinUrl: "join-url" }], groups: [] });
cy.visit("/");
cy.get(".MuiCard-root").as("card");
cy.assertCard({ alias: "@card", title: "A room", isJoinable: true });
cy.webhook("meeting.participant_joined", "123", {
id: "user1",
user_id: "user1",
user_name: "Test User",
});
cy.webhook("meeting.participant_joined", "123", {
id: "user2",
user_id: "user2",
user_name: "Another User",
});
cy.get(".MuiAvatar-root").first().should("contain", "AU");
cy.get(".MuiAvatar-root").last().should("contain", "TU");
cy.webhook("meeting.participant_left", "123", {
id: "user2",
user_id: "user2",
user_name: "Another User",
});
cy.get(".MuiAvatar-root").should("contain", "TU");
cy.webhook("meeting.participant_left", "123", {
id: "user1",
user_id: "user1",
user_name: "Test User",
});
cy.get("@card").should("contain", "No one is here");
});
});
|
Splenic Injury After Colonoscopy
Colonoscopy is a routine procedure to screen for colorectal cancer. Splenic injury is an extremely rare but potentially fatal complication. We present a case of a 74-year-old woman on edoxaban who underwent a screening colonoscopy at a nearby outpatient surgery center. While in the recovery room, she experienced abdominal pain, hypotension, and episodes of syncope, arriving to our Emergency Department approximately 10 hours after the colonoscopy. She presented to the Emergency Department with a distended abdomen, hypotensive, and with significant abdominal pain. Abdominal computed tomography scan showed significant hemoperitoneum around the bilateral paracolic gutters, spleen, and gastric fundus. She underwent emergent midline laparotomy with evacuation of 1.5 L of hemoperitoneum with ongoing bleeding from her deseroalized spleen, suggesting traction injury from colonoscopy. In patients with abdominal pain, hypotension, and low hemoglobin postcolonoscopy, splenic injury should be considered in order to recognize early and manage appropriately. |
use actix_web::{Responder, web, HttpResponse};
use sqlx::{ MySqlPool};
use tracing::Subscriber;
use unicode_segmentation::UnicodeSegmentation;
use crate::domain::{NewSubscriber, SubscriberName};
#[tracing::instrument(
name="Adding a new subscriber",
skip(form,connection),
fields(
subscriber_email=%form.email,
subscriber_name=%form.name
)
)]
pub async fn subscribe(form: web::Form<FormData>, connection: web::Data<MySqlPool>) -> impl Responder {
let name = match SubscriberName::parse(form.0.name) {
Ok(name) => name,
Err(_) => return HttpResponse::BadRequest().finish()
};
let subscriber = NewSubscriber{email: form.0.email,name};
match insert_subscriber(&connection, &subscriber).await {
Ok(_) => HttpResponse::Ok().finish(),
Err(_) => HttpResponse::InternalServerError().finish()
}
}
#[tracing::instrument(
name = "Saving new subscriber details in the database", skip(subscriber, connection)
)]
async fn insert_subscriber(connection: &MySqlPool, subscriber: &NewSubscriber) -> Result<(), sqlx::Error>{
sqlx::query!( r#"
INSERT INTO subscriptions (email, name)
VALUES (?, ?)
"#,
subscriber.email, subscriber.name.as_ref()
)
.execute(connection)
.await
.map_err(|e| {
tracing::error!("Failed to execute query: {:?}", e);
e
})?;
Ok(())
}
#[derive(serde::Deserialize)]
pub struct FormData {
name: String,
email: String
} |
Libby Anne is wondering about a certain atheist trope: reading the Bible makes you an atheist.
First, because while I’m sure there are plenty of Christians who don’t read the Bible, everyone in the evangelical community where I grew up read it on a daily basis, and not just the easier books like the Gospels. Second, because I read the Bible through numerous times before I even graduated from high school, and doing so didn’t shake my fundamentalist/evangelical faith one iota.
I think there’s a difference between reading the Bible and having the Bible explained to you. Let me try to explain it this way:
What The Bible Says vs. What We Say the Bible Says
There’s the Bible, a collection of letters and books produced by different authors over the course of five or six hundred years. But then there’s a field of interpretations surrounding that Bible, a mixture of explanations and stories associated with the Bible that get passed down through tradition.
Well before you ever read the Bible – well before you can read – you have already begun to encounter that field. You are told what the Bible contains, what the Bible means, how it is used, what authority it possesses and so forth. You hear Bible stories and hear snatches of the Bible quoted authoritatively. Even if you were not raised Christian, you most likely encountered that field countless times.
The most obvious example is the nativity story. Before you came to know good from evil, you probably encountered the nativity story a dozen times, either by hearing the story told and preached or by seeing a creche. You heard about the shepherds and the angels and the three wise men. You heard about the trek to Bethlehem and the murderous King Herod.
But of course, there are actually two different stories there that have been mixed together. And there are no “three wise men,” that’s just a traditional guess. But many people have grown up with that story, and so opening the Bible they see that story in Matthew and Luke and do not question the idea that the two stories should be combined. They do not note that the wise men are not numbered.
Such people are not encountering the Bible directly, they are only perceiving it as it is visible through that field of interpretation. And those interpretations come to them through their community.
Let It Challenge You
When I was young, my family was Episcopalian, but most of my friends were Evangelicals. I got fed up with the way Episcopalians would evasively answer questions about what certain passages in the Bible meant. “What do you think it means?” was a typical response. In contrast, most of my Baptist friends could expect clear authoritative answers.
In hindsight, I recognize that my community was very conscious of that field. They were trying to avoid giving me pat answers. Better for me to be challenged by a Biblical passage than to through life anchored to some interpretation simply because of something my Sunday school teacher said.
Most of the Evangelical families living in the semi-rural south with me actually did believe that there were pat answers. They had no problem teaching the answers which they had learned from their families. And in this process the problems of the Bible are papered over, the challenges are swiftly removed and the contradictions are given a gloss that minimizes them. And since this process has been going on for generations, most of these answers are quite good and sound very reasonable.
Of course, this means that these families are not encountering the Bible directly. They were dealing with the field of interpretation that hovers around the Bible, while insisting that it really was the Bible all along. This field distorts the text, highlighting some passages and covering others – picking and choosing.
I write all this, partially to respond to Libby Anne’s questions, but also as a response to people in the recent discussions of Progressive Christianity who were arguing that at least the Fundamentalists don’t cherry pick the Bible. As I’ve pointed out before, they most definately do pick and choose what verses apply to their lives.
Or rather, they let the field do it for them. That allows them to say with a straight face that they accept the authority of the Bible while still ignoring large sections. They’re unaware that they’re still miles away from the Bible, interacting with the field of traditional interpretations that their community has passed on to them.
So the difference between Fundamentalists and Progressives is not that one the first take the Bible literally and the second pick and choose. Both groups interpret the Bible in ways that minimize or remove certain sections and highlight others. The difference is that the Progressives do it consciously. |
<reponame>pauljamescleary/money<gh_stars>10-100
package com.comcast.money.samples.springmvc.services;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.HttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import com.comcast.money.core.Money;
import com.comcast.money.annotations.Traced;
import com.comcast.money.http.client.TraceFriendlyHttpClient;
@Component
public class NestedService {
private HttpClient httpClient = new TraceFriendlyHttpClient(HttpClientBuilder.create().build());
@Traced("NESTED_SERVICE")
public String doSomethingElse(String message) throws Exception {
double wait = RandomUtil.nextRandom(100, 500);
Money.Environment().tracer().record("nested-wait", wait);
// invoking the http client will activate the http tracing...
callHttpClient();
return message + ". Nested service made you wait an additional " + wait + " millseconds.";
}
// here, we will test that the http tracing works as expected
private void callHttpClient() {
try {
// it doesn't really matter if it all works for sample purposes
HttpResponse response = httpClient.execute(new HttpGet("http://www.google.com"));
// need to call EntityUtils in order to tie into the http trace aspect
// if you sniff the request, you will also see the X-MoneyTrace request header in the HTTP request
EntityUtils.consumeQuietly(response.getEntity());
Thread.sleep(1);
} catch(Exception ex) {
// just eat it
ex.printStackTrace();
}
}
}
|
#include<cstdio>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<cstdlib>
using namespace std;
#define db double
#define ll long long
#define MAXB 17
#define N 200005
int last[N][MAXB+1];
int pre[N], ocr[N];
int mx[5*N];
int n,x,y,m,q,p[N],a[N];
int go(int x,int y){
for(int i=0;i<=MAXB;i++){
if (y&1) x = last[x][i];
y/=2;
} return x;
}
void add(int s,int l,int r,int x,int y){
if (l==r) {mx[s]=y; return;}
if (x<=(l+r)/2) add(s*2,l,(l+r)/2,x,y);
else add(s*2+1,(l+r)/2+1,r,x,y);
mx[s] = max(mx[s*2], mx[s*2+1]);
}
int query(int s,int l,int r,int x,int y){
if (x<=l && r<=y) return mx[s];
if (x>r || y<l) return 0;
return max(query(s*2,l,(l+r)/2,x,y), query(s*2+1,(l+r)/2+1,r,x,y));
}
int main(){
scanf("%d %d %d",&n,&m,&q);
for(int i=1;i<=n;i++)
scanf("%d",&p[i]);
p[0] = p[n];
for(int i=1;i<=n;i++)
pre[p[i]] = p[i-1];
for(int i=1;i<=m;i++){
scanf("%d",&a[i]);
last[i][0] = ocr[pre[a[i]]];
ocr[a[i]] = i;
}
for(int i=0;i<MAXB;i++)
for(int j=1;j<=m;j++)
last[j][i+1] = last[last[j][i]][i];
for(int i=1;i<=m;i++)
add(1, 1, m, i, go(i, n-1));
for(;q--;){
scanf("%d %d",&x,&y);
printf("%d",query(1, 1, m, x, y)>=x);
}
return 0;
} |
export function getConwaySequenceForRow(targetRowNumber: number) : string
{
if (targetRowNumber >= 80)
{
return "Sequence is too long to compute!";
}
if (targetRowNumber <= 1)
{
return "1";
}
return getConwaySequenceForRowRec(1, targetRowNumber, "1");
}
function getConwaySequenceForRowRec(
currentRowNumber : number,
targetRowNumber : number,
lastConwayValue : string
)
{
if (currentRowNumber >= targetRowNumber)
{
return lastConwayValue;
}
var currentConwayValue = calculateConwayValueRec(
lastConwayValue.split(''),
0,
''
);
return getConwaySequenceForRowRec(currentRowNumber + 1, targetRowNumber, currentConwayValue);
}
function calculateConwayValueRec(
baseValue : string[],
index : number,
result : string
) : string
{
if (index >= baseValue.length)
{
return result;
}
var currentChar = baseValue[index];
var counted = countSequentialIdenticalCharactersRec(
baseValue,
currentChar,
0,
index
);
return calculateConwayValueRec(baseValue, counted.Index, result + counted.ResultString);
}
function countSequentialIdenticalCharactersRec(
baseValue : string[],
currentChar : string,
currentAccumulatedCharCount : number,
index : number
) : SequentialCharactersResult
{
if (baseValue[index] === currentChar)
{
return countSequentialIdenticalCharactersRec(
baseValue,
currentChar,
currentAccumulatedCharCount + 1,
index + 1
);
}
return new SequentialCharactersResult(currentAccumulatedCharCount.toString() + currentChar, index);
}
class SequentialCharactersResult
{
constructor(resultString : string, index : number)
{
this._resultString = resultString;
this._index = index;
}
private _resultString : string;
public get ResultString() : string {
return this._resultString;
}
private _index : number;
public get Index() : number {
return this._index;
}
}
|
module Widget.LessonList (
lessonListWidget
) where
import Import
lessonListWidget :: Maybe Text -> [(Text,Text)] -> WidgetT App IO ()
lessonListWidget mTitle lsnLst =
$(widgetFile "widget/lessonlist")
|
<reponame>Dviros/NovaJS
import { DisplayMod } from "./display/DisplayMod";
import { EngineMod } from "./engine/EngineMod";
export interface Mod {
engineMod?: EngineMod,
displayMod?: DisplayMod,
}
|
from allosaurus.pm.mfcc import MFCC
import json
from argparse import Namespace
def read_pm(model_path, inference_config):
"""
read feature extraction model
:param pm_config:
:return:
"""
pm_config = Namespace(**json.load(open(str(model_path / 'pm_config.json'))))
assert pm_config.model == 'mfcc_hires', 'only mfcc_hires is supported for allosaurus now'
assert pm_config.backend == 'numpy', 'only numpy backend is supported for allosaurus now'
model = MFCC(pm_config)
return model |
import requests
import urllib.parse
import csv
import time
def getGeoLoc(street_address,city,zipcode):
address = street_address+" "+city+" "+zipcode
coords = {}
url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) +'?format=json'
try:
response = requests.get(url).json()
except:
print(street_address, city, zipcode)
if(response):
lon =(response[0]["lon"])
lat = (response[0]["lat"])
coords['long'] = lon
coords['lat'] = lat
#print(lon,lat)
return coords
else:
return 400
if __name__=="__main__":
device_id = 0;
with open("./profile/address_reformated_withCoord.csv", mode='r') as house:
next(house)
csv_reader1 = csv.reader(house, delimiter=',')
house = list(csv_reader1)
with open("./profile/address_reformated_withCoord2.csv", mode='w+') as house1:
csvwriter = csv.writer(house1, delimiter=',')
csvwriter.writerow(["street_name","city","state","zipcode","lat","long","device_id"])
for row in house:
# print row
street_name = row[0]
city = row[1]
zipcode = row[2]
lat = row[3]
long = row[4]
csvrow = [street_name,city,zipcode,lat,long,device_id]
csvwriter.writerow(csvrow)
device_id+=1
#time.sleep(5)
|
/**
* Grava um registro na tabela satelite se IdResultado igual a zero, caso contrario atualiza o registro.
@author Antonio Cassiano
@param sateliteDTO
**/
public void gravar(SateliteDTO sateliteDTO) {
Database.manager.getTransaction().begin();
if (sateliteDTO.getIdSatelite() == 0) {
Database.manager.persist(sateliteDTO);
} else {
Database.manager.merge(sateliteDTO);
}
Database.manager.getTransaction().commit();
} |
/**
* @param list what the special key sequences are
* @param listCount how many special key sequences there are
* @param a_CLI the command line interface to get the data from
*/
int returnKey(const EscapeTranslate * list, const int listCount, CLI::BufferManager * a_CLI) {
int bufrSize = a_CLI->getInputBufferCount();
const int *bufr = a_CLI->getInputBuffer();
if(bufrSize > 0) {
int result = bufr[0];
if(result >= 128 || result < -128) {
result = translateSpecialCharacters(result, list, listCount);
}
a_CLI->inputBufferConsume(1);
return result;
}
return EOF;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.